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 158, Mon Nov 8 12:26:12 2010 UTC revision 394, Mon Dec 23 15:36:20 2013 UTC
# Line 1  Line 1 
1    #
2    # vim:set ff=unix expandtab ts=2 sw=2:
3    do.not.generate <- structure(function
4    ### Make a Parser Function used to indicate that certain Rd files
5    ### should not be generated.
6    (...
7    ### Character strings indicating Rd files without the .Rd suffix.
8     ){
9      filenames <- c(...)
10      function(docs,...){
11        for(fn in filenames){
12          docs[[fn]] <- list()
13        }
14        docs$.overwrite <- TRUE
15        docs
16      }
17    ### A Parser Function that will delete items from the outer
18    ### Documentation List.
19    },ex=function(){
20      silly.pkg <- system.file("silly",package="inlinedocs")
21      owd <- setwd(tempdir())
22      file.copy(silly.pkg,".",recursive=TRUE)
23    
24      ## define a custom Parser Function that will not generate some Rd
25      ## files
26      custom <- do.not.generate("silly-package","Silly-class")
27      parsers <- c(default.parsers,list(exclude=custom))
28    
29      ## At first, no Rd files in the man subdirectory.
30      man.dir <- file.path("silly","man")
31      dir(man.dir)
32    
33      ## Running package.skeleton.dx will generate bare-bones files for
34      ## those specified in do.not.generate, if they do not exist.
35      package.skeleton.dx("silly",parsers)
36      Rd.files <- c("silly-package.Rd","Silly-class.Rd","silly.example.Rd")
37      Rd.paths <- file.path(man.dir,Rd.files)
38      stopifnot(all(file.exists(Rd.paths)))
39    
40      ## Save the modification times of the Rd files
41      old <- file.info(Rd.paths)$mtime
42    
43      ## make sure there is at least 2 seconds elapsed, which is the
44      ## resolution for recording times on windows file systems.
45      Sys.sleep(4)
46    
47      ## However, it will NOT generate Rd for files specified in
48      ## do.not.generate, if they DO exist already.
49      package.skeleton.dx("silly",parsers)
50      mtimes <- data.frame(old,new=file.info(Rd.paths)$mtime)
51      rownames(mtimes) <- Rd.files
52      mtimes$changed <- mtimes$old != mtimes$new
53      print(mtimes)
54      stopifnot(mtimes["silly-package.Rd","changed"]==FALSE)
55      stopifnot(mtimes["Silly-class.Rd","changed"]==FALSE)
56      stopifnot(mtimes["silly.example.Rd","changed"]==TRUE)
57    
58      unlink("silly",recursive=TRUE)
59      setwd(owd)
60    })
61    
62    ### combine NULL objects.
63    combine.NULL<-function(x,y){
64        if (class(x) == "NULL"){
65            # print(paste("mm x=",x))
66            # print(paste("mm class(x)=",class(x)))
67            x=list("")
68        }
69        if (class(y) == "NULL"){
70            # print(paste("mm y=",y))
71            # print(paste("mm class(y)=",class(y)))
72            y=list("")
73        }
74        return(combine(x,y))
75    }
76    
77  ### combine lists or character strings  ### combine lists or character strings
78  combine <- function(x,y)UseMethod("combine")  combine <- function(x,y){
79        UseMethod("combine")
80    }
81    
82  ### combine character strings by pasting them together  ### combine character strings by pasting them together
83  combine.character <- function(x,y)  combine.character <- function(x,y)
# Line 7  Line 85 
85    
86  ### combine lists by adding elements or adding to existing elements  ### combine lists by adding elements or adding to existing elements
87  combine.list <- function(x,y){  combine.list <- function(x,y){
88    toadd <- !names(y)%in%names(x)    toadd <- if(".overwrite"%in%names(y)){
89    toup <- names(y)[names(y)%in%names(x)]      y <- y[names(y)!=".overwrite"]
90        rep(TRUE,length(y))
91      }else{
92        !names(y)%in%names(x)
93      }
94      toup <- names(y)[!toadd]
95    x[names(y)[toadd]] <- y[toadd]    x[names(y)[toadd]] <- y[toadd]
96    for(up in toup)x[[up]] <- combine(x[[up]],y[[up]])    for(up in toup)x[[up]] <- combine(x[[up]],y[[up]])
97    return(x)    x
98  ### A list, same type as x, but with added elements from y.  ### A list, same type as x, but with added elements from y.
99  }  }
100    
101    
102    getSource <- function
103    ### Extract a function's source code.
104    (fun.obj
105    ### A function.
106     ) {
107          srcref <- attr(fun.obj, "srcref")
108          if (!is.null(srcref)) {
109            ##unlist(strsplit(as.character(srcref), "\n"))
110            as.character(srcref)
111          }
112          else attr(fun.obj, "source")
113    ### Source code lines as a character vector.
114    }
115    
116  ### Prefix for code comments used with grep and gsub.  ### Prefix for code comments used with grep and gsub.
117  prefix <- "^[ \t]*###[ \t]"  prefix <- "^[ \t]*###[ \t]*"
118    
119  decomment <- function  decomment <- function
120  ### Remove comment prefix and join lines of code to form a  ### Remove comment prefix and join lines of code to form a
# Line 24  Line 122 
122  (comments  (comments
123  ### Character vector of prefixed comment lines.  ### Character vector of prefixed comment lines.
124   ){   ){
125    paste(gsub(prefix,"",comments),collapse="\n")    gsub(prefix,"",comments)
126  ### String without prefixes or newlines.  ### String without prefixes or newlines.
127  }  }
128    
129    forall <- function
130  ### For each object in the package that satisfies the criterion  ### For each object in the package that satisfies the criterion
131  ### checked by subfun, parse source using FUN and return the resulting  ### checked by subfun, parse source using FUN and return the resulting
132  ### documentation list.  ### documentation list.
 forall <- function  
