SCM

SCM Repository

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

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

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

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

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

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