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 304, Tue Jul 19 17:03:18 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 <- if(".overwrite"%in%names(y)){
11        y <- y[names(y)!=".overwrite"]
12        rep(TRUE,length(y))
13      }else{
14        !names(y)%in%names(x)
15      }
16      toup <- names(y)[!toadd]
17      x[names(y)[toadd]] <- y[toadd]
18      for(up in toup)x[[up]] <- combine(x[[up]],y[[up]])
19      x
20    ### A list, same type as x, but with added elements from y.
21    }
22    
23    
24    getSource <- function
25    ### Extract a function's source code.
26    (fun.obj
27    ### A function.
28     ) {
29          srcref <- attr(fun.obj, "srcref")
30          if (!is.null(srcref)) unlist(strsplit(as.character(srcref), "\n"))
31          else attr(fun.obj, "source")
32    ### Source code lines as a character vector.
33    }
34    
35    ### Prefix for code comments used with grep and gsub.
36    prefix <- "^[ \t]*###[ \t]*"
37    
38    decomment <- function
39    ### Remove comment prefix and join lines of code to form a
40    ### documentation string.
41    (comments
42    ### Character vector of prefixed comment lines.
43     ){
44      gsub(prefix,"",comments)
45    ### String without prefixes or newlines.
46    }
47    
48    forall <- function
49  ### For each object in the package that satisfies the criterion  ### For each object in the package that satisfies the criterion
50  ### checked by subfun, parse source using FUN and return the resulting  ### checked by subfun, parse source using FUN and return the resulting
51  ### documentation list.  ### documentation list.
 forall <- function  
