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 115, Fri Jun 18 10:35:11 2010 UTC revision 307, Fri Oct 21 11:37:19 2011 UTC
# Line 7  Line 7 
7    
8  ### combine lists by adding elements or adding to existing elements  ### combine lists by adding elements or adding to existing elements
9  combine.list <- function(x,y){  combine.list <- function(x,y){
10    toadd <- !names(y)%in%names(x)    toadd <- if(".overwrite"%in%names(y)){
11    toup <- names(y)[names(y)%in%names(x)]      y <- y[names(y)!=".overwrite"]
12        rep(TRUE,length(y))
13      }else{
14        !names(y)%in%names(x)
15      }
16      toup <- names(y)[!toadd]
17    x[names(y)[toadd]] <- y[toadd]    x[names(y)[toadd]] <- y[toadd]
18    for(up in toup)x[[up]] <- combine(x[[up]],y[[up]])    for(up in toup)x[[up]] <- combine(x[[up]],y[[up]])
19    return(x)    x
20  ### A list, same type as x, but with added elements from y.  ### A list, same type as x, but with added elements from y.
21  }  }
22    
23    
24    getSource <- function
25    ### Extract a function's source code.
26    (fun.obj
27    ### A function.
28     ) {
29          srcref <- attr(fun.obj, "srcref")
30          if (!is.null(srcref)) unlist(strsplit(as.character(srcref), "\n"))
31          else attr(fun.obj, "source")
32    ### Source code lines as a character vector.
33    }
34    
35  ### Prefix for code comments used with grep and gsub.  ### Prefix for code comments used with grep and gsub.
36  prefix <- "^[ \t]*###[ \t]"  prefix <- "^[ \t]*###[ \t]*"
37    
38  decomment <- function  decomment <- function
39  ### Remove comment prefix and join lines of code to form a  ### Remove comment prefix and join lines of code to form a
# Line 24  Line 41 
41  (comments  (comments
42  ### Character vector of prefixed comment lines.  ### Character vector of prefixed comment lines.
43   ){   ){
44    paste(gsub(prefix,"",comments),collapse="\n")    gsub(prefix,"",comments)
45  ### String without prefixes or newlines.  ### String without prefixes or newlines.
46  }  }
47    
48    forall <- function
49  ### For each object in the package that satisfies the criterion  ### For each object in the package that satisfies the criterion
50  ### checked by subfun, parse source using FUN and return the resulting  ### checked by subfun, parse source using FUN and return the resulting
51  ### documentation list.  ### documentation list.
 forall <- function  