133  (FUN,  (FUN,
134  ### Function to apply to each element in the package.  ### Function to apply to each element in the package.
135   subfun=function(x)TRUE   subfun=function(x)TRUE
# Line 41  Line 139 
139   ){   ){
140    FUN <- FUN    FUN <- FUN
141    f <- function(objs,docs,...){    f <- function(objs,docs,...){
142        if(length(objs)==0)return(list())
143      objs <- objs[sapply(objs,subfun)]      objs <- objs[sapply(objs,subfun)]
144      L <- list()      L <- list()
145      for(N in names(docs)){      on.exit(cat(sprintf("Parser Function failed on %s\n",N)))
146        for(N in union(names(docs),names(objs))){
147        o <- objs[[N]]        o <- objs[[N]]
148        L[[N]] <- FUN(src=attr(o,"source"),        L[[N]] <- FUN(src=getSource(o),
149                      name=N,objs=objs,o=o,docs=docs,doc=docs[[N]],...)                      name=N,objs=objs,o=o,docs=docs,doc=docs[[N]],...)
150      }      }
151        on.exit()## remove warning message
152      L      L
153    }    }
154    class(f) <- c("allfun","function")    class(f) <- c("allfun","function")
# Line 67  Line 168 
168  ### For each function in the package, do something.  ### For each function in the package, do something.
169  forfun <- function(FUN)forall(FUN,is.function)  forfun <- function(FUN)forall(FUN,is.function)
170    
171  examples.after.return <- function  forGeneric<- function(
172  ### Get examples from inline definitions after return()    FUN  ### Function to apply to each method in the package (usually FUN is a parser)
173  ### PhG: this does not work well! Think of these situations:    ,
174  ### 1) You have multiple return() in the code of your function,    env
175  ### 2) You have return() appearing is some example code, ...    ,
176  ### I can hardly propose a hack here. The whole code of the function    gens
177  ### must be parsed, and one must determine which one is the last line    ){
178  ### of code that is actually executed.      #pe(quote(getwd()),environment())
179  ###    force(FUN)
180  ### I make two propositions here          f <- function(objs,docs,...){
181  ### 1) to keep the same mechanism that has the advantage of simplicity      genericFuncNames=names(gens)
182  ###    but to use a special tag            L <- list()
183  ###    ##examples<< or #{{{examples to separate      for(genName in genericFuncNames){
184  ###    function code from examples explicitly, and        fg=gens[[genName]]
185  ### 2) to place the example in an "ex" attribute        meths=findMethods(fg,where=env)
186  ###    attached to the function        signatureStrings=names(meths)
187  ###    (see next parser). That solution will be also interesting for        pp("signatureStrings",environment())
188  ###    documenting datasets, something not done yet by inlinedocs!              on.exit(cat(sprintf("Parser Function failed on %s\n",N)))
189  (src,name="",...) {        for ( sig in signatureStrings){
190    ## Look for the examples mark                method <- meths[[sig]]
191    m <- grep("^\\s*(##examples<<|#\\{\\{\\{examples)", src)          src=getSource(method)
192    if (!length(m)) return(list())          N <- paste(genName,"-method-#",sig,sep="")
193    if (length(m) > 1)          L[[N]]  <-  FUN(src=src,objs=meths,name=N,...)
194      warning("More than one examples tag for ", name,        }
195              ". Taking the last one")              on.exit()## remove warning message
196    m <- m[length(m)]      }
197    ## Look for the lines containing return value comments just before      L
198    r <- grep("\\s*### ", src[1:(m-1)])    }
199      if (!length(r)) {    f
200        value <- NULL  }
201      } else {  
202        ## Only take consecutive lines before the mark  kill.prefix.whitespace <- function
203        keep <- rev((m - rev(r)) == 1:length(r))  ### Figure out what the whitespace preceding the example code is, and
204        if (!any(keep)) {  ### then delete that from every line.
205          value <- NULL  (ex
206        } else {  ### character vector of example code lines.
207          value <- decomment(src[r[keep]])   ){
208        }    tlines <- gsub("\\s*","",ex)
209      }    ##tlines <- gsub("#.*","",tlines)
210    ## Collect now the example code beneath the mark    prefixes <- unique(gsub("\\S.*","",ex[tlines!=""]))
   ex <- src[(m + 1):(length(src) - 1)]  
   ## Possibly eliminate a #}}} tag  
   ex <- ex[!grepl("#}}}", ex)]  
   ## Eliminate leading tabulations or four spaces  
   prefixes <- gsub("(\\s*).*","\\1",ex,perl=TRUE)[grep("\\w",ex)]  
211    FIND <- prefixes[which.min(nchar(prefixes))]    FIND <- prefixes[which.min(nchar(prefixes))]
212    ex <- sub(FIND,"",ex)    ## Eliminate leading tabulations or 2/4 spaces
213    ## Add an empty line before and after example    sub(FIND, "", ex)
214    ex <- c("", ex, "")  ### Character vector of code lines with preceding whitespace removed.
   ## Return examples and value  
   list(examples = paste(ex, collapse = "\n"), value = value)  
215  }  }
216    
217  prefixed.lines <- function(src,...){  prefixed.lines <- structure(function(src,...){
218  ### The primary mechanism of inline documentation is via consecutive  ### The primary mechanism of inline documentation is via consecutive
219  ### groups of lines matching the specified prefix regular expression  ### groups of lines matching the specified prefix regular expression
220  ### "\code{^### }" (i.e. lines beginning with "\code{### }") are  ### "\code{^### }" (i.e. lines beginning with "\code{### }") are
# Line 136  Line 230 
230    starts <- c(1,bounds+1)    starts <- c(1,bounds+1)
231    ends <- c(bounds,length(clines))    ends <- c(bounds,length(clines))
232    ## detect body of function using paren matching    ## detect body of function using paren matching
233    f <- function(ch)cumsum(nchar(gsub(sprintf("[^%s]",ch),"",src)))    code <- gsub("#.*","",src)
234      f <- function(ch)cumsum(nchar(gsub(sprintf("[^%s]",ch),"",code)))
235    parens <- f("(")-f(")")    parens <- f("(")-f(")")
236    body.begin <- which(diff(parens)<0 & parens[-1]==0)+2    body.begin <- which(diff(parens)<0 & parens[-1]==0)+2
237      if(length(body.begin)==0)body.begin <- 1 ## rare cases
238    is.arg <- function(){    is.arg <- function(){
239      0 == length(grep("^\\s*#",src[start-1],perl=TRUE)) &&      gres <- grep("^\\s*#",src[start-1],perl=TRUE)
240        start<=body.begin      0 == length(gres) && start<=body.begin
241      }      }
242    res <- list()    res <- list()
243    for(i in seq_along(starts)){    for(i in seq_along(starts)){
244      start <- clines[starts[i]]      start <- clines[starts[i]]
245      end <- clines[ends[i]]      end <- clines[ends[i]]
246      lab <- if(end+1==length(src))"value"      processed <- gsub("#.*","",gsub("[ }]","",src[(end+1):length(src)]))
247        lab <- if(all(processed==""))"value"
248      else if(start==2)"description"      else if(start==2)"description"
249      else if(is.arg()){      else if(is.arg()){
250        ##twutz: strip leading white spaces and brackets and ,        ##twutz: strip leading white spaces and brackets and ,
# Line 155  Line 252 
252        arg <- gsub("^([^=,]*)[=,].*", "\\1", arg)        arg <- gsub("^([^=,]*)[=,].*", "\\1", arg)
253        ##twutz: remove trailing whitespaces        ##twutz: remove trailing whitespaces
254        arg <- gsub("^([^ \t]*)([ \t]+)$","\\1",arg)        arg <- gsub("^([^ \t]*)([ \t]+)$","\\1",arg)
255        arg <- gsub("...", "\\dots", arg, fix = TRUE)        arg <- gsub("...", "\\dots", arg, fixed = TRUE)
256        paste("item{",arg,"}",sep="")        paste("item{",arg,"}",sep="")
257      } else {      } else {
258        next;        next;
# Line 163  Line 260 
260      res[[lab]] <- decomment(src[start:end])      res[[lab]] <- decomment(src[start:end])
261    }    }
262    res    res
263  }  },ex=function(){
264    test <- function
265    ### the description
266    (x,
267    ### the first argument
268     y ##<< another argument
269     ){
270      5
271    ### the return value
272    ##seealso<< foobar
273    }
274    src <- getSource(test)
275    prefixed.lines(src)
276    extract.xxx.chunks(src)
277    })
278    
279  extract.xxx.chunks <- function # Extract documentation from a function  extract.xxx.chunks <- function # Extract documentation from a function
280  ### Given source code of a function, return a list describing inline  ### Given source code of a function, return a list describing inline
# Line 249  Line 360 
360          chunk.sep <- "\n\n"          chunk.sep <- "\n\n"
361        }        }
362        chunk.res <- NULL        chunk.res <- NULL
363        if ( 0 == length(grep("^\\s*$",payload,perl=TRUE)) )        if ( !grepl("^\\s*$",payload,perl=TRUE) )
364          chunk.res <-          chunk.res <-
365            if ( is.null(res[[field]]) ) payload            if ( is.null(res[[field]]) ) payload
366            else paste(res[[field]], payload, sep=chunk.sep)            else paste(res[[field]], payload, sep=chunk.sep)
# Line 257  Line 368 
368      }      }
369    while ( k <= length(src) ){    while ( k <= length(src) ){
370      line <- src[k]      line <- src[k]
371      if ( 0 < length(grep(extra.regexp,line,perl=TRUE) ) ){      ##print(line)
372        ##if(grepl("^$",line))browser()
373        if ( grepl(extra.regexp,line,perl=TRUE) ){
374        ## 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
375        new.field <- gsub(extra.regexp,"\\1",line,perl=TRUE)        new.field <- gsub(extra.regexp,"\\1",line,perl=TRUE)
376        new.contents <- gsub(extra.regexp,"\\2",line,perl=TRUE)        new.contents <- gsub(extra.regexp,"\\2",line,perl=TRUE)
377          ##cat(new.field,"\n-----\n",new.contents,"\n\n")
378        ##details<< As a special case, the construct \code{##describe<<} causes        ##details<< As a special case, the construct \code{##describe<<} causes
379        ## similar processing to the main function arguments to be        ## similar processing to the main function arguments to be
380        ## applied in order to construct a describe block within the        ## applied in order to construct a describe block within the
# Line 270  Line 383 
383        ## block until terminated by a subsequent \code{##}\emph{xxx}\code{<<} line.        ## block until terminated by a subsequent \code{##}\emph{xxx}\code{<<} line.
384        if ( "describe" == new.field ){        if ( "describe" == new.field ){
385          ##details<< Such regions may be nested, but not in such a way          ##details<< Such regions may be nested, but not in such a way
386          ## that the first element in a \code{describe} is another \code{describe}.          ## that the first element in a \code{describe} is another
387          ## Thus there must be at least one \code{##<<} comment between each          ## \code{describe}.  Thus there must be at least one
388          ## pair of \code{##describe<<} comments.          ## \code{##<<} comment between each pair of
389            ## \code{##describe<<} comments.
390          if ( first.describe ){          if ( first.describe ){
391            stop("consecutive ##describe<< at line",k,"in",name.fun)            stop("consecutive ##describe<< at line",k,"in",name.fun)
392          } else {          } else {
# Line 332  Line 446 
446            first.describe <- TRUE;            first.describe <- TRUE;
447          }          }
448        }        }
449      } else if ( in.chunk && 0<length(grep(cont.re,line,perl=TRUE)) ){      } else if ( in.chunk && grepl(cont.re,line,perl=TRUE) ){
450        ## append this line to current chunk        ## append this line to current chunk
451        if ( 0 == length(grep(prefix,line,perl=TRUE)) ){        if ( !grepl(prefix,line,perl=TRUE) ){
452          ##describe<< Any lines with "\code{### }" at the left hand          ##describe<< Any lines with "\code{### }" at the left hand
453          ## margin within the included chunks are handled separately,          ## margin within the included chunks are handled separately,
454          ## so if they appear in the documentation they will appear          ## so if they appear in the documentation they will appear
# Line 347  Line 461 
461            payload <- stripped            payload <- stripped
462          }          }
463        }        }
464      } else if ( 0 < length(grep(arg.pat,line,perl=TRUE)) ){      } else if ( grepl(arg.pat,line,perl=TRUE) ){
465        not.describe <- (0==in.describe && !first.describe)        not.describe <- (0==in.describe && !first.describe)
466        if ( in.chunk && not.describe){        if ( in.chunk && not.describe){
467          res[[cur.field]] <- end.chunk(cur.field,payload)          res[[cur.field]] <- end.chunk(cur.field,payload)
# Line 359  Line 473 
473          ## TDH 2010-06-18 For item{}s in the documentation list names,          ## TDH 2010-06-18 For item{}s in the documentation list names,
474          ## we don't need to have a backslash before, so delete it.          ## we don't need to have a backslash before, so delete it.
475          arg <- gsub("^[\\]+","",arg)          arg <- gsub("^[\\]+","",arg)
476          cur.field <- gsub("...","\\dots",arg,fix=TRUE) ##special case for dots          cur.field <- gsub("...","\\dots",arg,fixed=TRUE) ##special case for dots
477          payload <- comment          payload <- comment
478        } else {        } else {
479          ## this is a describe block, so we need to paste with existing          ## this is a describe block, so we need to paste with existing
# Line 409  Line 523 
523  ### with the string in this list (implemented in modify.Rd.file).  ### with the string in this list (implemented in modify.Rd.file).
524  }  }
525    
526    leadingS3generic <- function # check whether function name is an S3 generic
527    ### Determines whether a function name looks like an S3 generic function
528    (name,                     ##<< name of function
529     env,                      ##<< environment to search for additional generics
530     ...)                      ##<< ignored here
531    {
532      ##details<< This function is one of the default parsers, but exposed as
533      ## possibly of more general interest. Given a function name of the form
534      ## x.y.z it looks for the generic function x applying to objects of class
535      ## y.z and also for generic function x.y applying to objects of class z.
536      ##
537      parts <- strsplit(name, ".", fixed = TRUE)[[1]]
538      l <- length(parts)
539      if (l > 1) {
540        for (i in 1:(l - 1)) {
541          ## Look for a generic function (known by the system or defined
542          ## in the package) that matches that part of the function name
543          generic <- paste(parts[1:i], collapse = ".")
544          if (any(generic %in% getKnownS3generics()) ||
545              findGeneric(generic, env) != "") {
546            object <- paste(parts[(i + 1):l], collapse = ".")
547            ##details<< Assumes that the first name which matches any known
548            ## generics is the target generic function, so if both x and x.y
549            ## are generic functions, will assume generic x applying to objects
550            ## of class y.z
551            ##value<< If a matching generic found returns a list with a single component:
552            return(list(.s3method=c(generic, object))) ##<< a character vector containing generic name and object name.
553          }
554        }
555      }
556      ##value<< If no matching generic functions are found, returns an empty list.
557      list()
558    }
559    
560    definition.from.source=function(doc,src,...){
561      def <- doc$definition
562      is.empty <- function(x)is.null(x)||x==""
563      if(is.empty(def) && !is.empty(src))
564        list(definition=src)
565      else list()
566    }
567    ## title from first line of function def
568    title.from.firstline=function(src,...){
569      first <- src[1]
570      if(!is.character(first))return(list())
571      if(!grepl("#",first))return(list())
572      list(title=gsub("[^#]*#\\s*(.*)","\\1",first,perl=TRUE))
573    }
574    ############
575    mm.examples.from.testfile=function(name,...){
576      pp("name",environment())
577      tsubdir <- getOption("inlinedocs.exampleDir")
578      trunk<- getOption("inlinedocs.exampleRegExpression")
579      if (is.null(tsubdir)) return(list())# do nothing
580      #pe(quote(getwd()),environment())
581      #pp("tsubdir",environment())
582      p <- paste(trunk,name,"\\.R$",sep="")
583      #pp("p",environment())
584      allfiles=dir(tsubdir)
585      #pp("allfiles",environment())
586      L<- allfiles[grepl(pattern=p,allfiles)]
587      #pp("L",environment())
588      path=function(l){file.path(tsubdir,l)}
589      paths=lapply(L,path)
590      print(lapply(paths,file.exists))
591    
592      if(length(L)>0){
593        exampleTexts= lapply(paths,readLines)
594        #pp("exampleTexts",environment())
595        combinedText <- unlist(exampleTexts)
596    
597          return(list(examples=combinedText))
598          #pp("combinedTexts",environment())
599      }
600      else{
601        list()
602      }
603    }
604  ### Parsers for each function that are constructed automatically. This  ### Parsers for each function that are constructed automatically. This
605  ### is a named list, and each element is a parser function for an  ### is a named list, and each element is a parser function for an
606  ### individual object.  ### individual object.
607  forfun.parsers <-  forfun.parsers <-
608    list(prefixed.lines=prefixed.lines,    list(prefixed.lines=prefixed.lines,
        examples.after.return=examples.after.return,  
609         extract.xxx.chunks=extract.xxx.chunks,         extract.xxx.chunks=extract.xxx.chunks,
610         ## title from first line of function def         title.from.firstline=title.from.firstline,
        title.from.firstline=function(src,name,code,...){  
          if(length(grep("#",src[1]))){  
            list(title=gsub("[^#]*#\\s*(.*)","\\1",src[1],perl=TRUE))  
          } else list()  
        },  
611         ## PhG: it is tests/FUN.R!!! I would like more flexibility here         ## PhG: it is tests/FUN.R!!! I would like more flexibility here
612         ## please, let me choose which dir to use for examples!         ## please, let me choose which dir to use for examples!
613         ## Get examples for FUN from the file tests/FUN.R         ## Get examples for FUN from the file tests/FUN.R
# Line 429  Line 615 
615           tsubdir <- getOption("inlinedocs.exdir")           tsubdir <- getOption("inlinedocs.exdir")
616           if (is.null(tsubdir)) tsubdir <- "tests"       # Default value           if (is.null(tsubdir)) tsubdir <- "tests"       # Default value
617           tfile <- file.path("..",tsubdir,paste(name,".R",sep=""))           tfile <- file.path("..",tsubdir,paste(name,".R",sep=""))
618           if(file.exists(tfile))           print(file.exists(tfile))
619             list(examples=paste(readLines(tfile),collapse="\n"))           if(file.exists(tfile)){
620           else list()             list(examples=readLines(tfile))
621         },           }
        definition.from.source=function(doc,src,...){  
          def <- doc$definition  
          is.empty <- function(x)is.null(x)||x==""  
          if(is.empty(def) && !is.empty(src))  
            list(definition=paste(src,collapse="\n"))  
622           else list()           else list()
        })  
   
 ### List of Parser Functions that can be applied to any object.  
 forall.parsers <-  
   list(## Fill in author from DESCRIPTION and titles.  
        author.from.description=function(desc,...){  
          list(author=desc[,"Maintainer"])  
        },  
        ## The format section sometimes causes problems, so erase it.  
        erase.format=function(...){  
          list(format="")  
623         },         },
624         ## Convert the function name to a title.         mm.examples.from.testfile=mm.examples.from.testfile,
625         title.from.name=function(name,doc,...){         definition.from.source=definition.from.source
626           if("title"%in%names(doc))list() else         )
          list(title=gsub("[._]"," ",name))  
        },  
        ## PhG: here is what I propose for examples code in the 'ex' attribute  
        examples.in.attr =  function (name, o, ...) {  
          ex <- attr(o, "ex")  
          if (!is.null(ex)) {  
            ## Special case for code contained in a function  
            if (inherits(ex, "function")) {  
              ## If source is available, start from there  
              src <- attr(ex, "source")  
              if (!is.null(src)) {  
                ex <- src  
              } else { ## Use the body of the function  
                ex <- deparse(body(ex))  
              }  
              ## Eliminate leading and trailing code  
              ex <- ex[-c(1, length(ex))]  
              ## Eliminate leading tabulations or 2/4 spaces  
              ex <- sub("^\t|    |  ", "", ex)  
              ## Add an empty line before and after example  
              ex <- c("", ex, "")  
            }  
            list(examples = paste(ex, collapse = "\n"))  
          } else list()  
        })  
   
 ### List of parser functions that operate on single objects. This list  
 ### is useful for testing these functions.  
 lonely <- c(forall.parsers,forfun.parsers)  
 attr(lonely,"ex") <- function(){  
   f <- function # title  
 ### description  
   (x, ##<< arg x  
    y  
 ### arg y  
    ){  
     ##value<< a list with elements  
     list(x=x, ##<< original x value  
          y=y, ##<< original y value  
          sum=x+y) ##<< their sum  
     ##end<<  
   }  
   src <- attr(f,"source")  
   lonely$extract.xxx.chunks(src)  
   lonely$prefixed.lines(src)  
 }  
