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 105, Tue May 18 17:32:43 2010 UTC revision 159, Tue Nov 9 16:42:39 2010 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  ### For each object in the package that satisfies the criterion  ### For each object in the package that satisfies the criterion
32  ### checked by subfun, parse source using FUN and return the resulting  ### checked by subfun, parse source using FUN and return the resulting
33  ### documentation list.  ### documentation list.
# 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(docs)){      for(N in names(docs)){
# Line 19  Line 50 
50      }      }
51      L      L
52    }    }
53      class(f) <- c("allfun","function")
54      f
55  ### A Parser Function.  ### A Parser Function.
56  }  }
57    
58    ### Print method for functions constructed using forall.
59    print.allfun <- function(x,...){
60      e <- environment(x)
61      cat("Function to apply to every element.\nselector:")
62      print(e$subfun)
63      cat("processor:")
64      print(e$FUN)
65    }
66    
67  ### For each function in the package, do something.  ### For each function in the package, do something.
68  forfun <- function(FUN)forall(FUN,is.function)  forfun <- function(FUN)forall(FUN,is.function)
69    
70  ### Parsers for each object/function that are constructed  examples.after.return <- function
71  ### automatically. This is a named list, each element is a list of 2  ### Get examples from inline definitions after return()
72  ### elements: forfun/forall, then a parser function for an individual  ### PhG: this does not work well! Think of these situations:
73  ### object.  ### 1) You have multiple return() in the code of your function,
74  forall.parsers <-  ### 2) You have return() appearing is some example code, ...
75    list(## Extract lots of info from normal functions.  ### I can hardly propose a hack here. The whole code of the function
76         parsefun=list(forfun,function(src,name,...){  ### must be parsed, and one must determine which one is the last line
77           extract.docs.fun(src,name)  ### of code that is actually executed.
78         }),  ###
79         ## Fill in author from DESCRIPTION and titles.  ### I make two propositions here
80         author.from.description=list(forall,function(desc,...){  ### 1) to keep the same mechanism that has the advantage of simplicity
81           list(author=desc[,"Maintainer"])  ###    but to use a special tag
82         }),  ###    ##examples<< or #{{{examples to separate
83         ## The format section sometimes causes problems, so erase it.  ###    function code from examples explicitly, and
84         erase.format=list(forall,function(...){  ### 2) to place the example in an "ex" attribute
85           list(format="")  ###    attached to the function
86         }),  ###    (see next parser). That solution will be also interesting for
87         ## Convert the function name to a title.  ###    documenting datasets, something not done yet by inlinedocs!
88         title.from.name=list(forall,function(name,doc,...){  (src,name="",...) {
89           if("title"%in%names(doc))list() else    ## Look for the examples mark
90           list(title=gsub("[._]"," ",name))    m <- grep("^\\s*(##examples<<|#\\{\\{\\{examples)", src)
91         }),    if (!length(m)) return(list())
92         ## Get examples for FUN from the file test/FUN.R    if (length(m) > 1)
93         examples.from.testfile=list(forfun,function(name,...){      warning("More than one examples tag for ", name,
94           tfile <- file.path("..","tests",paste(name,".R",sep=""))              ". Taking the last one")
95           if(file.exists(tfile))    m <- m[length(m)]
96             list(examples=paste(readLines(tfile),collapse="\n"))    ## Look for the lines containing return value comments just before
97           else list()    r <- grep("\\s*### ", src[1:(m-1)])
98         }),      if (!length(r)) {
99         ## Get examples from inline definitions after return()        value <- NULL
100         examples.after.return=list(forfun,function(name,src,...){      } else {
101           coll <- paste(src,collapse="\n")        ## Only take consecutive lines before the mark
102           thispre <- gsub("^[\\^]","",prefix)        keep <- rev((m - rev(r)) == 1:length(r))
103           FIND <- paste("(return|UseMethod)[(][^\\n]*\\n",thispre,sep="")        if (!any(keep)) {
104           m <- regexpr(FIND,coll)          value <- NULL
105           if(m[1]==-1)return(list())        } else {
106           after <- substr(coll,m[1],nchar(coll))          value <- decomment(src[r[keep]])
107           FIND <-        }
108             paste("[^\\n]*",# rest of the return line      }
109                   "((?:\\n###[^\\n]*)+)",#comment value lines \\1    ## Collect now the example code beneath the mark
110                   "([\\w\\W]*)[}]",#examples \\2    ex <- src[(m + 1):(length(src) - 1)]
111                   sep="")    ## Possibly eliminate a #}}} tag
112           SEP <- "-/-/-/-/-=====-----"    ex <- ex[!grepl("#}}}", ex)]
113           REP <- paste("\\1",SEP,"\\2",sep="")    ## Eliminate leading tabulations or four spaces
114           r <- strsplit(gsub(FIND,REP,after,perl=TRUE),split=SEP)[[1]]    prefixes <- gsub("(\\s*).*","\\1",ex,perl=TRUE)[grep("\\w",ex)]
          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)]  
115           FIND <- prefixes[which.min(nchar(prefixes))]           FIND <- prefixes[which.min(nchar(prefixes))]
116           list(examples=paste(sub(FIND,"",excode),collapse="\n"),    ex <- sub(FIND,"",ex)
117                value=decomment(l[[1]][-1]))    ## Add an empty line before and after example
118         }))    ex <- c("", ex, "")
119      ## Return examples and value
120  ### List of parser functions that operate on single objects. This list    list(examples = paste(ex, collapse = "\n"), value = value)
121  ### is useful for testing these functions, ie  }
122  ### lonely$parsefun(attr(extract.docs.file,"source"),"extract.docs.file")  
123  lonely <- sapply(forall.parsers,function(L)L[[2]])  prefixed.lines <- function(src,...){
124    ### The primary mechanism of inline documentation is via consecutive
125  extract.docs.file <- function # Extract documentation from a file  ### groups of lines matching the specified prefix regular expression
126  ### Parse R code to extract inline documentation from comments around  ### "\code{^### }" (i.e. lines beginning with "\code{### }") are
127  ### each function. These are not able to be retreived simply by  ### collected as follows into documentation sections:\describe{
128  ### looking at the "source" attribute. This is a Parser Function that  ### \item{description}{group starting at line 2 in the code}
129  ### can be used in the parser list of package.skeleton.dx().  ### \item{arguments}{group following each function argument}
130  (code,  ### \item{value}{group ending at the penultimate line of the code}}
131  ### Code lines in a character vector containing multiple R objects to  ### These may be added to by use of the \code{##<<} constructs
132  ### parse for documentation.  ### described below.
133   objs,    clines <- grep(prefix,src)
134  ### The objects defined in the code.    if(length(clines)==0)return(list())
  ...  
 ### 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.  
 }  
   
 ### List of parsers to use by default with package.skeleton.dx.  
 default.parsers <- c(extract.docs.file=extract.docs.file,  
                      sapply(forall.parsers,function(L)L[[1]](L[[2]])))  
   
 extract.docs.fun <- function # Extract documentation from a function  
 ### Given source code of a function, return a list describing inline  
 ### documentation in that source code.  
 (code,  
 ### The function to examine.  
  name.fun  
 ### The name of the function/chunk to use in warning messages.  
  ){  
   res <- list()  
   clines <- grep(prefix,code)  
   if(length(grep("#",code[1]))){  
     res$title <- gsub("[^#]*#\\s*(.*)","\\1",code[1],perl=TRUE)  
   }  
   if(length(clines) > 0){  
     ##details<<  
     ## The primary mechanism is that consecutive groups of lines matching  
     ## the specified prefix regular expression "\code{^### }" (i.e. lines  
     ## beginning with "\code{### }") are collected  
     ## as follows into documentation sections:\describe{  
     ## \item{description}{group starting at line 2 in the code}  
     ## \item{arguments}{group following each function argument}  
     ## \item{value}{group ending at the penultimate line of the code}}  
     ## These may be added to by use of the \code{##<<} constructs described  
     ## below.  
135      bounds <- which(diff(clines)!=1)      bounds <- which(diff(clines)!=1)
136      starts <- c(1,bounds+1)      starts <- c(1,bounds+1)
137      ends <- c(bounds,length(clines))      ends <- c(bounds,length(clines))
138      ## detect body of function using paren matching
139      code <- gsub("#.*","",src)
140      f <- function(ch)cumsum(nchar(gsub(sprintf("[^%s]",ch),"",code)))
141      parens <- f("(")-f(")")
142      body.begin <- which(diff(parens)<0 & parens[-1]==0)+2
143      is.arg <- function(){
144        gres <- grep("^\\s*#",src[start-1],perl=TRUE)
145        0 == length(gres) && start<=body.begin
146      }
147      res <- list()
148      for(i in seq_along(starts)){      for(i in seq_along(starts)){
149        start <- clines[starts[i]]        start <- clines[starts[i]]
150        end <- clines[ends[i]]        end <- clines[ends[i]]
151        lab <- if(end+1==length(code))"value"      lab <- if(end+1==length(src))"value"
152        else if(start==2)"description"        else if(start==2)"description"
153        else if ( 0 == length(grep("^\\s*#",code[start-1],perl=TRUE)) ){      else if(is.arg()){
154           #arg <- gsub("^[ (]*","",code[start-1])        ##twutz: strip leading white spaces and brackets and ,
155           #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 ,  
156                   arg <- gsub("^([^=,]*)[=,].*", "\\1", arg)                   arg <- gsub("^([^=,]*)[=,].*", "\\1", arg)
157                   arg <- gsub("^([^ \t]*)([ \t]+)$","\\1",arg)   #twutz: remove trailing whitespaces        ##twutz: remove trailing whitespaces
158          arg <- gsub("^([^ \t]*)([ \t]+)$","\\1",arg)
159                   arg <- gsub("...", "\\dots", arg, fix = TRUE)                   arg <- gsub("...", "\\dots", arg, fix = TRUE)
160           paste("item{",arg,"}",sep="")           paste("item{",arg,"}",sep="")
161         } else {         } else {
162           next;           next;
163         }         }
164        res[[lab]] <- decomment(code[start:end])      res[[lab]] <- decomment(src[start:end])
165      }      }
166      res
167    }    }
168    
169    extract.xxx.chunks <- function # Extract documentation from a function
170    ### Given source code of a function, return a list describing inline
171    ### documentation in that source code.
172    (src,
173    ### The source lines of the function to examine, as a character
174    ### vector.
175     name.fun="(unnamed function)",
176    ### The name of the function/chunk to use in warning messages.
177     ...
178    ### ignored.
179     ){
180      res <- list()
181    ##details<< For simple functions/arguments, the argument may also be    ##details<< For simple functions/arguments, the argument may also be
182    ## documented by appending \code{##<<} comments on the same line as the    ## documented by appending \code{##<<} comments on the same line as the
183    ## argument name. Mixing this mechanism with \code{###} comment lines for    ## argument name. Mixing this mechanism with \code{###} comment lines for
# Line 324  Line 256 
256            else paste(res[[field]], payload, sep=chunk.sep)            else paste(res[[field]], payload, sep=chunk.sep)
257        invisible(chunk.res)        invisible(chunk.res)
258      }      }
259    while ( k <= length(code) ){    while ( k <= length(src) ){
260      line <- code[k]      line <- src[k]
261      if ( 0 < length(grep(extra.regexp,line,perl=TRUE) ) ){      if ( 0 < length(grep(extra.regexp,line,perl=TRUE) ) ){
262        ## 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
263        new.field <- gsub(extra.regexp,"\\1",line,perl=TRUE)        new.field <- gsub(extra.regexp,"\\1",line,perl=TRUE)
# Line 425  Line 357 
357        arg <- gsub(arg.pat,"\\\\item\\{\\1\\}",line,perl=TRUE)        arg <- gsub(arg.pat,"\\\\item\\{\\1\\}",line,perl=TRUE)
358        in.chunk <- TRUE        in.chunk <- TRUE
359        if ( not.describe ){        if ( not.describe ){
360            ## TDH 2010-06-18 For item{}s in the documentation list names,
361            ## we don't need to have a backslash before, so delete it.
362            arg <- gsub("^[\\]+","",arg)
363          cur.field <- gsub("...","\\dots",arg,fix=TRUE) ##special case for dots          cur.field <- gsub("...","\\dots",arg,fix=TRUE) ##special case for dots
364          payload <- comment          payload <- comment
365        } else {        } else {
# Line 475  Line 410 
410  ### with the string in this list (implemented in modify.Rd.file).  ### with the string in this list (implemented in modify.Rd.file).
411  }  }
412    
413    ### Parsers for each function that are constructed automatically. This
414    ### is a named list, and each element is a parser function for an
415    ### individual object.
416    forfun.parsers <-
417      list(prefixed.lines=prefixed.lines,
418           examples.after.return=examples.after.return,
419           extract.xxx.chunks=extract.xxx.chunks,
420           ## title from first line of function def
421           title.from.firstline=function(src,name,code,...){
422             if(length(grep("#",src[1]))){
423               list(title=gsub("[^#]*#\\s*(.*)","\\1",src[1],perl=TRUE))
424             } else list()
425           },
426           ## PhG: it is tests/FUN.R!!! I would like more flexibility here
427           ## please, let me choose which dir to use for examples!
428           ## Get examples for FUN from the file tests/FUN.R
429           examples.from.testfile=function(name,...){
430             tsubdir <- getOption("inlinedocs.exdir")
431             if (is.null(tsubdir)) tsubdir <- "tests"       # Default value
432             tfile <- file.path("..",tsubdir,paste(name,".R",sep=""))
433             if(file.exists(tfile))
434               list(examples=paste(readLines(tfile),collapse="\n"))
435             else list()
436           },
437           definition.from.source=function(doc,src,...){
438             def <- doc$definition
439             is.empty <- function(x)is.null(x)||x==""
440             if(is.empty(def) && !is.empty(src))
441               list(definition=paste(src,collapse="\n"))
442             else list()
443           })
444    
445    ### List of Parser Functions that can be applied to any object.
446    forall.parsers <-
447      list(## Fill in author from DESCRIPTION and titles.
448           author.from.description=function(desc,...){
449             list(author=desc[,"Maintainer"])
450           },
451           ## The format section sometimes causes problems, so erase it.
452           erase.format=function(...){
453             list(format="")
454           },
455           ## Convert the function name to a title.
456           title.from.name=function(name,doc,...){
457             if("title"%in%names(doc))list() else
458             list(title=gsub("[._]"," ",name))
459           },
460           ## PhG: here is what I propose for examples code in the 'ex' attribute
461           examples.in.attr =  function (name, o, ...) {
462             ex <- attr(o, "ex")
463             if (!is.null(ex)) {
464               ## Special case for code contained in a function
465               if (inherits(ex, "function")) {
466                 ## If source is available, start from there
467                 src <- attr(ex, "source")
468                 if (!is.null(src)) {
469                   ex <- src
470                 } else { ## Use the body of the function
471                   ex <- deparse(body(ex))
472                 }
473                 ## Eliminate leading and trailing code
474                 ex <- ex[-c(1, length(ex))]
475                 ## Eliminate leading tabulations or 2/4 spaces
476                 ex <- sub("^\t|    |  ", "", ex)
477                 ## Add an empty line before and after example
478                 ex <- c("", ex, "")
479               }
480               list(examples = paste(ex, collapse = "\n"))
481             } else list()
482           })
483    
484    ### List of parser functions that operate on single objects. This list
485    ### is useful for testing these functions.
486    lonely <- c(forall.parsers,forfun.parsers)
487    attr(lonely,"ex") <- function(){
488      f <- function # title
489    ### description
490      (x, ##<< arg x
491       y
492    ### arg y
493       ){
494        ##value<< a list with elements
495        list(x=x, ##<< original x value
496             y=y, ##<< original y value
497             sum=x+y) ##<< their sum
498        ##end<<
499      }
500      src <- attr(f,"source")
501      lonely$extract.xxx.chunks(src)
502      lonely$prefixed.lines(src)
503    }
504    
505    extra.code.docs <- function # Extract documentation from code chunks
506    ### Parse R code to extract inline documentation from comments around
507    ### each function. These are not able to be retreived simply by
508    ### looking at the "source" attribute. This is a Parser Function that
509    ### can be used in the parser list of package.skeleton.dx(). TODO:
510    ### Modularize this into separate Parsers Functions for S4 classes,
511    ### prefixes, ##<<blocks, etc. Right now it is not very clean!
512    (code,
513    ### Code lines in a character vector containing multiple R objects to
514    ### parse for documentation.
515     objs,
516    ### The objects defined in the code.
517     ...
518    ### ignored
519     ){
520      parsed <- extract.file.parse(code)
521      extract.docs.try <- function(o,on)
522        {
523          ## Note: we could use parsed information here too, but that
524          ## would produce different results for setMethodS3 etc.
525          doc <- list()
526          if ( !is.null(parsed[[on]]) ){
527            if ( !is.na(parsed[[on]]@code[1]) ){ # no code given for generics
528              doc$definition <- paste(parsed[[on]]@code,collapse="\n")
529            }
530            if(!"description"%in%names(doc) && !is.na(parsed[[on]]@description) ){
531              doc$description <- parsed[[on]]@description
532            }
533            if ( "setMethodS3" == parsed[[on]]@created ){
534              # PhG: this may be wrong! It does not catch correctly how the method
535              # must be splitted in case of methods containing dots. for instance,
536              # as.data.frame.matrix must be split into: m1 = as.data.frame and
537              # m2 = matrix... here you got m1 = as, and m2 = data.frame.matrix!!!
538                      pattern <- "^([^\\.]+)\\.(.*)$"
539              doc$s3method=c(m1 <- gsub(pattern,"\\1",on,perl=TRUE),
540                  m2 <- gsub(pattern,"\\2",on,perl=TRUE))
541              if ( 0 < length(grep("\\W",m1,perl=TRUE)) ){
542                              m1 <- paste("`",m1,"`",sep="")
543              }
544              cat("S3method(",m1,",",m2,")\n",sep="")
545            }
546          }
547          if("title" %in% names(doc) && !"description" %in% names(doc) ){
548            ## For short functions having both would duplicate, but a
549            ## description is required. Therefore automatically copy title
550            ## across to avoid errors at package build time.
551            doc$description <- doc$title
552          }
553          doc
554        }
555      extract.docs <- function(on){
556        res <- try({o <- objs[[on]]
557                    extract.docs.try(o, on)},FALSE)
558        if(class(res)=="try-error"){
559          cat("Failed to extract docs for: ",on,"\n\n")
560          list()
561        } else if(0 == length(res) && inherits(objs[[on]],"standardGeneric")){
562          NULL
563        } else if(0 == length(res) && "function" %in% class(o)
564                  && 1 == length(osource <- attr(o,"source"))
565                  && 1 == length(grep(paste("UseMethod(",on,")",sep="\""),osource))
566                  ){
567          ## phew - this should only pick up R.oo S3 generic definitions like:
568          ## attr(*, "source")= chr "function(...) UseMethod(\"select\")"
569          NULL
570        } else res
571      }
572      doc.names <- names(objs)
573      res <- sapply(doc.names,extract.docs,simplify=FALSE)
574      ## Special processing for S4 classes as they do not appear in normal ls()
575      for ( nn in names(parsed) ){
576        if ( parsed[[nn]]@created == "setClass" ){
577          S4class.docs <- extract.docs.setClass(parsed[[nn]])
578          docname <- paste(nn,"class",sep="-")
579          if ( is.null(res[[docname]]) ){
580            res[[docname]] <- S4class.docs
581            doc.names <- c(doc.names,docname)
582          } else {
583            stop(nn," appears as both S4 class and some other definition")
584          }
585        }
586      }
587      inherit.docs <- function(on){
588        in.res <- res[[on]]
589        if ( !is.null(parsed[[on]]) ){
590          for ( parent in parsed[[on]]@parent ){
591            if ( !is.na(parent) ){
592              if ( is.null(in.res) ){
593                in.res <- res[[parent]]
594              } else if ( parent %in% names(res) ){
595                parent.docs <- res[[parent]]
596                for ( nn in names(parent.docs) ){
597                  if ( !nn %in% names(in.res) ){
598                    in.res[[nn]] <- parent.docs[[nn]]
599                  }
600                }
601              }
602            }
603          }
604        }
605        invisible(in.res)
606      }
607      all.done <- FALSE
608      while ( !all.done ){
609        res1 <- sapply(doc.names,inherit.docs,simplify=FALSE)
610        all.done <- identical(res1,res)
611        res <- res1
612      }
613      ## now strip out any generics (which have value NULL in res):
614      res.not.null <- sapply(res,function(x){!is.null(x)})
615      if ( 0 < length(res.not.null) && length(res.not.null) < length(res) ){
616        res <- res[res.not.null]
617      }
618      res
619    ### named list of lists, one for each object to document.
620    }
621    
622    ### List of parsers to use by default with package.skeleton.dx.
623    default.parsers <-
624      c(extra.code.docs=extra.code.docs, ## TODO: cleanup!
625        sapply(forfun.parsers,forfun),
626        sapply(forall.parsers,forall),
627        edit.package.file=function(desc,...){
628          in.details <- setdiff(colnames(desc),"Description")
629          details <- paste(paste(in.details,": \\tab ",desc[,in.details],"\\cr",
630                                 sep=""),collapse="\n")
631          L <-
632            list(list(title=desc[,"Title"],
633                      description=desc[,"Description"],
634                      `tabular{ll}`=details,
635                      author=desc[,"Maintainer"]))
636          names(L) <- paste(desc[,"Package"],"-package",sep="")
637          L
638        })
639    
640  setClass("DocLink", # Link documentation among related functions  setClass("DocLink", # Link documentation among related functions
641  ### The \code{.DocLink} class provides the basis for hooking together  ### The \code{.DocLink} class provides the basis for hooking together
642  ### documentation of related classes/functions/objects. The aim is that  ### documentation of related classes/functions/objects. The aim is that
# Line 613  Line 775 
775    ## the same line or \code{### } comments at the beginning of the    ## the same line or \code{### } comments at the beginning of the
776    ## following line.    ## following line.
777    f.n <- paste(class.name,"class",sep="-")    f.n <- paste(class.name,"class",sep="-")
778    docs <- extract.docs.fun(chunk.source,f.n)    docs <- extract.xxx.chunks(chunk.source,f.n)
779      ## also apply source parsing functions that I separated out into
780      ## separate functions
781      docs <- combine(docs,lonely$prefixed.lines(chunk.source))
782      docs$title <- lonely$title.from.firstline(chunk.source)
783    ##details<<    ##details<<
784    ## The class definition skeleton includes an \code{Objects from the Class}    ## The class definition skeleton includes an \code{Objects from the Class}
785    ## section, to which any \code{##details<<} documentation chunks are    ## section, to which any \code{##details<<} documentation chunks are
# Line 638  Line 804 
804    invisible(docs)    invisible(docs)
805  }  }
806    
807  extract.docs.code <- function  apply.parsers <- function
808  ### Write code to a file and parse it to r objs, then run all the  ### Parse code to r objs, then run all the parsers and return the
809  ### parsers and return the documentation list.  ### documentation list.
810  (code,  (code,
811  ### Character vector of code lines.  ### Character vector of code lines.
812   parsers,   parsers=default.parsers,
813  ### List of Parser Functions.  ### List of Parser Functions.
814   verbose=TRUE,   verbose=FALSE,
815  ### Echo names of Parser Functions?  ### Echo names of Parser Functions?
816   ...   ...
817  ### Additional arguments to pass to Parser Functions.  ### Additional arguments to pass to Parser Functions.
818   ){   ){
   code.file <- tempfile()  
   writeLines(code,code.file)  
819    e <- new.env()    e <- new.env()
820    old <- options(keep.source.pkgs=TRUE)    old <- options(keep.source=TRUE)
821    tryCatch(suppressWarnings(sys.source(code.file,e)),error=function(e){    on.exit(options(old))
822      stop("source ",code.file," failed with error:\n",e)    exprs <- parse(text=code)
823      for (i in exprs){
824        tryCatch(eval(i, e),error=function(e){
825          ##print(e)
826    })    })
827    options(old)    }
828    objs <- sapply(ls(e),get,e,simplify=FALSE)    objs <- sapply(ls(e),get,e,simplify=FALSE)
829    
   ## apply parsers in sequence to code and objs  
830    docs <- list()    docs <- list()
831    
832      # PhG: Automatically determine who is S3 methods
833      for (name in names(objs)) {
834        parts <- strsplit(name, ".", fixed = TRUE)[[1]]
835            l <- length(parts)
836            if (l > 1) {
837            for (i in 1:(l - 1)) {
838                # Look for a generic function (known by the system or defined
839                # in the package) that matches that part of the function name
840                generic <- paste(parts[1:i], collapse = ".")
841                if (any(generic %in% utils:::getKnownS3generics()) ||
842                    utils:::findGeneric(generic, e) != "") {
843                    object <- paste(parts[(i + 1):l], collapse = ".")
844                    docs[[name]]$s3method <- c(generic, object)
845                    break
846                }
847            }
848        }
849      }
850      ## apply parsers in sequence to code and objs
851    for(i in seq_along(parsers)){    for(i in seq_along(parsers)){
852      N <- names(parsers[i])      N <- names(parsers[i])
853      if(verbose){      if(verbose){
# Line 678  Line 864 
864    docs    docs
865  ### A list of extracted documentation from code.  ### A list of extracted documentation from code.
866  }  }
867    
868    ### Names of Parser Functions that operate on the desc arg.
869    descfile.names <- c("author.from.description","edit.package.file")
870    
871    ### Names of Parser Functions that do NOT use the desc arg.
872    non.descfile.names <-
873      names(default.parsers)[!names(default.parsers)%in%descfile.names]
874    
875    ### Parsers that operate only on R code, independently of the
876    ### description file.
877    nondesc.parsers <- default.parsers[non.descfile.names]
878    
879    extract.docs.file <- function
880    ### Apply all parsers relevant to extract info from just 1 code file.
881    (f,
882    ### File name of R code to read and parse.
883     parsers=nondesc.parsers,
884    ### Parser Functions to use to parse the code and extract
885    ### documentation.
886     ...
887    ### Other arguments to pass to Parser Functions.
888     ){
889      apply.parsers(readLines(f),parsers,verbose=FALSE,...)
890    }

Legend:
Removed from v.105  
changed lines
  Added in v.159

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