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 186, Fri Jan 14 18:43:36 2011 UTC revision 300, Fri Jun 17 07:37:46 2011 UTC
# Line 7  Line 7 
7    
8  ### combine lists by adding elements or adding to existing elements  ### combine lists by adding elements or adding to existing elements
9  combine.list <- function(x,y){  combine.list <- function(x,y){
10    toadd <- !names(y)%in%names(x)    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]    toup <- names(y)[!toadd]
   if("doc"%in%names(x))return(x$doc)  
   if("doc"%in%names(y))return(y$doc)  
17    x[names(y)[toadd]] <- y[toadd]    x[names(y)[toadd]] <- y[toadd]
18    for(up in toup)x[[up]] <- combine(x[[up]],y[[up]])    for(up in toup)x[[up]] <- combine(x[[up]],y[[up]])
19    return(x)    x
20  ### A list, same type as x, but with added elements from y.  ### A list, same type as x, but with added elements from y.
21  }  }
22    
23  ### Prefix for code comments used with grep and gsub.  ### Prefix for code comments used with grep and gsub.
24  prefix <- "^[ \t]*###[ \t]"  prefix <- "^[ \t]*###[ \t]*"
25    
26  decomment <- function  decomment <- function
27  ### Remove comment prefix and join lines of code to form a  ### Remove comment prefix and join lines of code to form a
# Line 43  Line 46 
46   ){   ){
47    FUN <- FUN    FUN <- FUN
48    f <- function(objs,docs,...){    f <- function(objs,docs,...){
49        if(length(objs)==0)return(list())
50      objs <- objs[sapply(objs,subfun)]      objs <- objs[sapply(objs,subfun)]
51      L <- list()      L <- list()
52      on.exit(cat(sprintf("Parser Function failed on %s\n",N)))      on.exit(cat(sprintf("Parser Function failed on %s\n",N)))
53      for(N in names(docs)){      for(N in union(names(docs),names(objs))){
54        o <- objs[[N]]        o <- objs[[N]]
55        L[[N]] <- FUN(src=attr(o,"source"),        L[[N]] <- FUN(src=attr(o,"source"),
56                      name=N,objs=objs,o=o,docs=docs,doc=docs[[N]],...)                      name=N,objs=objs,o=o,docs=docs,doc=docs[[N]],...)
# Line 86  Line 90 
90  ### Character vector of code lines with preceding whitespace removed.  ### Character vector of code lines with preceding whitespace removed.
91  }  }
92    
 examples.after.return <- function  
 ### Get examples from inline definitions after return()  
 ### PhG: this does not work well! Think of these situations:  
 ### 1) You have multiple return() in the code of your function,  
 ### 2) You have return() appearing is some example code, ...  
 ### I can hardly propose a hack here. The whole code of the function  
 ### must be parsed, and one must determine which one is the last line  
 ### of code that is actually executed.  
 ###  
 ### I make two propositions here  
 ### 1) to keep the same mechanism that has the advantage of simplicity  
 ###    but to use a special tag  
 ###    ##examples<< or #{{{examples to separate  
 ###    function code from examples explicitly, and  
 ### 2) to place the example in an "ex" attribute  
 ###    attached to the function  
 ###    (see next parser). That solution will be also interesting for  
 ###    documenting datasets, something not done yet by inlinedocs!  
 (src,name="",...) {  
   ## Look for the examples mark  
   m <- grep("^\\s*(##examples<<|#\\{\\{\\{examples)", src)  
   if (!length(m)) return(list())  
   if (length(m) > 1)  
     warning("More than one examples tag for ", name,  
             ". Taking the last one")  
   m <- m[length(m)]  
   ## Look for the lines containing return value comments just before  
   r <- grep("\\s*### ", src[1:(m-1)])  
     if (!length(r)) {  
       value <- NULL  
     } else {  
       ## Only take consecutive lines before the mark  
       keep <- rev((m - rev(r)) == 1:length(r))  
       if (!any(keep)) {  
         value <- NULL  
       } else {  
         value <- decomment(src[r[keep]])  
       }  
     }  
   ## Collect now the example code beneath the mark  
   ex <- src[(m + 1):(length(src) - 1)]  
   ## Possibly eliminate a #}}} tag  
   ex <- ex[!grepl("#}}}", ex)]  
   ## Eliminate leading tabulations or four spaces  
   ex <- kill.prefix.whitespace(ex)  
   ## Add an empty line before and after example  
   ex <- c("", ex, "")  
   ## Return examples and value  
   list(examples = ex, value = value)  
 }  
   
93  prefixed.lines <- structure(function(src,...){  prefixed.lines <- structure(function(src,...){
94  ### The primary mechanism of inline documentation is via consecutive  ### The primary mechanism of inline documentation is via consecutive
95  ### groups of lines matching the specified prefix regular expression  ### groups of lines matching the specified prefix regular expression
# Line 184  Line 137 
137    res    res
138  },ex=function(){  },ex=function(){
139  test <- function  test <- function
140  ### the desc  ### the description
141  (x,  (x,
142  ### the first argument  ### the first argument
143   y ##<< another argument   y ##<< another argument
# Line 282  Line 235 
235          chunk.sep <- "\n\n"          chunk.sep <- "\n\n"
236        }        }
237        chunk.res <- NULL        chunk.res <- NULL
238        if ( 0 == length(grep("^\\s*$",payload,perl=TRUE)) )        if ( !grepl("^\\s*$",payload,perl=TRUE) )
239          chunk.res <-          chunk.res <-
240            if ( is.null(res[[field]]) ) payload            if ( is.null(res[[field]]) ) payload
241            else paste(res[[field]], payload, sep=chunk.sep)            else paste(res[[field]], payload, sep=chunk.sep)
# Line 290  Line 243 
243      }      }
244    while ( k <= length(src) ){    while ( k <= length(src) ){
245      line <- src[k]      line <- src[k]
246      if ( 0 < length(grep(extra.regexp,line,perl=TRUE) ) ){      if ( grepl(extra.regexp,line,perl=TRUE) ){
247        ## 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
248        new.field <- gsub(extra.regexp,"\\1",line,perl=TRUE)        new.field <- gsub(extra.regexp,"\\1",line,perl=TRUE)
249        new.contents <- gsub(extra.regexp,"\\2",line,perl=TRUE)        new.contents <- gsub(extra.regexp,"\\2",line,perl=TRUE)
# Line 365  Line 318 
318            first.describe <- TRUE;            first.describe <- TRUE;
319          }          }
320        }        }
321      } else if ( in.chunk && 0<length(grep(cont.re,line,perl=TRUE)) ){      } else if ( in.chunk && grepl(cont.re,line,perl=TRUE) ){
322        ## append this line to current chunk        ## append this line to current chunk
323        if ( 0 == length(grep(prefix,line,perl=TRUE)) ){        if ( !grepl(prefix,line,perl=TRUE) ){
324          ##describe<< Any lines with "\code{### }" at the left hand          ##describe<< Any lines with "\code{### }" at the left hand
325          ## margin within the included chunks are handled separately,          ## margin within the included chunks are handled separately,
326          ## so if they appear in the documentation they will appear          ## so if they appear in the documentation they will appear
# Line 380  Line 333 
333            payload <- stripped            payload <- stripped
334          }          }
335        }        }
336      } else if ( 0 < length(grep(arg.pat,line,perl=TRUE)) ){      } else if ( grepl(arg.pat,line,perl=TRUE) ){
337        not.describe <- (0==in.describe && !first.describe)        not.describe <- (0==in.describe && !first.describe)
338        if ( in.chunk && not.describe){        if ( in.chunk && not.describe){
339          res[[cur.field]] <- end.chunk(cur.field,payload)          res[[cur.field]] <- end.chunk(cur.field,payload)
# Line 442  Line 395 
395  ### with the string in this list (implemented in modify.Rd.file).  ### with the string in this list (implemented in modify.Rd.file).
396  }  }
397    
398    leadingS3generic <- function # check whether function name is an S3 generic
399    ### Determines whether a function name looks like an S3 generic function
400    (name,                     ##<< name of function
401     env,                      ##<< environment to search for additional generics
402     ...)                      ##<< ignored here
403    {
404      ##details<< This function is one of the default parsers, but exposed as
405      ## possibly of more general interest. Given a function name of the form
406      ## x.y.z it looks for the generic function x applying to objects of class
407      ## y.z and also for generic function x.y applying to objects of class z.
408      ##
409      parts <- strsplit(name, ".", fixed = TRUE)[[1]]
410      l <- length(parts)
411      if (l > 1) {
412        for (i in 1:(l - 1)) {
413          ## Look for a generic function (known by the system or defined
414          ## in the package) that matches that part of the function name
415          generic <- paste(parts[1:i], collapse = ".")
416          if (any(generic %in% utils:::getKnownS3generics()) ||
417              utils:::findGeneric(generic, env) != "") {
418            object <- paste(parts[(i + 1):l], collapse = ".")
419            ##details<< Assumes that the first name which matches any known
420            ## generics is the target generic function, so if both x and x.y
421            ## are generic functions, will assume generic x applying to objects
422            ## of class y.z
423            ##value<< If a matching generic found returns a list with a single component:
424            return(list(.s3method=c(generic, object))) ##<< a character vector containing generic name and object name.
425          }
426        }
427      }
428      ##value<< If no matching generic functions are found, returns an empty list.
429      list()
430    }
431    
432  ### Parsers for each function that are constructed automatically. This  ### Parsers for each function that are constructed automatically. This
433  ### 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
434  ### individual object.  ### individual object.
435  forfun.parsers <-  forfun.parsers <-
436    list(prefixed.lines=prefixed.lines,    list(prefixed.lines=prefixed.lines,
        examples.after.return=examples.after.return,  
437         extract.xxx.chunks=extract.xxx.chunks,         extract.xxx.chunks=extract.xxx.chunks,
438         ## title from first line of function def         ## title from first line of function def
439         title.from.firstline=function(src,name,code,...){         title.from.firstline=function(src,...){
440           if(length(grep("#",src[1]))){           first <- src[1]
441             list(title=gsub("[^#]*#\\s*(.*)","\\1",src[1],perl=TRUE))           if(!is.character(first))return(list())
442           } else list()           if(!grepl("#",first))return(list())
443             list(title=gsub("[^#]*#\\s*(.*)","\\1",first,perl=TRUE))
444         },         },
445         ## PhG: it is tests/FUN.R!!! I would like more flexibility here         ## PhG: it is tests/FUN.R!!! I would like more flexibility here
446         ## please, let me choose which dir to use for examples!         ## please, let me choose which dir to use for examples!
# Line 511  Line 498 
498             }             }
499             list(examples = ex)             list(examples = ex)
500           } else list()           } else list()
501         },         },collapse=function(doc,...){
502         collapse.docs=function(doc,...){           L <- lapply(doc,paste,collapse="\n")
503           list(doc=lapply(doc,paste,collapse="\n"))           L$.overwrite <- TRUE
504         })           L
505           },tag.s3methods=leadingS3generic
506           )
507    
508  ### List of parser functions that operate on single objects. This list  ### List of parser functions that operate on single objects. This list
509  ### is useful for testing these functions.  ### is useful for testing these functions.
510  lonely <- c(forall.parsers,forfun.parsers)  lonely <- structure(c(forall.parsers,forfun.parsers),ex=function(){
 attr(lonely,"ex") <- function(){  
511    f <- function # title    f <- function # title
512  ### description  ### description
513    (x, ##<< arg x    (x, ##<< arg x
# Line 535  Line 523 
523    src <- attr(f,"source")    src <- attr(f,"source")
524    lonely$extract.xxx.chunks(src)    lonely$extract.xxx.chunks(src)
525    lonely$prefixed.lines(src)    lonely$prefixed.lines(src)
526  }  })
527    
528  extra.code.docs <- function # Extract documentation from code chunks  extra.code.docs <- function # Extract documentation from code chunks
529  ### Parse R code to extract inline documentation from comments around  ### Parse R code to extract inline documentation from comments around
# Line 565  Line 553 
553          if(!"description"%in%names(doc) && !is.na(parsed[[on]]@description) ){          if(!"description"%in%names(doc) && !is.na(parsed[[on]]@description) ){
554            doc$description <- parsed[[on]]@description            doc$description <- parsed[[on]]@description
555          }          }
556          if ( "setMethodS3" == parsed[[on]]@created ){          ## if ( "setMethodS3" == parsed[[on]]@created ){
557            # PhG: this may be wrong! It does not catch correctly how the method          ##   gen <- leadingS3generic(on,topenv())
558            # must be splitted in case of methods containing dots. for instance,          ##   if ( 0 < length(gen) ){
559            # as.data.frame.matrix must be split into: m1 = as.data.frame and          ##     doc$.s3method <- gen$.s3method
560            # m2 = matrix... here you got m1 = as, and m2 = data.frame.matrix!!!          ##     cat("S3method(",gen$.s3method[1],",",gen$.s3method[2],")\n",sep="")
561                    pattern <- "^([^\\.]+)\\.(.*)$"          ##   }
562            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="")  
         }  
