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 103, Tue May 18 16:33:29 2010 UTC revision 356, Mon Apr 9 15:39:09 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 <- function(x,y)UseMethod("combine")
62    
63    ### combine character strings by pasting them together
64    combine.character <- function(x,y)
65        paste(x,y,sep="\n")
66    
67    ### combine lists by adding elements or adding to existing elements
68    combine.list <- function(x,y){
69      toadd <- if(".overwrite"%in%names(y)){
70        y <- y[names(y)!=".overwrite"]
71        rep(TRUE,length(y))
72      }else{
73        !names(y)%in%names(x)
74      }
75      toup <- names(y)[!toadd]
76      x[names(y)[toadd]] <- y[toadd]
77      for(up in toup)x[[up]] <- combine(x[[up]],y[[up]])
78      x
79    ### A list, same type as x, but with added elements from y.
80    }
81    
82    
83    getSource <- function
84    ### Extract a function's source code.
85    (fun.obj
86    ### A function.
87     ) {
88          srcref <- attr(fun.obj, "srcref")
89          if (!is.null(srcref)) {
90            ##unlist(strsplit(as.character(srcref), "\n"))
91            as.character(srcref)
92          }
93          else attr(fun.obj, "source")
94    ### Source code lines as a character vector.
95    }
96    
97    ### Prefix for code comments used with grep and gsub.
98    prefix <- "^[ \t]*###[ \t]*"
99    
100    decomment <- function
101    ### Remove comment prefix and join lines of code to form a
102    ### documentation string.
103    (comments
104    ### Character vector of prefixed comment lines.
105     ){
106      gsub(prefix,"",comments)
107    ### String without prefixes or newlines.
108    }
109    
110    forall <- function
111  ### For each object in the package that satisfies the criterion  ### For each object in the package that satisfies the criterion
112  ### checked by subfun, parse source using FUN and return the resulting  ### checked by subfun, parse source using FUN and return the resulting
113  ### documentation list.  ### documentation list.
 forall <- function  
114  (FUN,  (FUN,
115  ### Function to apply to each element in the package.  ### Function to apply to each element in the package.
116   subfun=function(x)TRUE   subfun=function(x)TRUE
# Line 9  Line 118 
118  ### 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
119  ### the result will be returned.  ### the result will be returned.
120   ){   ){
121    function(objs,docs,...){    FUN <- FUN
122      f <- function(objs,docs,...){
123        if(length(objs)==0)return(list())
124      objs <- objs[sapply(objs,subfun)]      objs <- objs[sapply(objs,subfun)]
125      L <- list()      L <- list()
126      for(N in names(docs)){      on.exit(cat(sprintf("Parser Function failed on %s\n",N)))
127        for(N in union(names(docs),names(objs))){
128        o <- objs[[N]]        o <- objs[[N]]
129        L[[N]] <- FUN(src=attr(o,"source"),        L[[N]] <- FUN(src=getSource(o),
130                      name=N,objs=objs,o=o,docs=docs,doc=docs[[N]],...)                      name=N,objs=objs,o=o,docs=docs,doc=docs[[N]],...)
131      }      }
132        on.exit()## remove warning message
133      L      L
134    }    }
135      class(f) <- c("allfun","function")
136      f
137  ### A Parser Function.  ### A Parser Function.
138  }  }
139    
140  ### For each function in the package, do something.  ### Print method for functions constructed using forall.
141  forfun <- function(FUN)forall(FUN,is.function)  print.allfun <- function(x,...){
142      e <- environment(x)
143  ### Parsers for each object/function that are constructed    cat("Function to apply to every element.\nselector:")
144  ### automatically. This is a named list, each element is a list of 2    print(e$subfun)
145  ### elements: forfun/forall, then a parser function for an individual    cat("processor:")
146  ### object.    print(e$FUN)
 forall.parsers <-  
   list(## Extract lots of info from normal functions.  
        parsefun=list(forfun,function(src,name,...){  
          extract.docs.fun(src,name)  
        }),  
        ## Fill in author from DESCRIPTION and titles.  
        author.from.description=list(forall,function(desc,...){  
          list(author=desc[,"Maintainer"])  
        }),  
        ## The format section sometimes causes problems, so erase it.  
        erase.format=list(forall,function(...){  
          list(format="")  
        }),  
        ## Convert the function name to a title.  
        title.from.name=list(forall,function(name,doc,...){  
          if("title"%in%names(doc))list() else  
          list(title=gsub("[._]"," ",name))  
        }),  
        ## Get examples for FUN from the file test/FUN.R  
        examples.from.testfile=list(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=list(forfun,function(name,src,...){  
          coll <- paste(src,collapse="\n")  
          thispre <- gsub("^[\\^]","",prefix)  
          FIND <- paste("(return|UseMethod)[(][^\\n]*\\n",thispre,sep="")  
          m <- regexpr(FIND,coll)  
          if(m[1]==-1)return(list())  
          after <- substr(coll,m[1],nchar(coll))  
          FIND <-  
            paste("[^\\n]*",# rest of the return line  
                  "((?:\\n###[^\\n]*)+)",#comment value lines \\1  
                  "([\\w\\W]*)[}]",#examples \\2  
                  sep="")  
          SEP <- "----------"  
          REP <- paste("\\1",SEP,"\\2",sep="")  
          r <- strsplit(gsub(FIND,REP,after,perl=TRUE),split=SEP)[[1]]  
          l <- strsplit(r,split="\n")  
          excode <- c(l[[2]],"")  
          if(length(l)<2||paste(excode,collapse="")=="")return(list())  
          prefixes <- gsub("(\\s*).*","\\1",excode,perl=TRUE)[grep("\\w",excode)]  
          FIND <- prefixes[which.min(nchar(prefixes))]  
          list(examples=paste(sub(FIND,"",excode),collapse="\n"),  
               value=decomment(l[[1]][-1]))  
        }))  
   
 ### List of parser functions that operate on single objects. This list  
 ### is useful for testing these functions, ie  
 ### lonely$parsefun(attr(extract.docs.file,"source"),"extract.docs.file")  
 lonely <- sapply(forall.parsers,function(L)L[[2]])  
   
 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))  
               ){  
       ## phew - this should only pick up R.oo S3 generic definitions like:  
       ## attr(*, "source")= chr "function(...) UseMethod(\"select\")"  
       NULL  
     } else res  
   }  
   doc.names <- names(objs)  
   res <- sapply(doc.names,extract.docs,simplify=FALSE)  
   ## 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.  
