SCM

SCM Repository

[inlinedocs] Diff of /pkg/inlinedocs/R/parsers.R
ViewVC logotype

Diff of /pkg/inlinedocs/R/parsers.R

Parent Directory Parent Directory | Revision Log Revision Log | View Patch Patch

revision 142, Wed Oct 20 09:21:53 2010 UTC revision 198, Fri Feb 18 14:17:08 2011 UTC
# Line 8  Line 8 
8  ### combine lists by adding elements or adding to existing elements  ### combine lists by adding elements or adding to existing elements
9  combine.list <- function(x,y){  combine.list <- function(x,y){
10    toadd <- !names(y)%in%names(x)    toadd <- !names(y)%in%names(x)
11    toup <- names(y)[names(y)%in%names(x)]    toup <- names(y)[!toadd]
12      ##if("doc"%in%names(x))return(x$doc)
13      ##if("doc"%in%names(y))return(y$doc)
14    x[names(y)[toadd]] <- y[toadd]    x[names(y)[toadd]] <- y[toadd]
15    for(up in toup)x[[up]] <- combine(x[[up]],y[[up]])    for(up in toup)x[[up]] <- combine(x[[up]],y[[up]])
16    return(x)    return(x)
# Line 24  Line 26 
26  (comments  (comments
27  ### Character vector of prefixed comment lines.  ### Character vector of prefixed comment lines.
28   ){   ){
29    paste(gsub(prefix,"",comments),collapse="\n")    gsub(prefix,"",comments)
30  ### String without prefixes or newlines.  ### String without prefixes or newlines.
31  }  }
32    
 ### For each object in the package that satisfies the criterion#  
 ## checked by subfun, parse source using FUN and return the resulting  
 ### documentation list.  
33  forall <- function  forall <- function
34    ### For each object in the package that satisfies the criterion
35    ### checked by subfun, parse source using FUN and return the resulting
36    ### documentation list.
37  (FUN,  (FUN,
38  ### Function to apply to each element in the package.  ### Function to apply to each element in the package.
39   subfun=function(x)TRUE   subfun=function(x)TRUE
# Line 43  Line 45 
45    f <- function(objs,docs,...){    f <- function(objs,docs,...){
46      objs <- objs[sapply(objs,subfun)]      objs <- objs[sapply(objs,subfun)]
47      L <- list()      L <- list()
48        on.exit(cat(sprintf("Parser Function failed on %s\n",N)))
49      for(N in names(docs)){      for(N in names(docs)){
50        o <- objs[[N]]        o <- objs[[N]]
51        L[[N]] <- FUN(src=attr(o,"source"),        L[[N]] <- FUN(src=attr(o,"source"),
52                      name=N,objs=objs,o=o,docs=docs,doc=docs[[N]],...)                      name=N,objs=objs,o=o,docs=docs,doc=docs[[N]],...)
53      }      }
54        on.exit()## remove warning message
55      L      L
56    }    }
57    class(f) <- c("allfun","function")    class(f) <- c("allfun","function")
# Line 67  Line 71 
71  ### For each function in the package, do something.  ### For each function in the package, do something.
72  forfun <- function(FUN)forall(FUN,is.function)  forfun <- function(FUN)forall(FUN,is.function)
73    
74    kill.prefix.whitespace <- function
75    ### Figure out what the whitespace preceding the example code is, and
76    ### then delete that from every line.
77    (ex
78    ### character vector of example code lines.
79     ){
80      tlines <- gsub("\\s*","",ex)
81      ##tlines <- gsub("#.*","",tlines)
82      prefixes <- unique(gsub("\\S.*","",ex[tlines!=""]))
83      FIND <- prefixes[which.min(nchar(prefixes))]
84      ## Eliminate leading tabulations or 2/4 spaces
85      sub(FIND, "", ex)
86    ### Character vector of code lines with preceding whitespace removed.
87    }
88    
89  examples.after.return <- function  examples.after.return <- function
90  ### Get examples from inline definitions after return()  ### Get examples from inline definitions after return()
91  ### PhG: this does not work well! Think of these situations:  ### PhG: this does not work well! Think of these situations:
# Line 111  Line 130 
130    ## Possibly eliminate a #}}} tag    ## Possibly eliminate a #}}} tag
131    ex <- ex[!grepl("#}}}", ex)]    ex <- ex[!grepl("#}}}", ex)]
132    ## Eliminate leading tabulations or four spaces    ## Eliminate leading tabulations or four spaces
133    prefixes <- gsub("(\\s*).*","\\1",ex,perl=TRUE)[grep("\\w",ex)]    ex <- kill.prefix.whitespace(ex)
   FIND <- prefixes[which.min(nchar(prefixes))]  
   ex <- sub(FIND,"",ex)  
134    ## Add an empty line before and after example    ## Add an empty line before and after example
135    ex <- c("", ex, "")    ex <- c("", ex, "")
136    ## Return examples and value    ## Return examples and value
137    list(examples = paste(ex, collapse = "\n"), value = value)    list(examples = ex, value = value)
138  }  }
139    
140  prefixed.lines <- function(src,...){  prefixed.lines <- structure(function(src,...){
141  ### The primary mechanism of inline documentation is via consecutive  ### The primary mechanism of inline documentation is via consecutive
142  ### groups of lines matching the specified prefix regular expression  ### groups of lines matching the specified prefix regular expression
143  ### "\code{^### }" (i.e. lines beginning with "\code{### }") are  ### "\code{^### }" (i.e. lines beginning with "\code{### }") are
# Line 136  Line 153 
153    starts <- c(1,bounds+1)    starts <- c(1,bounds+1)
154    ends <- c(bounds,length(clines))    ends <- c(bounds,length(clines))
155    ## detect body of function using paren matching    ## detect body of function using paren matching
156    f <- function(ch)cumsum(nchar(gsub(sprintf("[^%s]",ch),"",src)))    code <- gsub("#.*","",src)
157      f <- function(ch)cumsum(nchar(gsub(sprintf("[^%s]",ch),"",code)))
158    parens <- f("(")-f(")")    parens <- f("(")-f(")")
159    body.begin <- which(diff(parens)<0 & parens[-1]==0)+2    body.begin <- which(diff(parens)<0 & parens[-1]==0)+2
160      if(length(body.begin)==0)body.begin <- 1 ## rare cases
161    is.arg <- function(){    is.arg <- function(){
162      0 == length(grep("^\\s*#",src[start-1],perl=TRUE)) &&      gres <- grep("^\\s*#",src[start-1],perl=TRUE)
163        start<=body.begin      0 == length(gres) && start<=body.begin
164      }      }
165    res <- list()    res <- list()
166    for(i in seq_along(starts)){    for(i in seq_along(starts)){
167      start <- clines[starts[i]]      start <- clines[starts[i]]
168      end <- clines[ends[i]]      end <- clines[ends[i]]
169      lab <- if(end+1==length(src))"value"      lab <- if(all(grepl("^\\s*#",src[end:(length(src)-1)])))"value"
170      else if(start==2)"description"      else if(start==2)"description"
171      else if(is.arg()){      else if(is.arg()){
172        ##twutz: strip leading white spaces and brackets and ,        ##twutz: strip leading white spaces and brackets and ,
# Line 163  Line 182 
182      res[[lab]] <- decomment(src[start:end])      res[[lab]] <- decomment(src[start:end])
183    }    }
184    res    res
185  }  },ex=function(){
186    test <- function
187  ### Parsers for each object/function that are constructed  ### the description
188  ### automatically. This is a named list, each element is a list of 2  (x,
189  ### elements: forfun/forall, then a parser function for an individual  ### the first argument
190  ### object.   y ##<< another argument
 forfun.parsers <-  
   list(prefixed.lines=prefixed.lines,  
        examples.after.return=examples.after.return,  
        ## Extract lots of info from normal functions.  
        parsefun=function(src,name,...){  
          extract.docs.fun(src,name)  
        },  
        ## title from first line of function def  
        title.from.firstline=function(src,name,code,...){  
          if(length(grep("#",src[1]))){  
            list(title=gsub("[^#]*#\\s*(.*)","\\1",src[1],perl=TRUE))  
          } else list()  
        },  
        ## PhG: it is tests/FUN.R!!! I would like more flexibility here  
        ## please, let me choose which dir to use for examples!  
        ## Get examples for FUN from the file tests/FUN.R  
        examples.from.testfile=function(name,...){  
          tsubdir <- getOption("inlinedocs.exdir")  
          if (is.null(tsubdir)) tsubdir <- "tests"       # Default value  
          tfile <- file.path("..",tsubdir,paste(name,".R",sep=""))  
          if(file.exists(tfile))  
            list(examples=paste(readLines(tfile),collapse="\n"))  
          else list()  
        },  
        definition.from.source=function(doc,src,...){  
          def <- doc$definition  
          if(is.null(def)||def=="")  
            list(definition=paste(src,collapse="\n"))  
          else list()  
        })  
   
 ### List of Parser Functions that can be applied to any object.  
 forall.parsers <-  
   list(## Fill in author from DESCRIPTION and titles.  
        author.from.description=function(desc,...){  
          list(author=desc[,"Maintainer"])  
        },  
        ## The format section sometimes causes problems, so erase it.  
        erase.format=function(...){  
          list(format="")  
        },  
        ## Convert the function name to a title.  
        title.from.name=function(name,doc,...){  
          if("title"%in%names(doc))list() else  
          list(title=gsub("[._]"," ",name))  
        },  
        ## PhG: here is what I propose for examples code in the 'ex' attribute  
        examples.in.attr =  function (name, o, ...) {  
          ex <- attr(o, "ex")  
          if (!is.null(ex)) {  
            ## Special case for code contained in a function  
            if (inherits(ex, "function")) {  
              ## If source is available, start from there  
              src <- attr(ex, "source")  
              if (!is.null(src)) {  
                ex <- src  
              } else { ## Use the body of the function  
                ex <- deparse(body(ex))  
              }  
              ## Eliminate leading and trailing code  
              ex <- ex[-c(1, length(ex))]  
              ## Eliminate leading tabulations or 2/4 spaces  
              ex <- sub("^\t|    |  ", "", ex)  
              ## Add an empty line before and after example  
              ex <- c("", ex, "")  
            }  
            list(examples = paste(ex, collapse = "\n"))  
          } else list()  
        })  
   
 ### List of parser functions that operate on single objects. This list  
 ### is useful for testing these functions.  
 lonely <- c(forall.parsers,forfun.parsers)  
 attr(lonely,"ex") <- function(){  
   lonely$parsefun(attr(extract.docs.file,"source"),"extract.docs.file")  
 }  
   
 extra.code.docs <- function # Extract documentation from code chunks  
 ### Parse R code to extract inline documentation from comments around  
 ### each function. These are not able to be retreived simply by  
 ### looking at the "source" attribute. This is a Parser Function that  
 ### can be used in the parser list of package.skeleton.dx(). TODO:  
 ### Modularize this into separate Parsers Functions for S4 classes,  
 ### prefixes, ##<<blocks, etc. Right now it is not very clean!  
 (code,  
 ### Code lines in a character vector containing multiple R objects to  
 ### parse for documentation.  
  objs,  
 ### The objects defined in the code.  
  ...  
 ### ignored  
  ){  
   parsed <- extract.file.parse(code)  
   extract.docs.try <- function(o,on)  
     {  
       ## Note: we could use parsed information here too, but that  
       ## would produce different results for setMethodS3 etc.  
       doc <- list()  
       if ( !is.null(parsed[[on]]) ){  
         if ( !is.na(parsed[[on]]@code[1]) ){ # no code given for generics  
           doc$definition <- paste(parsed[[on]]@code,collapse="\n")  
         }  
         if(!"description"%in%names(doc) && !is.na(parsed[[on]]@description) ){  
           doc$description <- parsed[[on]]@description  
         }  
         if ( "setMethodS3" == parsed[[on]]@created ){  
           # PhG: this may be wrong! It does not catch correctly how the method  
           # must be splitted in case of methods containing dots. for instance,  
           # as.data.frame.matrix must be split into: m1 = as.data.frame and  
           # m2 = matrix... here you got m1 = as, and m2 = data.frame.matrix!!!  
                   pattern <- "^([^\\.]+)\\.(.*)$"  
           doc$s3method=c(m1 <- gsub(pattern,"\\1",on,perl=TRUE),  
               m2 <- gsub(pattern,"\\2",on,perl=TRUE))  
           if ( 0 < length(grep("\\W",m1,perl=TRUE)) ){  
                           m1 <- paste("`",m1,"`",sep="")  
           }  
           cat("S3method(",m1,",",m2,")\n",sep="")  
         }  
       }  
       if("title" %in% names(doc) && !"description" %in% names(doc) ){  
         ## For short functions having both would duplicate, but a  
         ## description is required. Therefore automatically copy title  
         ## across to avoid errors at package build time.  
         doc$description <- doc$title  
       }  
       doc  
     }  
   extract.docs <- function(on){  
     res <- try({o <- objs[[on]]  
                 extract.docs.try(o, on)},FALSE)  
     if(class(res)=="try-error"){  
       cat("Failed to extract docs for: ",on,"\n\n")  
       list()  
     } else if(0 == length(res) && inherits(objs[[on]],"standardGeneric")){  
       NULL  
     } else if(0 == length(res) && "function" %in% class(o)  
               && 1 == length(osource <- attr(o,"source"))  
               && 1 == length(grep(paste("UseMethod(",on,")",sep="\""),osource))  
191                ){                ){
192        ## phew - this should only pick up R.oo S3 generic definitions like:    5
193        ## attr(*, "source")= chr "function(...) UseMethod(\"select\")"  ### the return value
194        NULL  ##seealso<< foobar
195      } else res  }
196    }  src <- attr(test,"source")
197    doc.names <- names(objs)  prefixed.lines(src)
198    res <- sapply(doc.names,extract.docs,simplify=FALSE)  extract.xxx.chunks(src)
   ## Special processing for S4 classes as they do not appear in normal ls()  
   for ( nn in names(parsed) ){  
     if ( parsed[[nn]]@created == "setClass" ){  
       S4class.docs <- extract.docs.setClass(parsed[[nn]])  
       docname <- paste(nn,"class",sep="-")  
       if ( is.null(res[[docname]]) ){  
         res[[docname]] <- S4class.docs  
         doc.names <- c(doc.names,docname)  
       } else {  
         stop(nn," appears as both S4 class and some other definition")  
       }  
     }  
   }  
   inherit.docs <- function(on){  
     in.res <- res[[on]]  
     if ( !is.null(parsed[[on]]) ){  
       for ( parent in parsed[[on]]@parent ){  
         if ( !is.na(parent) ){  
           if ( is.null(in.res) ){  
             in.res <- res[[parent]]  
           } else if ( parent %in% names(res) ){  
             parent.docs <- res[[parent]]  
             for ( nn in names(parent.docs) ){  
               if ( !nn %in% names(in.res) ){  
                 in.res[[nn]] <- parent.docs[[nn]]  
               }  
             }  
           }  
         }  
       }  
     }  
     invisible(in.res)  
   }  
   all.done <- FALSE  
   while ( !all.done ){  
     res1 <- sapply(doc.names,inherit.docs,simplify=FALSE)  
     all.done <- identical(res1,res)  
     res <- res1  
   }  
   ## now strip out any generics (which have value NULL in res):  
   res.not.null <- sapply(res,function(x){!is.null(x)})  
   if ( 0 < length(res.not.null) && length(res.not.null) < length(res) ){  
     res <- res[res.not.null]  
   }  
   res  
 ### named list of lists, one for each object to document.  
 }  
   
 ### List of parsers to use by default with package.skeleton.dx.  
 default.parsers <-  
   c(extra.code.docs=extra.code.docs, ## TODO: cleanup!  
     sapply(forfun.parsers,forfun),  
     sapply(forall.parsers,forall),  
     edit.package.file=function(desc,...){  
       in.details <- setdiff(colnames(desc),"Description")  
       details <- paste(paste(in.details,": \\tab ",desc[,in.details],"\\cr",  
                              sep=""),collapse="\n")  
       L <-  
         list(list(title=desc[,"Title"],  
                   description=desc[,"Description"],  
                   `tabular{ll}`=details,  
                   author=desc[,"Maintainer"]))  
       names(L) <- paste(desc[,"Package"],"-package",sep="")  
       L  
199      })      })
200    
201  extract.docs.fun <- function # Extract documentation from a function  extract.xxx.chunks <- function # Extract documentation from a function
202  ### Given source code of a function, return a list describing inline  ### Given source code of a function, return a list describing inline
203  ### documentation in that source code.  ### documentation in that source code.
204  (code,  (src,
205  ### The function to examine.  ### The source lines of the function to examine, as a character
206   name.fun  ### vector.
207     name.fun="(unnamed function)",
208  ### The name of the function/chunk to use in warning messages.  ### The name of the function/chunk to use in warning messages.
209     ...
210    ### ignored.
211   ){   ){
212    res <- list()    res <- list()
213    ##details<< For simple functions/arguments, the argument may also be    ##details<< For simple functions/arguments, the argument may also be
# Line 462  Line 282 
282          chunk.sep <- "\n\n"          chunk.sep <- "\n\n"
283        }        }
284        chunk.res <- NULL        chunk.res <- NULL
285        if ( 0 == length(grep("^\\s*$",payload,perl=TRUE)) )        if ( !grepl("^\\s*$",payload,perl=TRUE) )
286          chunk.res <-          chunk.res <-
287            if ( is.null(res[[field]]) ) payload            if ( is.null(res[[field]]) ) payload
288            else paste(res[[field]], payload, sep=chunk.sep)            else paste(res[[field]], payload, sep=chunk.sep)
289        invisible(chunk.res)        invisible(chunk.res)
290      }      }
291    while ( k <= length(code) ){    while ( k <= length(src) ){
292      line <- code[k]      line <- src[k]
293      if ( 0 < length(grep(extra.regexp,line,perl=TRUE) ) ){      if ( grepl(extra.regexp,line,perl=TRUE) ){
294        ## we have a new extra chunk - first get field name and any payload        ## we have a new extra chunk - first get field name and any payload
295        new.field <- gsub(extra.regexp,"\\1",line,perl=TRUE)        new.field <- gsub(extra.regexp,"\\1",line,perl=TRUE)
296        new.contents <- gsub(extra.regexp,"\\2",line,perl=TRUE)        new.contents <- gsub(extra.regexp,"\\2",line,perl=TRUE)
# Line 545  Line 365 
365            first.describe <- TRUE;            first.describe <- TRUE;
366          }          }
367        }        }
368      } else if ( in.chunk && 0<length(grep(cont.re,line,perl=TRUE)) ){      } else if ( in.chunk && grepl(cont.re,line,perl=TRUE) ){
369        ## append this line to current chunk        ## append this line to current chunk
370        if ( 0 == length(grep(prefix,line,perl=TRUE)) ){        if ( !grepl(prefix,line,perl=TRUE) ){
371          ##describe<< Any lines with "\code{### }" at the left hand          ##describe<< Any lines with "\code{### }" at the left hand
372          ## margin within the included chunks are handled separately,          ## margin within the included chunks are handled separately,
373          ## so if they appear in the documentation they will appear          ## so if they appear in the documentation they will appear
# Line 560  Line 380 
380            payload <- stripped            payload <- stripped
381          }          }
382        }        }
383      } else if ( 0 < length(grep(arg.pat,line,perl=TRUE)) ){      } else if ( grepl(arg.pat,line,perl=TRUE) ){
384        not.describe <- (0==in.describe && !first.describe)        not.describe <- (0==in.describe && !first.describe)
385        if ( in.chunk && not.describe){        if ( in.chunk && not.describe){
386          res[[cur.field]] <- end.chunk(cur.field,payload)          res[[cur.field]] <- end.chunk(cur.field,payload)
# Line 622  Line 442 
442  ### with the string in this list (implemented in modify.Rd.file).  ### with the string in this list (implemented in modify.Rd.file).
443  }  }
444    
445    ### Parsers for each function that are constructed automatically. This
446    ### is a named list, and each element is a parser function for an
447    ### individual object.
448    forfun.parsers <-
449      list(prefixed.lines=prefixed.lines,
450           examples.after.return=examples.after.return,
451           extract.xxx.chunks=extract.xxx.chunks,
452           ## title from first line of function def
453           title.from.firstline=function(src,...){
454             first <- src[1]
455             if(!is.character(first))return(list())
456             if(!grepl("#",first))return(list())
457             list(title=gsub("[^#]*#\\s*(.*)","\\1",first,perl=TRUE))
458           },
459           ## PhG: it is tests/FUN.R!!! I would like more flexibility here
460           ## please, let me choose which dir to use for examples!
461           ## Get examples for FUN from the file tests/FUN.R
462           examples.from.testfile=function(name,...){
463             tsubdir <- getOption("inlinedocs.exdir")
464             if (is.null(tsubdir)) tsubdir <- "tests"       # Default value
465             tfile <- file.path("..",tsubdir,paste(name,".R",sep=""))
466             if(file.exists(tfile))
467               list(examples=readLines(tfile))
468             else list()
469           },
470           definition.from.source=function(doc,src,...){
471             def <- doc$definition
472             is.empty <- function(x)is.null(x)||x==""
473             if(is.empty(def) && !is.empty(src))
474               list(definition=src)
475             else list()
476           })
477    
478    ### List of Parser Functions that can be applied to any object.
479    forall.parsers <-
480      list(## Fill in author from DESCRIPTION and titles.
481           author.from.description=function(desc,...){
482             list(author=desc[,"Maintainer"])
483           },
484           ## The format section sometimes causes problems, so erase it.
485           erase.format=function(...){
486             list(format="")
487           },
488           ## Convert the function name to a title.
489           title.from.name=function(name,doc,...){
490             if("title"%in%names(doc))list() else
491             list(title=gsub("[._]"," ",name))
492           },
493           ## PhG: here is what I propose for examples code in the 'ex' attribute
494           examples.in.attr =  function (name, o, ...) {
495             ex <- attr(o, "ex")
496             if (!is.null(ex)) {
497               ## Special case for code contained in a function
498               if (inherits(ex, "function")) {
499                 ## If source is available, start from there
500                 src <- attr(ex, "source")
501                 if (!is.null(src)) {
502                   ex <- src
503                 } else { ## Use the body of the function
504                   ex <- deparse(body(ex))
505                 }
506                 ## Eliminate leading and trailing code
507                 ex <- ex[-c(1, length(ex))]
508                 ## all the prefixes
509                 ex <- kill.prefix.whitespace(ex)
510                 ## Add an empty line before and after example
511                 ex <- c("", ex, "")
512               }
513               list(examples = ex)
514             } else list()
515           }
516           )
517    
518    ### List of parser functions that operate on single objects. This list
519    ### is useful for testing these functions.
520    lonely <- structure(c(forall.parsers,forfun.parsers),ex=function(){
521      f <- function # title
522    ### description
523      (x, ##<< arg x
524       y
525    ### arg y
526       ){
527        ##value<< a list with elements
528        list(x=x, ##<< original x value
529             y=y, ##<< original y value
530             sum=x+y) ##<< their sum
531        ##end<<
532      }
533      src <- attr(f,"source")
534      lonely$extract.xxx.chunks(src)
535      lonely$prefixed.lines(src)
536    })
537    
538    extra.code.docs <- function # Extract documentation from code chunks
539    ### Parse R code to extract inline documentation from comments around
540    ### each function. These are not able to be retreived simply by
541    ### looking at the "source" attribute. This is a Parser Function that
542    ### can be used in the parser list of package.skeleton.dx(). TODO:
543    ### Modularize this into separate Parsers Functions for S4 classes,
544    ### prefixes, ##<<blocks, etc. Right now it is not very clean!
545    (code,
546    ### Code lines in a character vector containing multiple R objects to
547    ### parse for documentation.
548     objs,
549    ### The objects defined in the code.
550     ...
551    ### ignored
552     ){
553      parsed <- extract.file.parse(code)
554      extract.docs.try <- function(o,on)
555        {
556          ## Note: we could use parsed information here too, but that
557          ## would produce different results for setMethodS3 etc.
558          doc <- list()
559          if ( !is.null(parsed[[on]]) ){
560            if ( !is.na(parsed[[on]]@code[1]) ){ # no code given for generics
561              doc$definition <- paste(parsed[[on]]@code)
562            }
563            if(!"description"%in%names(doc) && !is.na(parsed[[on]]@description) ){
564              doc$description <- parsed[[on]]@description
565            }
566            if ( "setMethodS3" == parsed[[on]]@created ){
567              # PhG: this may be wrong! It does not catch correctly how the method
568              # must be splitted in case of methods containing dots. for instance,
569              # as.data.frame.matrix must be split into: m1 = as.data.frame and
570              # m2 = matrix... here you got m1 = as, and m2 = data.frame.matrix!!!
571                      pattern <- "^([^\\.]+)\\.(.*)$"
572              doc$.s3method=c(m1 <- gsub(pattern,"\\1",on,perl=TRUE),
573                  m2 <- gsub(pattern,"\\2",on,perl=TRUE))
574              if ( grepl("\\W",m1,perl=TRUE) ){
575                              m1 <- paste("`",m1,"`",sep="")
576              }
577              cat("S3method(",m1,",",m2,")\n",sep="")
578            }
579          }
580          if("title" %in% names(doc) && !"description" %in% names(doc) ){
581            ## For short functions having both would duplicate, but a
582            ## description is required. Therefore automatically copy title
583            ## across to avoid errors at package build time.
584            doc$description <- doc$title
585          }
586          doc
587        }
588      extract.docs <- function(on){
589        res <- try({o <- objs[[on]]
590                    extract.docs.try(o, on)},FALSE)
591        if(class(res)=="try-error"){
592          cat("Failed to extract docs for: ",on,"\n\n")
593          list()
594        } else if(0 == length(res) && inherits(objs[[on]],"standardGeneric")){
595          NULL
596        } else if(0 == length(res) && "function" %in% class(o)
597                  && 1 == length(osource <- attr(o,"source"))
598                  && grepl(paste("UseMethod(",on,")",sep="\""),osource)
599                  ){
600          ## phew - this should only pick up R.oo S3 generic definitions like:
601          ## attr(*, "source")= chr "function(...) UseMethod(\"select\")"
602          NULL
603        } else res
604      }
605      doc.names <- names(objs)
606      res <- sapply(doc.names,extract.docs,simplify=FALSE)
607      ## Special processing for S4 classes as they do not appear in normal ls()
608      for ( nn in names(parsed) ){
609        if ( parsed[[nn]]@created == "setClass" ){
610          S4class.docs <- extract.docs.setClass(parsed[[nn]])
611          docname <- paste(nn,"class",sep="-")
612          if ( is.null(res[[docname]]) ){
613            res[[docname]] <- S4class.docs
614            doc.names <- c(doc.names,docname)
615          } else {
616            stop(nn," appears as both S4 class and some other definition")
617          }
618        }
619      }
620      inherit.docs <- function(on){
621        in.res <- res[[on]]
622        if ( !is.null(parsed[[on]]) ){
623          for ( parent in parsed[[on]]@parent ){
624            if ( !is.na(parent) ){
625              if ( is.null(in.res) ){
626                in.res <- res[[parent]]
627              } else if ( parent %in% names(res) ){
628                parent.docs <- res[[parent]]
629                for ( nn in names(parent.docs) ){
630                  if ( !nn %in% names(in.res) ){
631                    in.res[[nn]] <- parent.docs[[nn]]
632                  }
633                }
634              }
635            }
636          }
637        }
638        invisible(in.res)
639      }
640      all.done <- FALSE
641      while ( !all.done ){
642        res1 <- sapply(doc.names,inherit.docs,simplify=FALSE)
643        all.done <- identical(res1,res)
644        res <- res1
645      }
646      ## now strip out any generics (which have value NULL in res):
647      res.not.null <- sapply(res,function(x){!is.null(x)})
648      if ( 0 < length(res.not.null) && length(res.not.null) < length(res) ){
649        res <- res[res.not.null]
650      }
651      res
652    ### named list of lists, one for each object to document.
653    }
654    
655    ### List of parsers to use by default with package.skeleton.dx.
656    default.parsers <-
657      c(extra.code.docs=extra.code.docs, ## TODO: cleanup!
658        sapply(forfun.parsers,forfun),
659        edit.package.file=function(desc,...){
660          in.details <- setdiff(colnames(desc),"Description")
661          details <- sprintf("%s: \\tab %s\\cr",in.details,desc[,in.details])
662          L <-
663            list(list(title=desc[,"Title"],
664                      description=desc[,"Description"],
665                      `tabular{ll}`=details))
666          names(L) <- paste(desc[,"Package"],"-package",sep="")
667          L
668        },
669        sapply(forall.parsers,forall)
670        )
671    
672  setClass("DocLink", # Link documentation among related functions  setClass("DocLink", # Link documentation among related functions
673  ### The \code{.DocLink} class provides the basis for hooking together  ### The \code{.DocLink} class provides the basis for hooking together
674  ### documentation of related classes/functions/objects. The aim is that  ### documentation of related classes/functions/objects. The aim is that
# Line 660  Line 707 
707      ## "prefix" lines will be used instead.      ## "prefix" lines will be used instead.
708      default.description <- NULL      default.description <- NULL
709      while ( start > last.end+1      while ( start > last.end+1
710             && 1 == length(grep(prefix,code[start-1],perl=TRUE)) ){             && grepl(prefix,code[start-1],perl=TRUE) ){
711        start <- start-1        start <- start-1
712      }      }
713      if ( start < chunks[[k]][1] ){      if ( start < chunks[[k]][1] ){
# Line 687  Line 734 
734        ## If the function definition is not embedded within the call, then        ## If the function definition is not embedded within the call, then
735        ## the parent is that function. Test whether the the third value        ## the parent is that function. Test whether the the third value
736        ## looks like a name and add it to parents if so.        ## looks like a name and add it to parents if so.
737        if ( 1 == length(grep("^[\\._\\w]+$",chars[3],perl=TRUE)) ){        if ( grepl("^[\\._\\w]+$",chars[3],perl=TRUE) ){
738          parent <- chars[3]          parent <- chars[3]
739        }        }
740        res[[object.name]] <- new("DocLink",name=object.name,        res[[object.name]] <- new("DocLink",name=object.name,
# Line 719  Line 766 
766        ## If the function definition is not embedded within the call, then        ## If the function definition is not embedded within the call, then
767        ## the parent is that function. Test whether the the fourth value        ## the parent is that function. Test whether the the fourth value
768        ## looks like a name and add it to parents if so.        ## looks like a name and add it to parents if so.
769        if ( 1 == length(grep("^[\\._\\w]+$",chars[4],perl=TRUE)) ){        if ( grepl("^[\\._\\w]+$",chars[4],perl=TRUE) ){
770          parent <- c(chars[4],parent)          parent <- c(chars[4],parent)
771        }        }
772        res[[object.name]] <- new("DocLink",name=object.name,        res[[object.name]] <- new("DocLink",name=object.name,
# Line 760  Line 807 
807    ## the same line or \code{### } comments at the beginning of the    ## the same line or \code{### } comments at the beginning of the
808    ## following line.    ## following line.
809    f.n <- paste(class.name,"class",sep="-")    f.n <- paste(class.name,"class",sep="-")
810    docs <- extract.docs.fun(chunk.source,f.n)    docs <- extract.xxx.chunks(chunk.source,f.n)
811    ## also apply source parsing functions that I separated out into    ## also apply source parsing functions that I separated out into
812    ## separate functions    ## separate functions
813    docs <- combine(docs,lonely$prefixed.lines(chunk.source))    docs <- combine(docs,lonely$prefixed.lines(chunk.source))
# Line 805  Line 852 
852    old <- options(keep.source=TRUE)    old <- options(keep.source=TRUE)
853    on.exit(options(old))    on.exit(options(old))
854    exprs <- parse(text=code)    exprs <- parse(text=code)
855    for (i in exprs) eval(i, e)    for (i in exprs){
856        tryCatch(eval(i, e),error=function(e){
857          ##print(e)
858        })
859      }
860    objs <- sapply(ls(e),get,e,simplify=FALSE)    objs <- sapply(ls(e),get,e,simplify=FALSE)
861    
862    docs <- list()    docs <- list()
# Line 822  Line 873 
873              if (any(generic %in% utils:::getKnownS3generics()) ||              if (any(generic %in% utils:::getKnownS3generics()) ||
874                  utils:::findGeneric(generic, e) != "") {                  utils:::findGeneric(generic, e) != "") {
875                  object <- paste(parts[(i + 1):l], collapse = ".")                  object <- paste(parts[(i + 1):l], collapse = ".")
876                  docs[[name]]$s3method <- c(generic, object)                  docs[[name]]$.s3method <- c(generic, object)
877                  break                  break
878              }              }
879          }          }
# Line 841  Line 892 
892      L <- p(code=code,objs=objs,docs=docs,...)      L <- p(code=code,objs=objs,docs=docs,...)
893      docs <- combine(docs,L)      docs <- combine(docs,L)
894    }    }
895      ## post-process to collapse all character vectors
896      for(i in seq_along(docs)){
897        for(j in seq_along(docs[[i]])){
898          if(names(docs[[i]])[j]!=".s3method")
899          docs[[i]][[j]] <- paste(docs[[i]][[j]],collapse="\n")
900        }
901      }
902    if(verbose)cat("\n")    if(verbose)cat("\n")
903    docs    docs
904  ### A list of extracted documentation from code.  ### A list of extracted documentation from code.

Legend:
Removed from v.142  
changed lines
  Added in v.198

root@r-forge.r-project.org
ViewVC Help
Powered by ViewVC 1.0.0  
Thanks to:
Vienna University of Economics and Business University of Wisconsin - Madison Powered By FusionForge