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 87, Sat May 1 12:21:27 2010 UTC revision 370, Fri Nov 9 19:48:27 2012 UTC
# Line 1  Line 1 
1    do.not.generate <- structure(function
2    ### Make a Parser Function used to indicate that certain Rd files
3    ### should not be generated.
4    (...
5    ### Character strings indicating Rd files without the .Rd suffix.
6     ){
7      filenames <- c(...)
8      function(docs,...){
9        for(fn in filenames){
10          docs[[fn]] <- list()
11        }
12        docs$.overwrite <- TRUE
13        docs
14      }
15    ### A Parser Function that will delete items from the outer
16    ### Documentation List.
17    },ex=function(){
18      silly.pkg <- system.file("silly",package="inlinedocs")
19      owd <- setwd(tempdir())
20      file.copy(silly.pkg,".",recursive=TRUE)
21    
22      ## define a custom Parser Function that will not generate some Rd
23      ## files
24      custom <- do.not.generate("silly-package","Silly-class")
25      parsers <- c(default.parsers,list(exclude=custom))
26    
27      ## At first, no Rd files in the man subdirectory.
28      man.dir <- file.path("silly","man")
29      dir(man.dir)
30    
31      ## Running package.skeleton.dx will generate bare-bones files for
32      ## those specified in do.not.generate, if they do not exist.
33      package.skeleton.dx("silly",parsers)
34      Rd.files <- c("silly-package.Rd","Silly-class.Rd","silly.example.Rd")
35      Rd.paths <- file.path(man.dir,Rd.files)
36      stopifnot(all(file.exists(Rd.paths)))
37    
38      ## Save the modification times of the Rd files
39      old <- file.info(Rd.paths)$mtime
40    
41      ## make sure there is at least 2 seconds elapsed, which is the
42      ## resolution for recording times on windows file systems.
43      Sys.sleep(4)
44    
45      ## However, it will NOT generate Rd for files specified in
46      ## do.not.generate, if they DO exist already.
47      package.skeleton.dx("silly",parsers)
48      mtimes <- data.frame(old,new=file.info(Rd.paths)$mtime)
49      rownames(mtimes) <- Rd.files
50      mtimes$changed <- mtimes$old != mtimes$new
51      print(mtimes)
52      stopifnot(mtimes["silly-package.Rd","changed"]==FALSE)
53      stopifnot(mtimes["Silly-class.Rd","changed"]==FALSE)
54      stopifnot(mtimes["silly.example.Rd","changed"]==TRUE)
55    
56      unlink("silly",recursive=TRUE)
57      setwd(owd)
58    })
59    
60    ### combine lists or character strings
61    combine.NULL<-function(x,y){
62        if (class(x) == "NULL"){
63            # print(paste("mm x=",x))
64            # print(paste("mm class(x)=",class(x)))
65            x=list("")
66        }
67        if (class(y) == "NULL"){
68            # print(paste("mm y=",y))
69            # print(paste("mm class(y)=",class(y)))
70            y=list("")
71        }
72        return(combine(x,y))
73    }
74    combine <- function(x,y){
75        UseMethod("combine")
76    }
77    
78    ### combine character strings by pasting them together
79    combine.character <- function(x,y)
80        paste(x,y,sep="\n")
81    
82    ### combine lists by adding elements or adding to existing elements
83    combine.list <- function(x,y){
84      toadd <- if(".overwrite"%in%names(y)){
85        y <- y[names(y)!=".overwrite"]
86        rep(TRUE,length(y))
87      }else{
88        !names(y)%in%names(x)
89      }
90      toup <- names(y)[!toadd]
91      x[names(y)[toadd]] <- y[toadd]
92      for(up in toup)x[[up]] <- combine(x[[up]],y[[up]])
93      x
94    ### A list, same type as x, but with added elements from y.
95    }
96    
97    
98    getSource <- function
99    ### Extract a function's source code.
100    (fun.obj
101    ### A function.
102     ) {
103          srcref <- attr(fun.obj, "srcref")
104          if (!is.null(srcref)) {
105            ##unlist(strsplit(as.character(srcref), "\n"))
106            as.character(srcref)
107          }
108          else attr(fun.obj, "source")
109    ### Source code lines as a character vector.
110    }
111    
112    ### Prefix for code comments used with grep and gsub.
113    prefix <- "^[ \t]*###[ \t]*"
114    
115    decomment <- function
116    ### Remove comment prefix and join lines of code to form a
117    ### documentation string.
118    (comments
119    ### Character vector of prefixed comment lines.
120     ){
121      gsub(prefix,"",comments)
122    ### String without prefixes or newlines.
123    }
124    
125    forall <- function
126  ### For each object in the package that satisfies the criterion  ### For each object in the package that satisfies the criterion
127  ### checked by subfun, parse source using FUN and return the resulting  ### checked by subfun, parse source using FUN and return the resulting
128  ### documentation list.  ### documentation list.
 forall <- function  