52  (FUN,  (FUN,
53  ### Function to apply to each element in the package.  ### Function to apply to each element in the package.
54   subfun=function(x)TRUE   subfun=function(x)TRUE
# Line 39  Line 56 
56  ### 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
57  ### the result will be returned.  ### the result will be returned.
58   ){   ){
59    function(objs,docs,...){    FUN <- FUN
60      f <- function(objs,docs,...){
61        if(length(objs)==0)return(list())
62      objs <- objs[sapply(objs,subfun)]      objs <- objs[sapply(objs,subfun)]
63      L <- list()      L <- list()
64      for(N in names(docs)){      on.exit(cat(sprintf("Parser Function failed on %s\n",N)))
65        for(N in union(names(docs),names(objs))){
66        o <- objs[[N]]        o <- objs[[N]]
67        L[[N]] <- FUN(src=attr(o,"source"),        L[[N]] <- FUN(src=getSource(o),
68                      name=N,objs=objs,o=o,docs=docs,doc=docs[[N]],...)                      name=N,objs=objs,o=o,docs=docs,doc=docs[[N]],...)
69      }      }
70        on.exit()## remove warning message
71      L      L
72    }    }
73      class(f) <- c("allfun","function")
74      f
75  ### A Parser Function.  ### A Parser Function.
76  }  }
77    
78  ### For each function in the package, do something.  ### Print method for functions constructed using forall.
79  forfun <- function(FUN)forall(FUN,is.function)  print.allfun <- function(x,...){
80      e <- environment(x)
81  ### Parsers for each object/function that are constructed    cat("Function to apply to every element.\nselector:")
82  ### automatically. This is a named list, each element is a list of 2    print(e$subfun)
83  ### elements: forfun/forall, then a parser function for an individual    cat("processor:")
84  ### 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))  
        }),  
        # PhG: it is tests/FUN.R!!! I would like more flexibility here  
            # please, let me choose which dir to use for examples!  
            ## Get examples for FUN from the file tests/FUN.R  
        examples.from.testfile=list(forfun,function(name,...){  
          tsubdir <- getOption("inlinedocs.exdir")  
                  if (is.null(tsubdir)) tsubdir <- "tests"       # Default value  
                  tfile <- file.path("..",tsubdir,paste(name,".R",sep=""))  
          if(file.exists(tfile))  
            list(examples=paste(readLines(tfile),collapse="\n"))  
          else list()  
        }),  
        ## Get examples from inline definitions after return()  
            # PhG: this does not work well! Think at these situations:  
            # 1) You have multiple return() in the code of your function,  
            # 2) You have return() appearing is some example code, ...  
            # I can hardly propose a hack here. The whole code of the function  
            # must be parsed, and one must determine which one is the last line  
            # of code that is actually executed.  
            #  
            # I make two propositions here  
            # 1) to keep the same mechanism that has the advantage of simplicity  
            #    but to use a special tag ##examples<< or #{{{examples to separate  
            #    function code from examples explicitly, and  
            # 2) to place the example in an "ex" attribute attached to the function  
            #    (see next parser). That solution will be also interesting for  
            #    documenting datasets, something not done yet by inlinedocs!  
            examples.after.return = list(forfun, function(name, src, ...) {  
                         # Look for the examples mark  
                         m <- grep("##examples<<|#\\{\\{\\{examples", src)  
                         if (!length(m)) return(list())  
                         if (length(m) > 1)  
                                 warning("More than one examples tag for ", name, ". Taking the last one")  
                         m <- m[length(m)]  
                         # Look for the lines containing return value comments just before  
                         r <- grep("\\s*### ", src[1:(m-1)])  
                         if (!length(r)) {  
                                 value <- NULL  
                         } else {  
                                 # Only take consecutive lines before the mark  
                                 keep <- rev((m - rev(r)) == 1:length(r))  
                                 if (!any(keep)) {  
                                         value <- NULL  
                                 } else {  
                                         value <- decomment(src[r[keep]])  
                                 }  
                         }  
                         # Collect now the example code beneath the mark  
                         ex <- src[(m + 1):(length(src) - 1)]  
                         # Possibly eliminate a #}}} tag  
                         ex <- ex[!grepl("#}}}", ex)]  
                         # Eliminate leading tabulations or four spaces  
                         ex <- sub("^\t|    ", "", ex)  
                         # Add an empty line before and after example  
                         ex <- c("", ex, "")  
                         # Return examples and value  
                         list(examples = paste(ex, collapse = "\n"), value = value)  
            }),  
            # PhG: here is what I propose for examples code in the 'ex' attribute  
            examples.in.attr = list(forfun, function (name, o, ...) {  
                         ex <- attr(o, "ex")  
                         if (!is.null(ex)) {  
                                 # Special case for code contained in a function  
                                 if (inherits(ex, "function")) {  
                                         # If source is available, start from there  
                                         src <- attr(ex, "source")  
                                         if (!is.null(src)) {  
                                                 ex <- src  
                                         } else { # Use the body of the function  
                                                 ex <- deparse(body(ex))  
                                         }  
                                         # Eliminate leading and trailing code  
                                         ex <- ex[-c(1, length(ex))]  
                                         # Eliminate leading tabulations or four spaces  
                                         ex <- sub("^\t|    ", "", ex)  
                                         # Add an empty line before and after example  
                                         ex <- c("", ex, "")  
85                                  }                                  }
                                 list(examples = paste(ex, collapse = "\n"))  
                         } else list()  
            }))  
   
 ### List of parser functions that operate on single objects. This list  
 ### is useful for testing these functions, ie  
 ### lonely$parsefun(attr(extract.docs.file,"source"),"extract.docs.file")  
 lonely <- sapply(forall.parsers,function(L)L[[2]])  
