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

Legend:
Removed from v.104  
changed lines
  Added in v.393

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