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 185, Thu Jan 13 16:08:14 2011 UTC
# Line 1  Line 1 
1    ### combine lists or character strings
2    combine <- function(x,y)UseMethod("combine")
3    
4    ### combine character strings by pasting them together
5    combine.character <- function(x,y)
6        paste(x,y,sep="\n")
7    
8    ### combine lists by adding elements or adding to existing elements
9    combine.list <- function(x,y){
10      toadd <- !names(y)%in%names(x)
11      toup <- names(y)[!toadd]
12      if("doc"%in%names(x))return(x$doc)
13      if("doc"%in%names(y))return(y$doc)
14      x[names(y)[toadd]] <- y[toadd]
15      for(up in toup)x[[up]] <- combine(x[[up]],y[[up]])
16      return(x)
17    ### A list, same type as x, but with added elements from y.
18    }
19    
20    ### Prefix for code comments used with grep and gsub.
21    prefix <- "^[ \t]*###[ \t]"
22    
23    decomment <- function
24    ### Remove comment prefix and join lines of code to form a
25    ### documentation string.
26    (comments
27    ### Character vector of prefixed comment lines.
28     ){
29      gsub(prefix,"",comments)
30    ### String without prefixes or newlines.
31    }
32    
33    forall <- function
34  ### For each object in the package that satisfies the criterion  ### For each object in the package that satisfies the criterion
35  ### checked by subfun, parse source using FUN and return the resulting  ### checked by subfun, parse source using FUN and return the resulting
36  ### documentation list.  ### documentation list.
 forall <- function  