129  (FUN,  (FUN,
130  ### Function to apply to each element in the package.  ### Function to apply to each element in the package.
131   subfun=function(x)TRUE   subfun=function(x)TRUE
# Line 9  Line 133 
133  ### is.function. subfun(x)==TRUE means FUN will be applied to x and  ### is.function. subfun(x)==TRUE means FUN will be applied to x and
134  ### the result will be returned.  ### the result will be returned.
135   ){   ){
136    function(objs,docs,...){    FUN <- FUN
137      f <- function(objs,docs,...){
138        if(length(objs)==0)return(list())
139      objs <- objs[sapply(objs,subfun)]      objs <- objs[sapply(objs,subfun)]
140      L <- list()      L <- list()
141      for(N in names(objs)){      on.exit(cat(sprintf("Parser Function failed on %s\n",N)))
142        for(N in union(names(docs),names(objs))){
143        o <- objs[[N]]        o <- objs[[N]]
144        L[[N]] <- FUN(src=attr(o,"source"),name=N,objs=objs,o=o,docs=docs,doc=docs[[N]],...)        L[[N]] <- FUN(src=getSource(o),
145                        name=N,objs=objs,o=o,docs=docs,doc=docs[[N]],...)
146      }      }
147        on.exit()## remove warning message
148      L      L
149    }    }
150      class(f) <- c("allfun","function")
151      f
152  ### A Parser Function.  ### A Parser Function.
153  }  }
154    
155    ### Print method for functions constructed using forall.
156    print.allfun <- function(x,...){
157      e <- environment(x)
158      cat("Function to apply to every element.\nselector:")
159      print(e$subfun)
160      cat("processor:")
161      print(e$FUN)
162    }
163    
164  ### For each function in the package, do something.  ### For each function in the package, do something.
165  forfun <- function(FUN)forall(FUN,is.function)  forfun <- function(FUN)forall(FUN,is.function)
166    
167  ### Get last line (test)  kill.prefix.whitespace <- function
168  parsefuns <- forfun(function(src,name,...){  ### Figure out what the whitespace preceding the example code is, and
169    extract.docs.fun(src,name)  ### then delete that from every line.
170  })  (ex
171    ### character vector of example code lines.
 ### Fill in author from DESCRIPTION and titles.  
 author.from.description <- forall(function(desc,...){  
   list(author=desc[,"Maintainer"])  
 })  
   
 ### The format section sometimes causes problems, so erase it.  
 erase.format <- forall(function(...){  
   list(format="")  
 })  
   
 ### Convert the function name to a title.  
 title.from.name <- forall(function(name,...){  
   list(title=gsub("[._]"," ",name))  
 })  
   
 ### Get examples for FUN from the file test/FUN.R  
 examples.from.testfile <- forfun(function(name,...){  
   tfile <- file.path("..","tests",paste(name,".R",sep=""))  
   if(file.exists(tfile))  
     list(examples=paste(readLines(tfile),collapse="\n"))  
   else list()  
 })  
   
 ### Get examples from inline definitions after return()  
 examples.after.return <- forfun(function(src,...){  
   rline <- grep("return([^)]*)",src)  
   if(length(rline)==0)return(list())  
   rline <- rline[length(rline)]  
   comment.line.nums <- grep(prefix,src)  
   if(!(comment.end <- rline+1)%in%comment.line.nums)return(list())  
   while(comment.end%in%comment.line.nums)comment.end <- comment.end+1  
   excode <- src[comment.end:(length(src)-1)]  
   list(examples=paste(gsub("^\\W*","",excode),collapse="\n"))  
 })  
   
 extract.docs.file <- function # Extract documentation from a file  
 ### 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().  
 (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 ){  
           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))  