52  (FUN,  (FUN,
53  ### Function to apply to each element in the package.  ### Function to apply to each element in the package.
54   subfun=function(x)TRUE   subfun=function(x)TRUE
# Line 9  Line 56 
56  ### 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
57  ### the result will be returned.  ### the result will be returned.
58   ){   ){
59    function(objs,docs,...){    FUN <- FUN
60      f <- function(objs,docs,...){
61        if(length(objs)==0)return(list())
62      objs <- objs[sapply(objs,subfun)]      objs <- objs[sapply(objs,subfun)]
63      L <- list()      L <- list()
64      for(N in names(docs)){      on.exit(cat(sprintf("Parser Function failed on %s\n",N)))
65        for(N in union(names(docs),names(objs))){
66        o <- objs[[N]]        o <- objs[[N]]
67        L[[N]] <- FUN(src=attr(o,"source"),        L[[N]] <- FUN(src=getSource(o),
68                      name=N,objs=objs,o=o,docs=docs,doc=docs[[N]],...)                      name=N,objs=objs,o=o,docs=docs,doc=docs[[N]],...)
69      }      }
70        on.exit()## remove warning message
71      L      L
72    }    }
73      class(f) <- c("allfun","function")
74      f
75  ### A Parser Function.  ### A Parser Function.
76  }  }
77    
78  ### For each function in the package, do something.  ### Print method for functions constructed using forall.
79  forfun <- function(FUN)forall(FUN,is.function)  print.allfun <- function(x,...){
80      e <- environment(x)
81  ### Parsers for each object/function that are constructed    cat("Function to apply to every element.\nselector:")
82  ### automatically. This is a named list, each element is a list of 2    print(e$subfun)
83  ### elements: forfun/forall, then a parser function for an individual    cat("processor:")
84  ### 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.  
85  }  }
86    
87  ### List of parsers to use by default with package.skeleton.dx.  ### For each function in the package, do something.
88  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]])))  
89    
90  extract.docs.fun <- function # Extract documentation from a function  kill.prefix.whitespace <- function
91  ### Given source code of a function, return a list describing inline  ### Figure out what the whitespace preceding the example code is, and
92  ### documentation in that source code.  ### then delete that from every line.
93  (code,  (ex
94  ### The function to examine.  ### character vector of example code lines.
  name.fun  
 ### The name of the function/chunk to use in warning messages.  
95   ){   ){
96    res <- list()    tlines <- gsub("\\s*","",ex)
97    clines <- grep(prefix,code)    ##tlines <- gsub("#.*","",tlines)
98    if(length(grep("#",code[1]))){    prefixes <- unique(gsub("\\S.*","",ex[tlines!=""]))
99      res$title <- gsub("[^#]*#\\s*(.*)","\\1",code[1],perl=TRUE)    FIND <- prefixes[which.min(nchar(prefixes))]
100    }    ## Eliminate leading tabulations or 2/4 spaces
101    if(length(clines) > 0){    sub(FIND, "", ex)
102      ##details<<  ### Character vector of code lines with preceding whitespace removed.
103      ## The primary mechanism is that consecutive groups of lines matching  }
104      ## the specified prefix regular expression "\code{^### }" (i.e. lines  
105      ## beginning with "\code{### }") are collected  prefixed.lines <- structure(function(src,...){
106      ## as follows into documentation sections:\describe{  ### The primary mechanism of inline documentation is via consecutive
107      ## \item{description}{group starting at line 2 in the code}  ### groups of lines matching the specified prefix regular expression
108      ## \item{arguments}{group following each function argument}  ### "\code{^### }" (i.e. lines beginning with "\code{### }") are
109      ## \item{value}{group ending at the penultimate line of the code}}  ### collected as follows into documentation sections:\describe{
110      ## These may be added to by use of the \code{##<<} constructs described  ### \item{description}{group starting at line 2 in the code}
111      ## below.  ### \item{arguments}{group following each function argument}
112    ### \item{value}{group ending at the penultimate line of the code}}
113    ### These may be added to by use of the \code{##<<} constructs
114    ### described below.
115      clines <- grep(prefix,src)
116      if(length(clines)==0)return(list())
117      bounds <- which(diff(clines)!=1)      bounds <- which(diff(clines)!=1)
118      starts <- c(1,bounds+1)      starts <- c(1,bounds+1)
119      ends <- c(bounds,length(clines))      ends <- c(bounds,length(clines))
120      ## detect body of function using paren matching
121      code <- gsub("#.*","",src)
122      f <- function(ch)cumsum(nchar(gsub(sprintf("[^%s]",ch),"",code)))
123      parens <- f("(")-f(")")
124      body.begin <- which(diff(parens)<0 & parens[-1]==0)+2
125      if(length(body.begin)==0)body.begin <- 1 ## rare cases
126      is.arg <- function(){
127        gres <- grep("^\\s*#",src[start-1],perl=TRUE)
128        0 == length(gres) && start<=body.begin
129      }
130      res <- list()
131      for(i in seq_along(starts)){      for(i in seq_along(starts)){
132        start <- clines[starts[i]]        start <- clines[starts[i]]
133        end <- clines[ends[i]]        end <- clines[ends[i]]
134        lab <- if(end+1==length(code))"value"      processed <- gsub("#.*","",gsub("[ }]","",src[(end+1):length(src)]))
135        lab <- if(all(processed==""))"value"
136        else if(start==2)"description"        else if(start==2)"description"
137        else if ( 0 == length(grep("^\\s*#",code[start-1],perl=TRUE)) ){      else if(is.arg()){
138           #arg <- gsub("^[ (]*","",code[start-1])        ##twutz: strip leading white spaces and brackets and ,
139           #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 ,  
140                   arg <- gsub("^([^=,]*)[=,].*", "\\1", arg)                   arg <- gsub("^([^=,]*)[=,].*", "\\1", arg)
141                   arg <- gsub("^([^ \t]*)([ \t]+)$","\\1",arg)   #twutz: remove trailing whitespaces        ##twutz: remove trailing whitespaces
142          arg <- gsub("^([^ \t]*)([ \t]+)$","\\1",arg)
143                   arg <- gsub("...", "\\dots", arg, fix = TRUE)                   arg <- gsub("...", "\\dots", arg, fix = TRUE)
144           paste("item{",arg,"}",sep="")           paste("item{",arg,"}",sep="")
145         } else {         } else {
146           next;           next;
147         }         }
148        res[[lab]] <- decomment(code[start:end])      res[[lab]] <- decomment(src[start:end])
     }  
149    }    }
150      res
151    },ex=function(){
152    test <- function
153    ### the description
154    (x,
155    ### the first argument
156     y ##<< another argument
157     ){
158      5
159    ### the return value
160    ##seealso<< foobar
161    }
162    src <- getSource(test)
163    prefixed.lines(src)
164    extract.xxx.chunks(src)
165    })
166    
167    extract.xxx.chunks <- function # Extract documentation from a function
168    ### Given source code of a function, return a list describing inline
169    ### documentation in that source code.
170    (src,
171    ### The source lines of the function to examine, as a character
172    ### vector.
173     name.fun="(unnamed function)",
174    ### The name of the function/chunk to use in warning messages.
175     ...
176    ### ignored.
177     ){
178      res <- list()
179    ##details<< For simple functions/arguments, the argument may also be    ##details<< For simple functions/arguments, the argument may also be
180    ## documented by appending \code{##<<} comments on the same line as the    ## documented by appending \code{##<<} comments on the same line as the
181    ## argument name. Mixing this mechanism with \code{###} comment lines for    ## argument name. Mixing this mechanism with \code{###} comment lines for
# Line 318  Line 248 
248          chunk.sep <- "\n\n"          chunk.sep <- "\n\n"
249        }        }
250        chunk.res <- NULL        chunk.res <- NULL
251        if ( 0 == length(grep("^\\s*$",payload,perl=TRUE)) )        if ( !grepl("^\\s*$",payload,perl=TRUE) )
252          chunk.res <-          chunk.res <-
253            if ( is.null(res[[field]]) ) payload            if ( is.null(res[[field]]) ) payload
254            else paste(res[[field]], payload, sep=chunk.sep)            else paste(res[[field]], payload, sep=chunk.sep)
255        invisible(chunk.res)        invisible(chunk.res)
256      }      }
257    while ( k <= length(code) ){    while ( k <= length(src) ){
258      line <- code[k]      line <- src[k]
259      if ( 0 < length(grep(extra.regexp,line,perl=TRUE) ) ){      if ( grepl(extra.regexp,line,perl=TRUE) ){
260        ## 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
261        new.field <- gsub(extra.regexp,"\\1",line,perl=TRUE)        new.field <- gsub(extra.regexp,"\\1",line,perl=TRUE)
262        new.contents <- gsub(extra.regexp,"\\2",line,perl=TRUE)        new.contents <- gsub(extra.regexp,"\\2",line,perl=TRUE)
# Line 401  Line 331 
331            first.describe <- TRUE;            first.describe <- TRUE;
332          }          }
333        }        }
334      } else if ( in.chunk && 0<length(grep(cont.re,line,perl=TRUE)) ){      } else if ( in.chunk && grepl(cont.re,line,perl=TRUE) ){
335        ## append this line to current chunk        ## append this line to current chunk
336        if ( 0 == length(grep(prefix,line,perl=TRUE)) ){        if ( !grepl(prefix,line,perl=TRUE) ){
337          ##describe<< Any lines with "\code{### }" at the left hand          ##describe<< Any lines with "\code{### }" at the left hand
338          ## margin within the included chunks are handled separately,          ## margin within the included chunks are handled separately,
339          ## so if they appear in the documentation they will appear          ## so if they appear in the documentation they will appear
# Line 416  Line 346 
346            payload <- stripped            payload <- stripped
347          }          }
348        }        }
349      } else if ( 0 < length(grep(arg.pat,line,perl=TRUE)) ){      } else if ( grepl(arg.pat,line,perl=TRUE) ){
350        not.describe <- (0==in.describe && !first.describe)        not.describe <- (0==in.describe && !first.describe)
351        if ( in.chunk && not.describe){        if ( in.chunk && not.describe){
352          res[[cur.field]] <- end.chunk(cur.field,payload)          res[[cur.field]] <- end.chunk(cur.field,payload)
# Line 425  Line 355 
355        arg <- gsub(arg.pat,"\\\\item\\{\\1\\}",line,perl=TRUE)        arg <- gsub(arg.pat,"\\\\item\\{\\1\\}",line,perl=TRUE)
356        in.chunk <- TRUE        in.chunk <- TRUE
357        if ( not.describe ){        if ( not.describe ){
358            ## TDH 2010-06-18 For item{}s in the documentation list names,
359            ## we don't need to have a backslash before, so delete it.
360            arg <- gsub("^[\\]+","",arg)
361          cur.field <- gsub("...","\\dots",arg,fix=TRUE) ##special case for dots          cur.field <- gsub("...","\\dots",arg,fix=TRUE) ##special case for dots
362          payload <- comment          payload <- comment
363        } else {        } else {
# Line 475  Line 408 
408  ### with the string in this list (implemented in modify.Rd.file).  ### with the string in this list (implemented in modify.Rd.file).
409  }  }
410    
411    leadingS3generic <- function # check whether function name is an S3 generic
412    ### Determines whether a function name looks like an S3 generic function
413    (name,                     ##<< name of function
414     env,                      ##<< environment to search for additional generics
415     ...)                      ##<< ignored here
416    {
417      ##details<< This function is one of the default parsers, but exposed as
418      ## possibly of more general interest. Given a function name of the form
419      ## x.y.z it looks for the generic function x applying to objects of class
420      ## y.z and also for generic function x.y applying to objects of class z.
421      ##
422      parts <- strsplit(name, ".", fixed = TRUE)[[1]]
423      l <- length(parts)
424      if (l > 1) {
425        for (i in 1:(l - 1)) {
426          ## Look for a generic function (known by the system or defined
427          ## in the package) that matches that part of the function name
428          generic <- paste(parts[1:i], collapse = ".")
429          if (any(generic %in% utils:::getKnownS3generics()) ||
430              utils:::findGeneric(generic, env) != "") {
431            object <- paste(parts[(i + 1):l], collapse = ".")
432            ##details<< Assumes that the first name which matches any known
433            ## generics is the target generic function, so if both x and x.y
434            ## are generic functions, will assume generic x applying to objects
435            ## of class y.z
436            ##value<< If a matching generic found returns a list with a single component:
437            return(list(.s3method=c(generic, object))) ##<< a character vector containing generic name and object name.
438          }
439        }
440      }
441      ##value<< If no matching generic functions are found, returns an empty list.
442      list()
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           extract.xxx.chunks=extract.xxx.chunks,
451           ## title from first line of function def
452           title.from.firstline=function(src,...){
453             first <- src[1]
454             if(!is.character(first))return(list())
455             if(!grepl("#",first))return(list())
456             list(title=gsub("[^#]*#\\s*(.*)","\\1",first,perl=TRUE))
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 <- getSource(ex)
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                 if(ex[1]=="{")ex <- ex[-1]
508                 ## all the prefixes
509                 ex <- kill.prefix.whitespace(ex)
510                 ## Add an empty line before and after example
511                 ex <- c("", ex, "")
512               }
513               list(examples = ex)
514             } else list()
515           },collapse=function(doc,...){
516             L <- lapply(doc,paste,collapse="\n")
517             L$.overwrite <- TRUE
518             L
519           },tag.s3methods=leadingS3generic
520           )
521    
522    ### List of parser functions that operate on single objects. This list
523    ### is useful for testing these functions.
524    lonely <- structure(c(forall.parsers,forfun.parsers),ex=function(){
525      f <- function # title
526    ### description
527      (x, ##<< arg x
528       y
529    ### arg y
530       ){
531        ##value<< a list with elements
532        list(x=x, ##<< original x value
533             y=y, ##<< original y value
534             sum=x+y) ##<< their sum
535        ##end<<
536      }
537      src <- getSource(f)
538      lonely$extract.xxx.chunks(src)
539      lonely$prefixed.lines(src)
540    })
541    
542    extra.code.docs <- function # Extract documentation from code chunks
543    ### Parse R code to extract inline documentation from comments around
544    ### each function. These are not able to be retreived simply by
545    ### looking at the "source" attribute. This is a Parser Function that
546    ### can be used in the parser list of package.skeleton.dx(). TODO:
547    ### Modularize this into separate Parsers Functions for S4 classes,
548    ### prefixes, ##<<blocks, etc. Right now it is not very clean!
549    (code,
550    ### Code lines in a character vector containing multiple R objects to
551    ### parse for documentation.
552     objs,
553    ### The objects defined in the code.
554     ...
555    ### ignored
556     ){
557      parsed <- extract.file.parse(code)
558      extract.docs.try <- function(o,on)
559        {
560          ## Note: we could use parsed information here too, but that
561          ## would produce different results for setMethodS3 etc.
562          doc <- list()
563          if ( !is.null(parsed[[on]]) ){
564            if ( !is.na(parsed[[on]]@code[1]) ){ # no code given for generics
565              doc$definition <- paste(parsed[[on]]@code)
566            }
567            if(!"description"%in%names(doc) && !is.na(parsed[[on]]@description) ){
568              doc$description <- parsed[[on]]@description
569            }
570            ## if ( "setMethodS3" == parsed[[on]]@created ){
571            ##   gen <- leadingS3generic(on,topenv())
572            ##   if ( 0 < length(gen) ){
573            ##     doc$.s3method <- gen$.s3method
574            ##     cat("S3method(",gen$.s3method[1],",",gen$.s3method[2],")\n",sep="")
575            ##   }
576            ## }
577          }
578          if("title" %in% names(doc) && !"description" %in% names(doc) ){
579            ## For short functions having both would duplicate, but a
580            ## description is required. Therefore automatically copy title
581            ## across to avoid errors at package build time.
582            doc$description <- doc$title
583          }
584          doc
585        }
586      extract.docs <- function(on){
587        res <- try({o <- objs[[on]]
588                    extract.docs.try(o, on)},FALSE)
589        if(class(res)=="try-error"){
590          cat("Failed to extract docs for: ",on,"\n\n")
591          list()
592        } else if(0 == length(res) && inherits(objs[[on]],"standardGeneric")){
593          NULL
594        } else if(0 == length(res) && "function" %in% class(o)
595                  && 1 == length(osource <- getSource(o))
596                  && grepl(paste("UseMethod(",on,")",sep="\""),osource)
597                  ){
598          ## phew - this should only pick up R.oo S3 generic definitions like:
599          ## attr(*, "source")= chr "function(...) UseMethod(\"select\")"
600          NULL
601        } else res
602      }
603      doc.names <- names(objs)
604      res <- sapply(doc.names,extract.docs,simplify=FALSE)
605      ## Special processing for S4 classes as they do not appear in normal ls()
606      for ( nn in names(parsed) ){
607        if ( parsed[[nn]]@created == "setClass" ){
608          S4class.docs <- extract.docs.setClass(parsed[[nn]])
609          docname <- paste(nn,"class",sep="-")
610          if ( is.null(res[[docname]]) ){
611            res[[docname]] <- S4class.docs
612            doc.names <- c(doc.names,docname)
613          } else {
614            stop(nn," appears as both S4 class and some other definition")
615          }
616        }
617      }
618      inherit.docs <- function(on){
619        in.res <- res[[on]]
620        if ( !is.null(parsed[[on]]) ){
621          for ( parent in parsed[[on]]@parent ){
622            if ( !is.na(parent) ){
623              if ( is.null(in.res) ){
624                in.res <- res[[parent]]
625              } else if ( parent %in% names(res) ){
626                parent.docs <- res[[parent]]
627                for ( nn in names(parent.docs) ){
628                  if ( !nn %in% names(in.res) ){
629                    in.res[[nn]] <- parent.docs[[nn]]
630                  }
631                }
632              }
633            }
634          }
635        }
636        invisible(in.res)
637      }
638      all.done <- FALSE
639      while ( !all.done ){
640        res1 <- sapply(doc.names,inherit.docs,simplify=FALSE)
641        all.done <- identical(res1,res)
642        res <- res1
643      }
644      ## now strip out any generics (which have value NULL in res):
645      res.not.null <- sapply(res,function(x){!is.null(x)})
646      if ( 0 < length(res.not.null) && length(res.not.null) < length(res) ){
647        res <- res[res.not.null]
648      }
649      res
650    ### named list of lists, one for each object to document.
651    }
652    
653    ### List of parsers to use by default with package.skeleton.dx.
654    default.parsers <-
655      c(extra.code.docs=extra.code.docs, ## TODO: cleanup!
656        sapply(forfun.parsers,forfun),
657        edit.package.file=function(desc,...){
658          in.details <- setdiff(colnames(desc),"Description")
659          details <- sprintf("%s: \\tab %s\\cr",in.details,desc[,in.details])
660          L <-
661            list(list(title=desc[,"Title"],
662                      description=desc[,"Description"],
663                      `tabular{ll}`=details))
664          names(L) <- paste(desc[,"Package"],"-package",sep="")
665          L
666        },
667        sapply(forall.parsers,forall)
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
673  ### documentation sections missing from the child are  ### documentation sections missing from the child are inherited from
674    ### the parent class.
675           representation(name="character", ##<< name of object           representation(name="character", ##<< name of object
676                          created="character", ##<< how created                          created="character", ##<< how created
677                          parent="character", ##<< parent class or NA                          parent="character", ##<< parent class or NA
# Line 513  Line 706 
706      ## "prefix" lines will be used instead.      ## "prefix" lines will be used instead.
707      default.description <- NULL      default.description <- NULL
708      while ( start > last.end+1      while ( start > last.end+1
709             && 1 == length(grep(prefix,code[start-1],perl=TRUE)) ){             && grepl(prefix,code[start-1],perl=TRUE) ){
710        start <- start-1        start <- start-1
711      }      }
712      if ( start < chunks[[k]][1] ){      if ( start < chunks[[k]][1] ){
# Line 540  Line 733 
733        ## If the function definition is not embedded within the call, then        ## If the function definition is not embedded within the call, then
734        ## the parent is that function. Test whether the the third value        ## the parent is that function. Test whether the the third value
735        ## looks like a name and add it to parents if so.        ## looks like a name and add it to parents if so.
736        if ( 1 == length(grep("^[\\._\\w]+$",chars[3],perl=TRUE)) ){        if ( grepl("^[\\._\\w]+$",chars[3],perl=TRUE) ){
737          parent <- chars[3]          parent <- chars[3]
738        }        }
739        res[[object.name]] <- new("DocLink",name=object.name,        res[[object.name]] <- new("DocLink",name=object.name,
# Line 572  Line 765 
765        ## If the function definition is not embedded within the call, then        ## If the function definition is not embedded within the call, then
766        ## the parent is that function. Test whether the the fourth value        ## the parent is that function. Test whether the the fourth value
767        ## looks like a name and add it to parents if so.        ## looks like a name and add it to parents if so.
768        if ( 1 == length(grep("^[\\._\\w]+$",chars[4],perl=TRUE)) ){        if ( grepl("^[\\._\\w]+$",chars[4],perl=TRUE) ){
769          parent <- c(chars[4],parent)          parent <- c(chars[4],parent)
770        }        }
771        res[[object.name]] <- new("DocLink",name=object.name,        res[[object.name]] <- new("DocLink",name=object.name,
# Line 613  Line 806 
806    ## the same line or \code{### } comments at the beginning of the    ## the same line or \code{### } comments at the beginning of the
807    ## following line.    ## following line.
808    f.n <- paste(class.name,"class",sep="-")    f.n <- paste(class.name,"class",sep="-")
809    docs <- extract.docs.fun(chunk.source,f.n)    docs <- extract.xxx.chunks(chunk.source,f.n)
810      ## also apply source parsing functions that I separated out into
811      ## separate functions
812      docs <- combine(docs,lonely$prefixed.lines(chunk.source))
813      docs$title <- lonely$title.from.firstline(chunk.source)
814    ##details<<    ##details<<
815    ## The class definition skeleton includes an \code{Objects from the Class}    ## The class definition skeleton includes an \code{Objects from the Class}
816    ## section, to which any \code{##details<<} documentation chunks are    ## section, to which any \code{##details<<} documentation chunks are
# Line 637  Line 834 
834    }    }
835    invisible(docs)    invisible(docs)
836  }  }
837    
838    apply.parsers <- function
839    ### Parse code to r objs, then run all the parsers and return the
840    ### documentation list.
841    (code,
842    ### Character vector of code lines.
843     parsers=default.parsers,
844    ### List of Parser Functions.
845     verbose=FALSE,
846    ### Echo names of Parser Functions?
847     ...
848    ### Additional arguments to pass to Parser Functions.
849     ){
850      e <- new.env()
851      ## KMP 2011-03-09 fix problem with DocLink when inlinedocs ran on itself
852      ## Error in assignClassDef(Class, classDef, where) :
853      ##   Class "DocLink" has a locked definition in package "inlinedocs"
854      ## Traced to "where" argument in setClassDef which defaults to topenv()
855      ## which in turn is inlinedocs when processing inlinedocs package, hence
856      ## the clash. The following works (under R 2.12.2), so that the topenv()
857      ## now finds e before finding the inlinedocs environment.
858      old <- options(keep.source=TRUE,topLevelEnvironment=e)
859      on.exit(options(old))
860      exprs <- parse(text=code)
861      ## TDH 2011-04-07 set this so that no warnings about creating a fake
862      ## package when we try to process S4 classes defined in code
863      e$.packageName <- "inlinedocs.processor"
864      for (i in exprs){
865        ## TDH 2011-04-07 Disable this tryCatch since it makes it harder
866        ##to debug errors/warnings in the evaluated code
867    
868        ##tryCatch({
869          eval(i, e)
870        ##},error=function(e){
871          ##print(e)
872        ##})
873      }
874      objs <- sapply(ls(e),get,e,simplify=FALSE)
875    
876      docs <- list()
877    
878      ## apply parsers in sequence to code and objs
879      for(i in seq_along(parsers)){
880        N <- names(parsers[i])
881        if(verbose){
882          if(is.character(N) && N!=""){
883            cat(N," ",sep="")
884          }else cat('. ')
885        }
886        p <- parsers[[i]]
887        ## This is the argument list that each parser receives:
888        L <- p(code=code,objs=objs,docs=docs,env=e,...)
889        docs <- combine(docs,L)
890      }
891      ## post-process to collapse all character vectors
892      for(i in seq_along(docs)){
893        for(j in seq_along(docs[[i]])){
894          if(names(docs[[i]])[j]!=".s3method")
895          docs[[i]][[j]] <- paste(docs[[i]][[j]],collapse="\n")
896        }
897      }
898      if(verbose)cat("\n")
899      docs
900    ### A list of extracted documentation from code.
901    }
902    
903    ### Names of Parser Functions that operate on the desc arg.
904    descfile.names <- c("author.from.description","edit.package.file")
905    
906    ### Names of Parser Functions that do NOT use the desc arg.
907    non.descfile.names <-
908      names(default.parsers)[!names(default.parsers)%in%descfile.names]
909    
910    ### Parsers that operate only on R code, independently of the
911    ### description file.
912    nondesc.parsers <- default.parsers[non.descfile.names]
913    
914    extract.docs.file <- structure(function
915    ### Apply all parsers relevant to extract info from just 1 code file.
916    (f,
917    ### File name of R code to read and parse.
918     parsers=NULL,
919    ### Parser Functions to use to parse the code and extract
920    ### documentation.
921     ...
922    ### Other arguments to pass to Parser Functions.
923     ){
924      if(is.null(parsers))parsers <- nondesc.parsers
925      apply.parsers(readLines(f),parsers,verbose=FALSE,...)
926    },ex=function(){
927      f <- system.file("silly","R","silly.R",package="inlinedocs")
928      extract.docs.file(f)
929    })
930    

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

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