37  (FUN,  (FUN,
38  ### Function to apply to each element in the package.  ### Function to apply to each element in the package.
39   subfun=function(x)TRUE   subfun=function(x)TRUE
# Line 9  Line 41 
41  ### 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
42  ### the result will be returned.  ### the result will be returned.
43   ){   ){
44    function(objs,docs,...){    FUN <- FUN
45      f <- function(objs,docs,...){
46      objs <- objs[sapply(objs,subfun)]      objs <- objs[sapply(objs,subfun)]
47      L <- list()      L <- list()
48        on.exit(cat(sprintf("Parser Function failed on %s\n",N)))
49      for(N in names(docs)){      for(N in names(docs)){
50        o <- objs[[N]]        o <- objs[[N]]
51        L[[N]] <- FUN(src=attr(o,"source"),        L[[N]] <- FUN(src=attr(o,"source"),
52                      name=N,objs=objs,o=o,docs=docs,doc=docs[[N]],...)                      name=N,objs=objs,o=o,docs=docs,doc=docs[[N]],...)
53      }      }
54        on.exit()## remove warning message
55      L      L
56    }    }
57      class(f) <- c("allfun","function")
58      f
59  ### A Parser Function.  ### A Parser Function.
60  }  }
61    
62  ### For each function in the package, do something.  ### Print method for functions constructed using forall.
63  forfun <- function(FUN)forall(FUN,is.function)  print.allfun <- function(x,...){
64      e <- environment(x)
65  ### Parsers for each object/function that are constructed    cat("Function to apply to every element.\nselector:")
66  ### automatically. This is a named list, each element is a list of 2    print(e$subfun)
67  ### elements: forfun/forall, then a parser function for an individual    cat("processor:")
68  ### object.    print(e$FUN)
 forall.parsers <-  
   list(## Extract lots of info from normal functions.  
        parsefun=list(forfun,function(src,name,...){  
          extract.docs.fun(src,name)  
        }),  
        ## Fill in author from DESCRIPTION and titles.  
        author.from.description=list(forall,function(desc,...){  
          list(author=desc[,"Maintainer"])  
        }),  
        ## The format section sometimes causes problems, so erase it.  
        erase.format=list(forall,function(...){  
          list(format="")  
        }),  
        ## Convert the function name to a title.  
        title.from.name=list(forall,function(name,doc,...){  
          if("title"%in%names(doc))list() else  
          list(title=gsub("[._]"," ",name))  
        }),  
        ## 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  
  ){  
   parsed <- extract.file.parse(code)  
   extract.docs.try <- function(o,on)  
     {  
       ## Note: we could use parsed information here too, but that  
       ## would produce different results for setMethodS3 etc.  
       doc <- list()  
       if ( !is.null(parsed[[on]]) ){  
         if ( !is.na(parsed[[on]]@code[1]) ){ # no code given for generics  
           doc$definition <- paste(parsed[[on]]@code,collapse="\n")  
         }  
         if(!"description"%in%names(doc) && !is.na(parsed[[on]]@description) ){  
           doc$description <- parsed[[on]]@description  
         }  
         if ( "setMethodS3" == parsed[[on]]@created ){  
           pattern <- "^([^\\.]+)\\.(.*)$"  
           doc$s3method=c(m1 <- gsub(pattern,"\\1",on,perl=TRUE),  
               m2 <- gsub(pattern,"\\2",on,perl=TRUE))  
           if ( 0 < length(grep("\\W",m1,perl=TRUE)) ){  
             m1 <- paste("`",m1,"`",sep="")  
           }  
           cat("S3method(",m1,",",m2,")\n",sep="")  
         }  
       }  
       if("title" %in% names(doc) && !"description" %in% names(doc) ){  
         ## For short functions having both would duplicate, but a  
         ## description is required. Therefore automatically copy title  
         ## across to avoid errors at package build time.  
         doc$description <- doc$title  
       }  
       doc  
     }  
   extract.docs <- function(on){  
     res <- try({o <- objs[[on]]  
                 extract.docs.try(o, on)},FALSE)  
     if(class(res)=="try-error"){  
       cat("Failed to extract docs for: ",on,"\n\n")  
       list()  
     } else if(0 == length(res) && inherits(objs[[on]],"standardGeneric")){  
       NULL  
     } else if(0 == length(res) && "function" %in% class(o)  
               && 1 == length(osource <- attr(o,"source"))  
               && 1 == length(grep(paste("UseMethod(",on,")",sep="\""),osource))  
               ){  
       ## 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.  
69  }  }
70    
71  ### List of parsers to use by default with package.skeleton.dx.  ### For each function in the package, do something.
72  default.parsers <- c(extract.docs.file=extract.docs.file,  forfun <- function(FUN)forall(FUN,is.function)
                      sapply(forall.parsers,function(L)L[[1]](L[[2]])))  
73    
74  extract.docs.fun <- function # Extract documentation from a function  kill.prefix.whitespace <- function
75  ### Given source code of a function, return a list describing inline  ### Figure out what the whitespace preceding the example code is, and
76  ### documentation in that source code.  ### then delete that from every line.
77  (code,  (ex
78  ### The function to examine.  ### character vector of example code lines.
  name.fun  
 ### The name of the function/chunk to use in warning messages.  
79   ){   ){
80    res <- list()    tlines <- gsub("\\s*","",ex)
81    clines <- grep(prefix,code)    ##tlines <- gsub("#.*","",tlines)
82    if(length(grep("#",code[1]))){    prefixes <- unique(gsub("\\S.*","",ex[tlines!=""]))
83      res$title <- gsub("[^#]*#\\s*(.*)","\\1",code[1],perl=TRUE)    FIND <- prefixes[which.min(nchar(prefixes))]
84    }    ## Eliminate leading tabulations or 2/4 spaces
85    if(length(clines) > 0){    sub(FIND, "", ex)
86      ##details<<  ### Character vector of code lines with preceding whitespace removed.
87      ## The primary mechanism is that consecutive groups of lines matching  }
88      ## the specified prefix regular expression "\code{^### }" (i.e. lines  
89      ## beginning with "\code{### }") are collected  examples.after.return <- function
90      ## as follows into documentation sections:\describe{  ### Get examples from inline definitions after return()
91      ## \item{description}{group starting at line 2 in the code}  ### PhG: this does not work well! Think of these situations:
92      ## \item{arguments}{group following each function argument}  ### 1) You have multiple return() in the code of your function,
93      ## \item{value}{group ending at the penultimate line of the code}}  ### 2) You have return() appearing is some example code, ...
94      ## These may be added to by use of the \code{##<<} constructs described  ### I can hardly propose a hack here. The whole code of the function
95      ## below.  ### must be parsed, and one must determine which one is the last line
96    ### of code that is actually executed.
97    ###
98    ### I make two propositions here
99    ### 1) to keep the same mechanism that has the advantage of simplicity
100    ###    but to use a special tag
101    ###    ##examples<< or #{{{examples to separate
102    ###    function code from examples explicitly, and
103    ### 2) to place the example in an "ex" attribute
104    ###    attached to the function
105    ###    (see next parser). That solution will be also interesting for
106    ###    documenting datasets, something not done yet by inlinedocs!
107    (src,name="",...) {
108      ## Look for the examples mark
109      m <- grep("^\\s*(##examples<<|#\\{\\{\\{examples)", src)
110      if (!length(m)) return(list())
111      if (length(m) > 1)
112        warning("More than one examples tag for ", name,
113                ". Taking the last one")
114      m <- m[length(m)]
115      ## Look for the lines containing return value comments just before
116      r <- grep("\\s*### ", src[1:(m-1)])
117        if (!length(r)) {
118          value <- NULL
119        } else {
120          ## Only take consecutive lines before the mark
121          keep <- rev((m - rev(r)) == 1:length(r))
122          if (!any(keep)) {
123            value <- NULL
124          } else {
125            value <- decomment(src[r[keep]])
126          }
127        }
128      ## Collect now the example code beneath the mark
129      ex <- src[(m + 1):(length(src) - 1)]
130      ## Possibly eliminate a #}}} tag
131      ex <- ex[!grepl("#}}}", ex)]
132      ## Eliminate leading tabulations or four spaces
133      ex <- kill.prefix.whitespace(ex)
134      ## Add an empty line before and after example
135      ex <- c("", ex, "")
136      ## Return examples and value
137      list(examples = ex, value = value)
138    }
139    
140    prefixed.lines <- structure(function(src,...){
141    ### The primary mechanism of inline documentation is via consecutive
142    ### groups of lines matching the specified prefix regular expression
143    ### "\code{^### }" (i.e. lines beginning with "\code{### }") are
144    ### collected as follows into documentation sections:\describe{
145    ### \item{description}{group starting at line 2 in the code}
146    ### \item{arguments}{group following each function argument}
147    ### \item{value}{group ending at the penultimate line of the code}}
148    ### These may be added to by use of the \code{##<<} constructs
149    ### described below.
150      clines <- grep(prefix,src)
151      if(length(clines)==0)return(list())
152      bounds <- which(diff(clines)!=1)      bounds <- which(diff(clines)!=1)
153      starts <- c(1,bounds+1)      starts <- c(1,bounds+1)
154      ends <- c(bounds,length(clines))      ends <- c(bounds,length(clines))
155      ## detect body of function using paren matching
156      code <- gsub("#.*","",src)
157      f <- function(ch)cumsum(nchar(gsub(sprintf("[^%s]",ch),"",code)))
158      parens <- f("(")-f(")")
159      body.begin <- which(diff(parens)<0 & parens[-1]==0)+2
160      if(length(body.begin)==0)body.begin <- 1 ## rare cases
161      is.arg <- function(){
162        gres <- grep("^\\s*#",src[start-1],perl=TRUE)
163        0 == length(gres) && start<=body.begin
164      }
165      res <- list()
166      for(i in seq_along(starts)){      for(i in seq_along(starts)){
167        start <- clines[starts[i]]        start <- clines[starts[i]]
168        end <- clines[ends[i]]        end <- clines[ends[i]]
169        lab <- if(end+1==length(code))"value"      lab <- if(all(grepl("^\\s*#",src[end:(length(src)-1)])))"value"
170        else if(start==2)"description"        else if(start==2)"description"
171        else if ( 0 == length(grep("^\\s*#",code[start-1],perl=TRUE)) ){      else if(is.arg()){
172           #arg <- gsub("^[ (]*","",code[start-1])        ##twutz: strip leading white spaces and brackets and ,
173           #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 ,  
174                   arg <- gsub("^([^=,]*)[=,].*", "\\1", arg)                   arg <- gsub("^([^=,]*)[=,].*", "\\1", arg)
175                   arg <- gsub("^([^ \t]*)([ \t]+)$","\\1",arg)   #twutz: remove trailing whitespaces        ##twutz: remove trailing whitespaces
176          arg <- gsub("^([^ \t]*)([ \t]+)$","\\1",arg)
177                   arg <- gsub("...", "\\dots", arg, fix = TRUE)                   arg <- gsub("...", "\\dots", arg, fix = TRUE)
178           paste("item{",arg,"}",sep="")           paste("item{",arg,"}",sep="")
179         } else {         } else {
180           next;           next;
181         }         }
182        res[[lab]] <- decomment(code[start:end])      res[[lab]] <- decomment(src[start:end])
     }  
183    }    }
184      res
185    },ex=function(){
186    test <- function
187    ### the desc
188    (x,
189    ### the first argument
190     y ##<< another argument
191     ){
192      5
193    ### the return value
194    ##seealso<< foobar
195    }
196    src <- attr(test,"source")
197    prefixed.lines(src)
198    extract.xxx.chunks(src)
199    })
200    
201    extract.xxx.chunks <- function # Extract documentation from a function
202    ### Given source code of a function, return a list describing inline
203    ### documentation in that source code.
204    (src,
205    ### The source lines of the function to examine, as a character
206    ### vector.
207     name.fun="(unnamed function)",
208    ### The name of the function/chunk to use in warning messages.
209     ...
210    ### ignored.
211     ){
212      res <- list()
213    ##details<< For simple functions/arguments, the argument may also be    ##details<< For simple functions/arguments, the argument may also be
214    ## documented by appending \code{##<<} comments on the same line as the    ## documented by appending \code{##<<} comments on the same line as the
215    ## argument name. Mixing this mechanism with \code{###} comment lines for    ## argument name. Mixing this mechanism with \code{###} comment lines for
# Line 324  Line 288 
288            else paste(res[[field]], payload, sep=chunk.sep)            else paste(res[[field]], payload, sep=chunk.sep)
289        invisible(chunk.res)        invisible(chunk.res)
290      }      }
291    while ( k <= length(code) ){    while ( k <= length(src) ){
292      line <- code[k]      line <- src[k]
293      if ( 0 < length(grep(extra.regexp,line,perl=TRUE) ) ){      if ( 0 < length(grep(extra.regexp,line,perl=TRUE) ) ){
294        ## 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
295        new.field <- gsub(extra.regexp,"\\1",line,perl=TRUE)        new.field <- gsub(extra.regexp,"\\1",line,perl=TRUE)
# Line 425  Line 389 
389        arg <- gsub(arg.pat,"\\\\item\\{\\1\\}",line,perl=TRUE)        arg <- gsub(arg.pat,"\\\\item\\{\\1\\}",line,perl=TRUE)
390        in.chunk <- TRUE        in.chunk <- TRUE
391        if ( not.describe ){        if ( not.describe ){
392            ## TDH 2010-06-18 For item{}s in the documentation list names,
393            ## we don't need to have a backslash before, so delete it.
394            arg <- gsub("^[\\]+","",arg)
395          cur.field <- gsub("...","\\dots",arg,fix=TRUE) ##special case for dots          cur.field <- gsub("...","\\dots",arg,fix=TRUE) ##special case for dots
396          payload <- comment          payload <- comment
397        } else {        } else {
# Line 475  Line 442 
442  ### with the string in this list (implemented in modify.Rd.file).  ### with the string in this list (implemented in modify.Rd.file).
443  }  }
444    
445    ### Parsers for each function that are constructed automatically. This
446    ### is a named list, and each element is a parser function for an
447    ### individual object.
448    forfun.parsers <-
449      list(prefixed.lines=prefixed.lines,
450           examples.after.return=examples.after.return,
451           extract.xxx.chunks=extract.xxx.chunks,
452           ## title from first line of function def
453           title.from.firstline=function(src,name,code,...){
454             if(length(grep("#",src[1]))){
455               list(title=gsub("[^#]*#\\s*(.*)","\\1",src[1],perl=TRUE))
456             } else list()
457           },
458           ## PhG: it is tests/FUN.R!!! I would like more flexibility here
459           ## please, let me choose which dir to use for examples!
460           ## Get examples for FUN from the file tests/FUN.R
461           examples.from.testfile=function(name,...){
462             tsubdir <- getOption("inlinedocs.exdir")
463             if (is.null(tsubdir)) tsubdir <- "tests"       # Default value
464             tfile <- file.path("..",tsubdir,paste(name,".R",sep=""))
465             if(file.exists(tfile))
466               list(examples=readLines(tfile))
467             else list()
468           },
469           definition.from.source=function(doc,src,...){
470             def <- doc$definition
471             is.empty <- function(x)is.null(x)||x==""
472             if(is.empty(def) && !is.empty(src))
473               list(definition=src)
474             else list()
475           })
476    
477    ### List of Parser Functions that can be applied to any object.
478    forall.parsers <-
479      list(## Fill in author from DESCRIPTION and titles.
480           author.from.description=function(desc,...){
481             list(author=desc[,"Maintainer"])
482           },
483           ## The format section sometimes causes problems, so erase it.
484           erase.format=function(...){
485             list(format="")
486           },
487           ## Convert the function name to a title.
488           title.from.name=function(name,doc,...){
489             if("title"%in%names(doc))list() else
490             list(title=gsub("[._]"," ",name))
491           },
492           ## PhG: here is what I propose for examples code in the 'ex' attribute
493           examples.in.attr =  function (name, o, ...) {
494             ex <- attr(o, "ex")
495             if (!is.null(ex)) {
496               ## Special case for code contained in a function
497               if (inherits(ex, "function")) {
498                 ## If source is available, start from there
499                 src <- attr(ex, "source")
500                 if (!is.null(src)) {
501                   ex <- src
502                 } else { ## Use the body of the function
503                   ex <- deparse(body(ex))
504                 }
505                 ## Eliminate leading and trailing code
506                 ex <- ex[-c(1, length(ex))]
507                 ## all the prefixes
508                 ex <- kill.prefix.whitespace(ex)
509                 ## Add an empty line before and after example
510                 ex <- c("", ex, "")
511               }
512               list(examples = ex)
513             } else list()
514           },
515           collapse.docs=function(doc,...){
516             list(doc=lapply(doc,paste,collapse="\n"))
517           })
518    
519    ### List of parser functions that operate on single objects. This list
520    ### is useful for testing these functions.
521    lonely <- c(forall.parsers,forfun.parsers)
522    attr(lonely,"ex") <- function(){
523      f <- function # title
524    ### description
525      (x, ##<< arg x
526       y
527    ### arg y
528       ){
529        ##value<< a list with elements
530        list(x=x, ##<< original x value
531             y=y, ##<< original y value
532             sum=x+y) ##<< their sum
533        ##end<<
534      }
535      src <- attr(f,"source")
536      lonely$extract.xxx.chunks(src)
537      lonely$prefixed.lines(src)
538    }
539    
540    extra.code.docs <- function # Extract documentation from code chunks
541    ### Parse R code to extract inline documentation from comments around
542    ### each function. These are not able to be retreived simply by
543    ### looking at the "source" attribute. This is a Parser Function that
544    ### can be used in the parser list of package.skeleton.dx(). TODO:
545    ### Modularize this into separate Parsers Functions for S4 classes,
546    ### prefixes, ##<<blocks, etc. Right now it is not very clean!
547    (code,
548    ### Code lines in a character vector containing multiple R objects to
549    ### parse for documentation.
550     objs,
551    ### The objects defined in the code.
552     ...
553    ### ignored
554     ){
555      parsed <- extract.file.parse(code)
556      extract.docs.try <- function(o,on)
557        {
558          ## Note: we could use parsed information here too, but that
559          ## would produce different results for setMethodS3 etc.
560          doc <- list()
561          if ( !is.null(parsed[[on]]) ){
562            if ( !is.na(parsed[[on]]@code[1]) ){ # no code given for generics
563              doc$definition <- paste(parsed[[on]]@code)
564            }
565            if(!"description"%in%names(doc) && !is.na(parsed[[on]]@description) ){
566              doc$description <- parsed[[on]]@description
567            }
568            if ( "setMethodS3" == parsed[[on]]@created ){
569              # PhG: this may be wrong! It does not catch correctly how the method
570              # must be splitted in case of methods containing dots. for instance,
571              # as.data.frame.matrix must be split into: m1 = as.data.frame and
572              # m2 = matrix... here you got m1 = as, and m2 = data.frame.matrix!!!
573                      pattern <- "^([^\\.]+)\\.(.*)$"
574              doc$s3method=c(m1 <- gsub(pattern,"\\1",on,perl=TRUE),
575                  m2 <- gsub(pattern,"\\2",on,perl=TRUE))
576              if ( 0 < length(grep("\\W",m1,perl=TRUE)) ){
577                              m1 <- paste("`",m1,"`",sep="")
578              }
579              cat("S3method(",m1,",",m2,")\n",sep="")
580            }
581          }
582          if("title" %in% names(doc) && !"description" %in% names(doc) ){
583            ## For short functions having both would duplicate, but a
584            ## description is required. Therefore automatically copy title
585            ## across to avoid errors at package build time.
586            doc$description <- doc$title
587          }
588          doc
589        }
590      extract.docs <- function(on){
591        res <- try({o <- objs[[on]]
592                    extract.docs.try(o, on)},FALSE)
593        if(class(res)=="try-error"){
594          cat("Failed to extract docs for: ",on,"\n\n")
595          list()
596        } else if(0 == length(res) && inherits(objs[[on]],"standardGeneric")){
597          NULL
598        } else if(0 == length(res) && "function" %in% class(o)
599                  && 1 == length(osource <- attr(o,"source"))
600                  && 1 == length(grep(paste("UseMethod(",on,")",sep="\""),osource))
601                  ){
602          ## phew - this should only pick up R.oo S3 generic definitions like:
603          ## attr(*, "source")= chr "function(...) UseMethod(\"select\")"
604          NULL
605        } else res
606      }
607      doc.names <- names(objs)
608      res <- sapply(doc.names,extract.docs,simplify=FALSE)
609      ## Special processing for S4 classes as they do not appear in normal ls()
610      for ( nn in names(parsed) ){
611        if ( parsed[[nn]]@created == "setClass" ){
612          S4class.docs <- extract.docs.setClass(parsed[[nn]])
613          docname <- paste(nn,"class",sep="-")
614          if ( is.null(res[[docname]]) ){
615            res[[docname]] <- S4class.docs
616            doc.names <- c(doc.names,docname)
617          } else {
618            stop(nn," appears as both S4 class and some other definition")
619          }
620        }
621      }
622      inherit.docs <- function(on){
623        in.res <- res[[on]]
624        if ( !is.null(parsed[[on]]) ){
625          for ( parent in parsed[[on]]@parent ){
626            if ( !is.na(parent) ){
627              if ( is.null(in.res) ){
628                in.res <- res[[parent]]
629              } else if ( parent %in% names(res) ){
630                parent.docs <- res[[parent]]
631                for ( nn in names(parent.docs) ){
632                  if ( !nn %in% names(in.res) ){
633                    in.res[[nn]] <- parent.docs[[nn]]
634                  }
635                }
636              }
637            }
638          }
639        }
640        invisible(in.res)
641      }
642      all.done <- FALSE
643      while ( !all.done ){
644        res1 <- sapply(doc.names,inherit.docs,simplify=FALSE)
645        all.done <- identical(res1,res)
646        res <- res1
647      }
648      ## now strip out any generics (which have value NULL in res):
649      res.not.null <- sapply(res,function(x){!is.null(x)})
650      if ( 0 < length(res.not.null) && length(res.not.null) < length(res) ){
651        res <- res[res.not.null]
652      }
653      res
654    ### named list of lists, one for each object to document.
655    }
656    
657    ### List of parsers to use by default with package.skeleton.dx.
658    default.parsers <-
659      c(extra.code.docs=extra.code.docs, ## TODO: cleanup!
660        sapply(forfun.parsers,forfun),
661        sapply(forall.parsers,forall),
662        edit.package.file=function(desc,...){
663          in.details <- setdiff(colnames(desc),"Description")
664          details <- sprintf("%s: \\tab %s\\cr",in.details,desc[,in.details])
665          L <-
666            list(list(title=desc[,"Title"],
667                      description=desc[,"Description"],
668                      `tabular{ll}`=details,
669                      author=desc[,"Maintainer"]))
670          names(L) <- paste(desc[,"Package"],"-package",sep="")
671          L
672        })
673    
674  setClass("DocLink", # Link documentation among related functions  setClass("DocLink", # Link documentation among related functions
675  ### The \code{.DocLink} class provides the basis for hooking together  ### The \code{.DocLink} class provides the basis for hooking together
676  ### documentation of related classes/functions/objects. The aim is that  ### documentation of related classes/functions/objects. The aim is that
# Line 613  Line 809 
809    ## the same line or \code{### } comments at the beginning of the    ## the same line or \code{### } comments at the beginning of the
810    ## following line.    ## following line.
811    f.n <- paste(class.name,"class",sep="-")    f.n <- paste(class.name,"class",sep="-")
812    docs <- extract.docs.fun(chunk.source,f.n)    docs <- extract.xxx.chunks(chunk.source,f.n)
813      ## also apply source parsing functions that I separated out into
814      ## separate functions
815      docs <- combine(docs,lonely$prefixed.lines(chunk.source))
816      docs$title <- lonely$title.from.firstline(chunk.source)
817    ##details<<    ##details<<
818    ## The class definition skeleton includes an \code{Objects from the Class}    ## The class definition skeleton includes an \code{Objects from the Class}
819    ## section, to which any \code{##details<<} documentation chunks are    ## section, to which any \code{##details<<} documentation chunks are
# Line 637  Line 837 
837    }    }
838    invisible(docs)    invisible(docs)
839  }  }
840    
841    apply.parsers <- function
842    ### Parse code to r objs, then run all the parsers and return the
843    ### documentation list.
844    (code,
845    ### Character vector of code lines.
846     parsers=default.parsers,
847    ### List of Parser Functions.
848     verbose=FALSE,
849    ### Echo names of Parser Functions?
850     ...
851    ### Additional arguments to pass to Parser Functions.
852     ){
853      e <- new.env()
854      old <- options(keep.source=TRUE)
855      on.exit(options(old))
856      exprs <- parse(text=code)
857      for (i in exprs){
858        tryCatch(eval(i, e),error=function(e){
859          ##print(e)
860        })
861      }
862      objs <- sapply(ls(e),get,e,simplify=FALSE)
863    
864      docs <- list()
865    
866      # PhG: Automatically determine who is S3 methods
867      for (name in names(objs)) {
868        parts <- strsplit(name, ".", fixed = TRUE)[[1]]
869            l <- length(parts)
870            if (l > 1) {
871            for (i in 1:(l - 1)) {
872                # Look for a generic function (known by the system or defined
873                # in the package) that matches that part of the function name
874                generic <- paste(parts[1:i], collapse = ".")
875                if (any(generic %in% utils:::getKnownS3generics()) ||
876                    utils:::findGeneric(generic, e) != "") {
877                    object <- paste(parts[(i + 1):l], collapse = ".")
878                    docs[[name]]$s3method <- c(generic, object)
879                    break
880                }
881            }
882        }
883      }
884      ## apply parsers in sequence to code and objs
885      for(i in seq_along(parsers)){
886        N <- names(parsers[i])
887        if(verbose){
888          if(is.character(N) && N!=""){
889            cat(N," ",sep="")
890          }else cat('. ')
891        }
892        p <- parsers[[i]]
893        ## This is the argument list that each parser receives:
894        L <- p(code=code,objs=objs,docs=docs,...)
895        docs <- combine(docs,L)
896      }
897      if(verbose)cat("\n")
898      docs
899    ### A list of extracted documentation from code.
900    }
901    
902    ### Names of Parser Functions that operate on the desc arg.
903    descfile.names <- c("author.from.description","edit.package.file")
904    
905    ### Names of Parser Functions that do NOT use the desc arg.
906    non.descfile.names <-
907      names(default.parsers)[!names(default.parsers)%in%descfile.names]
908    
909    ### Parsers that operate only on R code, independently of the
910    ### description file.
911    nondesc.parsers <- default.parsers[non.descfile.names]
912    
913    extract.docs.file <- function
914    ### Apply all parsers relevant to extract info from just 1 code file.
915    (f,
916    ### File name of R code to read and parse.
917     parsers=nondesc.parsers,
918    ### Parser Functions to use to parse the code and extract
919    ### documentation.
920     ...
921    ### Other arguments to pass to Parser Functions.
922     ){
923      apply.parsers(readLines(f),parsers,verbose=FALSE,...)
924    }

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

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