SCM

SCM Repository

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

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

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

revision 142, Wed Oct 20 09:21:53 2010 UTC revision 352, Mon Apr 9 12:43:46 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      Sys.sleep(1/60) ## to make sure there is at least 1 second elapsed
41    
42      ## However, it will NOT generate Rd for files specified in
43      ## do.not.generate, if they DO exist already.
44      package.skeleton.dx("silly",parsers)
45      mtimes <- data.frame(old,new=file.info(Rd.paths)$mtime)
46      rownames(mtimes) <- Rd.files
47      mtimes$changed <- mtimes$old != mtimes$new
48      print(mtimes)
49      stopifnot(mtimes["silly-package.Rd","changed"]==FALSE)
50      stopifnot(mtimes["Silly-class.Rd","changed"]==FALSE)
51      stopifnot(mtimes["silly.example.Rd","changed"]==TRUE)
52    
53      unlink("silly",recursive=TRUE)
54      setwd(owd)
55    })
56    
57  ### combine lists or character strings  ### combine lists or character strings
58  combine <- function(x,y)UseMethod("combine")  combine <- function(x,y)UseMethod("combine")
59    
# Line 7  Line 63 
63    
64  ### combine lists by adding elements or adding to existing elements  ### combine lists by adding elements or adding to existing elements
65  combine.list <- function(x,y){  combine.list <- function(x,y){
66    toadd <- !names(y)%in%names(x)    toadd <- if(".overwrite"%in%names(y)){
67    toup <- names(y)[names(y)%in%names(x)]      y <- y[names(y)!=".overwrite"]
68        rep(TRUE,length(y))
69      }else{
70        !names(y)%in%names(x)
71      }
72      toup <- names(y)[!toadd]
73    x[names(y)[toadd]] <- y[toadd]    x[names(y)[toadd]] <- y[toadd]
74    for(up in toup)x[[up]] <- combine(x[[up]],y[[up]])    for(up in toup)x[[up]] <- combine(x[[up]],y[[up]])
75    return(x)    x
76  ### A list, same type as x, but with added elements from y.  ### A list, same type as x, but with added elements from y.
77  }  }
78    
79    
80    getSource <- function
81    ### Extract a function's source code.
82    (fun.obj
83    ### A function.
84     ) {
85          srcref <- attr(fun.obj, "srcref")
86          if (!is.null(srcref)) {
87            ##unlist(strsplit(as.character(srcref), "\n"))
88            as.character(srcref)
89          }
90          else attr(fun.obj, "source")
91    ### Source code lines as a character vector.
92    }
93    
94  ### Prefix for code comments used with grep and gsub.  ### Prefix for code comments used with grep and gsub.
95  prefix <- "^[ \t]*###[ \t]"  prefix <- "^[ \t]*###[ \t]*"
96    
97  decomment <- function  decomment <- function
98  ### 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 100 
100  (comments  (comments
101  ### Character vector of prefixed comment lines.  ### Character vector of prefixed comment lines.
102   ){   ){
103    paste(gsub(prefix,"",comments),collapse="\n")    gsub(prefix,"",comments)
104  ### String without prefixes or newlines.  ### String without prefixes or newlines.
105  }  }
106    
 ### For each object in the package that satisfies the criterion#  
 ## checked by subfun, parse source using FUN and return the resulting  
 ### documentation list.  