627    
628  extra.code.docs <- function # Extract documentation from code chunks  extract.docs<-function(parsed,objs,on){
629  ### Parse R code to extract inline documentation from comments around    #pp("on",environment())
 ### each function. These are not able to be retreived simply by  
 ### looking at the "source" attribute. This is a Parser Function that  
 ### can be used in the parser list of package.skeleton.dx(). TODO:  
 ### Modularize this into separate Parsers Functions for S4 classes,  
 ### prefixes, ##<<blocks, etc. Right now it is not very clean!  
 (code,  
 ### Code lines in a character vector containing multiple R objects to  
 ### parse for documentation.  
  objs,  
 ### The objects defined in the code.  
  ...  
 ### ignored  
  ){  
   parsed <- extract.file.parse(code)  
630    extract.docs.try <- function(o,on)    extract.docs.try <- function(o,on)
631      {      {
632        ## Note: we could use parsed information here too, but that        ## Note: we could use parsed information here too, but that
633        ## would produce different results for setMethodS3 etc.        ## would produce different results for R.methodsS3::setMethodS3 etc.
634        doc <- list()        doc <- list()
635        if ( !is.null(parsed[[on]]) ){        if ( !is.null(parsed[[on]]) ){
636          if ( !is.na(parsed[[on]]@code[1]) ){ # no code given for generics          if ( !is.na(parsed[[on]]@code[1]) ){ # no code given for generics
637            doc$definition <- paste(parsed[[on]]@code,collapse="\n")            doc$definition <- paste(parsed[[on]]@code)
638          }          }
639          if(!"description"%in%names(doc) && !is.na(parsed[[on]]@description) ){          if(!"description"%in%names(doc) && !is.na(parsed[[on]]@description) ){
640            doc$description <- parsed[[on]]@description            doc$description <- parsed[[on]]@description
641          }          }
642          if ( "setMethodS3" == parsed[[on]]@created ){          ## if ( "R.methodsS3::setMethodS3" == parsed[[on]]@created ){
643            # PhG: this may be wrong! It does not catch correctly how the method          ##   gen <- leadingS3generic(on,topenv())
644            # must be splitted in case of methods containing dots. for instance,          ##   if ( 0 < length(gen) ){
645            # as.data.frame.matrix must be split into: m1 = as.data.frame and          ##     doc$.s3method <- gen$.s3method
646            # m2 = matrix... here you got m1 = as, and m2 = data.frame.matrix!!!          ##     cat("S3method(",gen$.s3method[1],",",gen$.s3method[2],")\n",sep="")
647                    pattern <- "^([^\\.]+)\\.(.*)$"          ##   }
648            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="")  
         }  
649        }        }
650        if("title" %in% names(doc) && !"description" %in% names(doc) ){        if("title" %in% names(doc) && !"description" %in% names(doc) ){
651          ## For short functions having both would duplicate, but a          ## For short functions having both would duplicate, but a
# Line 551  Line 655 
655        }        }
656        doc        doc
657      }      }
   extract.docs <- function(on){  
658      res <- try({o <- objs[[on]]      res <- try({o <- objs[[on]]
659                  extract.docs.try(o, on)},FALSE)                  extract.docs.try(o, on)},FALSE)
660      if(class(res)=="try-error"){      if(class(res)=="try-error"){
# Line 560  Line 663 
663      } else if(0 == length(res) && inherits(objs[[on]],"standardGeneric")){      } else if(0 == length(res) && inherits(objs[[on]],"standardGeneric")){
664        NULL        NULL
665      } else if(0 == length(res) && "function" %in% class(o)      } else if(0 == length(res) && "function" %in% class(o)
666                && 1 == length(osource <- attr(o,"source"))                && 1 == length(osource <- getSource(o))
667                && 1 == length(grep(paste("UseMethod(",on,")",sep="\""),osource))                && grepl(paste("UseMethod(",on,")",sep="\""),osource)
668                ){                ){
669        ## phew - this should only pick up R.oo S3 generic definitions like:        ## phew - this should only pick up R.oo S3 generic definitions like:
670        ## attr(*, "source")= chr "function(...) UseMethod(\"select\")"        ## attr(*, "source")= chr "function(...) UseMethod(\"select\")"
671        NULL        NULL
672      } else res      } else res
673    }    }
674    doc.names <- names(objs)  
675    res <- sapply(doc.names,extract.docs,simplify=FALSE)  inherit.docs <- function(
676    ## Special processing for S4 classes as they do not appear in normal ls()    parsed, ##<< a list of doc.link objects
677    for ( nn in names(parsed) ){    res,    ##<< the list of documentation to be extended
678      if ( parsed[[nn]]@created == "setClass" ){    childName      ##<< the name of the object who possibly inherits
679        S4class.docs <- extract.docs.setClass(parsed[[nn]])    ){
680        docname <- paste(nn,"class",sep="-")    in.res <- res[[childName]] #start with the present
681        if ( is.null(res[[docname]]) ){    #pp("in.res",environment())
682          res[[docname]] <- S4class.docs    childsDocLink <-parsed[[childName]]
683          doc.names <- c(doc.names,docname)    if ( !is.null(childsDocLink) ){
684        } else {      for ( parent in childsDocLink@parent ){
         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 ){  
685          if ( !is.na(parent) ){          if ( !is.na(parent) ){
686            #pp("parent",environment())
687            #pe(quote(names(res)),environment())
688            #pe(quote(parent %in% names(res)),environment())
689            if ( is.null(in.res) ){            if ( is.null(in.res) ){
690              in.res <- res[[parent]]              in.res <- res[[parent]]
691            } else if ( parent %in% names(res) ){            } else if ( parent %in% names(res) ){
# Line 602  Line 700 
700        }        }
701      }      }
702      invisible(in.res)      invisible(in.res)
703      ### the possibly extended list of documentation
704    }    }
705    extra.class.docs <- function # Extract documentation from code chunks
706    ### Parse R code to extract inline documentation from comments around
707    ### each class
708    ### looking at the "source" attribute. This is a Parser Function that
709    ### can be used in the parser list of package.skeleton.dx(). TODO:
710    (code,
711    ### Code lines in a character vector containing multiple R objects to
712    ### parse for documentation.
713    objs,
714    ### The objects defined in the code.
715    env,
716    ### The environment they inhibit (needed to pass on)
717    ...
718    ### ignored
719     ){
720      doc.names <- names(objs)
721      parsed <- extract.file.parse(code,env)
722      res=list()
723      for ( nn in names(parsed) ){
724        if ( parsed[[nn]]@created == "setClass" ){
725          S4class.docs <- extract.docs.setClass(parsed[[nn]])
726          docname <- paste(nn,"class",sep="-")
727          if ( is.null(res[[docname]]) ){
728            res[[docname]] <- S4class.docs
729            doc.names <- c(doc.names,docname)
730          } else {
731            stop(nn," appears as both S4 class and some other definition")
732          }
733        }
734      }
735      all.done <- FALSE
736      while ( !all.done ){
737        res1 <- sapply(doc.names,inherit.docs,parsed=parsed,res=res,simplify=FALSE)
738        all.done <- identical(res1,res)
739        res <- res1
740      }
741      res
742    ### named list of lists, one for each object to document.
743    }
744    extra.code.docs <- function # Extract documentation from code chunks
745    ### Parse R code to extract inline documentation from comments around
746    ### each function. These are not able to be retreived simply by
747    ### looking at the "source" attribute. This is a Parser Function that
748    ### can be used in the parser list of package.skeleton.dx(). TODO:
749    ### Modularize this into separate Parsers Functions for S4 classes,
750    ### prefixes, ##<<blocks, etc. Right now it is not very clean!
751    (code,
752    ### Code lines in a character vector containing multiple R objects to
753    ### parse for documentation.
754     objs,
755    ### The objects defined in the code.
756    env, # the environment
757     ...
758    ### ignored
759     ){
760      parsed <- extract.file.parse(code,env)
761      doc.names <- names(objs)
762      res <- sapply(doc.names,extract.docs,parsed=parsed,objs=objs,simplify=FALSE)
763    all.done <- FALSE    all.done <- FALSE
764    while ( !all.done ){    while ( !all.done ){
765      res1 <- sapply(doc.names,inherit.docs,simplify=FALSE)      res1 <- sapply(doc.names,inherit.docs,parsed=parsed,res=res,simplify=FALSE)
766      all.done <- identical(res1,res)      all.done <- identical(res1,res)
767      res <- res1      res <- res1
768    }    }
# Line 617  Line 774 
774    res    res
775  ### named list of lists, one for each object to document.  ### named list of lists, one for each object to document.
776  }  }
777    forMethod.parsers<-
778      list(
779        prefixed.lines=prefixed.lines,
780        extract.xxx.chunks=extract.xxx.chunks,
781        title.from.firstline=title.from.firstline,
782        mm.examples.from.testfile
783      )
784    ### List of Parser Functions that can be applied to any object.
785    forall.parsers <-
786      list(## Fill in author from DESCRIPTION and titles.
787           author.from.description=function(desc,...){
788             list(author=desc[,"Author"])
789           },
790           ## The format section sometimes causes problems, so erase it.
791           erase.format=function(...){
792             list(format="")
793           },
794           ## Convert the function name to a title.
795           title.from.name=function(name,doc,...){
796             if("title"%in%names(doc))list() else
797             list(title=gsub("[._]"," ",name))
798           },
799           ## PhG: here is what I propose for examples code in the 'ex' attribute
800           examples.in.attr =  function (name, o, ...) {
801             ex <- attr(o, "ex")
802             if (!is.null(ex)) {
803               ## Special case for code contained in a function
804               if (inherits(ex, "function")) {
805                 ## If source is available, start from there
806                 src <- getSource(ex)
807                 if (!is.null(src)) {
808                   ex <- src
809                 } else { ## Use the body of the function
810                   ex <- deparse(body(ex))
811                 }
812                 ## Eliminate leading and trailing code
813                 ex <- ex[-c(1, length(ex))]
814                 if( length(ex) ){  # avoid error on yet empty example
815                     if(ex[1]=="{")ex <- ex[-1]
816                     ## all the prefixes
817                     ex <- kill.prefix.whitespace(ex)
818                 }
819                 ## Add an empty line before and after example
820                 ex <- c("", ex, "")
821               }
822               list(examples = ex)
823             } else list()
824           },collapse=function(doc,...){
825             L <- lapply(doc,paste,collapse="\n")
826             L$.overwrite <- TRUE
827             L
828           },tag.s3methods=leadingS3generic
829           )
830    
831    ### List of parser functions that operate on single objects. This list
832    ### is useful for testing these functions.
833    lonely <- structure(c(forall.parsers,forfun.parsers),ex=function(){
834      f <- function # title
835    ### description
836      (x, ##<< arg x
837       y
838    ### arg y
839       ){
840        ##value<< a list with elements
841        list(x=x, ##<< original x value
842             y=y, ##<< original y value
843             sum=x+y) ##<< their sum
844        ##end<<
845      }
846      src <- getSource(f)
847      lonely$extract.xxx.chunks(src)
848      lonely$prefixed.lines(src)
849    })
850    
851    
852  ### List of parsers to use by default with package.skeleton.dx.  ### List of parsers to use by default with package.skeleton.dx.
853  default.parsers <-  default.parsers <-
854    c(extra.code.docs=extra.code.docs, ## TODO: cleanup!    c(
855        extra.code.docs=extra.code.docs, ## TODO: cleanup!
856        extra.class.docs=extra.class.docs, ## TODO: cleanup!
857      sapply(forfun.parsers,forfun),      sapply(forfun.parsers,forfun),
     sapply(forall.parsers,forall),  
858      edit.package.file=function(desc,...){      edit.package.file=function(desc,...){
859        in.details <- setdiff(colnames(desc),"Description")        in.details <- setdiff(colnames(desc),"Description")
860        details <- paste(paste(in.details,": \\tab ",desc[,in.details],"\\cr",        details <- sprintf("%s: \\tab %s\\cr",in.details,desc[,in.details])
                              sep=""),collapse="\n")  
861        L <-        L <-
862          list(list(title=desc[,"Title"],          list(list(title=desc[,"Title"],
863                    description=desc[,"Description"],                    description=desc[,"Description"],
864                    `tabular{ll}`=details,                    `tabular{ll}`=details))
                   author=desc[,"Maintainer"]))  
865        names(L) <- paste(desc[,"Package"],"-package",sep="")        names(L) <- paste(desc[,"Package"],"-package",sep="")
866        L        L
867      })      },
868        sapply(forall.parsers,forall)
869        )
870    
871  setClass("DocLink", # Link documentation among related functions  setClass("DocLink", # Link documentation among related functions
872  ### The \code{.DocLink} class provides the basis for hooking together  ### The \code{.DocLink} class provides the basis for hooking together
873  ### documentation of related classes/functions/objects. The aim is that  ### documentation of related classes/functions/objects. The aim is that
874  ### documentation sections missing from the child are  ### documentation sections missing from the child are inherited from
875    ### the parent class.
876           representation(name="character", ##<< name of object           representation(name="character", ##<< name of object
877                          created="character", ##<< how created                          created="character", ##<< how created
878                          parent="character", ##<< parent class or NA                          parent="character", ##<< parent class or NA
# Line 648  Line 881 
881           )           )
882    
883  extract.file.parse <- function # File content analysis  extract.file.parse <- function # File content analysis
884  ### Using the base \code{\link{parse}} function, analyse the file to link  ### Using the base \code{parse} function, analyse the file to link
885  ### preceding "prefix" comments to each active chunk. Those comments form  ### preceding "prefix" comments to each active chunk. Those comments form
886  ### the default description for that chunk. The analysis also looks for  ### the default description for that chunk. The analysis also looks for
887  ### S4 class "setClass" calls and R.oo setConstructorS3 and setMethodS3  ### S4 class "setClass" ,R.oo setConstructorS3  R.methodsS3::setMethodS3
888  ### calls in order to link the documentation of those properly.  ### or S4 setMethod calls in order to link the documentation of those properly.
889  (code  (code,
890  ### Lines of R source code in a character vector - note that any  ### Lines of R source code in a character vector - note that any
891  ### nested \code{source} statements are \emph{ignored} when scanning  ### nested \code{source} statements are \emph{ignored} when scanning
892  ### for class definitions.  ### for class definitions.
893     env
894     ### the environment in which the code has been evaluated before.
895     ### This is e.g. iportant to make sure that we can evaluate expressions
896     ### like signature definitions for methods
897   ){   ){
898    res <- list()    res <- list()
899    old.opt <- options(keep.source=TRUE)    old.opt <- options(keep.source=TRUE)
# Line 674  Line 911 
911      ## "prefix" lines will be used instead.      ## "prefix" lines will be used instead.
912      default.description <- NULL      default.description <- NULL
913      while ( start > last.end+1      while ( start > last.end+1
914             && 1 == length(grep(prefix,code[start-1],perl=TRUE)) ){             && grepl(prefix,code[start-1],perl=TRUE) ){
915        start <- start-1        start <- start-1
916      }      }
917      if ( start < chunks[[k]][1] ){      if ( start < chunks[[k]][1] ){
# Line 686  Line 923 
923      ## determined by expression type: \describe{      ## determined by expression type: \describe{
924      ## \item{assignment (<-)}{Ordinary assignment of value/function;}      ## \item{assignment (<-)}{Ordinary assignment of value/function;}
925      ## \item{setClass}{Definition of S4 class;}      ## \item{setClass}{Definition of S4 class;}
926        ## \item{setMethod}{Definition of a method of a S4 generic;}
927      ## \item{setConstructorS3}{Definition of S3 class using R.oo package;}      ## \item{setConstructorS3}{Definition of S3 class using R.oo package;}
928      ## \item{setMethodS3}{Definition of method for S3 class using R.oo package.}}      ## \item{R.methodsS3::setMethodS3}{Definition of method for S3 class using R.oo package.}}
929      ## Additionally, the value may be a name of a function defined elsewhere,      ## Additionally, the value may be a name of a function defined elsewhere,
930      ## in which case the documentation should be copied from that other definition.      ## in which case the documentation should be copied from that other definition.
931      ## This is handled using the concept of documentation links.      ## This is handled using the concept of documentation links.
# Line 696  Line 934 
934      expr.type <- chars[1]      expr.type <- chars[1]
935      parent <- NA_character_      parent <- NA_character_
936    
937      if ( expr.type == "<-" || expr.type == "setConstructorS3" || expr.type == "setClass" ){      if ( expr.type == "<-" || expr.type == "setConstructorS3" ){
938        object.name <- chars[2]        object.name <- chars[2]
939        ## If the function definition is not embedded within the call, then        ## If the function definition is not embedded within the call, then
940        ## the parent is that function. Test whether the the third value        ## the parent is that function. Test whether the the third value
941        ## looks like a name and add it to parents if so.        ## looks like a name and add it to parents if so.
942        if ( 1 == length(grep("^[\\._\\w]+$",chars[3],perl=TRUE)) ){        if ( grepl("^[\\._\\w]+$",chars[3],perl=TRUE) ){
943          parent <- chars[3]          parent <- chars[3]
944        }        }
945        res[[object.name]] <- new("DocLink",name=object.name,        res[[object.name]] <- new("DocLink",name=object.name,
# Line 709  Line 947 
947                                  parent=parent,                                  parent=parent,
948                                  code=paste(chunks[[k]],sep=""),                                  code=paste(chunks[[k]],sep=""),
949                                  description=default.description)                                  description=default.description)
950      } else if ( expr.type == "setMethodS3" ){      } else if ( expr.type == "setClass" ){
951        ##details<< The \code{setMethodS3} calls introduce additional        object.name <- chars[2]
952          res[[object.name]] <- new("DocLink",name=object.name,
953                                    created=expr.type,
954                                    parent=parent,
955                                    code=paste(chunks[[k]],sep=""),
956                                    description=default.description)
957    
958        }
959        else if ( expr.type == "R.methodsS3::setMethodS3" || expr.type ==  "R.methodsS3::R.methodsS3::setMethodS3"){
960          ##details<< The \code{R.methodsS3::setMethodS3} calls introduce additional
961        ## complexity: they will define an additional S3 generic (which        ## complexity: they will define an additional S3 generic (which
962        ## needs documentation to avoid warnings at package build time)        ## needs documentation to avoid warnings at package build time)
963        ## unless one already exists. This also is handled by "linking"        ## unless one already exists. This also is handled by "linking"
964        ## documentation. A previously unseen generic is linked to the        ## documentation. A previously unseen S3generic is linked to the
965        ## first defining instances, subsequent definitions of that generic        ## first defining instances, subsequent definitions of that S3generic
966        ## also link back to the first defining instance.        ## also link back to the first defining instance.
967        generic.name <- chars[2]        S3generic.name <- chars[2]
968        object.name <- paste(generic.name,chars[3],sep=".")        object.name <- paste(S3generic.name,chars[3],sep=".")
969        if ( is.null(res[[generic.name]]) ){        if ( is.null(res[[S3generic.name]]) ){
970          generic.desc <- paste("Generic method behind \\code{\\link{",object.name,"}}",sep="")          ## TDH 9 April 2012 Do NOT add \\link in S3generic.desc below,
971          res[[generic.name]] <- new("DocLink",          ## since it causes problems on R CMD check.
972                                     name=generic.name,          ##* checking Rd cross-references ... WARNING
973            ##Error in find.package(package, lib.loc) :
974            ##  there is no package called ‘MASS’
975            ##Calls: <Anonymous> -> lapply -> FUN -> find.package
976    
977            S3generic.desc <-
978              paste("Generic method behind \\code{",object.name,"}",sep="")
979            res[[S3generic.name]] <- new("DocLink",
980                                       name=S3generic.name,
981                                     created=expr.type,                                     created=expr.type,
982                                     parent=object.name,                                     parent=object.name,
983                                     code=NA_character_,                                     code=NA_character_,
984                                     description=generic.desc)                                     description=S3generic.desc)
985        } else {        } else {
986          parent <- res[[generic.name]]@parent          parent <- res[[S3generic.name]]@parent
987        }        }
988        ## If the function definition is not embedded within the call, then        ## If the function definition is not embedded within the call, then
989        ## the parent is that function. Test whether the the fourth value        ## the parent is that function. Test whether the the fourth value
990        ## looks like a name and add it to parents if so.        ## looks like a name and add it to parents if so.
991        if ( 1 == length(grep("^[\\._\\w]+$",chars[4],perl=TRUE)) ){        if ( grepl("^[\\._\\w]+$",chars[4],perl=TRUE) ){
992          parent <- c(chars[4],parent)          parent <- c(chars[4],parent)
993        }        }
994        res[[object.name]] <- new("DocLink",name=object.name,        res[[object.name]] <- new("DocLink",name=object.name,
# Line 741  Line 996 
996                                  parent=parent,                                  parent=parent,
997                                  code=paste(chunks[[k]],sep=""),                                  code=paste(chunks[[k]],sep=""),
998                                  description=default.description)                                  description=default.description)
999        } else if (expr.type == "setMethod" ) {
1000          pp("lang",environment())
1001          pp("chars",environment())
1002    
1003          ## Since we do not know if the arguments in the call to setMethod are given with
1004          ## keywords, partially matching keywords as an ordered list ore any
1005          ## combination of it, we use the same function as R  (match.arg )
1006          ## to rewrite our argumentlist to a (pair)list from which
1007          ## we can extract the information easily
1008          KeyWords=c("f","signature","definition","where")
1009          NamedArgs=list() # the new argument list
1010          args=lang[2:length(lang)]
1011          argNames=names(args)
1012          pp("args",environment())
1013          pp("argNames",environment())
1014          for (i in seq_along(lang[2:length(lang)])){
1015             argName=argNames[[i]]
1016             if(argNames[[i]]==""){ # no keyword=value given for this arg
1017               NamedArgs[[KeyWords[[i]]]] <- args[[i]] #determining the keyword  by position
1018      } else {      } else {
1019        ## Not sure what to do with these yet. Need to deal with setMethod, setAs etc.            newName=try(match.arg(argNames[[i]],KeyWords))
1020              if (class(newName)=="try-error") {
1021                stop(paste("could not match the argument with name : " ,argNames[[i]]," to a formal argument of setMethod",sep=""))
1022              }else{
1023               NamedArgs[[newName]] <- args[[i]]
1024             }
1025            }
1026          }
1027          pp("NamedArgs",environment())
1028          genName=NamedArgs[["f"]]
1029          sigexp=NamedArgs[["signature"]]
1030          pp("sigexp",environment())
1031          sig=eval(sigexp,env)
1032          pp("sig",environment())
1033          sigString <- paste(sig,collapse="#")
1034          N=paste(genName,"-method-#",sigString,sep="")
1035          object.name <- N
1036          pp("object.name",environment())
1037    
1038          ## If the function definition is not embedded within the call, then
1039          ## the parent is that function. Test whether the value for "definition"
1040          ## looks like a funktion name and add it to parents if so.
1041          def=paste(as.character(NamedArgs[["definition"]]),collapse="\n")
1042          if ( grepl("^[\\._\\w]+$",def,perl=TRUE) ){
1043            parent <- def
1044          }
1045          res[[object.name]] <- new("DocLink",name=object.name,
1046                                    created=expr.type,
1047                                    parent=parent,
1048                                    code=paste(chunks[[k]],sep=""),
1049                                    description=default.description)
1050        }else {
1051          ## Not sure what to do with these yet. Need to deal with setAs etc.
1052      }      }
1053    }    }
1054    invisible(res)    invisible(res)
# Line 754  Line 1060 
1060  ### in the form \code{setClass("classname",\dots)} are also located and  ### in the form \code{setClass("classname",\dots)} are also located and
1061  ### scanned for inline comments.  ### scanned for inline comments.
1062  (doc.link  (doc.link
1063  ### DocLink object as created by \code{\link{extract.file.parse}}.  ### DocLink object as created by \code{extract.file.parse}.
1064  ### Note that \code{source} statements are \emph{ignored} when scanning for  ### Note that \code{source} statements are \emph{ignored} when scanning for
1065  ### class definitions.  ### class definitions.
1066   ){   ){
# Line 780  Line 1086 
1086    docs <- combine(docs,lonely$prefixed.lines(chunk.source))    docs <- combine(docs,lonely$prefixed.lines(chunk.source))
1087    docs$title <- lonely$title.from.firstline(chunk.source)    docs$title <- lonely$title.from.firstline(chunk.source)
1088    ##details<<    ##details<<
1089      ## If there is no explicit title on the first line of setClass, then
1090      ## one is made up from the class name.
1091      if ( 0 == length(docs$title) ){
1092        docs$title <- list(title=paste(class.name,"S4 class"))
1093      }
1094      ##details<<
1095    ## The class definition skeleton includes an \code{Objects from the Class}    ## The class definition skeleton includes an \code{Objects from the Class}
1096    ## section, to which any \code{##details<<} documentation chunks are    ## section, to which any \code{##details<<} documentation chunks are
1097    ## written. It is given a vanilla content if there are no specific    ## written. It is given a vanilla content if there are no specific
# Line 802  Line 1114 
1114    }    }
1115    invisible(docs)    invisible(docs)
1116  }  }
1117    createObjects <- function(code){
1118      # this is factored out to make writing tests easier
1119      # since we often need the objects and the environment
1120      # they inhabit
1121      e <- new.env()
1122      ## KMP 2011-03-09 fix problem with DocLink when inlinedocs ran on itself
1123      ## Error in assignClassDef(Class, classDef, where) :
1124      ##   Class "DocLink" has a locked definition in package "inlinedocs"
1125      ## Traced to "where" argument in setClassDef which defaults to topenv()
1126      ## which in turn is inlinedocs when processing inlinedocs package, hence
1127      ## the clash. The following works (under R 2.12.2), so that the topenv()
1128      ## now finds e before finding the inlinedocs environment.
1129      old <- options(keep.source=TRUE,topLevelEnvironment=e)
1130      on.exit(options(old))
1131      exprs <- parse(text=code)
1132      ## TDH 2011-04-07 set this so that no warnings about creating a fake
1133      ## package when we try to process S4 classes defined in code
1134      e$.packageName <- "inlinedocs.processor"
1135      for (i in exprs){
1136          eval(i, e)
1137      }
1138      objs <- sapply(ls(e),get,e,simplify=FALSE) # note that ls will not find S4 classes nor methods for generic functions
1139      list(objs=objs,env=e,exprs=exprs)
1140    }
1141    
1142    
1143  apply.parsers <- function  apply.parsers <- function
1144  ### Parse code to r objs, then run all the parsers and return the  ### Parse code to r objs, then run all the parsers and return the
# Line 815  Line 1152 
1152   ...   ...
1153  ### Additional arguments to pass to Parser Functions.  ### Additional arguments to pass to Parser Functions.
1154   ){   ){
1155    e <- new.env()  #  #####################################
1156    old <- options(keep.source=TRUE)  #  e <- new.env()
1157    on.exit(options(old))  #  ## KMP 2011-03-09 fix problem with DocLink when inlinedocs ran on itself
1158    exprs <- parse(text=code)  #  ## Error in assignClassDef(Class, classDef, where) :
1159    for (i in exprs){  #  ##   Class "DocLink" has a locked definition in package "inlinedocs"
1160      tryCatch(eval(i, e),error=function(e){  #  ## Traced to "where" argument in setClassDef which defaults to topenv()
1161        ##print(e)  #  ## which in turn is inlinedocs when processing inlinedocs package, hence
1162      })  #  ## the clash. The following works (under R 2.12.2), so that the topenv()
1163    #  ## now finds e before finding the inlinedocs environment.
1164    #  old <- options(keep.source=TRUE,topLevelEnvironment=e)
1165    #  on.exit(options(old))
1166    #  exprs <- parse(text=code)
1167    #  ## TDH 2011-04-07 set this so that no warnings about creating a fake
1168    #  ## package when we try to process S4 classes defined in code
1169    #  e$.packageName <- "inlinedocs.processor"
1170    #  for (i in exprs){
1171    #      eval(i, e)
1172    #  }
1173    #  objs <- sapply(ls(e),get,e,simplify=FALSE) # note that ls will not find S4 classes nor methods for generic functions
1174      l=createObjects(code)
1175      objs=l[["objs"]]
1176      e=l[["env"]]
1177      exprs=l[["exprs"]]
1178      # since th method definitions do not appear in ls() so are not represented in obs
1179      # so we have to find them in the parsed code
1180      glo=list()
1181      for ( k in 1:length(exprs)){
1182        lang <- exprs[[k]]
1183        chars <- as.character(lang)
1184        #pp("chars",environment())
1185        expr.type <- chars[[1]]
1186        object.name <- chars[[2]]
1187        if (expr.type == "setMethod"){glo=c(glo,object.name)}
1188    }    }
1189    objs <- sapply(ls(e),get,e,simplify=FALSE)    gloFuncs=unlist(sapply(glo,getGeneric,where=e))
1190      #####################################
1191    docs <- list()    docs <- list()
1192      # now find generic Functions that are defined in the code
1193    # PhG: Automatically determine who is S3 methods    # since those lead to entries in objs we can find them
1194    for (name in names(objs)) {    pe(quote(length(names(objs))),environment())
1195      parts <- strsplit(name, ".", fixed = TRUE)[[1]]    if (length(names(objs))!=0){
1196          l <- length(parts)      definedGenerics=objs[sapply(names(objs),isGeneric,e)]
1197          if (l > 1) {    }else{
1198          for (i in 1:(l - 1)) {      definedGenerics=list()
             # Look for a generic function (known by the system or defined  
             # in the package) that matches that part of the function name  
             generic <- paste(parts[1:i], collapse = ".")  
             if (any(generic %in% utils:::getKnownS3generics()) ||  
                 utils:::findGeneric(generic, e) != "") {  
                 object <- paste(parts[(i + 1):l], collapse = ".")  
                 docs[[name]]$s3method <- c(generic, object)  
                 break  
             }  
         }  
     }  
1199    }    }
1200      #gens=unique(c(definedGenerics,gloFuncs))
1201      gens=definedGenerics
1202      #gens=gloFuncs
1203      # gens=glo
1204      pp("gens",environment())
1205    
1206    
1207    ## apply parsers in sequence to code and objs    ## apply parsers in sequence to code and objs
1208      if(verbose)cat("Applying parsers:\n")
1209    for(i in seq_along(parsers)){    for(i in seq_along(parsers)){
1210      N <- names(parsers[i])      N <- names(parsers[i])
1211      if(verbose){      if(verbose){
1212        if(is.character(N) && N!=""){        if(is.character(N) && N!=""){
1213          cat(N," ",sep="")          cat(" this is parser:",N,"\n",sep="")
1214        }else cat('. ')        }else cat('.\n')
1215      }      }
1216      p <- parsers[[i]]      p <- parsers[[i]]
1217      ## This is the argument list that each parser receives:      ## This is the argument list that each parser receives:
1218      L <- p(code=code,objs=objs,docs=docs,...)      L <- p(code=code,objs=objs,docs=docs,env=e,...)
1219      docs <- combine(docs,L)      docs <- combine(docs,L)
1220    }    }
1221      ## post-process to collapse all character vectors
1222      for(i in seq_along(docs)){
1223        for(j in seq_along(docs[[i]])){
1224          if(names(docs[[i]])[j]!=".s3method")
1225          docs[[i]][[j]] <- paste(docs[[i]][[j]],collapse="\n")
1226        }
1227     }
1228    if(verbose)cat("\n")    if(verbose)cat("\n")
1229    docs    ## mm I added a second parser loop here for my method parsers
1230      ## It would perhaps be possible to integrate the new parsers in the
1231      ## main loop above
1232      docs2 <- list()
1233      parsersForMethods=sapply(forMethod.parsers,forGeneric,env=e,gens=gens)
1234      for(i in seq_along(parsersForMethods)){
1235        N <- names(parsersForMethods[[i]])
1236        p <- parsersForMethods[[i]]
1237        cat(" this is parser:",N,"\n",sep="")
1238        L <- p(code=code,objs=objs,docs=docs2,env=e,...)
1239        #pp("L",environment())
1240        docs2 <- combine(docs2,L)
1241      }
1242    
1243      return(list(docs=combine(docs,docs2),env=e,objs=objs,gens=gens))
1244  ### A list of extracted documentation from code.  ### A list of extracted documentation from code.
1245  }  }
1246    
# Line 875  Line 1255 
1255  ### description file.  ### description file.
1256  nondesc.parsers <- default.parsers[non.descfile.names]  nondesc.parsers <- default.parsers[non.descfile.names]
1257    
1258  extract.docs.file <- function  extract.docs.file <- structure(function
1259  ### Apply all parsers relevant to extract info from just 1 code file.  ### Apply all parsers relevant to extract info from just 1 code file.
1260  (f,  (f,
1261  ### File name of R code to read and parse.  ### File name of R code to read and parse.
1262   parsers=nondesc.parsers,   parsers=NULL,
1263  ### Parser Functions to use to parse the code and extract  ### Parser Functions to use to parse the code and extract
1264  ### documentation.  ### documentation.
1265   ...   ...
1266  ### Other arguments to pass to Parser Functions.  ### Other arguments to pass to Parser Functions.
1267   ){   ){
1268    apply.parsers(readLines(f),parsers,verbose=FALSE,...)    if(is.null(parsers))parsers <- nondesc.parsers
1269  }    apply.parsers(readLines(f),parsers,verbose=FALSE,...)[["docs"]]
1270    },ex=function(){
1271      f <- system.file("silly","R","silly.R",package="inlinedocs")
1272      extract.docs.file(f)
1273    })
1274    

Legend:
Removed from v.158  
changed lines
  Added in v.394

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