172                ){                ){
173        ## phew - this should only pick up R.oo S3 generic definitions like:    tlines <- gsub("\\s*","",ex)
174        ## attr(*, "source")= chr "function(...) UseMethod(\"select\")"    ##tlines <- gsub("#.*","",tlines)
175        NULL    prefixes <- unique(gsub("\\S.*","",ex[tlines!=""]))
176      } else res    FIND <- prefixes[which.min(nchar(prefixes))]
177    }    ## Eliminate leading tabulations or 2/4 spaces
178    doc.names <- names(objs)    sub(FIND, "", ex)
179    res <- sapply(doc.names,extract.docs,simplify=FALSE)  ### Character vector of code lines with preceding whitespace removed.
180    ## Special processing for S4 classes as they do not appear in normal ls()  }
181    for ( nn in names(parsed) ){  
182      if ( parsed[[nn]]@created == "setClass" ){  prefixed.lines <- structure(function(src,...){
183        S4class.docs <- extract.docs.setClass(parsed[[nn]])  ### The primary mechanism of inline documentation is via consecutive
184        docname <- paste(nn,"class",sep="-")  ### groups of lines matching the specified prefix regular expression
185        if ( is.null(res[[docname]]) ){  ### "\code{^### }" (i.e. lines beginning with "\code{### }") are
186          res[[docname]] <- S4class.docs  ### collected as follows into documentation sections:\describe{
187          doc.names <- c(doc.names,docname)  ### \item{description}{group starting at line 2 in the code}
188        } else {  ### \item{arguments}{group following each function argument}
189          stop(nn," appears as both S4 class and some other definition")  ### \item{value}{group ending at the penultimate line of the code}}
190        }  ### These may be added to by use of the \code{##<<} constructs
191      }  ### described below.
192    }    clines <- grep(prefix,src)
193    inherit.docs <- function(on){    if(length(clines)==0)return(list())
     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.  
 }  
   
 ### Default parsers to use with package.skeleton.dx  
 default.parsers <- list("parsefuns","extract.docs.file",  
                         "examples.after.return","examples.from.testfile",  
                         "author.from.description","erase.format","title.from.name")  
   
 extract.docs.fun <- function # Extract documentation from a function  
 ### Given source code of a function, return a list describing inline  
 ### documentation in that source code.  
 (code,  
 ### The function to examine.  
  name.fun  
 ### The name of the function/chunk to use in warning messages.  
  )  
 {  
   res <- list()  
   clines <- grep(prefix,code)  
   if(length(grep("#",code[1]))){  
     res$title <- gsub("[^#]*#\\s*(.*)","\\1",code[1],perl=TRUE)  
   }  
   if(length(clines) > 0){  
     ##details<<  
     ## The primary mechanism is that consecutive groups of lines matching  
     ## the specified prefix regular expression "\code{^### }" (i.e. lines  
     ## beginning with "\code{### }") are collected  
     ## as follows into documentation sections:\describe{  
     ## \item{description}{group starting at line 2 in the code}  
     ## \item{arguments}{group following each function argument}  
     ## \item{value}{group ending at the penultimate line of the code}}  
     ## These may be added to by use of the \code{##<<} constructs described  
     ## below.  
194      bounds <- which(diff(clines)!=1)      bounds <- which(diff(clines)!=1)
195      starts <- c(1,bounds+1)      starts <- c(1,bounds+1)
196      ends <- c(bounds,length(clines))      ends <- c(bounds,length(clines))
197      ## detect body of function using paren matching
198      code <- gsub("#.*","",src)
199      f <- function(ch)cumsum(nchar(gsub(sprintf("[^%s]",ch),"",code)))
200      parens <- f("(")-f(")")
201      body.begin <- which(diff(parens)<0 & parens[-1]==0)+2
202      if(length(body.begin)==0)body.begin <- 1 ## rare cases
203      is.arg <- function(){
204        gres <- grep("^\\s*#",src[start-1],perl=TRUE)
205        0 == length(gres) && start<=body.begin
206      }
207      res <- list()
208      for(i in seq_along(starts)){      for(i in seq_along(starts)){
209        start <- clines[starts[i]]        start <- clines[starts[i]]
210        end <- clines[ends[i]]        end <- clines[ends[i]]
211        lab <- if(end+1==length(code))"value"      processed <- gsub("#.*","",gsub("[ }]","",src[(end+1):length(src)]))
212        lab <- if(all(processed==""))"value"
213        else if(start==2)"description"        else if(start==2)"description"
214        else if ( 0 == length(grep("^\\s*#",code[start-1],perl=TRUE)) ){      else if(is.arg()){
215           #arg <- gsub("^[ (]*","",code[start-1])        ##twutz: strip leading white spaces and brackets and ,
216           #arg <- gsub("^([^=,]*)[=,].*","\\1",arg)        arg <- gsub("^[ \t(,]*", "", src[start - 1])
          #arg <- gsub("...","\\dots",arg,fix=TRUE) ##special case for dots  
                  arg <- gsub("^[ \t(,]*", "", code[start - 1])  #twutz: strip leading white spaces and brackets and ,  
217                   arg <- gsub("^([^=,]*)[=,].*", "\\1", arg)                   arg <- gsub("^([^=,]*)[=,].*", "\\1", arg)
218                   arg <- gsub("^([^ \t]*)([ \t]+)$","\\1",arg)   #twutz: remove trailing whitespaces        ##twutz: remove trailing whitespaces
219                   arg <- gsub("...", "\\dots", arg, fix = TRUE)        arg <- gsub("^([^ \t]*)([ \t]+)$","\\1",arg)
220          arg <- gsub("...", "\\dots", arg, fixed = TRUE)
221           paste("item{",arg,"}",sep="")           paste("item{",arg,"}",sep="")
222         } else {         } else {
223           next;           next;
224         }         }
225        res[[lab]] <- decomment(code[start:end])      res[[lab]] <- decomment(src[start:end])
     }  
226    }    }
227      res
228    },ex=function(){
229    test <- function
230    ### the description
231    (x,
232    ### the first argument
233     y ##<< another argument
234     ){
235      5
236    ### the return value
237    ##seealso<< foobar
238    }
239    src <- getSource(test)
240    prefixed.lines(src)
241    extract.xxx.chunks(src)
242    })
243    
244    extract.xxx.chunks <- function # Extract documentation from a function
245    ### Given source code of a function, return a list describing inline
246    ### documentation in that source code.
247    (src,
248    ### The source lines of the function to examine, as a character
249    ### vector.
250     name.fun="(unnamed function)",
251    ### The name of the function/chunk to use in warning messages.
252     ...
253    ### ignored.
254     ){
255      res <- list()
256    ##details<< For simple functions/arguments, the argument may also be    ##details<< For simple functions/arguments, the argument may also be
257    ## documented by appending \code{##<<} comments on the same line as the    ## documented by appending \code{##<<} comments on the same line as the
258    ## argument name. Mixing this mechanism with \code{###} comment lines for    ## argument name. Mixing this mechanism with \code{###} comment lines for
# Line 300  Line 325 
325          chunk.sep <- "\n\n"          chunk.sep <- "\n\n"
326        }        }
327        chunk.res <- NULL        chunk.res <- NULL
328        if ( 0 == length(grep("^\\s*$",payload,perl=TRUE)) )        if ( !grepl("^\\s*$",payload,perl=TRUE) )
329          chunk.res <-          chunk.res <-
330            if ( is.null(res[[field]]) ) payload            if ( is.null(res[[field]]) ) payload
331            else paste(res[[field]], payload, sep=chunk.sep)            else paste(res[[field]], payload, sep=chunk.sep)
332        invisible(chunk.res)        invisible(chunk.res)
333      }      }
334    while ( k <= length(code) ){    while ( k <= length(src) ){
335      line <- code[k]      line <- src[k]
336      if ( 0 < length(grep(extra.regexp,line,perl=TRUE) ) ){      ##print(line)
337        ##if(grepl("^$",line))browser()
338        if ( grepl(extra.regexp,line,perl=TRUE) ){
339        ## 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
340        new.field <- gsub(extra.regexp,"\\1",line,perl=TRUE)        new.field <- gsub(extra.regexp,"\\1",line,perl=TRUE)
341        new.contents <- gsub(extra.regexp,"\\2",line,perl=TRUE)        new.contents <- gsub(extra.regexp,"\\2",line,perl=TRUE)
342          ##cat(new.field,"\n-----\n",new.contents,"\n\n")
343        ##details<< As a special case, the construct \code{##describe<<} causes        ##details<< As a special case, the construct \code{##describe<<} causes
344        ## similar processing to the main function arguments to be        ## similar processing to the main function arguments to be
345        ## applied in order to construct a describe block within the        ## applied in order to construct a describe block within the
# Line 321  Line 348 
348        ## block until terminated by a subsequent \code{##}\emph{xxx}\code{<<} line.        ## block until terminated by a subsequent \code{##}\emph{xxx}\code{<<} line.
349        if ( "describe" == new.field ){        if ( "describe" == new.field ){
350          ##details<< Such regions may be nested, but not in such a way          ##details<< Such regions may be nested, but not in such a way
351          ## that the first element in a \code{describe} is another \code{describe}.          ## that the first element in a \code{describe} is another
352          ## Thus there must be at least one \code{##<<} comment between each          ## \code{describe}.  Thus there must be at least one
353          ## pair of \code{##describe<<} comments.          ## \code{##<<} comment between each pair of
354            ## \code{##describe<<} comments.
355          if ( first.describe ){          if ( first.describe ){
356            stop("consecutive ##describe<< at line",k,"in",name.fun)            stop("consecutive ##describe<< at line",k,"in",name.fun)
357          } else {          } else {
# Line 383  Line 411 
411            first.describe <- TRUE;            first.describe <- TRUE;
412          }          }
413        }        }
414      } else if ( in.chunk && 0<length(grep(cont.re,line,perl=TRUE)) ){      } else if ( in.chunk && grepl(cont.re,line,perl=TRUE) ){
415        ## append this line to current chunk        ## append this line to current chunk
416        if ( 0 == length(grep(prefix,line,perl=TRUE)) ){        if ( !grepl(prefix,line,perl=TRUE) ){
417          ##describe<< Any lines with "\code{### }" at the left hand          ##describe<< Any lines with "\code{### }" at the left hand
418          ## margin within the included chunks are handled separately,          ## margin within the included chunks are handled separately,
419          ## so if they appear in the documentation they will appear          ## so if they appear in the documentation they will appear
# Line 398  Line 426 
426            payload <- stripped            payload <- stripped
427          }          }
428        }        }
429      } else if ( 0 < length(grep(arg.pat,line,perl=TRUE)) ){      } else if ( grepl(arg.pat,line,perl=TRUE) ){
430        not.describe <- (0==in.describe && !first.describe)        not.describe <- (0==in.describe && !first.describe)
431        if ( in.chunk && not.describe){        if ( in.chunk && not.describe){
432          res[[cur.field]] <- end.chunk(cur.field,payload)          res[[cur.field]] <- end.chunk(cur.field,payload)
# Line 407  Line 435 
435        arg <- gsub(arg.pat,"\\\\item\\{\\1\\}",line,perl=TRUE)        arg <- gsub(arg.pat,"\\\\item\\{\\1\\}",line,perl=TRUE)
436        in.chunk <- TRUE        in.chunk <- TRUE
437        if ( not.describe ){        if ( not.describe ){
438          cur.field <- gsub("...","\\dots",arg,fix=TRUE) ##special case for dots          ## TDH 2010-06-18 For item{}s in the documentation list names,
439            ## we don't need to have a backslash before, so delete it.
440            arg <- gsub("^[\\]+","",arg)
441            cur.field <- gsub("...","\\dots",arg,fixed=TRUE) ##special case for dots
442          payload <- comment          payload <- comment
443        } else {        } else {
444          ## this is a describe block, so we need to paste with existing          ## this is a describe block, so we need to paste with existing
# Line 457  Line 488 
488  ### with the string in this list (implemented in modify.Rd.file).  ### with the string in this list (implemented in modify.Rd.file).
489  }  }
490    
491    leadingS3generic <- function # check whether function name is an S3 generic
492    ### Determines whether a function name looks like an S3 generic function
493    (name,                     ##<< name of function
494     env,                      ##<< environment to search for additional generics
495     ...)                      ##<< ignored here
496    {
497      ##details<< This function is one of the default parsers, but exposed as
498      ## possibly of more general interest. Given a function name of the form
499      ## x.y.z it looks for the generic function x applying to objects of class
500      ## y.z and also for generic function x.y applying to objects of class z.
501      ##
502      parts <- strsplit(name, ".", fixed = TRUE)[[1]]
503      l <- length(parts)
504      if (l > 1) {
505        for (i in 1:(l - 1)) {
506          ## Look for a generic function (known by the system or defined
507          ## in the package) that matches that part of the function name
508          generic <- paste(parts[1:i], collapse = ".")
509          if (any(generic %in% utils:::getKnownS3generics()) ||
510              utils:::findGeneric(generic, env) != "") {
511            object <- paste(parts[(i + 1):l], collapse = ".")
512            ##details<< Assumes that the first name which matches any known
513            ## generics is the target generic function, so if both x and x.y
514            ## are generic functions, will assume generic x applying to objects
515            ## of class y.z
516            ##value<< If a matching generic found returns a list with a single component:
517            return(list(.s3method=c(generic, object))) ##<< a character vector containing generic name and object name.
518          }
519        }
520      }
521      ##value<< If no matching generic functions are found, returns an empty list.
522      list()
523    }
524    
525    ### Parsers for each function that are constructed automatically. This
526    ### is a named list, and each element is a parser function for an
527    ### individual object.
528    forfun.parsers <-
529      list(prefixed.lines=prefixed.lines,
530           extract.xxx.chunks=extract.xxx.chunks,
531           ## title from first line of function def
532           title.from.firstline=function(src,...){
533             first <- src[1]
534             if(!is.character(first))return(list())
535             if(!grepl("#",first))return(list())
536             list(title=gsub("[^#]*#\\s*(.*)","\\1",first,perl=TRUE))
537           },
538           ## PhG: it is tests/FUN.R!!! I would like more flexibility here
539           ## please, let me choose which dir to use for examples!
540           ## Get examples for FUN from the file tests/FUN.R
541           examples.from.testfile=function(name,...){
542             tsubdir <- getOption("inlinedocs.exdir")
543             if (is.null(tsubdir)) tsubdir <- "tests"       # Default value
544             tfile <- file.path("..",tsubdir,paste(name,".R",sep=""))
545             if(file.exists(tfile))
546               list(examples=readLines(tfile))
547             else list()
548           },
549           definition.from.source=function(doc,src,...){
550             def <- doc$definition
551             is.empty <- function(x)is.null(x)||x==""
552             if(is.empty(def) && !is.empty(src))
553               list(definition=src)
554             else list()
555           })
556    
557    ### List of Parser Functions that can be applied to any object.
558    forall.parsers <-
559      list(## Fill in author from DESCRIPTION and titles.
560           author.from.description=function(desc,...){
561             list(author=desc[,"Author"])
562           },
563           ## The format section sometimes causes problems, so erase it.
564           erase.format=function(...){
565             list(format="")
566           },
567           ## Convert the function name to a title.
568           title.from.name=function(name,doc,...){
569             if("title"%in%names(doc))list() else
570             list(title=gsub("[._]"," ",name))
571           },
572           ## PhG: here is what I propose for examples code in the 'ex' attribute
573           examples.in.attr =  function (name, o, ...) {
574             ex <- attr(o, "ex")
575             if (!is.null(ex)) {
576               ## Special case for code contained in a function
577               if (inherits(ex, "function")) {
578                 ## If source is available, start from there
579                 src <- getSource(ex)
580                 if (!is.null(src)) {
581                   ex <- src
582                 } else { ## Use the body of the function
583                   ex <- deparse(body(ex))
584                 }
585                 ## Eliminate leading and trailing code
586                 ex <- ex[-c(1, length(ex))]
587                 if(ex[1]=="{")ex <- ex[-1]
588                 ## all the prefixes
589                 ex <- kill.prefix.whitespace(ex)
590                 ## Add an empty line before and after example
591                 ex <- c("", ex, "")
592               }
593               list(examples = ex)
594             } else list()
595           },collapse=function(doc,...){
596             L <- lapply(doc,paste,collapse="\n")
597             L$.overwrite <- TRUE
598             L
599           },tag.s3methods=leadingS3generic
600           )
601    
602    ### List of parser functions that operate on single objects. This list
603    ### is useful for testing these functions.
604    lonely <- structure(c(forall.parsers,forfun.parsers),ex=function(){
605      f <- function # title
606    ### description
607      (x, ##<< arg x
608       y
609    ### arg y
610       ){
611        ##value<< a list with elements
612        list(x=x, ##<< original x value
613             y=y, ##<< original y value
614             sum=x+y) ##<< their sum
615        ##end<<
616      }
617      src <- getSource(f)
618      lonely$extract.xxx.chunks(src)
619      lonely$prefixed.lines(src)
620    })
621    
622    extra.code.docs <- function # Extract documentation from code chunks
623    ### Parse R code to extract inline documentation from comments around
624    ### each function. These are not able to be retreived simply by
625    ### looking at the "source" attribute. This is a Parser Function that
626    ### can be used in the parser list of package.skeleton.dx(). TODO:
627    ### Modularize this into separate Parsers Functions for S4 classes,
628    ### prefixes, ##<<blocks, etc. Right now it is not very clean!
629    (code,
630    ### Code lines in a character vector containing multiple R objects to
631    ### parse for documentation.
632     objs,
633    ### The objects defined in the code.
634     ...
635    ### ignored
636     ){
637      parsed <- extract.file.parse(code)
638      extract.docs.try <- function(o,on)
639        {
640          ## Note: we could use parsed information here too, but that
641          ## would produce different results for setMethodS3 etc.
642          doc <- list()
643          if ( !is.null(parsed[[on]]) ){
644            if ( !is.na(parsed[[on]]@code[1]) ){ # no code given for generics
645              doc$definition <- paste(parsed[[on]]@code)
646            }
647            if(!"description"%in%names(doc) && !is.na(parsed[[on]]@description) ){
648              doc$description <- parsed[[on]]@description
649            }
650            ## if ( "setMethodS3" == parsed[[on]]@created ){
651            ##   gen <- leadingS3generic(on,topenv())
652            ##   if ( 0 < length(gen) ){
653            ##     doc$.s3method <- gen$.s3method
654            ##     cat("S3method(",gen$.s3method[1],",",gen$.s3method[2],")\n",sep="")
655            ##   }
656            ## }
657          }
658          if("title" %in% names(doc) && !"description" %in% names(doc) ){
659            ## For short functions having both would duplicate, but a
660            ## description is required. Therefore automatically copy title
661            ## across to avoid errors at package build time.
662            doc$description <- doc$title
663          }
664          doc
665        }
666      extract.docs <- function(on){
667        res <- try({o <- objs[[on]]
668                    extract.docs.try(o, on)},FALSE)
669        if(class(res)=="try-error"){
670          cat("Failed to extract docs for: ",on,"\n\n")
671          list()
672        } else if(0 == length(res) && inherits(objs[[on]],"standardGeneric")){
673          NULL
674        } else if(0 == length(res) && "function" %in% class(o)
675                  && 1 == length(osource <- getSource(o))
676                  && grepl(paste("UseMethod(",on,")",sep="\""),osource)
677                  ){
678          ## phew - this should only pick up R.oo S3 generic definitions like:
679          ## attr(*, "source")= chr "function(...) UseMethod(\"select\")"
680          NULL
681        } else res
682      }
683      doc.names <- names(objs)
684      res <- sapply(doc.names,extract.docs,simplify=FALSE)
685      ## Special processing for S4 classes as they do not appear in normal ls()
686      for ( nn in names(parsed) ){
687        if ( parsed[[nn]]@created == "setClass" ){
688          S4class.docs <- extract.docs.setClass(parsed[[nn]])
689          docname <- paste(nn,"class",sep="-")
690          if ( is.null(res[[docname]]) ){
691            res[[docname]] <- S4class.docs
692            doc.names <- c(doc.names,docname)
693          } else {
694            stop(nn," appears as both S4 class and some other definition")
695          }
696        }
697      }
698      inherit.docs <- function(on){
699        in.res <- res[[on]]
700        if ( !is.null(parsed[[on]]) ){
701          for ( parent in parsed[[on]]@parent ){
702            if ( !is.na(parent) ){
703              if ( is.null(in.res) ){
704                in.res <- res[[parent]]
705              } else if ( parent %in% names(res) ){
706                parent.docs <- res[[parent]]
707                for ( nn in names(parent.docs) ){
708                  if ( !nn %in% names(in.res) ){
709                    in.res[[nn]] <- parent.docs[[nn]]
710                  }
711                }
712              }
713            }
714          }
715        }
716        invisible(in.res)
717      }
718      all.done <- FALSE
719      while ( !all.done ){
720        res1 <- sapply(doc.names,inherit.docs,simplify=FALSE)
721        all.done <- identical(res1,res)
722        res <- res1
723      }
724      ## now strip out any generics (which have value NULL in res):
725      res.not.null <- sapply(res,function(x){!is.null(x)})
726      if ( 0 < length(res.not.null) && length(res.not.null) < length(res) ){
727        res <- res[res.not.null]
728      }
729      res
730    ### named list of lists, one for each object to document.
731    }
732    
733    ### List of parsers to use by default with package.skeleton.dx.
734    default.parsers <-
735      c(extra.code.docs=extra.code.docs, ## TODO: cleanup!
736        sapply(forfun.parsers,forfun),
737        edit.package.file=function(desc,...){
738          in.details <- setdiff(colnames(desc),"Description")
739          details <- sprintf("%s: \\tab %s\\cr",in.details,desc[,in.details])
740          L <-
741            list(list(title=desc[,"Title"],
742                      description=desc[,"Description"],
743                      `tabular{ll}`=details))
744          names(L) <- paste(desc[,"Package"],"-package",sep="")
745          L
746        },
747        sapply(forall.parsers,forall)
748        )
749    
750  setClass("DocLink", # Link documentation among related functions  setClass("DocLink", # Link documentation among related functions
751  ### The \code{.DocLink} class provides the basis for hooking together  ### The \code{.DocLink} class provides the basis for hooking together
752  ### documentation of related classes/functions/objects. The aim is that  ### documentation of related classes/functions/objects. The aim is that
753  ### documentation sections missing from the child are  ### documentation sections missing from the child are inherited from
754    ### the parent class.
755           representation(name="character", ##<< name of object           representation(name="character", ##<< name of object
756                          created="character", ##<< how created                          created="character", ##<< how created
757                          parent="character", ##<< parent class or NA                          parent="character", ##<< parent class or NA
# Line 469  Line 760 
760           )           )
761    
762  extract.file.parse <- function # File content analysis  extract.file.parse <- function # File content analysis
763  ### Using the base \code{\link{parse}} function, analyse the file to link  ### Using the base \code{parse} function, analyse the file to link
764  ### preceding "prefix" comments to each active chunk. Those comments form  ### preceding "prefix" comments to each active chunk. Those comments form
765  ### the default description for that chunk. The analysis also looks for  ### the default description for that chunk. The analysis also looks for
766  ### S4 class "setClass" calls and R.oo setConstructorS3 and setMethodS3  ### S4 class "setClass" calls and R.oo setConstructorS3 and setMethodS3
# Line 495  Line 786 
786      ## "prefix" lines will be used instead.      ## "prefix" lines will be used instead.
787      default.description <- NULL      default.description <- NULL
788      while ( start > last.end+1      while ( start > last.end+1
789             && 1 == length(grep(prefix,code[start-1],perl=TRUE)) ){             && grepl(prefix,code[start-1],perl=TRUE) ){
790        start <- start-1        start <- start-1
791      }      }
792      if ( start < chunks[[k]][1] ){      if ( start < chunks[[k]][1] ){
# Line 522  Line 813 
813        ## If the function definition is not embedded within the call, then        ## If the function definition is not embedded within the call, then
814        ## the parent is that function. Test whether the the third value        ## the parent is that function. Test whether the the third value
815        ## looks like a name and add it to parents if so.        ## looks like a name and add it to parents if so.
816        if ( 1 == length(grep("^[\\._\\w]+$",chars[3],perl=TRUE)) ){        if ( grepl("^[\\._\\w]+$",chars[3],perl=TRUE) ){
817          parent <- chars[3]          parent <- chars[3]
818        }        }
819        res[[object.name]] <- new("DocLink",name=object.name,        res[[object.name]] <- new("DocLink",name=object.name,
# Line 541  Line 832 
832        generic.name <- chars[2]        generic.name <- chars[2]
833        object.name <- paste(generic.name,chars[3],sep=".")        object.name <- paste(generic.name,chars[3],sep=".")
834        if ( is.null(res[[generic.name]]) ){        if ( is.null(res[[generic.name]]) ){
835          generic.desc <- paste("Generic method behind \\code{\\link{",object.name,"}}",sep="")          ## TDH 9 April 2012 Do NOT add \\link in generic.desc below,
836            ## since it causes problems on R CMD check.
837            ##* checking Rd cross-references ... WARNING
838            ##Error in find.package(package, lib.loc) :
839            ##  there is no package called ‘MASS’
840            ##Calls: <Anonymous> -> lapply -> FUN -> find.package
841    
842            generic.desc <-
843              paste("Generic method behind \\code{",object.name,"}",sep="")
844          res[[generic.name]] <- new("DocLink",          res[[generic.name]] <- new("DocLink",
845                                     name=generic.name,                                     name=generic.name,
846                                     created=expr.type,                                     created=expr.type,
# Line 554  Line 853 
853        ## If the function definition is not embedded within the call, then        ## If the function definition is not embedded within the call, then
854        ## the parent is that function. Test whether the the fourth value        ## the parent is that function. Test whether the the fourth value
855        ## looks like a name and add it to parents if so.        ## looks like a name and add it to parents if so.
856        if ( 1 == length(grep("^[\\._\\w]+$",chars[4],perl=TRUE)) ){        if ( grepl("^[\\._\\w]+$",chars[4],perl=TRUE) ){
857          parent <- c(chars[4],parent)          parent <- c(chars[4],parent)
858        }        }
859        res[[object.name]] <- new("DocLink",name=object.name,        res[[object.name]] <- new("DocLink",name=object.name,
# Line 574  Line 873 
873  ### Using the same conventions as for functions, definitions of S4 classes  ### Using the same conventions as for functions, definitions of S4 classes
874  ### in the form \code{setClass("classname",\dots)} are also located and  ### in the form \code{setClass("classname",\dots)} are also located and
875  ### scanned for inline comments.  ### scanned for inline comments.
876  (doc.link)  (doc.link
877  ### DocLink object as created by \code{\link{extract.file.parse}}.  ### DocLink object as created by \code{extract.file.parse}.
878  ### Note that \code{source} statements are \emph{ignored} when scanning for  ### Note that \code{source} statements are \emph{ignored} when scanning for
879  ### class definitions.  ### class definitions.
880  {   ){
881    chunk.source <- doc.link@code    chunk.source <- doc.link@code
882    ##details<<    ##details<<
883    ## Extraction of S4 class documentation is currently limited to expressions    ## Extraction of S4 class documentation is currently limited to expressions
# Line 595  Line 894 
894    ## the same line or \code{### } comments at the beginning of the    ## the same line or \code{### } comments at the beginning of the
895    ## following line.    ## following line.
896    f.n <- paste(class.name,"class",sep="-")    f.n <- paste(class.name,"class",sep="-")
897    docs <- extract.docs.fun(chunk.source,f.n)    docs <- extract.xxx.chunks(chunk.source,f.n)
898      ## also apply source parsing functions that I separated out into
899      ## separate functions
900      docs <- combine(docs,lonely$prefixed.lines(chunk.source))
901      docs$title <- lonely$title.from.firstline(chunk.source)
902      ##details<<
903      ## If there is no explicit title on the first line of setClass, then
904      ## one is made up from the class name.
905      if ( 0 == length(docs$title) ){
906        docs$title <- list(title=paste(class.name,"S4 class"))
907      }
908    ##details<<    ##details<<
909    ## The class definition skeleton includes an \code{Objects from the Class}    ## The class definition skeleton includes an \code{Objects from the Class}
910    ## section, to which any \code{##details<<} documentation chunks are    ## section, to which any \code{##details<<} documentation chunks are
# Line 619  Line 928 
928    }    }
929    invisible(docs)    invisible(docs)
930  }  }
931    
932    apply.parsers <- function
933    ### Parse code to r objs, then run all the parsers and return the
934    ### documentation list.
935    (code,
936    ### Character vector of code lines.
937     parsers=default.parsers,
938    ### List of Parser Functions.
939     verbose=FALSE,
940    ### Echo names of Parser Functions?
941     ...
942    ### Additional arguments to pass to Parser Functions.
943     ){
944      e <- new.env()
945      ## KMP 2011-03-09 fix problem with DocLink when inlinedocs ran on itself
946      ## Error in assignClassDef(Class, classDef, where) :
947      ##   Class "DocLink" has a locked definition in package "inlinedocs"
948      ## Traced to "where" argument in setClassDef which defaults to topenv()
949      ## which in turn is inlinedocs when processing inlinedocs package, hence
950      ## the clash. The following works (under R 2.12.2), so that the topenv()
951      ## now finds e before finding the inlinedocs environment.
952      old <- options(keep.source=TRUE,topLevelEnvironment=e)
953      on.exit(options(old))
954      exprs <- parse(text=code)
955      ## TDH 2011-04-07 set this so that no warnings about creating a fake
956      ## package when we try to process S4 classes defined in code
957      e$.packageName <- "inlinedocs.processor"
958      for (i in exprs){
959          eval(i, e)
960      }
961      objs <- sapply(ls(e),get,e,simplify=FALSE)
962    
963      docs <- list()
964    
965      ## apply parsers in sequence to code and objs
966      if(verbose)cat("Applying parsers:\n")
967      for(i in seq_along(parsers)){
968        N <- names(parsers[i])
969        #mm if(verbose){
970          if(is.character(N) && N!=""){
971            cat(" this is parser:",N,"\n",sep="")
972          }else cat('.\n')
973        #mm }
974        p <- parsers[[i]]
975        ## This is the argument list that each parser receives:
976        L <- p(code=code,objs=objs,docs=docs,env=e,...)
977        # print("mm point1")
978        #save(docs,L,file="/home/mm/SoilR/scripts/docs_L.RData")
979        #print(paste(L,"\n"))
980        #if(N=="exclude")browser()
981        docs <- combine(docs,L) #mm
982      }
983      ## post-process to collapse all character vectors
984      for(i in seq_along(docs)){
985        for(j in seq_along(docs[[i]])){
986          if(names(docs[[i]])[j]!=".s3method")
987          docs[[i]][[j]] <- paste(docs[[i]][[j]],collapse="\n")
988        }
989     }
990      if(verbose)cat("\n")
991      return(docs)
992    ### A list of extracted documentation from code.
993    }
994    
995    ### Names of Parser Functions that operate on the desc arg.
996    descfile.names <- c("author.from.description","edit.package.file")
997    
998    ### Names of Parser Functions that do NOT use the desc arg.
999    non.descfile.names <-
1000      names(default.parsers)[!names(default.parsers)%in%descfile.names]
1001    
1002    ### Parsers that operate only on R code, independently of the
1003    ### description file.
1004    nondesc.parsers <- default.parsers[non.descfile.names]
1005    
1006    extract.docs.file <- structure(function
1007    ### Apply all parsers relevant to extract info from just 1 code file.
1008    (f,
1009    ### File name of R code to read and parse.
1010     parsers=NULL,
1011    ### Parser Functions to use to parse the code and extract
1012    ### documentation.
1013     ...
1014    ### Other arguments to pass to Parser Functions.
1015     ){
1016      if(is.null(parsers))parsers <- nondesc.parsers
1017      apply.parsers(readLines(f),parsers,verbose=FALSE,...)
1018    },ex=function(){
1019      f <- system.file("silly","R","silly.R",package="inlinedocs")
1020      extract.docs.file(f)
1021    })
1022    

Legend:
Removed from v.87  
changed lines
  Added in v.370

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