SCM

SCM Repository

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

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

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

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

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

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