563        }        }
564        if("title" %in% names(doc) && !"description" %in% names(doc) ){        if("title" %in% names(doc) && !"description" %in% names(doc) ){
565          ## For short functions having both would duplicate, but a          ## For short functions having both would duplicate, but a
# Line 597  Line 579 
579        NULL        NULL
580      } else if(0 == length(res) && "function" %in% class(o)      } else if(0 == length(res) && "function" %in% class(o)
581                && 1 == length(osource <- attr(o,"source"))                && 1 == length(osource <- attr(o,"source"))
582                && 1 == length(grep(paste("UseMethod(",on,")",sep="\""),osource))                && grepl(paste("UseMethod(",on,")",sep="\""),osource)
583                ){                ){
584        ## phew - this should only pick up R.oo S3 generic definitions like:        ## phew - this should only pick up R.oo S3 generic definitions like:
585        ## attr(*, "source")= chr "function(...) UseMethod(\"select\")"        ## attr(*, "source")= chr "function(...) UseMethod(\"select\")"
# Line 664  Line 646 
646        L <-        L <-
647          list(list(title=desc[,"Title"],          list(list(title=desc[,"Title"],
648                    description=desc[,"Description"],                    description=desc[,"Description"],
649                    `tabular{ll}`=details,                    `tabular{ll}`=details))
                   author=desc[,"Maintainer"]))  
650        names(L) <- paste(desc[,"Package"],"-package",sep="")        names(L) <- paste(desc[,"Package"],"-package",sep="")
651        L        L
652      },      },
# Line 675  Line 656 
656  setClass("DocLink", # Link documentation among related functions  setClass("DocLink", # Link documentation among related functions
657  ### The \code{.DocLink} class provides the basis for hooking together  ### The \code{.DocLink} class provides the basis for hooking together
658  ### documentation of related classes/functions/objects. The aim is that  ### documentation of related classes/functions/objects. The aim is that
659  ### documentation sections missing from the child are  ### documentation sections missing from the child are inherited from
660    ### the parent class.
661           representation(name="character", ##<< name of object           representation(name="character", ##<< name of object
662                          created="character", ##<< how created                          created="character", ##<< how created
663                          parent="character", ##<< parent class or NA                          parent="character", ##<< parent class or NA
# Line 710  Line 692 
692      ## "prefix" lines will be used instead.      ## "prefix" lines will be used instead.
693      default.description <- NULL      default.description <- NULL
694      while ( start > last.end+1      while ( start > last.end+1
695             && 1 == length(grep(prefix,code[start-1],perl=TRUE)) ){             && grepl(prefix,code[start-1],perl=TRUE) ){
696        start <- start-1        start <- start-1
697      }      }
698      if ( start < chunks[[k]][1] ){      if ( start < chunks[[k]][1] ){
# Line 737  Line 719 
719        ## If the function definition is not embedded within the call, then        ## If the function definition is not embedded within the call, then
720        ## the parent is that function. Test whether the the third value        ## the parent is that function. Test whether the the third value
721        ## looks like a name and add it to parents if so.        ## looks like a name and add it to parents if so.
722        if ( 1 == length(grep("^[\\._\\w]+$",chars[3],perl=TRUE)) ){        if ( grepl("^[\\._\\w]+$",chars[3],perl=TRUE) ){
723          parent <- chars[3]          parent <- chars[3]
724        }        }
725        res[[object.name]] <- new("DocLink",name=object.name,        res[[object.name]] <- new("DocLink",name=object.name,
# Line 769  Line 751 
751        ## If the function definition is not embedded within the call, then        ## If the function definition is not embedded within the call, then
752        ## the parent is that function. Test whether the the fourth value        ## the parent is that function. Test whether the the fourth value
753        ## looks like a name and add it to parents if so.        ## looks like a name and add it to parents if so.
754        if ( 1 == length(grep("^[\\._\\w]+$",chars[4],perl=TRUE)) ){        if ( grepl("^[\\._\\w]+$",chars[4],perl=TRUE) ){
755          parent <- c(chars[4],parent)          parent <- c(chars[4],parent)
756        }        }
757        res[[object.name]] <- new("DocLink",name=object.name,        res[[object.name]] <- new("DocLink",name=object.name,
# Line 852  Line 834 
834  ### Additional arguments to pass to Parser Functions.  ### Additional arguments to pass to Parser Functions.
835   ){   ){
836    e <- new.env()    e <- new.env()
837    old <- options(keep.source=TRUE)    ## KMP 2011-03-09 fix problem with DocLink when inlinedocs ran on itself
838      ## Error in assignClassDef(Class, classDef, where) :
839      ##   Class "DocLink" has a locked definition in package "inlinedocs"
840      ## Traced to "where" argument in setClassDef which defaults to topenv()
841      ## which in turn is inlinedocs when processing inlinedocs package, hence
842      ## the clash. The following works (under R 2.12.2), so that the topenv()
843      ## now finds e before finding the inlinedocs environment.
844      old <- options(keep.source=TRUE,topLevelEnvironment=e)
845    on.exit(options(old))    on.exit(options(old))
846    exprs <- parse(text=code)    exprs <- parse(text=code)
847      ## TDH 2011-04-07 set this so that no warnings about creating a fake
848      ## package when we try to process S4 classes defined in code
849      e$.packageName <- "inlinedocs.processor"
850    for (i in exprs){    for (i in exprs){
851      tryCatch(eval(i, e),error=function(e){      ## TDH 2011-04-07 Disable this tryCatch since it makes it harder
852        ##to debug errors/warnings in the evaluated code
853    
854        ##tryCatch({
855          eval(i, e)
856        ##},error=function(e){
857        ##print(e)        ##print(e)
858      })      ##})
859    }    }
860    objs <- sapply(ls(e),get,e,simplify=FALSE)    objs <- sapply(ls(e),get,e,simplify=FALSE)
861    
862    docs <- list()    docs <- list()
863    
   # PhG: Automatically determine who is S3 methods  
   for (name in names(objs)) {  
     parts <- strsplit(name, ".", fixed = TRUE)[[1]]  
         l <- length(parts)  
         if (l > 1) {  
         for (i in 1:(l - 1)) {  
             # 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  
             }  
         }  
     }  
   }  
864    ## apply parsers in sequence to code and objs    ## apply parsers in sequence to code and objs
865    for(i in seq_along(parsers)){    for(i in seq_along(parsers)){
866      N <- names(parsers[i])      N <- names(parsers[i])
# Line 892  Line 871 
871      }      }
872      p <- parsers[[i]]      p <- parsers[[i]]
873      ## This is the argument list that each parser receives:      ## This is the argument list that each parser receives:
874      L <- p(code=code,objs=objs,docs=docs,...)      L <- p(code=code,objs=objs,docs=docs,env=e,...)
875      docs <- combine(docs,L)      docs <- combine(docs,L)
876    }    }
877      ## post-process to collapse all character vectors
878      for(i in seq_along(docs)){
879        for(j in seq_along(docs[[i]])){
880          if(names(docs[[i]])[j]!=".s3method")
881          docs[[i]][[j]] <- paste(docs[[i]][[j]],collapse="\n")
882        }
883      }
884    if(verbose)cat("\n")    if(verbose)cat("\n")
885    docs    docs
886  ### A list of extracted documentation from code.  ### A list of extracted documentation from code.
# Line 911  Line 897 
897  ### description file.  ### description file.
898  nondesc.parsers <- default.parsers[non.descfile.names]  nondesc.parsers <- default.parsers[non.descfile.names]
899    
900  extract.docs.file <- function  extract.docs.file <- structure(function
901  ### Apply all parsers relevant to extract info from just 1 code file.  ### Apply all parsers relevant to extract info from just 1 code file.
902  (f,  (f,
903  ### File name of R code to read and parse.  ### File name of R code to read and parse.
904   parsers=nondesc.parsers,   parsers=NULL,
905  ### Parser Functions to use to parse the code and extract  ### Parser Functions to use to parse the code and extract
906  ### documentation.  ### documentation.
907   ...   ...
908  ### Other arguments to pass to Parser Functions.  ### Other arguments to pass to Parser Functions.
909   ){   ){
910      if(is.null(parsers))parsers <- nondesc.parsers
911    apply.parsers(readLines(f),parsers,verbose=FALSE,...)    apply.parsers(readLines(f),parsers,verbose=FALSE,...)
912  }  },ex=function(){
913      f <- system.file("silly","R","silly.R",package="inlinedocs")
914      extract.docs.file(f)
915    })
916    

Legend:
Removed from v.186  
changed lines
  Added in v.300

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