107  forall <- function  forall <- function
108    ### For each object in the package that satisfies the criterion
109    ### checked by subfun, parse source using FUN and return the resulting
110    ### documentation list.
111  (FUN,  (FUN,
112  ### Function to apply to each element in the package.  ### Function to apply to each element in the package.
113   subfun=function(x)TRUE   subfun=function(x)TRUE
# Line 41  Line 117 
117   ){   ){
118    FUN <- FUN    FUN <- FUN
119    f <- function(objs,docs,...){    f <- function(objs,docs,...){
120        if(length(objs)==0)return(list())
121      objs <- objs[sapply(objs,subfun)]      objs <- objs[sapply(objs,subfun)]
122      L <- list()      L <- list()
123      for(N in names(docs)){      on.exit(cat(sprintf("Parser Function failed on %s\n",N)))
124        for(N in union(names(docs),names(objs))){
125        o <- objs[[N]]        o <- objs[[N]]
126        L[[N]] <- FUN(src=attr(o,"source"),        L[[N]] <- FUN(src=getSource(o),
127                      name=N,objs=objs,o=o,docs=docs,doc=docs[[N]],...)                      name=N,objs=objs,o=o,docs=docs,doc=docs[[N]],...)
128      }      }
129        on.exit()## remove warning message
130      L      L
131    }    }
132    class(f) <- c("allfun","function")    class(f) <- c("allfun","function")
# Line 67  Line 146 
146  ### For each function in the package, do something.  ### For each function in the package, do something.
147  forfun <- function(FUN)forall(FUN,is.function)  forfun <- function(FUN)forall(FUN,is.function)
148    
149  examples.after.return <- function  kill.prefix.whitespace <- function
150  ### Get examples from inline definitions after return()  ### Figure out what the whitespace preceding the example code is, and
151  ### PhG: this does not work well! Think of these situations:  ### then delete that from every line.
152  ### 1) You have multiple return() in the code of your function,  (ex
153  ### 2) You have return() appearing is some example code, ...  ### character vector of example code lines.
154  ### I can hardly propose a hack here. The whole code of the function   ){
155  ### must be parsed, and one must determine which one is the last line    tlines <- gsub("\\s*","",ex)
156  ### of code that is actually executed.    ##tlines <- gsub("#.*","",tlines)
157  ###    prefixes <- unique(gsub("\\S.*","",ex[tlines!=""]))
 ### 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!  
 (src,name="",...) {  
   ## Look for the examples mark  
   m <- grep("^\\s*(##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  
   prefixes <- gsub("(\\s*).*","\\1",ex,perl=TRUE)[grep("\\w",ex)]  
158    FIND <- prefixes[which.min(nchar(prefixes))]    FIND <- prefixes[which.min(nchar(prefixes))]
159    ex <- sub(FIND,"",ex)    ## Eliminate leading tabulations or 2/4 spaces
160    ## Add an empty line before and after example    sub(FIND, "", ex)
161    ex <- c("", ex, "")  ### Character vector of code lines with preceding whitespace removed.
   ## Return examples and value  
   list(examples = paste(ex, collapse = "\n"), value = value)  
162  }  }
163    
164  prefixed.lines <- function(src,...){  prefixed.lines <- structure(function(src,...){
165  ### The primary mechanism of inline documentation is via consecutive  ### The primary mechanism of inline documentation is via consecutive
166  ### groups of lines matching the specified prefix regular expression  ### groups of lines matching the specified prefix regular expression
167  ### "\code{^### }" (i.e. lines beginning with "\code{### }") are  ### "\code{^### }" (i.e. lines beginning with "\code{### }") are
# Line 136  Line 177 
177    starts <- c(1,bounds+1)    starts <- c(1,bounds+1)
178    ends <- c(bounds,length(clines))    ends <- c(bounds,length(clines))
179    ## detect body of function using paren matching    ## detect body of function using paren matching
180    f <- function(ch)cumsum(nchar(gsub(sprintf("[^%s]",ch),"",src)))    code <- gsub("#.*","",src)
181      f <- function(ch)cumsum(nchar(gsub(sprintf("[^%s]",ch),"",code)))
182    parens <- f("(")-f(")")    parens <- f("(")-f(")")
183    body.begin <- which(diff(parens)<0 & parens[-1]==0)+2    body.begin <- which(diff(parens)<0 & parens[-1]==0)+2
184      if(length(body.begin)==0)body.begin <- 1 ## rare cases
185    is.arg <- function(){    is.arg <- function(){
186      0 == length(grep("^\\s*#",src[start-1],perl=TRUE)) &&      gres <- grep("^\\s*#",src[start-1],perl=TRUE)
187        start<=body.begin      0 == length(gres) && start<=body.begin
188      }      }
189    res <- list()    res <- list()
190    for(i in seq_along(starts)){    for(i in seq_along(starts)){
191      start <- clines[starts[i]]      start <- clines[starts[i]]
192      end <- clines[ends[i]]      end <- clines[ends[i]]
193      lab <- if(end+1==length(src))"value"      processed <- gsub("#.*","",gsub("[ }]","",src[(end+1):length(src)]))
194        lab <- if(all(processed==""))"value"
195      else if(start==2)"description"      else if(start==2)"description"
196      else if(is.arg()){      else if(is.arg()){
197        ##twutz: strip leading white spaces and brackets and ,        ##twutz: strip leading white spaces and brackets and ,
# Line 155  Line 199 
199        arg <- gsub("^([^=,]*)[=,].*", "\\1", arg)        arg <- gsub("^([^=,]*)[=,].*", "\\1", arg)
200        ##twutz: remove trailing whitespaces        ##twutz: remove trailing whitespaces
201        arg <- gsub("^([^ \t]*)([ \t]+)$","\\1",arg)        arg <- gsub("^([^ \t]*)([ \t]+)$","\\1",arg)
202        arg <- gsub("...", "\\dots", arg, fix = TRUE)        arg <- gsub("...", "\\dots", arg, fixed = TRUE)
203        paste("item{",arg,"}",sep="")        paste("item{",arg,"}",sep="")
204      } else {      } else {
205        next;        next;
# Line 163  Line 207 
207      res[[lab]] <- decomment(src[start:end])      res[[lab]] <- decomment(src[start:end])
208    }    }
209    res    res
210  }  },ex=function(){
211    test <- function
212  ### Parsers for each object/function that are constructed  ### the description
213  ### automatically. This is a named list, each element is a list of 2  (x,
214  ### elements: forfun/forall, then a parser function for an individual  ### the first argument
215  ### object.   y ##<< another argument
 forfun.parsers <-  
   list(prefixed.lines=prefixed.lines,  
        examples.after.return=examples.after.return,  
        ## Extract lots of info from normal functions.  
        parsefun=function(src,name,...){  
          extract.docs.fun(src,name)  
        },  
        ## title from first line of function def  
        title.from.firstline=function(src,name,code,...){  
          if(length(grep("#",src[1]))){  
            list(title=gsub("[^#]*#\\s*(.*)","\\1",src[1],perl=TRUE))  
          } else list()  
        },  
        ## PhG: it is tests/FUN.R!!! I would like more flexibility here  
        ## please, let me choose which dir to use for examples!  
        ## Get examples for FUN from the file tests/FUN.R  
        examples.from.testfile=function(name,...){  
          tsubdir <- getOption("inlinedocs.exdir")  
          if (is.null(tsubdir)) tsubdir <- "tests"       # Default value  
          tfile <- file.path("..",tsubdir,paste(name,".R",sep=""))  
          if(file.exists(tfile))  
            list(examples=paste(readLines(tfile),collapse="\n"))  
          else list()  
        },  
        definition.from.source=function(doc,src,...){  
          def <- doc$definition  
          if(is.null(def)||def=="")  
            list(definition=paste(src,collapse="\n"))  
          else list()  
        })  
   
 ### List of Parser Functions that can be applied to any object.  
 forall.parsers <-  
   list(## Fill in author from DESCRIPTION and titles.  
        author.from.description=function(desc,...){  
          list(author=desc[,"Maintainer"])  
        },  
        ## The format section sometimes causes problems, so erase it.  
        erase.format=function(...){  
          list(format="")  
        },  
        ## Convert the function name to a title.  
        title.from.name=function(name,doc,...){  
          if("title"%in%names(doc))list() else  
          list(title=gsub("[._]"," ",name))  
        },  
        ## PhG: here is what I propose for examples code in the 'ex' attribute  
        examples.in.attr =  function (name, o, ...) {  
          ex <- attr(o, "ex")  
          if (!is.null(ex)) {  
            ## Special case for code contained in a function  
            if (inherits(ex, "function")) {  
              ## If source is available, start from there  
              src <- attr(ex, "source")  
              if (!is.null(src)) {  
                ex <- src  
              } else { ## Use the body of the function  
                ex <- deparse(body(ex))  
              }  
              ## Eliminate leading and trailing code  
              ex <- ex[-c(1, length(ex))]  
              ## Eliminate leading tabulations or 2/4 spaces  
              ex <- sub("^\t|    |  ", "", ex)  
              ## Add an empty line before and after example  
              ex <- c("", ex, "")  
            }  
            list(examples = paste(ex, collapse = "\n"))  
          } else list()  
        })  
   
 ### List of parser functions that operate on single objects. This list  
 ### is useful for testing these functions.  
 lonely <- c(forall.parsers,forfun.parsers)  
 attr(lonely,"ex") <- function(){  
   lonely$parsefun(attr(extract.docs.file,"source"),"extract.docs.file")  
 }  
   
 extra.code.docs <- function # Extract documentation from code chunks  
 ### Parse R code to extract inline documentation from comments around  
 ### each function. These are not able to be retreived simply by  
 ### looking at the "source" attribute. This is a Parser Function that  
 ### can be used in the parser list of package.skeleton.dx(). TODO:  
 ### Modularize this into separate Parsers Functions for S4 classes,  
 ### prefixes, ##<<blocks, etc. Right now it is not very clean!  
 (code,  
 ### Code lines in a character vector containing multiple R objects to  
 ### parse for documentation.  
  objs,  
 ### The objects defined in the code.  
  ...  
 ### ignored  
  ){  
   parsed <- extract.file.parse(code)  
   extract.docs.try <- function(o,on)  
     {  
       ## Note: we could use parsed information here too, but that  
       ## would produce different results for setMethodS3 etc.  
       doc <- list()  
       if ( !is.null(parsed[[on]]) ){  
         if ( !is.na(parsed[[on]]@code[1]) ){ # no code given for generics  
           doc$definition <- paste(parsed[[on]]@code,collapse="\n")  
         }  
         if(!"description"%in%names(doc) && !is.na(parsed[[on]]@description) ){  
           doc$description <- parsed[[on]]@description  
         }  
         if ( "setMethodS3" == parsed[[on]]@created ){  
           # PhG: this may be wrong! It does not catch correctly how the method  
           # must be splitted in case of methods containing dots. for instance,  
           # as.data.frame.matrix must be split into: m1 = as.data.frame and  
           # m2 = matrix... here you got m1 = as, and m2 = data.frame.matrix!!!  
                   pattern <- "^([^\\.]+)\\.(.*)$"  
           doc$s3method=c(m1 <- gsub(pattern,"\\1",on,perl=TRUE),  
               m2 <- gsub(pattern,"\\2",on,perl=TRUE))  
           if ( 0 < length(grep("\\W",m1,perl=TRUE)) ){  
                           m1 <- paste("`",m1,"`",sep="")  
           }  
           cat("S3method(",m1,",",m2,")\n",sep="")  
         }  
       }  
       if("title" %in% names(doc) && !"description" %in% names(doc) ){  
         ## For short functions having both would duplicate, but a  
         ## description is required. Therefore automatically copy title  
         ## across to avoid errors at package build time.  
         doc$description <- doc$title  
       }  
       doc  
     }  
   extract.docs <- function(on){  
     res <- try({o <- objs[[on]]  
                 extract.docs.try(o, on)},FALSE)  
     if(class(res)=="try-error"){  
       cat("Failed to extract docs for: ",on,"\n\n")  
       list()  
     } else if(0 == length(res) && inherits(objs[[on]],"standardGeneric")){  
       NULL  
     } else if(0 == length(res) && "function" %in% class(o)  
               && 1 == length(osource <- attr(o,"source"))  
               && 1 == length(grep(paste("UseMethod(",on,")",sep="\""),osource))  
216                ){                ){
217        ## phew - this should only pick up R.oo S3 generic definitions like:    5
218        ## attr(*, "source")= chr "function(...) UseMethod(\"select\")"  ### the return value
219        NULL  ##seealso<< foobar
220      } else res  }
221    }  src <- getSource(test)
222    doc.names <- names(objs)  prefixed.lines(src)
223    res <- sapply(doc.names,extract.docs,simplify=FALSE)  extract.xxx.chunks(src)
   ## Special processing for S4 classes as they do not appear in normal ls()  
   for ( nn in names(parsed) ){  
     if ( parsed[[nn]]@created == "setClass" ){  
       S4class.docs <- extract.docs.setClass(parsed[[nn]])  
       docname <- paste(nn,"class",sep="-")  
       if ( is.null(res[[docname]]) ){  
         res[[docname]] <- S4class.docs  
         doc.names <- c(doc.names,docname)  
       } else {  
         stop(nn," appears as both S4 class and some other definition")  
       }  
     }  
   }  
   inherit.docs <- function(on){  
     in.res <- res[[on]]  
     if ( !is.null(parsed[[on]]) ){  
       for ( parent in parsed[[on]]@parent ){  
         if ( !is.na(parent) ){  
           if ( is.null(in.res) ){  
             in.res <- res[[parent]]  
           } else if ( parent %in% names(res) ){  
             parent.docs <- res[[parent]]  
             for ( nn in names(parent.docs) ){  
               if ( !nn %in% names(in.res) ){  
                 in.res[[nn]] <- parent.docs[[nn]]  
               }  
             }  
           }  
         }  
       }  
     }  
     invisible(in.res)  
   }  
   all.done <- FALSE  
   while ( !all.done ){  
     res1 <- sapply(doc.names,inherit.docs,simplify=FALSE)  
     all.done <- identical(res1,res)  
     res <- res1  
   }  
   ## now strip out any generics (which have value NULL in res):  
   res.not.null <- sapply(res,function(x){!is.null(x)})  
   if ( 0 < length(res.not.null) && length(res.not.null) < length(res) ){  
     res <- res[res.not.null]  
   }  
   res  
 ### named list of lists, one for each object to document.  
 }  
   
 ### List of parsers to use by default with package.skeleton.dx.  
 default.parsers <-  
   c(extra.code.docs=extra.code.docs, ## TODO: cleanup!  
     sapply(forfun.parsers,forfun),  
     sapply(forall.parsers,forall),  
     edit.package.file=function(desc,...){  
       in.details <- setdiff(colnames(desc),"Description")  
       details <- paste(paste(in.details,": \\tab ",desc[,in.details],"\\cr",  
                              sep=""),collapse="\n")  
       L <-  
         list(list(title=desc[,"Title"],  
                   description=desc[,"Description"],  
                   `tabular{ll}`=details,  
                   author=desc[,"Maintainer"]))  
       names(L) <- paste(desc[,"Package"],"-package",sep="")  
       L  
224      })      })
225    
226  extract.docs.fun <- function # Extract documentation from a function  extract.xxx.chunks <- function # Extract documentation from a function
227  ### Given source code of a function, return a list describing inline  ### Given source code of a function, return a list describing inline
228  ### documentation in that source code.  ### documentation in that source code.
229  (code,  (src,
230  ### The function to examine.  ### The source lines of the function to examine, as a character
231   name.fun  ### vector.
232     name.fun="(unnamed function)",
233  ### The name of the function/chunk to use in warning messages.  ### The name of the function/chunk to use in warning messages.
234     ...
235    ### ignored.
236   ){   ){
237    res <- list()    res <- list()
238    ##details<< For simple functions/arguments, the argument may also be    ##details<< For simple functions/arguments, the argument may also be
# Line 462  Line 307 
307          chunk.sep <- "\n\n"          chunk.sep <- "\n\n"
308        }        }
309        chunk.res <- NULL        chunk.res <- NULL
310        if ( 0 == length(grep("^\\s*$",payload,perl=TRUE)) )        if ( !grepl("^\\s*$",payload,perl=TRUE) )
311          chunk.res <-          chunk.res <-
312            if ( is.null(res[[field]]) ) payload            if ( is.null(res[[field]]) ) payload
313            else paste(res[[field]], payload, sep=chunk.sep)            else paste(res[[field]], payload, sep=chunk.sep)
314        invisible(chunk.res)        invisible(chunk.res)
315      }      }
316    while ( k <= length(code) ){    while ( k <= length(src) ){
317      line <- code[k]      line <- src[k]
318      if ( 0 < length(grep(extra.regexp,line,perl=TRUE) ) ){      ##print(line)
319        ##if(grepl("^$",line))browser()
320        if ( grepl(extra.regexp,line,perl=TRUE) ){
321        ## 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
322        new.field <- gsub(extra.regexp,"\\1",line,perl=TRUE)        new.field <- gsub(extra.regexp,"\\1",line,perl=TRUE)
323        new.contents <- gsub(extra.regexp,"\\2",line,perl=TRUE)        new.contents <- gsub(extra.regexp,"\\2",line,perl=TRUE)
324          ##cat(new.field,"\n-----\n",new.contents,"\n\n")
325        ##details<< As a special case, the construct \code{##describe<<} causes        ##details<< As a special case, the construct \code{##describe<<} causes
326        ## similar processing to the main function arguments to be        ## similar processing to the main function arguments to be
327        ## applied in order to construct a describe block within the        ## applied in order to construct a describe block within the
# Line 483  Line 330 
330        ## block until terminated by a subsequent \code{##}\emph{xxx}\code{<<} line.        ## block until terminated by a subsequent \code{##}\emph{xxx}\code{<<} line.
331        if ( "describe" == new.field ){        if ( "describe" == new.field ){
332          ##details<< Such regions may be nested, but not in such a way          ##details<< Such regions may be nested, but not in such a way
333          ## that the first element in a \code{describe} is another \code{describe}.          ## that the first element in a \code{describe} is another
334          ## Thus there must be at least one \code{##<<} comment between each          ## \code{describe}.  Thus there must be at least one
335          ## pair of \code{##describe<<} comments.          ## \code{##<<} comment between each pair of
336            ## \code{##describe<<} comments.
337          if ( first.describe ){          if ( first.describe ){
338            stop("consecutive ##describe<< at line",k,"in",name.fun)            stop("consecutive ##describe<< at line",k,"in",name.fun)
339          } else {          } else {
# Line 545  Line 393 
393            first.describe <- TRUE;            first.describe <- TRUE;
394          }          }
395        }        }
396      } else if ( in.chunk && 0<length(grep(cont.re,line,perl=TRUE)) ){      } else if ( in.chunk && grepl(cont.re,line,perl=TRUE) ){
397        ## append this line to current chunk        ## append this line to current chunk
398        if ( 0 == length(grep(prefix,line,perl=TRUE)) ){        if ( !grepl(prefix,line,perl=TRUE) ){
399          ##describe<< Any lines with "\code{### }" at the left hand          ##describe<< Any lines with "\code{### }" at the left hand
400          ## margin within the included chunks are handled separately,          ## margin within the included chunks are handled separately,
401          ## so if they appear in the documentation they will appear          ## so if they appear in the documentation they will appear
# Line 560  Line 408 
408            payload <- stripped            payload <- stripped
409          }          }
410        }        }
411      } else if ( 0 < length(grep(arg.pat,line,perl=TRUE)) ){      } else if ( grepl(arg.pat,line,perl=TRUE) ){
412        not.describe <- (0==in.describe && !first.describe)        not.describe <- (0==in.describe && !first.describe)
413        if ( in.chunk && not.describe){        if ( in.chunk && not.describe){
414          res[[cur.field]] <- end.chunk(cur.field,payload)          res[[cur.field]] <- end.chunk(cur.field,payload)
# Line 572  Line 420 
420          ## TDH 2010-06-18 For item{}s in the documentation list names,          ## TDH 2010-06-18 For item{}s in the documentation list names,
421          ## we don't need to have a backslash before, so delete it.          ## we don't need to have a backslash before, so delete it.
422          arg <- gsub("^[\\]+","",arg)          arg <- gsub("^[\\]+","",arg)
423          cur.field <- gsub("...","\\dots",arg,fix=TRUE) ##special case for dots          cur.field <- gsub("...","\\dots",arg,fixed=TRUE) ##special case for dots
424          payload <- comment          payload <- comment
425        } else {        } else {
426          ## 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 622  Line 470 
470  ### with the string in this list (implemented in modify.Rd.file).  ### with the string in this list (implemented in modify.Rd.file).
471  }  }
472    
473    leadingS3generic <- function # check whether function name is an S3 generic
474    ### Determines whether a function name looks like an S3 generic function
475    (name,                     ##<< name of function
476     env,                      ##<< environment to search for additional generics
477     ...)                      ##<< ignored here
478    {
479      ##details<< This function is one of the default parsers, but exposed as
480      ## possibly of more general interest. Given a function name of the form
481      ## x.y.z it looks for the generic function x applying to objects of class
482      ## y.z and also for generic function x.y applying to objects of class z.
483      ##
484      parts <- strsplit(name, ".", fixed = TRUE)[[1]]
485      l <- length(parts)
486      if (l > 1) {
487        for (i in 1:(l - 1)) {
488          ## Look for a generic function (known by the system or defined
489          ## in the package) that matches that part of the function name
490          generic <- paste(parts[1:i], collapse = ".")
491          if (any(generic %in% utils:::getKnownS3generics()) ||
492              utils:::findGeneric(generic, env) != "") {
493            object <- paste(parts[(i + 1):l], collapse = ".")
494            ##details<< Assumes that the first name which matches any known
495            ## generics is the target generic function, so if both x and x.y
496            ## are generic functions, will assume generic x applying to objects
497            ## of class y.z
498            ##value<< If a matching generic found returns a list with a single component:
499            return(list(.s3method=c(generic, object))) ##<< a character vector containing generic name and object name.
500          }
501        }
502      }
503      ##value<< If no matching generic functions are found, returns an empty list.
504      list()
505    }
506    
507    ### Parsers for each function that are constructed automatically. This
508    ### is a named list, and each element is a parser function for an
509    ### individual object.
510    forfun.parsers <-
511      list(prefixed.lines=prefixed.lines,
512           extract.xxx.chunks=extract.xxx.chunks,
513           ## title from first line of function def
514           title.from.firstline=function(src,...){
515             first <- src[1]
516             if(!is.character(first))return(list())
517             if(!grepl("#",first))return(list())
518             list(title=gsub("[^#]*#\\s*(.*)","\\1",first,perl=TRUE))
519           },
520           ## PhG: it is tests/FUN.R!!! I would like more flexibility here
521           ## please, let me choose which dir to use for examples!
522           ## Get examples for FUN from the file tests/FUN.R
523           examples.from.testfile=function(name,...){
524             tsubdir <- getOption("inlinedocs.exdir")
525             if (is.null(tsubdir)) tsubdir <- "tests"       # Default value
526             tfile <- file.path("..",tsubdir,paste(name,".R",sep=""))
527             if(file.exists(tfile))
528               list(examples=readLines(tfile))
529             else list()
530           },
531           definition.from.source=function(doc,src,...){
532             def <- doc$definition
533             is.empty <- function(x)is.null(x)||x==""
534             if(is.empty(def) && !is.empty(src))
535               list(definition=src)
536             else list()
537           })
538    
539    ### List of Parser Functions that can be applied to any object.
540    forall.parsers <-
541      list(## Fill in author from DESCRIPTION and titles.
542           author.from.description=function(desc,...){
543             list(author=desc[,"Author"])
544           },
545           ## The format section sometimes causes problems, so erase it.
546           erase.format=function(...){
547             list(format="")
548           },
549           ## Convert the function name to a title.
550           title.from.name=function(name,doc,...){
551             if("title"%in%names(doc))list() else
552             list(title=gsub("[._]"," ",name))
553           },
554           ## PhG: here is what I propose for examples code in the 'ex' attribute
555           examples.in.attr =  function (name, o, ...) {
556             ex <- attr(o, "ex")
557             if (!is.null(ex)) {
558               ## Special case for code contained in a function
559               if (inherits(ex, "function")) {
560                 ## If source is available, start from there
561                 src <- getSource(ex)
562                 if (!is.null(src)) {
563                   ex <- src
564                 } else { ## Use the body of the function
565                   ex <- deparse(body(ex))
566                 }
567                 ## Eliminate leading and trailing code
568                 ex <- ex[-c(1, length(ex))]
569                 if(ex[1]=="{")ex <- ex[-1]
570                 ## all the prefixes
571                 ex <- kill.prefix.whitespace(ex)
572                 ## Add an empty line before and after example
573                 ex <- c("", ex, "")
574               }
575               list(examples = ex)
576             } else list()
577           },collapse=function(doc,...){
578             L <- lapply(doc,paste,collapse="\n")
579             L$.overwrite <- TRUE
580             L
581           },tag.s3methods=leadingS3generic
582           )
583    
584    ### List of parser functions that operate on single objects. This list
585    ### is useful for testing these functions.
586    lonely <- structure(c(forall.parsers,forfun.parsers),ex=function(){
587      f <- function # title
588    ### description
589      (x, ##<< arg x
590       y
591    ### arg y
592       ){
593        ##value<< a list with elements
594        list(x=x, ##<< original x value
595             y=y, ##<< original y value
596             sum=x+y) ##<< their sum
597        ##end<<
598      }
599      src <- getSource(f)
600      lonely$extract.xxx.chunks(src)
601      lonely$prefixed.lines(src)
602    })
603    
604    extra.code.docs <- function # Extract documentation from code chunks
605    ### Parse R code to extract inline documentation from comments around
606    ### each function. These are not able to be retreived simply by
607    ### looking at the "source" attribute. This is a Parser Function that
608    ### can be used in the parser list of package.skeleton.dx(). TODO:
609    ### Modularize this into separate Parsers Functions for S4 classes,
610    ### prefixes, ##<<blocks, etc. Right now it is not very clean!
611    (code,
612    ### Code lines in a character vector containing multiple R objects to
613    ### parse for documentation.
614     objs,
615    ### The objects defined in the code.
616     ...
617    ### ignored
618     ){
619      parsed <- extract.file.parse(code)
620      extract.docs.try <- function(o,on)
621        {
622          ## Note: we could use parsed information here too, but that
623          ## would produce different results for setMethodS3 etc.
624          doc <- list()
625          if ( !is.null(parsed[[on]]) ){
626            if ( !is.na(parsed[[on]]@code[1]) ){ # no code given for generics
627              doc$definition <- paste(parsed[[on]]@code)
628            }
629            if(!"description"%in%names(doc) && !is.na(parsed[[on]]@description) ){
630              doc$description <- parsed[[on]]@description
631            }
632            ## if ( "setMethodS3" == parsed[[on]]@created ){
633            ##   gen <- leadingS3generic(on,topenv())
634            ##   if ( 0 < length(gen) ){
635            ##     doc$.s3method <- gen$.s3method
636            ##     cat("S3method(",gen$.s3method[1],",",gen$.s3method[2],")\n",sep="")
637            ##   }
638            ## }
639          }
640          if("title" %in% names(doc) && !"description" %in% names(doc) ){
641            ## For short functions having both would duplicate, but a
642            ## description is required. Therefore automatically copy title
643            ## across to avoid errors at package build time.
644            doc$description <- doc$title
645          }
646          doc
647        }
648      extract.docs <- function(on){
649        res <- try({o <- objs[[on]]
650                    extract.docs.try(o, on)},FALSE)
651        if(class(res)=="try-error"){
652          cat("Failed to extract docs for: ",on,"\n\n")
653          list()
654        } else if(0 == length(res) && inherits(objs[[on]],"standardGeneric")){
655          NULL
656        } else if(0 == length(res) && "function" %in% class(o)
657                  && 1 == length(osource <- getSource(o))
658                  && grepl(paste("UseMethod(",on,")",sep="\""),osource)
659                  ){
660          ## phew - this should only pick up R.oo S3 generic definitions like:
661          ## attr(*, "source")= chr "function(...) UseMethod(\"select\")"
662          NULL
663        } else res
664      }
665      doc.names <- names(objs)
666      res <- sapply(doc.names,extract.docs,simplify=FALSE)
667      ## Special processing for S4 classes as they do not appear in normal ls()
668      for ( nn in names(parsed) ){
669        if ( parsed[[nn]]@created == "setClass" ){
670          S4class.docs <- extract.docs.setClass(parsed[[nn]])
671          docname <- paste(nn,"class",sep="-")
672          if ( is.null(res[[docname]]) ){
673            res[[docname]] <- S4class.docs
674            doc.names <- c(doc.names,docname)
675          } else {
676            stop(nn," appears as both S4 class and some other definition")
677          }
678        }
679      }
680      inherit.docs <- function(on){
681        in.res <- res[[on]]
682        if ( !is.null(parsed[[on]]) ){
683          for ( parent in parsed[[on]]@parent ){
684            if ( !is.na(parent) ){
685              if ( is.null(in.res) ){
686                in.res <- res[[parent]]
687              } else if ( parent %in% names(res) ){
688                parent.docs <- res[[parent]]
689                for ( nn in names(parent.docs) ){
690                  if ( !nn %in% names(in.res) ){
691                    in.res[[nn]] <- parent.docs[[nn]]
692                  }
693                }
694              }
695            }
696          }
697        }
698        invisible(in.res)
699      }
700      all.done <- FALSE
701      while ( !all.done ){
702        res1 <- sapply(doc.names,inherit.docs,simplify=FALSE)
703        all.done <- identical(res1,res)
704        res <- res1
705      }
706      ## now strip out any generics (which have value NULL in res):
707      res.not.null <- sapply(res,function(x){!is.null(x)})
708      if ( 0 < length(res.not.null) && length(res.not.null) < length(res) ){
709        res <- res[res.not.null]
710      }
711      res
712    ### named list of lists, one for each object to document.
713    }
714    
715    ### List of parsers to use by default with package.skeleton.dx.
716    default.parsers <-
717      c(extra.code.docs=extra.code.docs, ## TODO: cleanup!
718        sapply(forfun.parsers,forfun),
719        edit.package.file=function(desc,...){
720          in.details <- setdiff(colnames(desc),"Description")
721          details <- sprintf("%s: \\tab %s\\cr",in.details,desc[,in.details])
722          L <-
723            list(list(title=desc[,"Title"],
724                      description=desc[,"Description"],
725                      `tabular{ll}`=details))
726          names(L) <- paste(desc[,"Package"],"-package",sep="")
727          L
728        },
729        sapply(forall.parsers,forall)
730        )
731    
732  setClass("DocLink", # Link documentation among related functions  setClass("DocLink", # Link documentation among related functions
733  ### The \code{.DocLink} class provides the basis for hooking together  ### The \code{.DocLink} class provides the basis for hooking together
734  ### documentation of related classes/functions/objects. The aim is that  ### documentation of related classes/functions/objects. The aim is that
735  ### documentation sections missing from the child are  ### documentation sections missing from the child are inherited from
736    ### the parent class.
737           representation(name="character", ##<< name of object           representation(name="character", ##<< name of object
738                          created="character", ##<< how created                          created="character", ##<< how created
739                          parent="character", ##<< parent class or NA                          parent="character", ##<< parent class or NA
# Line 660  Line 768 
768      ## "prefix" lines will be used instead.      ## "prefix" lines will be used instead.
769      default.description <- NULL      default.description <- NULL
770      while ( start > last.end+1      while ( start > last.end+1
771             && 1 == length(grep(prefix,code[start-1],perl=TRUE)) ){             && grepl(prefix,code[start-1],perl=TRUE) ){
772        start <- start-1        start <- start-1
773      }      }
774      if ( start < chunks[[k]][1] ){      if ( start < chunks[[k]][1] ){
# Line 687  Line 795 
795        ## If the function definition is not embedded within the call, then        ## If the function definition is not embedded within the call, then
796        ## the parent is that function. Test whether the the third value        ## the parent is that function. Test whether the the third value
797        ## looks like a name and add it to parents if so.        ## looks like a name and add it to parents if so.
798        if ( 1 == length(grep("^[\\._\\w]+$",chars[3],perl=TRUE)) ){        if ( grepl("^[\\._\\w]+$",chars[3],perl=TRUE) ){
799          parent <- chars[3]          parent <- chars[3]
800        }        }
801        res[[object.name]] <- new("DocLink",name=object.name,        res[[object.name]] <- new("DocLink",name=object.name,
# Line 719  Line 827 
827        ## If the function definition is not embedded within the call, then        ## If the function definition is not embedded within the call, then
828        ## the parent is that function. Test whether the the fourth value        ## the parent is that function. Test whether the the fourth value
829        ## looks like a name and add it to parents if so.        ## looks like a name and add it to parents if so.
830        if ( 1 == length(grep("^[\\._\\w]+$",chars[4],perl=TRUE)) ){        if ( grepl("^[\\._\\w]+$",chars[4],perl=TRUE) ){
831          parent <- c(chars[4],parent)          parent <- c(chars[4],parent)
832        }        }
833        res[[object.name]] <- new("DocLink",name=object.name,        res[[object.name]] <- new("DocLink",name=object.name,
# Line 760  Line 868 
868    ## the same line or \code{### } comments at the beginning of the    ## the same line or \code{### } comments at the beginning of the
869    ## following line.    ## following line.
870    f.n <- paste(class.name,"class",sep="-")    f.n <- paste(class.name,"class",sep="-")
871    docs <- extract.docs.fun(chunk.source,f.n)    docs <- extract.xxx.chunks(chunk.source,f.n)
872    ## also apply source parsing functions that I separated out into    ## also apply source parsing functions that I separated out into
873    ## separate functions    ## separate functions
874    docs <- combine(docs,lonely$prefixed.lines(chunk.source))    docs <- combine(docs,lonely$prefixed.lines(chunk.source))
875    docs$title <- lonely$title.from.firstline(chunk.source)    docs$title <- lonely$title.from.firstline(chunk.source)
876    ##details<<    ##details<<
877      ## If there is no explicit title on the first line of setClass, then
878      ## one is made up from the class name.
879      if ( 0 == length(docs$title) ){
880        docs$title <- list(title=paste(class.name,"S4 class"))
881      }
882      ##details<<
883    ## The class definition skeleton includes an \code{Objects from the Class}    ## The class definition skeleton includes an \code{Objects from the Class}
884    ## section, to which any \code{##details<<} documentation chunks are    ## section, to which any \code{##details<<} documentation chunks are
885    ## written. It is given a vanilla content if there are no specific    ## written. It is given a vanilla content if there are no specific
# Line 802  Line 916 
916  ### Additional arguments to pass to Parser Functions.  ### Additional arguments to pass to Parser Functions.
917   ){   ){
918    e <- new.env()    e <- new.env()
919    old <- options(keep.source=TRUE)    ## KMP 2011-03-09 fix problem with DocLink when inlinedocs ran on itself
920      ## Error in assignClassDef(Class, classDef, where) :
921      ##   Class "DocLink" has a locked definition in package "inlinedocs"
922      ## Traced to "where" argument in setClassDef which defaults to topenv()
923      ## which in turn is inlinedocs when processing inlinedocs package, hence
924      ## the clash. The following works (under R 2.12.2), so that the topenv()
925      ## now finds e before finding the inlinedocs environment.
926      old <- options(keep.source=TRUE,topLevelEnvironment=e)
927    on.exit(options(old))    on.exit(options(old))
928    exprs <- parse(text=code)    exprs <- parse(text=code)
929    for (i in exprs) eval(i, e)    ## TDH 2011-04-07 set this so that no warnings about creating a fake
930      ## package when we try to process S4 classes defined in code
931      e$.packageName <- "inlinedocs.processor"
932      for (i in exprs){
933          eval(i, e)
934      }
935    objs <- sapply(ls(e),get,e,simplify=FALSE)    objs <- sapply(ls(e),get,e,simplify=FALSE)
936    
937    docs <- list()    docs <- list()
938    
   # 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  
             }  
         }  
     }  
   }  
939    ## apply parsers in sequence to code and objs    ## apply parsers in sequence to code and objs
940      if(verbose)cat("Applying parsers:\n")
941    for(i in seq_along(parsers)){    for(i in seq_along(parsers)){
942      N <- names(parsers[i])      N <- names(parsers[i])
943      if(verbose){      if(verbose){
944        if(is.character(N) && N!=""){        if(is.character(N) && N!=""){
945          cat(N," ",sep="")          cat(N,"\n",sep="")
946        }else cat('. ')        }else cat('.\n')
947      }      }
948      p <- parsers[[i]]      p <- parsers[[i]]
949      ## This is the argument list that each parser receives:      ## This is the argument list that each parser receives:
950      L <- p(code=code,objs=objs,docs=docs,...)      L <- p(code=code,objs=objs,docs=docs,env=e,...)
951        #print(paste(L,"\n"))
952        #if(N=="exclude")browser()
953      docs <- combine(docs,L)      docs <- combine(docs,L)
954    }    }
955      ## post-process to collapse all character vectors
956      for(i in seq_along(docs)){
957        for(j in seq_along(docs[[i]])){
958          if(names(docs[[i]])[j]!=".s3method")
959          docs[[i]][[j]] <- paste(docs[[i]][[j]],collapse="\n")
960        }
961     }
962    if(verbose)cat("\n")    if(verbose)cat("\n")
963    docs    return(docs)
964  ### A list of extracted documentation from code.  ### A list of extracted documentation from code.
965  }  }
966    
# Line 857  Line 975 
975  ### description file.  ### description file.
976  nondesc.parsers <- default.parsers[non.descfile.names]  nondesc.parsers <- default.parsers[non.descfile.names]
977    
978  extract.docs.file <- function  extract.docs.file <- structure(function
979  ### Apply all parsers relevant to extract info from just 1 code file.  ### Apply all parsers relevant to extract info from just 1 code file.
980  (f,  (f,
981  ### File name of R code to read and parse.  ### File name of R code to read and parse.
982   parsers=nondesc.parsers,   parsers=NULL,
983  ### Parser Functions to use to parse the code and extract  ### Parser Functions to use to parse the code and extract
984  ### documentation.  ### documentation.
985   ...   ...
986  ### Other arguments to pass to Parser Functions.  ### Other arguments to pass to Parser Functions.
987   ){   ){
988      if(is.null(parsers))parsers <- nondesc.parsers
989    apply.parsers(readLines(f),parsers,verbose=FALSE,...)    apply.parsers(readLines(f),parsers,verbose=FALSE,...)
990  }  },ex=function(){
991      f <- system.file("silly","R","silly.R",package="inlinedocs")
992      extract.docs.file(f)
993    })
994    

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

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