147  }  }
148    
149  ### List of parsers to use by default with package.skeleton.dx.  ### For each function in the package, do something.
150  default.parsers <- c(extract.docs.file=extract.docs.file,  forfun <- function(FUN)forall(FUN,is.function)
                      sapply(forall.parsers,function(L)L[[1]](L[[2]])))  
151    
152  extract.docs.fun <- function # Extract documentation from a function  kill.prefix.whitespace <- function
153  ### Given source code of a function, return a list describing inline  ### Figure out what the whitespace preceding the example code is, and
154  ### documentation in that source code.  ### then delete that from every line.
155  (code,  (ex
156  ### The function to examine.  ### character vector of example code lines.
  name.fun  
 ### The name of the function/chunk to use in warning messages.  
157   ){   ){
158    res <- list()    tlines <- gsub("\\s*","",ex)
159    clines <- grep(prefix,code)    ##tlines <- gsub("#.*","",tlines)
160    if(length(grep("#",code[1]))){    prefixes <- unique(gsub("\\S.*","",ex[tlines!=""]))
161      res$title <- gsub("[^#]*#\\s*(.*)","\\1",code[1],perl=TRUE)    FIND <- prefixes[which.min(nchar(prefixes))]
162    }    ## Eliminate leading tabulations or 2/4 spaces
163    if(length(clines) > 0){    sub(FIND, "", ex)
164      ##details<<  ### Character vector of code lines with preceding whitespace removed.
165      ## The primary mechanism is that consecutive groups of lines matching  }
166      ## the specified prefix regular expression "\code{^### }" (i.e. lines  
167      ## beginning with "\code{### }") are collected  prefixed.lines <- structure(function(src,...){
168      ## as follows into documentation sections:\describe{  ### The primary mechanism of inline documentation is via consecutive
169      ## \item{description}{group starting at line 2 in the code}  ### groups of lines matching the specified prefix regular expression
170      ## \item{arguments}{group following each function argument}  ### "\code{^### }" (i.e. lines beginning with "\code{### }") are
171      ## \item{value}{group ending at the penultimate line of the code}}  ### collected as follows into documentation sections:\describe{
172      ## These may be added to by use of the \code{##<<} constructs described  ### \item{description}{group starting at line 2 in the code}
173      ## below.  ### \item{arguments}{group following each function argument}
174    ### \item{value}{group ending at the penultimate line of the code}}
175    ### These may be added to by use of the \code{##<<} constructs
176    ### described below.
177      clines <- grep(prefix,src)
178      if(length(clines)==0)return(list())
179      bounds <- which(diff(clines)!=1)      bounds <- which(diff(clines)!=1)
180      starts <- c(1,bounds+1)      starts <- c(1,bounds+1)
181      ends <- c(bounds,length(clines))      ends <- c(bounds,length(clines))
182      ## detect body of function using paren matching
183      code <- gsub("#.*","",src)
184      f <- function(ch)cumsum(nchar(gsub(sprintf("[^%s]",ch),"",code)))
185      parens <- f("(")-f(")")
186      body.begin <- which(diff(parens)<0 & parens[-1]==0)+2
187      if(length(body.begin)==0)body.begin <- 1 ## rare cases
188      is.arg <- function(){
189        gres <- grep("^\\s*#",src[start-1],perl=TRUE)
190        0 == length(gres) && start<=body.begin
191      }
192      res <- list()
193      for(i in seq_along(starts)){      for(i in seq_along(starts)){
194        start <- clines[starts[i]]        start <- clines[starts[i]]
195        end <- clines[ends[i]]        end <- clines[ends[i]]
196        lab <- if(end+1==length(code))"value"      processed <- gsub("#.*","",gsub("[ }]","",src[(end+1):length(src)]))
197        lab <- if(all(processed==""))"value"
198        else if(start==2)"description"        else if(start==2)"description"
199        else if ( 0 == length(grep("^\\s*#",code[start-1],perl=TRUE)) ){      else if(is.arg()){
200           #arg <- gsub("^[ (]*","",code[start-1])        ##twutz: strip leading white spaces and brackets and ,
201           #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 ,  
202                   arg <- gsub("^([^=,]*)[=,].*", "\\1", arg)                   arg <- gsub("^([^=,]*)[=,].*", "\\1", arg)
203                   arg <- gsub("^([^ \t]*)([ \t]+)$","\\1",arg)   #twutz: remove trailing whitespaces        ##twutz: remove trailing whitespaces
204                   arg <- gsub("...", "\\dots", arg, fix = TRUE)        arg <- gsub("^([^ \t]*)([ \t]+)$","\\1",arg)
205          arg <- gsub("...", "\\dots", arg, fixed = TRUE)
206           paste("item{",arg,"}",sep="")           paste("item{",arg,"}",sep="")
207         } else {         } else {
208           next;           next;
209         }         }
210        res[[lab]] <- decomment(code[start:end])      res[[lab]] <- decomment(src[start:end])
     }  
211    }    }
212      res
213    },ex=function(){
214    test <- function
215    ### the description
216    (x,
217    ### the first argument
218     y ##<< another argument
219     ){
220      5
221    ### the return value
222    ##seealso<< foobar
223    }
224    src <- getSource(test)
225    prefixed.lines(src)
226    extract.xxx.chunks(src)
227    })
228    
229    extract.xxx.chunks <- function # Extract documentation from a function
230    ### Given source code of a function, return a list describing inline
231    ### documentation in that source code.
232    (src,
233    ### The source lines of the function to examine, as a character
234    ### vector.
235     name.fun="(unnamed function)",
236    ### The name of the function/chunk to use in warning messages.
237     ...
238    ### ignored.
239     ){
240      res <- list()
241    ##details<< For simple functions/arguments, the argument may also be    ##details<< For simple functions/arguments, the argument may also be
242    ## documented by appending \code{##<<} comments on the same line as the    ## documented by appending \code{##<<} comments on the same line as the
243    ## argument name. Mixing this mechanism with \code{###} comment lines for    ## argument name. Mixing this mechanism with \code{###} comment lines for
# Line 318  Line 310 
310          chunk.sep <- "\n\n"          chunk.sep <- "\n\n"
311        }        }
312        chunk.res <- NULL        chunk.res <- NULL
313        if ( 0 == length(grep("^\\s*$",payload,perl=TRUE)) )        if ( !grepl("^\\s*$",payload,perl=TRUE) )
314          chunk.res <-          chunk.res <-
315            if ( is.null(res[[field]]) ) payload            if ( is.null(res[[field]]) ) payload
316            else paste(res[[field]], payload, sep=chunk.sep)            else paste(res[[field]], payload, sep=chunk.sep)
317        invisible(chunk.res)        invisible(chunk.res)
318      }      }
319    while ( k <= length(code) ){    while ( k <= length(src) ){
320      line <- code[k]      line <- src[k]
321      if ( 0 < length(grep(extra.regexp,line,perl=TRUE) ) ){      ##print(line)
322        ##if(grepl("^$",line))browser()
323        if ( grepl(extra.regexp,line,perl=TRUE) ){
324        ## 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
325        new.field <- gsub(extra.regexp,"\\1",line,perl=TRUE)        new.field <- gsub(extra.regexp,"\\1",line,perl=TRUE)
326        new.contents <- gsub(extra.regexp,"\\2",line,perl=TRUE)        new.contents <- gsub(extra.regexp,"\\2",line,perl=TRUE)
327          ##cat(new.field,"\n-----\n",new.contents,"\n\n")
328        ##details<< As a special case, the construct \code{##describe<<} causes        ##details<< As a special case, the construct \code{##describe<<} causes
329        ## similar processing to the main function arguments to be        ## similar processing to the main function arguments to be
330        ## applied in order to construct a describe block within the        ## applied in order to construct a describe block within the
# Line 339  Line 333 
333        ## block until terminated by a subsequent \code{##}\emph{xxx}\code{<<} line.        ## block until terminated by a subsequent \code{##}\emph{xxx}\code{<<} line.
334        if ( "describe" == new.field ){        if ( "describe" == new.field ){
335          ##details<< Such regions may be nested, but not in such a way          ##details<< Such regions may be nested, but not in such a way
336          ## that the first element in a \code{describe} is another \code{describe}.          ## that the first element in a \code{describe} is another
337          ## Thus there must be at least one \code{##<<} comment between each          ## \code{describe}.  Thus there must be at least one
338          ## pair of \code{##describe<<} comments.          ## \code{##<<} comment between each pair of
339            ## \code{##describe<<} comments.
340          if ( first.describe ){          if ( first.describe ){
341            stop("consecutive ##describe<< at line",k,"in",name.fun)            stop("consecutive ##describe<< at line",k,"in",name.fun)
342          } else {          } else {
# Line 401  Line 396 
396            first.describe <- TRUE;            first.describe <- TRUE;
397          }          }
398        }        }
399      } else if ( in.chunk && 0<length(grep(cont.re,line,perl=TRUE)) ){      } else if ( in.chunk && grepl(cont.re,line,perl=TRUE) ){
400        ## append this line to current chunk        ## append this line to current chunk
401        if ( 0 == length(grep(prefix,line,perl=TRUE)) ){        if ( !grepl(prefix,line,perl=TRUE) ){
402          ##describe<< Any lines with "\code{### }" at the left hand          ##describe<< Any lines with "\code{### }" at the left hand
403          ## margin within the included chunks are handled separately,          ## margin within the included chunks are handled separately,
404          ## so if they appear in the documentation they will appear          ## so if they appear in the documentation they will appear
# Line 416  Line 411 
411            payload <- stripped            payload <- stripped
412          }          }
413        }        }
414      } else if ( 0 < length(grep(arg.pat,line,perl=TRUE)) ){      } else if ( grepl(arg.pat,line,perl=TRUE) ){
415        not.describe <- (0==in.describe && !first.describe)        not.describe <- (0==in.describe && !first.describe)
416        if ( in.chunk && not.describe){        if ( in.chunk && not.describe){
417          res[[cur.field]] <- end.chunk(cur.field,payload)          res[[cur.field]] <- end.chunk(cur.field,payload)
# Line 425  Line 420 
420        arg <- gsub(arg.pat,"\\\\item\\{\\1\\}",line,perl=TRUE)        arg <- gsub(arg.pat,"\\\\item\\{\\1\\}",line,perl=TRUE)
421        in.chunk <- TRUE        in.chunk <- TRUE
422        if ( not.describe ){        if ( not.describe ){
423          cur.field <- gsub("...","\\dots",arg,fix=TRUE) ##special case for dots          ## TDH 2010-06-18 For item{}s in the documentation list names,
424            ## we don't need to have a backslash before, so delete it.
425            arg <- gsub("^[\\]+","",arg)
426            cur.field <- gsub("...","\\dots",arg,fixed=TRUE) ##special case for dots
427          payload <- comment          payload <- comment
428        } else {        } else {
429          ## 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 475  Line 473 
473  ### with the string in this list (implemented in modify.Rd.file).  ### with the string in this list (implemented in modify.Rd.file).
474  }  }
475    
476    leadingS3generic <- function # check whether function name is an S3 generic
477    ### Determines whether a function name looks like an S3 generic function
478    (name,                     ##<< name of function
479     env,                      ##<< environment to search for additional generics
480     ...)                      ##<< ignored here
481    {
482      ##details<< This function is one of the default parsers, but exposed as
483      ## possibly of more general interest. Given a function name of the form
484      ## x.y.z it looks for the generic function x applying to objects of class
485      ## y.z and also for generic function x.y applying to objects of class z.
486      ##
487      parts <- strsplit(name, ".", fixed = TRUE)[[1]]
488      l <- length(parts)
489      if (l > 1) {
490        for (i in 1:(l - 1)) {
491          ## Look for a generic function (known by the system or defined
492          ## in the package) that matches that part of the function name
493          generic <- paste(parts[1:i], collapse = ".")
494          if (any(generic %in% utils:::getKnownS3generics()) ||
495              utils:::findGeneric(generic, env) != "") {
496            object <- paste(parts[(i + 1):l], collapse = ".")
497            ##details<< Assumes that the first name which matches any known
498            ## generics is the target generic function, so if both x and x.y
499            ## are generic functions, will assume generic x applying to objects
500            ## of class y.z
501            ##value<< If a matching generic found returns a list with a single component:
502            return(list(.s3method=c(generic, object))) ##<< a character vector containing generic name and object name.
503          }
504        }
505      }
506      ##value<< If no matching generic functions are found, returns an empty list.
507      list()
508    }
509    
510    ### Parsers for each function that are constructed automatically. This
511    ### is a named list, and each element is a parser function for an
512    ### individual object.
513    forfun.parsers <-
514      list(prefixed.lines=prefixed.lines,
515           extract.xxx.chunks=extract.xxx.chunks,
516           ## title from first line of function def
517           title.from.firstline=function(src,...){
518             first <- src[1]
519             if(!is.character(first))return(list())
520             if(!grepl("#",first))return(list())
521             list(title=gsub("[^#]*#\\s*(.*)","\\1",first,perl=TRUE))
522           },
523           ## PhG: it is tests/FUN.R!!! I would like more flexibility here
524           ## please, let me choose which dir to use for examples!
525           ## Get examples for FUN from the file tests/FUN.R
526           examples.from.testfile=function(name,...){
527             tsubdir <- getOption("inlinedocs.exdir")
528             if (is.null(tsubdir)) tsubdir <- "tests"       # Default value
529             tfile <- file.path("..",tsubdir,paste(name,".R",sep=""))
530             if(file.exists(tfile))
531               list(examples=readLines(tfile))
532             else list()
533           },
534           definition.from.source=function(doc,src,...){
535             def <- doc$definition
536             is.empty <- function(x)is.null(x)||x==""
537             if(is.empty(def) && !is.empty(src))
538               list(definition=src)
539             else list()
540           })
541    
542    ### List of Parser Functions that can be applied to any object.
543    forall.parsers <-
544      list(## Fill in author from DESCRIPTION and titles.
545           author.from.description=function(desc,...){
546             list(author=desc[,"Author"])
547           },
548           ## The format section sometimes causes problems, so erase it.
549           erase.format=function(...){
550             list(format="")
551           },
552           ## Convert the function name to a title.
553           title.from.name=function(name,doc,...){
554             if("title"%in%names(doc))list() else
555             list(title=gsub("[._]"," ",name))
556           },
557           ## PhG: here is what I propose for examples code in the 'ex' attribute
558           examples.in.attr =  function (name, o, ...) {
559             ex <- attr(o, "ex")
560             if (!is.null(ex)) {
561               ## Special case for code contained in a function
562               if (inherits(ex, "function")) {
563                 ## If source is available, start from there
564                 src <- getSource(ex)
565                 if (!is.null(src)) {
566                   ex <- src
567                 } else { ## Use the body of the function
568                   ex <- deparse(body(ex))
569                 }
570                 ## Eliminate leading and trailing code
571                 ex <- ex[-c(1, length(ex))]
572                 if(ex[1]=="{")ex <- ex[-1]
573                 ## all the prefixes
574                 ex <- kill.prefix.whitespace(ex)
575                 ## Add an empty line before and after example
576                 ex <- c("", ex, "")
577               }
578               list(examples = ex)
579             } else list()
580           },collapse=function(doc,...){
581             L <- lapply(doc,paste,collapse="\n")
582             L$.overwrite <- TRUE
583             L
584           },tag.s3methods=leadingS3generic
585           )
586    
587    ### List of parser functions that operate on single objects. This list
588    ### is useful for testing these functions.
589    lonely <- structure(c(forall.parsers,forfun.parsers),ex=function(){
590      f <- function # title
591    ### description
592      (x, ##<< arg x
593       y
594    ### arg y
595       ){
596        ##value<< a list with elements
597        list(x=x, ##<< original x value
598             y=y, ##<< original y value
599             sum=x+y) ##<< their sum
600        ##end<<
601      }
602      src <- getSource(f)
603      lonely$extract.xxx.chunks(src)
604      lonely$prefixed.lines(src)
605    })
606    
607    extra.code.docs <- function # Extract documentation from code chunks
608    ### Parse R code to extract inline documentation from comments around
609    ### each function. These are not able to be retreived simply by
610    ### looking at the "source" attribute. This is a Parser Function that
611    ### can be used in the parser list of package.skeleton.dx(). TODO:
612    ### Modularize this into separate Parsers Functions for S4 classes,
613    ### prefixes, ##<<blocks, etc. Right now it is not very clean!
614    (code,
615    ### Code lines in a character vector containing multiple R objects to
616    ### parse for documentation.
617     objs,
618    ### The objects defined in the code.
619     ...
620    ### ignored
621     ){
622      parsed <- extract.file.parse(code)
623      extract.docs.try <- function(o,on)
624        {
625          ## Note: we could use parsed information here too, but that
626          ## would produce different results for setMethodS3 etc.
627          doc <- list()
628          if ( !is.null(parsed[[on]]) ){
629            if ( !is.na(parsed[[on]]@code[1]) ){ # no code given for generics
630              doc$definition <- paste(parsed[[on]]@code)
631            }
632            if(!"description"%in%names(doc) && !is.na(parsed[[on]]@description) ){
633              doc$description <- parsed[[on]]@description
634            }
635            ## if ( "setMethodS3" == parsed[[on]]@created ){
636            ##   gen <- leadingS3generic(on,topenv())
637            ##   if ( 0 < length(gen) ){
638            ##     doc$.s3method <- gen$.s3method
639            ##     cat("S3method(",gen$.s3method[1],",",gen$.s3method[2],")\n",sep="")
640            ##   }
641            ## }
642          }
643          if("title" %in% names(doc) && !"description" %in% names(doc) ){
644            ## For short functions having both would duplicate, but a
645            ## description is required. Therefore automatically copy title
646            ## across to avoid errors at package build time.
647            doc$description <- doc$title
648          }
649          doc
650        }
651      extract.docs <- function(on){
652        res <- try({o <- objs[[on]]
653                    extract.docs.try(o, on)},FALSE)
654        if(class(res)=="try-error"){
655          cat("Failed to extract docs for: ",on,"\n\n")
656          list()
657        } else if(0 == length(res) && inherits(objs[[on]],"standardGeneric")){
658          NULL
659        } else if(0 == length(res) && "function" %in% class(o)
660                  && 1 == length(osource <- getSource(o))
661                  && grepl(paste("UseMethod(",on,")",sep="\""),osource)
662                  ){
663          ## phew - this should only pick up R.oo S3 generic definitions like:
664          ## attr(*, "source")= chr "function(...) UseMethod(\"select\")"
665          NULL
666        } else res
667      }
668      doc.names <- names(objs)
669      res <- sapply(doc.names,extract.docs,simplify=FALSE)
670      ## Special processing for S4 classes as they do not appear in normal ls()
671      for ( nn in names(parsed) ){
672        if ( parsed[[nn]]@created == "setClass" ){
673          S4class.docs <- extract.docs.setClass(parsed[[nn]])
674          docname <- paste(nn,"class",sep="-")
675          if ( is.null(res[[docname]]) ){
676            res[[docname]] <- S4class.docs
677            doc.names <- c(doc.names,docname)
678          } else {
679            stop(nn," appears as both S4 class and some other definition")
680          }
681        }
682      }
683      inherit.docs <- function(on){
684        in.res <- res[[on]]
685        if ( !is.null(parsed[[on]]) ){
686          for ( parent in parsed[[on]]@parent ){
687            if ( !is.na(parent) ){
688              if ( is.null(in.res) ){
689                in.res <- res[[parent]]
690              } else if ( parent %in% names(res) ){
691                parent.docs <- res[[parent]]
692                for ( nn in names(parent.docs) ){
693                  if ( !nn %in% names(in.res) ){
694                    in.res[[nn]] <- parent.docs[[nn]]
695                  }
696                }
697              }
698            }
699          }
700        }
701        invisible(in.res)
702      }
703      all.done <- FALSE
704      while ( !all.done ){
705        res1 <- sapply(doc.names,inherit.docs,simplify=FALSE)
706        all.done <- identical(res1,res)
707        res <- res1
708      }
709      ## now strip out any generics (which have value NULL in res):
710      res.not.null <- sapply(res,function(x){!is.null(x)})
711      if ( 0 < length(res.not.null) && length(res.not.null) < length(res) ){
712        res <- res[res.not.null]
713      }
714      res
715    ### named list of lists, one for each object to document.
716    }
717    
718    ### List of parsers to use by default with package.skeleton.dx.
719    default.parsers <-
720      c(extra.code.docs=extra.code.docs, ## TODO: cleanup!
721        sapply(forfun.parsers,forfun),
722        edit.package.file=function(desc,...){
723          in.details <- setdiff(colnames(desc),"Description")
724          details <- sprintf("%s: \\tab %s\\cr",in.details,desc[,in.details])
725          L <-
726            list(list(title=desc[,"Title"],
727                      description=desc[,"Description"],
728                      `tabular{ll}`=details))
729          names(L) <- paste(desc[,"Package"],"-package",sep="")
730          L
731        },
732        sapply(forall.parsers,forall)
733        )
734    
735  setClass("DocLink", # Link documentation among related functions  setClass("DocLink", # Link documentation among related functions
736  ### The \code{.DocLink} class provides the basis for hooking together  ### The \code{.DocLink} class provides the basis for hooking together
737  ### documentation of related classes/functions/objects. The aim is that  ### documentation of related classes/functions/objects. The aim is that
738  ### documentation sections missing from the child are  ### documentation sections missing from the child are inherited from
739    ### the parent class.
740           representation(name="character", ##<< name of object           representation(name="character", ##<< name of object
741                          created="character", ##<< how created                          created="character", ##<< how created
742                          parent="character", ##<< parent class or NA                          parent="character", ##<< parent class or NA
# Line 487  Line 745 
745           )           )
746    
747  extract.file.parse <- function # File content analysis  extract.file.parse <- function # File content analysis
748  ### Using the base \code{\link{parse}} function, analyse the file to link  ### Using the base \code{parse} function, analyse the file to link
749  ### preceding "prefix" comments to each active chunk. Those comments form  ### preceding "prefix" comments to each active chunk. Those comments form
750  ### the default description for that chunk. The analysis also looks for  ### the default description for that chunk. The analysis also looks for
751  ### S4 class "setClass" calls and R.oo setConstructorS3 and setMethodS3  ### S4 class "setClass" calls and R.oo setConstructorS3 and setMethodS3
# Line 513  Line 771 
771      ## "prefix" lines will be used instead.      ## "prefix" lines will be used instead.
772      default.description <- NULL      default.description <- NULL
773      while ( start > last.end+1      while ( start > last.end+1
774             && 1 == length(grep(prefix,code[start-1],perl=TRUE)) ){             && grepl(prefix,code[start-1],perl=TRUE) ){
775        start <- start-1        start <- start-1
776      }      }
777      if ( start < chunks[[k]][1] ){      if ( start < chunks[[k]][1] ){
# Line 540  Line 798 
798        ## If the function definition is not embedded within the call, then        ## If the function definition is not embedded within the call, then
799        ## the parent is that function. Test whether the the third value        ## the parent is that function. Test whether the the third value
800        ## looks like a name and add it to parents if so.        ## looks like a name and add it to parents if so.
801        if ( 1 == length(grep("^[\\._\\w]+$",chars[3],perl=TRUE)) ){        if ( grepl("^[\\._\\w]+$",chars[3],perl=TRUE) ){
802          parent <- chars[3]          parent <- chars[3]
803        }        }
804        res[[object.name]] <- new("DocLink",name=object.name,        res[[object.name]] <- new("DocLink",name=object.name,
# Line 559  Line 817 
817        generic.name <- chars[2]        generic.name <- chars[2]
818        object.name <- paste(generic.name,chars[3],sep=".")        object.name <- paste(generic.name,chars[3],sep=".")
819        if ( is.null(res[[generic.name]]) ){        if ( is.null(res[[generic.name]]) ){
820          generic.desc <- paste("Generic method behind \\code{\\link{",object.name,"}}",sep="")          ## TDH 9 April 2012 Do NOT add \\link in generic.desc below,
821            ## since it causes problems on R CMD check.
822            ##* checking Rd cross-references ... WARNING
823            ##Error in find.package(package, lib.loc) :
824            ##  there is no package called ‘MASS’
825            ##Calls: <Anonymous> -> lapply -> FUN -> find.package
826    
827            generic.desc <-
828              paste("Generic method behind \\code{",object.name,"}",sep="")
829          res[[generic.name]] <- new("DocLink",          res[[generic.name]] <- new("DocLink",
830                                     name=generic.name,                                     name=generic.name,
831                                     created=expr.type,                                     created=expr.type,
# Line 572  Line 838 
838        ## If the function definition is not embedded within the call, then        ## If the function definition is not embedded within the call, then
839        ## the parent is that function. Test whether the the fourth value        ## the parent is that function. Test whether the the fourth value
840        ## looks like a name and add it to parents if so.        ## looks like a name and add it to parents if so.
841        if ( 1 == length(grep("^[\\._\\w]+$",chars[4],perl=TRUE)) ){        if ( grepl("^[\\._\\w]+$",chars[4],perl=TRUE) ){
842          parent <- c(chars[4],parent)          parent <- c(chars[4],parent)
843        }        }
844        res[[object.name]] <- new("DocLink",name=object.name,        res[[object.name]] <- new("DocLink",name=object.name,
# Line 593  Line 859 
859  ### in the form \code{setClass("classname",\dots)} are also located and  ### in the form \code{setClass("classname",\dots)} are also located and
860  ### scanned for inline comments.  ### scanned for inline comments.
861  (doc.link  (doc.link
862  ### DocLink object as created by \code{\link{extract.file.parse}}.  ### DocLink object as created by \code{extract.file.parse}.
863  ### Note that \code{source} statements are \emph{ignored} when scanning for  ### Note that \code{source} statements are \emph{ignored} when scanning for
864  ### class definitions.  ### class definitions.
865   ){   ){
# Line 613  Line 879 
879    ## the same line or \code{### } comments at the beginning of the    ## the same line or \code{### } comments at the beginning of the
880    ## following line.    ## following line.
881    f.n <- paste(class.name,"class",sep="-")    f.n <- paste(class.name,"class",sep="-")
882    docs <- extract.docs.fun(chunk.source,f.n)    docs <- extract.xxx.chunks(chunk.source,f.n)
883      ## also apply source parsing functions that I separated out into
884      ## separate functions
885      docs <- combine(docs,lonely$prefixed.lines(chunk.source))
886      docs$title <- lonely$title.from.firstline(chunk.source)
887      ##details<<
888      ## If there is no explicit title on the first line of setClass, then
889      ## one is made up from the class name.
890      if ( 0 == length(docs$title) ){
891        docs$title <- list(title=paste(class.name,"S4 class"))
892      }
893    ##details<<    ##details<<
894    ## The class definition skeleton includes an \code{Objects from the Class}    ## The class definition skeleton includes an \code{Objects from the Class}
895    ## section, to which any \code{##details<<} documentation chunks are    ## section, to which any \code{##details<<} documentation chunks are
# Line 637  Line 913 
913    }    }
914    invisible(docs)    invisible(docs)
915  }  }
916    
917    apply.parsers <- function
918    ### Parse code to r objs, then run all the parsers and return the
919    ### documentation list.
920    (code,
921    ### Character vector of code lines.
922     parsers=default.parsers,
923    ### List of Parser Functions.
924     verbose=FALSE,
925    ### Echo names of Parser Functions?
926     ...
927    ### Additional arguments to pass to Parser Functions.
928     ){
929      e <- new.env()
930      ## KMP 2011-03-09 fix problem with DocLink when inlinedocs ran on itself
931      ## Error in assignClassDef(Class, classDef, where) :
932      ##   Class "DocLink" has a locked definition in package "inlinedocs"
933      ## Traced to "where" argument in setClassDef which defaults to topenv()
934      ## which in turn is inlinedocs when processing inlinedocs package, hence
935      ## the clash. The following works (under R 2.12.2), so that the topenv()
936      ## now finds e before finding the inlinedocs environment.
937      old <- options(keep.source=TRUE,topLevelEnvironment=e)
938      on.exit(options(old))
939      exprs <- parse(text=code)
940      ## TDH 2011-04-07 set this so that no warnings about creating a fake
941      ## package when we try to process S4 classes defined in code
942      e$.packageName <- "inlinedocs.processor"
943      for (i in exprs){
944          eval(i, e)
945      }
946      objs <- sapply(ls(e),get,e,simplify=FALSE)
947    
948      docs <- list()
949    
950      ## apply parsers in sequence to code and objs
951      if(verbose)cat("Applying parsers:\n")
952      for(i in seq_along(parsers)){
953        N <- names(parsers[i])
954        if(verbose){
955          if(is.character(N) && N!=""){
956            cat(N,"\n",sep="")
957          }else cat('.\n')
958        }
959        p <- parsers[[i]]
960        ## This is the argument list that each parser receives:
961        L <- p(code=code,objs=objs,docs=docs,env=e,...)
962        #print(paste(L,"\n"))
963        #if(N=="exclude")browser()
964        docs <- combine(docs,L)
965      }
966      ## post-process to collapse all character vectors
967      for(i in seq_along(docs)){
968        for(j in seq_along(docs[[i]])){
969          if(names(docs[[i]])[j]!=".s3method")
970          docs[[i]][[j]] <- paste(docs[[i]][[j]],collapse="\n")
971        }
972     }
973      if(verbose)cat("\n")
974      return(docs)
975    ### A list of extracted documentation from code.
976    }
977    
978    ### Names of Parser Functions that operate on the desc arg.
979    descfile.names <- c("author.from.description","edit.package.file")
980    
981    ### Names of Parser Functions that do NOT use the desc arg.
982    non.descfile.names <-
983      names(default.parsers)[!names(default.parsers)%in%descfile.names]
984    
985    ### Parsers that operate only on R code, independently of the
986    ### description file.
987    nondesc.parsers <- default.parsers[non.descfile.names]
988    
989    extract.docs.file <- structure(function
990    ### Apply all parsers relevant to extract info from just 1 code file.
991    (f,
992    ### File name of R code to read and parse.
993     parsers=NULL,
994    ### Parser Functions to use to parse the code and extract
995    ### documentation.
996     ...
997    ### Other arguments to pass to Parser Functions.
998     ){
999      if(is.null(parsers))parsers <- nondesc.parsers
1000      apply.parsers(readLines(f),parsers,verbose=FALSE,...)
1001    },ex=function(){
1002      f <- system.file("silly","R","silly.R",package="inlinedocs")
1003      extract.docs.file(f)
1004    })
1005    

Legend:
Removed from v.103  
changed lines
  Added in v.356

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