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

Legend:
Removed from v.144  
changed lines
  Added in v.308

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