86    
87  extra.code.docs <- function # Extract documentation from code chunks  ### For each function in the package, do something.
88  ### Parse R code to extract inline documentation from comments around  forfun <- function(FUN)forall(FUN,is.function)
 ### each function. These are not able to be retreived simply by  
 ### looking at the "source" attribute. This is a Parser Function that  
 ### can be used in the parser list of package.skeleton.dx(). TODO:  
 ### Modularize this into separate Parsers Functions for S4 classes,  
 ### prefixes, ##<<blocks, etc. Right now it is not very clean!  
 (code,  
 ### Code lines in a character vector containing multiple R objects to  
 ### parse for documentation.  
  objs,  
 ### The objects defined in the code.  
  ...  
 ### ignored  
  ){  
   parsed <- extract.file.parse(code)  
   extract.docs.try <- function(o,on)  
     {  
       ## Note: we could use parsed information here too, but that  
       ## would produce different results for setMethodS3 etc.  
       doc <- list()  
       if ( !is.null(parsed[[on]]) ){  
         if ( !is.na(parsed[[on]]@code[1]) ){ # no code given for generics  
           doc$definition <- paste(parsed[[on]]@code,collapse="\n")  
         }  
         if(!"description"%in%names(doc) && !is.na(parsed[[on]]@description) ){  
           doc$description <- parsed[[on]]@description  
         }  
         if ( "setMethodS3" == parsed[[on]]@created ){  
           # PhG: this may be wrong! It does not catch correctly how the method  
                   # must be splitted in case of methods containing dots. for instance,  
                   # as.data.frame.matrix must be split into: m1 = as.data.frame and  
                   # m2 = matrix... here you got m1 = as, and m2 = data.frame.matrix!!!  
                   pattern <- "^([^\\.]+)\\.(.*)$"  
           doc$s3method=c(m1 <- gsub(pattern,"\\1",on,perl=TRUE),  
               m2 <- gsub(pattern,"\\2",on,perl=TRUE))  
           if ( 0 < length(grep("\\W",m1,perl=TRUE)) ){  
                           m1 <- paste("`",m1,"`",sep="")  
           }  
           cat("S3method(",m1,",",m2,")\n",sep="")  
         }  
       }  
       if("title" %in% names(doc) && !"description" %in% names(doc) ){  
         ## For short functions having both would duplicate, but a  
         ## description is required. Therefore automatically copy title  
         ## across to avoid errors at package build time.  
         doc$description <- doc$title  
       }  
       doc  
     }  
   extract.docs <- function(on){  
     res <- try({o <- objs[[on]]  
                 extract.docs.try(o, on)},FALSE)  
     if(class(res)=="try-error"){  
       cat("Failed to extract docs for: ",on,"\n\n")  
       list()  
     } else if(0 == length(res) && inherits(objs[[on]],"standardGeneric")){  
       NULL  
     } else if(0 == length(res) && "function" %in% class(o)  
               && 1 == length(osource <- attr(o,"source"))  
               && 1 == length(grep(paste("UseMethod(",on,")",sep="\""),osource))  
               ){  
       ## 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.  
 }  
   
 ### List of parsers to use by default with package.skeleton.dx.  
 default.parsers <-  
   c(extra.code.docs=extra.code.docs,  
     sapply(forall.parsers,function(L)L[[1]](L[[2]])),  
     edit.package.file=function(desc,...){  
       in.details <- setdiff(colnames(desc),"Description")  
       details <- paste(paste(in.details,": \\tab ",desc[,in.details],"\\cr",  
                              sep=""),collapse="\n")  
       L <-  
         list(list(title=desc[,"Title"],  
                   description=desc[,"Description"],  
                   `tabular{ll}`=details,  
                   author=desc[,"Maintainer"]))  
       names(L) <- paste(desc[,"Package"],"-package",sep="")  
       L  
     })  
89    
90  extract.docs.fun <- function # Extract documentation from a function  kill.prefix.whitespace <- function
91  ### Given source code of a function, return a list describing inline  ### Figure out what the whitespace preceding the example code is, and
92  ### documentation in that source code.  ### then delete that from every line.
93  (code,  (ex
94  ### The function to examine.  ### character vector of example code lines.
  name.fun  
 ### The name of the function/chunk to use in warning messages.  
95   ){   ){
96    res <- list()    tlines <- gsub("\\s*","",ex)
97    clines <- grep(prefix,code)    ##tlines <- gsub("#.*","",tlines)
98    if(length(grep("#",code[1]))){    prefixes <- unique(gsub("\\S.*","",ex[tlines!=""]))
99      res$title <- gsub("[^#]*#\\s*(.*)","\\1",code[1],perl=TRUE)    FIND <- prefixes[which.min(nchar(prefixes))]
100    }    ## Eliminate leading tabulations or 2/4 spaces
101    if(length(clines) > 0){    sub(FIND, "", ex)
102      ##details<<  ### Character vector of code lines with preceding whitespace removed.
103      ## The primary mechanism is that consecutive groups of lines matching  }
104      ## the specified prefix regular expression "\code{^### }" (i.e. lines  
105      ## beginning with "\code{### }") are collected  prefixed.lines <- structure(function(src,...){
106      ## as follows into documentation sections:\describe{  ### The primary mechanism of inline documentation is via consecutive
107      ## \item{description}{group starting at line 2 in the code}  ### groups of lines matching the specified prefix regular expression
108      ## \item{arguments}{group following each function argument}  ### "\code{^### }" (i.e. lines beginning with "\code{### }") are
109      ## \item{value}{group ending at the penultimate line of the code}}  ### collected as follows into documentation sections:\describe{
110      ## These may be added to by use of the \code{##<<} constructs described  ### \item{description}{group starting at line 2 in the code}
111      ## below.  ### \item{arguments}{group following each function argument}
112    ### \item{value}{group ending at the penultimate line of the code}}
113    ### These may be added to by use of the \code{##<<} constructs
114    ### described below.
115      clines <- grep(prefix,src)
116      if(length(clines)==0)return(list())
117      bounds <- which(diff(clines)!=1)      bounds <- which(diff(clines)!=1)
118      starts <- c(1,bounds+1)      starts <- c(1,bounds+1)
119      ends <- c(bounds,length(clines))      ends <- c(bounds,length(clines))
120      ## detect body of function using paren matching
121      code <- gsub("#.*","",src)
122      f <- function(ch)cumsum(nchar(gsub(sprintf("[^%s]",ch),"",code)))
123      parens <- f("(")-f(")")
124      body.begin <- which(diff(parens)<0 & parens[-1]==0)+2
125      if(length(body.begin)==0)body.begin <- 1 ## rare cases
126      is.arg <- function(){
127        gres <- grep("^\\s*#",src[start-1],perl=TRUE)
128        0 == length(gres) && start<=body.begin
129      }
130      res <- list()
131      for(i in seq_along(starts)){      for(i in seq_along(starts)){
132        start <- clines[starts[i]]        start <- clines[starts[i]]
133        end <- clines[ends[i]]        end <- clines[ends[i]]
134        lab <- if(end+1==length(code))"value"      processed <- gsub("#.*","",gsub("[ }]","",src[(end+1):length(src)]))
135        lab <- if(all(processed==""))"value"
136        else if(start==2)"description"        else if(start==2)"description"
137        else if ( 0 == length(grep("^\\s*#",code[start-1],perl=TRUE)) ){      else if(is.arg()){
138           #arg <- gsub("^[ (]*","",code[start-1])        ##twutz: strip leading white spaces and brackets and ,
139           #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 ,  
140                   arg <- gsub("^([^=,]*)[=,].*", "\\1", arg)                   arg <- gsub("^([^=,]*)[=,].*", "\\1", arg)
141                   arg <- gsub("^([^ \t]*)([ \t]+)$","\\1",arg)   #twutz: remove trailing whitespaces        ##twutz: remove trailing whitespaces
142          arg <- gsub("^([^ \t]*)([ \t]+)$","\\1",arg)
143                   arg <- gsub("...", "\\dots", arg, fix = TRUE)                   arg <- gsub("...", "\\dots", arg, fix = TRUE)
144           paste("item{",arg,"}",sep="")           paste("item{",arg,"}",sep="")
145         } else {         } else {
146           next;           next;
147         }         }
148        res[[lab]] <- decomment(code[start:end])      res[[lab]] <- decomment(src[start:end])
     }  
149    }    }
150      res
151    },ex=function(){
152    test <- function
153    ### the description
154    (x,
155    ### the first argument
156     y ##<< another argument
157     ){
158      5
159    ### the return value
160    ##seealso<< foobar
161    }
162    src <- getSource(test)
163    prefixed.lines(src)
164    extract.xxx.chunks(src)
165    })
166    
167    extract.xxx.chunks <- function # Extract documentation from a function
168    ### Given source code of a function, return a list describing inline
169    ### documentation in that source code.
170    (src,
171    ### The source lines of the function to examine, as a character
172    ### vector.
173     name.fun="(unnamed function)",
174    ### The name of the function/chunk to use in warning messages.
175     ...
176    ### ignored.
177     ){
178      res <- list()
179    ##details<< For simple functions/arguments, the argument may also be    ##details<< For simple functions/arguments, the argument may also be
180    ## documented by appending \code{##<<} comments on the same line as the    ## documented by appending \code{##<<} comments on the same line as the
181    ## argument name. Mixing this mechanism with \code{###} comment lines for    ## argument name. Mixing this mechanism with \code{###} comment lines for
# Line 416  Line 248 
248          chunk.sep <- "\n\n"          chunk.sep <- "\n\n"
249        }        }
250        chunk.res <- NULL        chunk.res <- NULL
251        if ( 0 == length(grep("^\\s*$",payload,perl=TRUE)) )        if ( !grepl("^\\s*$",payload,perl=TRUE) )
252          chunk.res <-          chunk.res <-
253            if ( is.null(res[[field]]) ) payload            if ( is.null(res[[field]]) ) payload
254            else paste(res[[field]], payload, sep=chunk.sep)            else paste(res[[field]], payload, sep=chunk.sep)
255        invisible(chunk.res)        invisible(chunk.res)
256      }      }
257    while ( k <= length(code) ){    while ( k <= length(src) ){
258      line <- code[k]      line <- src[k]
259      if ( 0 < length(grep(extra.regexp,line,perl=TRUE) ) ){      if ( grepl(extra.regexp,line,perl=TRUE) ){
260        ## 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
261        new.field <- gsub(extra.regexp,"\\1",line,perl=TRUE)        new.field <- gsub(extra.regexp,"\\1",line,perl=TRUE)
262        new.contents <- gsub(extra.regexp,"\\2",line,perl=TRUE)        new.contents <- gsub(extra.regexp,"\\2",line,perl=TRUE)
# Line 437  Line 269 
269        ## block until terminated by a subsequent \code{##}\emph{xxx}\code{<<} line.        ## block until terminated by a subsequent \code{##}\emph{xxx}\code{<<} line.
270        if ( "describe" == new.field ){        if ( "describe" == new.field ){
271          ##details<< Such regions may be nested, but not in such a way          ##details<< Such regions may be nested, but not in such a way
272          ## that the first element in a \code{describe} is another \code{describe}.          ## that the first element in a \code{describe} is another
273          ## Thus there must be at least one \code{##<<} comment between each          ## \code{describe}.  Thus there must be at least one
274          ## pair of \code{##describe<<} comments.          ## \code{##<<} comment between each pair of
275            ## \code{##describe<<} comments.
276          if ( first.describe ){          if ( first.describe ){
277            stop("consecutive ##describe<< at line",k,"in",name.fun)            stop("consecutive ##describe<< at line",k,"in",name.fun)
278          } else {          } else {
# Line 499  Line 332 
332            first.describe <- TRUE;            first.describe <- TRUE;
333          }          }
334        }        }
335      } else if ( in.chunk && 0<length(grep(cont.re,line,perl=TRUE)) ){      } else if ( in.chunk && grepl(cont.re,line,perl=TRUE) ){
336        ## append this line to current chunk        ## append this line to current chunk
337        if ( 0 == length(grep(prefix,line,perl=TRUE)) ){        if ( !grepl(prefix,line,perl=TRUE) ){
338          ##describe<< Any lines with "\code{### }" at the left hand          ##describe<< Any lines with "\code{### }" at the left hand
339          ## margin within the included chunks are handled separately,          ## margin within the included chunks are handled separately,
340          ## so if they appear in the documentation they will appear          ## so if they appear in the documentation they will appear
# Line 514  Line 347 
347            payload <- stripped            payload <- stripped
348          }          }
349        }        }
350      } else if ( 0 < length(grep(arg.pat,line,perl=TRUE)) ){      } else if ( grepl(arg.pat,line,perl=TRUE) ){
351        not.describe <- (0==in.describe && !first.describe)        not.describe <- (0==in.describe && !first.describe)
352        if ( in.chunk && not.describe){        if ( in.chunk && not.describe){
353          res[[cur.field]] <- end.chunk(cur.field,payload)          res[[cur.field]] <- end.chunk(cur.field,payload)
# Line 576  Line 409 
409  ### with the string in this list (implemented in modify.Rd.file).  ### with the string in this list (implemented in modify.Rd.file).
410  }  }
411    
412    leadingS3generic <- function # check whether function name is an S3 generic
413    ### Determines whether a function name looks like an S3 generic function
414    (name,                     ##<< name of function
415     env,                      ##<< environment to search for additional generics
416     ...)                      ##<< ignored here
417    {
418      ##details<< This function is one of the default parsers, but exposed as
419      ## possibly of more general interest. Given a function name of the form
420      ## x.y.z it looks for the generic function x applying to objects of class
421      ## y.z and also for generic function x.y applying to objects of class z.
422      ##
423      parts <- strsplit(name, ".", fixed = TRUE)[[1]]
424      l <- length(parts)
425      if (l > 1) {
426        for (i in 1:(l - 1)) {
427          ## Look for a generic function (known by the system or defined
428          ## in the package) that matches that part of the function name
429          generic <- paste(parts[1:i], collapse = ".")
430          if (any(generic %in% utils:::getKnownS3generics()) ||
431              utils:::findGeneric(generic, env) != "") {
432            object <- paste(parts[(i + 1):l], collapse = ".")
433            ##details<< Assumes that the first name which matches any known
434            ## generics is the target generic function, so if both x and x.y
435            ## are generic functions, will assume generic x applying to objects
436            ## of class y.z
437            ##value<< If a matching generic found returns a list with a single component:
438            return(list(.s3method=c(generic, object))) ##<< a character vector containing generic name and object name.
439          }
440        }
441      }
442      ##value<< If no matching generic functions are found, returns an empty list.
443      list()
444    }
445    
446    ### Parsers for each function that are constructed automatically. This
447    ### is a named list, and each element is a parser function for an
448    ### individual object.
449    forfun.parsers <-
450      list(prefixed.lines=prefixed.lines,
451           extract.xxx.chunks=extract.xxx.chunks,
452           ## title from first line of function def
453           title.from.firstline=function(src,...){
454             first <- src[1]
455             if(!is.character(first))return(list())
456             if(!grepl("#",first))return(list())
457             list(title=gsub("[^#]*#\\s*(.*)","\\1",first,perl=TRUE))
458           },
459           ## PhG: it is tests/FUN.R!!! I would like more flexibility here
460           ## please, let me choose which dir to use for examples!
461           ## Get examples for FUN from the file tests/FUN.R
462           examples.from.testfile=function(name,...){
463             tsubdir <- getOption("inlinedocs.exdir")
464             if (is.null(tsubdir)) tsubdir <- "tests"       # Default value
465             tfile <- file.path("..",tsubdir,paste(name,".R",sep=""))
466             if(file.exists(tfile))
467               list(examples=readLines(tfile))
468             else list()
469           },
470           definition.from.source=function(doc,src,...){
471             def <- doc$definition
472             is.empty <- function(x)is.null(x)||x==""
473             if(is.empty(def) && !is.empty(src))
474               list(definition=src)
475             else list()
476           })
477    
478    ### List of Parser Functions that can be applied to any object.
479    forall.parsers <-
480      list(## Fill in author from DESCRIPTION and titles.
481           author.from.description=function(desc,...){
482             list(author=desc[,"Maintainer"])
483           },
484           ## The format section sometimes causes problems, so erase it.
485           erase.format=function(...){
486             list(format="")
487           },
488           ## Convert the function name to a title.
489           title.from.name=function(name,doc,...){
490             if("title"%in%names(doc))list() else
491             list(title=gsub("[._]"," ",name))
492           },
493           ## PhG: here is what I propose for examples code in the 'ex' attribute
494           examples.in.attr =  function (name, o, ...) {
495             ex <- attr(o, "ex")
496             if (!is.null(ex)) {
497               ## Special case for code contained in a function
498               if (inherits(ex, "function")) {
499                 ## If source is available, start from there
500                 src <- getSource(ex)
501                 if (!is.null(src)) {
502                   ex <- src
503                 } else { ## Use the body of the function
504                   ex <- deparse(body(ex))
505                 }
506                 ## Eliminate leading and trailing code
507                 ex <- ex[-c(1, length(ex))]
508                 if(ex[1]=="{")ex <- ex[-1]
509                 ## all the prefixes
510                 ex <- kill.prefix.whitespace(ex)
511                 ## Add an empty line before and after example
512                 ex <- c("", ex, "")
513               }
514               list(examples = ex)
515             } else list()
516           },collapse=function(doc,...){
517             L <- lapply(doc,paste,collapse="\n")
518             L$.overwrite <- TRUE
519             L
520           },tag.s3methods=leadingS3generic
521           )
522    
523    ### List of parser functions that operate on single objects. This list
524    ### is useful for testing these functions.
525    lonely <- structure(c(forall.parsers,forfun.parsers),ex=function(){
526      f <- function # title
527    ### description
528      (x, ##<< arg x
529       y
530    ### arg y
531       ){
532        ##value<< a list with elements
533        list(x=x, ##<< original x value
534             y=y, ##<< original y value
535             sum=x+y) ##<< their sum
536        ##end<<
537      }
538      src <- getSource(f)
539      lonely$extract.xxx.chunks(src)
540      lonely$prefixed.lines(src)
541    })
542    
543    extra.code.docs <- function # Extract documentation from code chunks
544    ### Parse R code to extract inline documentation from comments around
545    ### each function. These are not able to be retreived simply by
546    ### looking at the "source" attribute. This is a Parser Function that
547    ### can be used in the parser list of package.skeleton.dx(). TODO:
548    ### Modularize this into separate Parsers Functions for S4 classes,
549    ### prefixes, ##<<blocks, etc. Right now it is not very clean!
550    (code,
551    ### Code lines in a character vector containing multiple R objects to
552    ### parse for documentation.
553     objs,
554    ### The objects defined in the code.
555     ...
556    ### ignored
557     ){
558      parsed <- extract.file.parse(code)
559      extract.docs.try <- function(o,on)
560        {
561          ## Note: we could use parsed information here too, but that
562          ## would produce different results for setMethodS3 etc.
563          doc <- list()
564          if ( !is.null(parsed[[on]]) ){
565            if ( !is.na(parsed[[on]]@code[1]) ){ # no code given for generics
566              doc$definition <- paste(parsed[[on]]@code)
567            }
568            if(!"description"%in%names(doc) && !is.na(parsed[[on]]@description) ){
569              doc$description <- parsed[[on]]@description
570            }
571            ## if ( "setMethodS3" == parsed[[on]]@created ){
572            ##   gen <- leadingS3generic(on,topenv())
573            ##   if ( 0 < length(gen) ){
574            ##     doc$.s3method <- gen$.s3method
575            ##     cat("S3method(",gen$.s3method[1],",",gen$.s3method[2],")\n",sep="")
576            ##   }
577            ## }
578          }
579          if("title" %in% names(doc) && !"description" %in% names(doc) ){
580            ## For short functions having both would duplicate, but a
581            ## description is required. Therefore automatically copy title
582            ## across to avoid errors at package build time.
583            doc$description <- doc$title
584          }
585          doc
586        }
587      extract.docs <- function(on){
588        res <- try({o <- objs[[on]]
589                    extract.docs.try(o, on)},FALSE)
590        if(class(res)=="try-error"){
591          cat("Failed to extract docs for: ",on,"\n\n")
592          list()
593        } else if(0 == length(res) && inherits(objs[[on]],"standardGeneric")){
594          NULL
595        } else if(0 == length(res) && "function" %in% class(o)
596                  && 1 == length(osource <- getSource(o))
597                  && grepl(paste("UseMethod(",on,")",sep="\""),osource)
598                  ){
599          ## phew - this should only pick up R.oo S3 generic definitions like:
600          ## attr(*, "source")= chr "function(...) UseMethod(\"select\")"
601          NULL
602        } else res
603      }
604      doc.names <- names(objs)
605      res <- sapply(doc.names,extract.docs,simplify=FALSE)
606      ## Special processing for S4 classes as they do not appear in normal ls()
607      for ( nn in names(parsed) ){
608        if ( parsed[[nn]]@created == "setClass" ){
609          S4class.docs <- extract.docs.setClass(parsed[[nn]])
610          docname <- paste(nn,"class",sep="-")
611          if ( is.null(res[[docname]]) ){
612            res[[docname]] <- S4class.docs
613            doc.names <- c(doc.names,docname)
614          } else {
615            stop(nn," appears as both S4 class and some other definition")
616          }
617        }
618      }
619      inherit.docs <- function(on){
620        in.res <- res[[on]]
621        if ( !is.null(parsed[[on]]) ){
622          for ( parent in parsed[[on]]@parent ){
623            if ( !is.na(parent) ){
624              if ( is.null(in.res) ){
625                in.res <- res[[parent]]
626              } else if ( parent %in% names(res) ){
627                parent.docs <- res[[parent]]
628                for ( nn in names(parent.docs) ){
629                  if ( !nn %in% names(in.res) ){
630                    in.res[[nn]] <- parent.docs[[nn]]
631                  }
632                }
633              }
634            }
635          }
636        }
637        invisible(in.res)
638      }
639      all.done <- FALSE
640      while ( !all.done ){
641        res1 <- sapply(doc.names,inherit.docs,simplify=FALSE)
642        all.done <- identical(res1,res)
643        res <- res1
644      }
645      ## now strip out any generics (which have value NULL in res):
646      res.not.null <- sapply(res,function(x){!is.null(x)})
647      if ( 0 < length(res.not.null) && length(res.not.null) < length(res) ){
648        res <- res[res.not.null]
649      }
650      res
651    ### named list of lists, one for each object to document.
652    }
653    
654    ### List of parsers to use by default with package.skeleton.dx.
655    default.parsers <-
656      c(extra.code.docs=extra.code.docs, ## TODO: cleanup!
657        sapply(forfun.parsers,forfun),
658        edit.package.file=function(desc,...){
659          in.details <- setdiff(colnames(desc),"Description")
660          details <- sprintf("%s: \\tab %s\\cr",in.details,desc[,in.details])
661          L <-
662            list(list(title=desc[,"Title"],
663                      description=desc[,"Description"],
664                      `tabular{ll}`=details))
665          names(L) <- paste(desc[,"Package"],"-package",sep="")
666          L
667        },
668        sapply(forall.parsers,forall)
669        )
670    
671  setClass("DocLink", # Link documentation among related functions  setClass("DocLink", # Link documentation among related functions
672  ### The \code{.DocLink} class provides the basis for hooking together  ### The \code{.DocLink} class provides the basis for hooking together
673  ### documentation of related classes/functions/objects. The aim is that  ### documentation of related classes/functions/objects. The aim is that
674  ### documentation sections missing from the child are  ### documentation sections missing from the child are inherited from
675    ### the parent class.
676           representation(name="character", ##<< name of object           representation(name="character", ##<< name of object
677                          created="character", ##<< how created                          created="character", ##<< how created
678                          parent="character", ##<< parent class or NA                          parent="character", ##<< parent class or NA
# Line 614  Line 707 
707      ## "prefix" lines will be used instead.      ## "prefix" lines will be used instead.
708      default.description <- NULL      default.description <- NULL
709      while ( start > last.end+1      while ( start > last.end+1
710             && 1 == length(grep(prefix,code[start-1],perl=TRUE)) ){             && grepl(prefix,code[start-1],perl=TRUE) ){
711        start <- start-1        start <- start-1
712      }      }
713      if ( start < chunks[[k]][1] ){      if ( start < chunks[[k]][1] ){
# Line 641  Line 734 
734        ## If the function definition is not embedded within the call, then        ## If the function definition is not embedded within the call, then
735        ## the parent is that function. Test whether the the third value        ## the parent is that function. Test whether the the third value
736        ## looks like a name and add it to parents if so.        ## looks like a name and add it to parents if so.
737        if ( 1 == length(grep("^[\\._\\w]+$",chars[3],perl=TRUE)) ){        if ( grepl("^[\\._\\w]+$",chars[3],perl=TRUE) ){
738          parent <- chars[3]          parent <- chars[3]
739        }        }
740        res[[object.name]] <- new("DocLink",name=object.name,        res[[object.name]] <- new("DocLink",name=object.name,
# Line 673  Line 766 
766        ## If the function definition is not embedded within the call, then        ## If the function definition is not embedded within the call, then
767        ## the parent is that function. Test whether the the fourth value        ## the parent is that function. Test whether the the fourth value
768        ## looks like a name and add it to parents if so.        ## looks like a name and add it to parents if so.
769        if ( 1 == length(grep("^[\\._\\w]+$",chars[4],perl=TRUE)) ){        if ( grepl("^[\\._\\w]+$",chars[4],perl=TRUE) ){
770          parent <- c(chars[4],parent)          parent <- c(chars[4],parent)
771        }        }
772        res[[object.name]] <- new("DocLink",name=object.name,        res[[object.name]] <- new("DocLink",name=object.name,
# Line 714  Line 807 
807    ## the same line or \code{### } comments at the beginning of the    ## the same line or \code{### } comments at the beginning of the
808    ## following line.    ## following line.
809    f.n <- paste(class.name,"class",sep="-")    f.n <- paste(class.name,"class",sep="-")
810    docs <- extract.docs.fun(chunk.source,f.n)    docs <- extract.xxx.chunks(chunk.source,f.n)
811      ## also apply source parsing functions that I separated out into
812      ## separate functions
813      docs <- combine(docs,lonely$prefixed.lines(chunk.source))
814      docs$title <- lonely$title.from.firstline(chunk.source)
815      ##details<<
816      ## If there is no explicit title on the first line of setClass, then
817      ## one is made up from the class name.
818      if ( 0 == length(docs$title) ){
819        docs$title <- list(title=paste(class.name,"S4 class"))
820      }
821    ##details<<    ##details<<
822    ## The class definition skeleton includes an \code{Objects from the Class}    ## The class definition skeleton includes an \code{Objects from the Class}
823    ## section, to which any \code{##details<<} documentation chunks are    ## section, to which any \code{##details<<} documentation chunks are
# Line 752  Line 855 
855  ### Additional arguments to pass to Parser Functions.  ### Additional arguments to pass to Parser Functions.
856   ){   ){
857    e <- new.env()    e <- new.env()
858    old <- options(keep.source=TRUE)    ## KMP 2011-03-09 fix problem with DocLink when inlinedocs ran on itself
859      ## Error in assignClassDef(Class, classDef, where) :
860      ##   Class "DocLink" has a locked definition in package "inlinedocs"
861      ## Traced to "where" argument in setClassDef which defaults to topenv()
862      ## which in turn is inlinedocs when processing inlinedocs package, hence
863      ## the clash. The following works (under R 2.12.2), so that the topenv()
864      ## now finds e before finding the inlinedocs environment.
865      old <- options(keep.source=TRUE,topLevelEnvironment=e)
866    on.exit(options(old))    on.exit(options(old))
867    exprs <- parse(text=code)    exprs <- parse(text=code)
868    for (i in exprs) eval(i, e)    ## TDH 2011-04-07 set this so that no warnings about creating a fake
869      ## package when we try to process S4 classes defined in code
870      e$.packageName <- "inlinedocs.processor"
871      for (i in exprs){
872        ## TDH 2011-04-07 Disable this tryCatch since it makes it harder
873        ##to debug errors/warnings in the evaluated code
874    
875        ##tryCatch({
876          eval(i, e)
877        ##},error=function(e){
878          ##print(e)
879        ##})
880      }
881    objs <- sapply(ls(e),get,e,simplify=FALSE)    objs <- sapply(ls(e),get,e,simplify=FALSE)
882    
883    docs <- list()    docs <- list()
884    
   # PhG: Automatically determine who is S3 methods  
   for (name in names(objs)) {  
     parts <- strsplit(name, ".", fixed = TRUE)[[1]]  
         l <- length(parts)  
         if (l > 1) {  
         for (i in 1:(l - 1)) {  
             # Look for a generic function (known by the system or defined  
             # in the package) that matches that part of the function name  
             generic <- paste(parts[1:i], collapse = ".")  
             if (any(generic %in% utils:::getKnownS3generics()) ||  
                 utils:::findGeneric(generic, e) != "") {  
                 object <- paste(parts[(i + 1):l], collapse = ".")  
                 docs[[name]]$s3method <- c(generic, object)  
                 break  
             }  
         }  
     }  
   }  
885    ## apply parsers in sequence to code and objs    ## apply parsers in sequence to code and objs
886    for(i in seq_along(parsers)){    for(i in seq_along(parsers)){
887      N <- names(parsers[i])      N <- names(parsers[i])
# Line 788  Line 892 
892      }      }
893      p <- parsers[[i]]      p <- parsers[[i]]
894      ## This is the argument list that each parser receives:      ## This is the argument list that each parser receives:
895      L <- p(code=code,objs=objs,docs=docs,...)      L <- p(code=code,objs=objs,docs=docs,env=e,...)
896      docs <- combine(docs,L)      docs <- combine(docs,L)
897    }    }
898      ## post-process to collapse all character vectors
899      for(i in seq_along(docs)){
900        for(j in seq_along(docs[[i]])){
901          if(names(docs[[i]])[j]!=".s3method")
902          docs[[i]][[j]] <- paste(docs[[i]][[j]],collapse="\n")
903        }
904      }
905    if(verbose)cat("\n")    if(verbose)cat("\n")
906    docs    docs
907  ### A list of extracted documentation from code.  ### A list of extracted documentation from code.
908  }  }
909    
910  extract.docs.file <- function  ### Names of Parser Functions that operate on the desc arg.
911    descfile.names <- c("author.from.description","edit.package.file")
912    
913    ### Names of Parser Functions that do NOT use the desc arg.
914    non.descfile.names <-
915      names(default.parsers)[!names(default.parsers)%in%descfile.names]
916    
917    ### Parsers that operate only on R code, independently of the
918    ### description file.
919    nondesc.parsers <- default.parsers[non.descfile.names]
920    
921    extract.docs.file <- structure(function
922  ### Apply all parsers relevant to extract info from just 1 code file.  ### Apply all parsers relevant to extract info from just 1 code file.
923  (f,  (f,
924  ### File name of R code to read and parse.  ### File name of R code to read and parse.
925   parsers=list(extra.code.docs,default.parsers$parsefun),   parsers=NULL,
926  ### Parser Functions to use to parse the code and extract  ### Parser Functions to use to parse the code and extract
927  ### documentation.  ### documentation.
928   ...   ...
929  ### Other arguments to pass to Parser Functions.  ### Other arguments to pass to Parser Functions.
930   ){   ){
931      if(is.null(parsers))parsers <- nondesc.parsers
932    apply.parsers(readLines(f),parsers,verbose=FALSE,...)    apply.parsers(readLines(f),parsers,verbose=FALSE,...)
933  }  },ex=function(){
934      f <- system.file("silly","R","silly.R",package="inlinedocs")
935      extract.docs.file(f)
936    })
937    

Legend:
Removed from v.115  
changed lines
  Added in v.307

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