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 175, Thu Jan 6 15:24:45 2011 UTC revision 246, Thu Apr 7 13:21:39 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    toup <- names(y)[names(y)%in%names(x)]      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]    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    
# Line 24  Line 29 
29  (comments  (comments
30  ### Character vector of prefixed comment lines.  ### Character vector of prefixed comment lines.
31   ){   ){
32    paste(gsub(prefix,"",comments),collapse="\n")    gsub(prefix,"",comments)
33  ### String without prefixes or newlines.  ### String without prefixes or newlines.
34  }  }
35    
# Line 44  Line 49 
49      objs <- objs[sapply(objs,subfun)]      objs <- objs[sapply(objs,subfun)]
50      L <- list()      L <- list()
51      on.exit(cat(sprintf("Parser Function failed on %s\n",N)))      on.exit(cat(sprintf("Parser Function failed on %s\n",N)))
52      for(N in names(docs)){      for(N in union(names(docs),names(objs))){
53        o <- objs[[N]]        o <- objs[[N]]
54        L[[N]] <- FUN(src=attr(o,"source"),        L[[N]] <- FUN(src=attr(o,"source"),
55                      name=N,objs=objs,o=o,docs=docs,doc=docs[[N]],...)                      name=N,objs=objs,o=o,docs=docs,doc=docs[[N]],...)
# Line 132  Line 137 
137    ## Add an empty line before and after example    ## Add an empty line before and after example
138    ex <- c("", ex, "")    ex <- c("", ex, "")
139    ## Return examples and value    ## Return examples and value
140    list(examples = paste(ex, collapse = "\n"), value = value)    list(examples = ex, value = value)
141  }  }
142    
143  prefixed.lines <- structure(function(src,...){  prefixed.lines <- structure(function(src,...){
# Line 182  Line 187 
187    res    res
188  },ex=function(){  },ex=function(){
189  test <- function  test <- function
190  ### the desc  ### the description
191  (x,  (x,
192  ### the first argument  ### the first argument
193   y ##<< another argument   y ##<< another argument
# Line 280  Line 285 
285          chunk.sep <- "\n\n"          chunk.sep <- "\n\n"
286        }        }
287        chunk.res <- NULL        chunk.res <- NULL
288        if ( 0 == length(grep("^\\s*$",payload,perl=TRUE)) )        if ( !grepl("^\\s*$",payload,perl=TRUE) )
289          chunk.res <-          chunk.res <-
290            if ( is.null(res[[field]]) ) payload            if ( is.null(res[[field]]) ) payload
291            else paste(res[[field]], payload, sep=chunk.sep)            else paste(res[[field]], payload, sep=chunk.sep)
# Line 288  Line 293 
293      }      }
294    while ( k <= length(src) ){    while ( k <= length(src) ){
295      line <- src[k]      line <- src[k]
296      if ( 0 < length(grep(extra.regexp,line,perl=TRUE) ) ){      if ( grepl(extra.regexp,line,perl=TRUE) ){
297        ## 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
298        new.field <- gsub(extra.regexp,"\\1",line,perl=TRUE)        new.field <- gsub(extra.regexp,"\\1",line,perl=TRUE)
299        new.contents <- gsub(extra.regexp,"\\2",line,perl=TRUE)        new.contents <- gsub(extra.regexp,"\\2",line,perl=TRUE)
# Line 363  Line 368 
368            first.describe <- TRUE;            first.describe <- TRUE;
369          }          }
370        }        }
371      } else if ( in.chunk && 0<length(grep(cont.re,line,perl=TRUE)) ){      } else if ( in.chunk && grepl(cont.re,line,perl=TRUE) ){
372        ## append this line to current chunk        ## append this line to current chunk
373        if ( 0 == length(grep(prefix,line,perl=TRUE)) ){        if ( !grepl(prefix,line,perl=TRUE) ){
374          ##describe<< Any lines with "\code{### }" at the left hand          ##describe<< Any lines with "\code{### }" at the left hand
375          ## margin within the included chunks are handled separately,          ## margin within the included chunks are handled separately,
376          ## so if they appear in the documentation they will appear          ## so if they appear in the documentation they will appear
# Line 378  Line 383 
383            payload <- stripped            payload <- stripped
384          }          }
385        }        }
386      } else if ( 0 < length(grep(arg.pat,line,perl=TRUE)) ){      } else if ( grepl(arg.pat,line,perl=TRUE) ){
387        not.describe <- (0==in.describe && !first.describe)        not.describe <- (0==in.describe && !first.describe)
388        if ( in.chunk && not.describe){        if ( in.chunk && not.describe){
389          res[[cur.field]] <- end.chunk(cur.field,payload)          res[[cur.field]] <- end.chunk(cur.field,payload)
# Line 440  Line 445 
445  ### with the string in this list (implemented in modify.Rd.file).  ### with the string in this list (implemented in modify.Rd.file).
446  }  }
447    
448    leadingS3generic <- function # check whether function name is an S3 generic
449    ### Determines whether a function name looks like an S3 generic function
450    (name,                     ##<< name of function
451     env,                      ##<< environment to search for additional generics
452     ...)                      ##<< ignored here
453    {
454      ##details<< This function is one of the default parsers, but exposed as
455      ## possibly of more general interest. Given a function name of the form
456      ## x.y.z it looks for the generic function x applying to objects of class
457      ## y.z and also for generic function x.y applying to objects of class z.
458      ##
459      parts <- strsplit(name, ".", fixed = TRUE)[[1]]
460      l <- length(parts)
461      if (l > 1) {
462        for (i in 1:(l - 1)) {
463          ## Look for a generic function (known by the system or defined
464          ## in the package) that matches that part of the function name
465          generic <- paste(parts[1:i], collapse = ".")
466          if (any(generic %in% utils:::getKnownS3generics()) ||
467              utils:::findGeneric(generic, env) != "") {
468            object <- paste(parts[(i + 1):l], collapse = ".")
469            ##details<< Assumes that the first name which matches any known
470            ## generics is the target generic function, so if both x and x.y
471            ## are generic functions, will assume generic x applying to objects
472            ## of class y.z
473            ##value<< If a matching generic found returns a list with a single component:
474            return(list(.s3method=c(generic, object))) ##<< a character vector containing generic name and object name.
475          }
476        }
477      }
478      ##value<< If no matching generic functions are found, returns an empty list.
479      list()
480    }
481    
482  ### Parsers for each function that are constructed automatically. This  ### Parsers for each function that are constructed automatically. This
483  ### 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
484  ### individual object.  ### individual object.
# Line 448  Line 487 
487         examples.after.return=examples.after.return,         examples.after.return=examples.after.return,
488         extract.xxx.chunks=extract.xxx.chunks,         extract.xxx.chunks=extract.xxx.chunks,
489         ## title from first line of function def         ## title from first line of function def
490         title.from.firstline=function(src,name,code,...){         title.from.firstline=function(src,...){
491           if(length(grep("#",src[1]))){           first <- src[1]
492             list(title=gsub("[^#]*#\\s*(.*)","\\1",src[1],perl=TRUE))           if(!is.character(first))return(list())
493           } else list()           if(!grepl("#",first))return(list())
494             list(title=gsub("[^#]*#\\s*(.*)","\\1",first,perl=TRUE))
495         },         },
496         ## PhG: it is tests/FUN.R!!! I would like more flexibility here         ## PhG: it is tests/FUN.R!!! I would like more flexibility here
497         ## please, let me choose which dir to use for examples!         ## please, let me choose which dir to use for examples!
# Line 461  Line 501 
501           if (is.null(tsubdir)) tsubdir <- "tests"       # Default value           if (is.null(tsubdir)) tsubdir <- "tests"       # Default value
502           tfile <- file.path("..",tsubdir,paste(name,".R",sep=""))           tfile <- file.path("..",tsubdir,paste(name,".R",sep=""))
503           if(file.exists(tfile))           if(file.exists(tfile))
504             list(examples=paste(readLines(tfile),collapse="\n"))             list(examples=readLines(tfile))
505           else list()           else list()
506         },         },
507         definition.from.source=function(doc,src,...){         definition.from.source=function(doc,src,...){
508           def <- doc$definition           def <- doc$definition
509           is.empty <- function(x)is.null(x)||x==""           is.empty <- function(x)is.null(x)||x==""
510           if(is.empty(def) && !is.empty(src))           if(is.empty(def) && !is.empty(src))
511             list(definition=paste(src,collapse="\n"))             list(definition=src)
512           else list()           else list()
513         })         })
514    
# Line 507  Line 547 
547               ## Add an empty line before and after example               ## Add an empty line before and after example
548               ex <- c("", ex, "")               ex <- c("", ex, "")
549             }             }
550             list(examples = paste(ex, collapse = "\n"))             list(examples = ex)
551           } else list()           } else list()
552         })         },collapse=function(doc,...){
553             L <- lapply(doc,paste,collapse="\n")
554             L$.overwrite <- TRUE
555             L
556           },tag.s3methods=leadingS3generic
557           )
558    
559  ### List of parser functions that operate on single objects. This list  ### List of parser functions that operate on single objects. This list
560  ### is useful for testing these functions.  ### is useful for testing these functions.
561  lonely <- c(forall.parsers,forfun.parsers)  lonely <- structure(c(forall.parsers,forfun.parsers),ex=function(){
 attr(lonely,"ex") <- function(){  
562    f <- function # title    f <- function # title
563  ### description  ### description
564    (x, ##<< arg x    (x, ##<< arg x
# Line 530  Line 574 
574    src <- attr(f,"source")    src <- attr(f,"source")
575    lonely$extract.xxx.chunks(src)    lonely$extract.xxx.chunks(src)
576    lonely$prefixed.lines(src)    lonely$prefixed.lines(src)
577  }  })
578    
579  extra.code.docs <- function # Extract documentation from code chunks  extra.code.docs <- function # Extract documentation from code chunks
580  ### Parse R code to extract inline documentation from comments around  ### Parse R code to extract inline documentation from comments around
# Line 555  Line 599 
599        doc <- list()        doc <- list()
600        if ( !is.null(parsed[[on]]) ){        if ( !is.null(parsed[[on]]) ){
601          if ( !is.na(parsed[[on]]@code[1]) ){ # no code given for generics          if ( !is.na(parsed[[on]]@code[1]) ){ # no code given for generics
602            doc$definition <- paste(parsed[[on]]@code,collapse="\n")            doc$definition <- paste(parsed[[on]]@code)
603          }          }
604          if(!"description"%in%names(doc) && !is.na(parsed[[on]]@description) ){          if(!"description"%in%names(doc) && !is.na(parsed[[on]]@description) ){
605            doc$description <- parsed[[on]]@description            doc$description <- parsed[[on]]@description
606          }          }
607          if ( "setMethodS3" == parsed[[on]]@created ){          ## if ( "setMethodS3" == parsed[[on]]@created ){
608            # PhG: this may be wrong! It does not catch correctly how the method          ##   gen <- leadingS3generic(on,topenv())
609            # must be splitted in case of methods containing dots. for instance,          ##   if ( 0 < length(gen) ){
610            # as.data.frame.matrix must be split into: m1 = as.data.frame and          ##     doc$.s3method <- gen$.s3method
611            # m2 = matrix... here you got m1 = as, and m2 = data.frame.matrix!!!          ##     cat("S3method(",gen$.s3method[1],",",gen$.s3method[2],")\n",sep="")
612                    pattern <- "^([^\\.]+)\\.(.*)$"          ##   }
613            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="")  
         }  
614        }        }
615        if("title" %in% names(doc) && !"description" %in% names(doc) ){        if("title" %in% names(doc) && !"description" %in% names(doc) ){
616          ## For short functions having both would duplicate, but a          ## For short functions having both would duplicate, but a
# Line 592  Line 630 
630        NULL        NULL
631      } else if(0 == length(res) && "function" %in% class(o)      } else if(0 == length(res) && "function" %in% class(o)
632                && 1 == length(osource <- attr(o,"source"))                && 1 == length(osource <- attr(o,"source"))
633                && 1 == length(grep(paste("UseMethod(",on,")",sep="\""),osource))                && grepl(paste("UseMethod(",on,")",sep="\""),osource)
634                ){                ){
635        ## phew - this should only pick up R.oo S3 generic definitions like:        ## phew - this should only pick up R.oo S3 generic definitions like:
636        ## attr(*, "source")= chr "function(...) UseMethod(\"select\")"        ## attr(*, "source")= chr "function(...) UseMethod(\"select\")"
# Line 653  Line 691 
691  default.parsers <-  default.parsers <-
692    c(extra.code.docs=extra.code.docs, ## TODO: cleanup!    c(extra.code.docs=extra.code.docs, ## TODO: cleanup!
693      sapply(forfun.parsers,forfun),      sapply(forfun.parsers,forfun),
     sapply(forall.parsers,forall),  
694      edit.package.file=function(desc,...){      edit.package.file=function(desc,...){
695        in.details <- setdiff(colnames(desc),"Description")        in.details <- setdiff(colnames(desc),"Description")
696        details <- paste(paste(in.details,": \\tab ",desc[,in.details],"\\cr",        details <- sprintf("%s: \\tab %s\\cr",in.details,desc[,in.details])
                              sep=""),collapse="\n")  
697        L <-        L <-
698          list(list(title=desc[,"Title"],          list(list(title=desc[,"Title"],
699                    description=desc[,"Description"],                    description=desc[,"Description"],
700                    `tabular{ll}`=details,                    `tabular{ll}`=details))
                   author=desc[,"Maintainer"]))  
701        names(L) <- paste(desc[,"Package"],"-package",sep="")        names(L) <- paste(desc[,"Package"],"-package",sep="")
702        L        L
703      })      },
704        sapply(forall.parsers,forall)
705        )
706    
707  setClass("DocLink", # Link documentation among related functions  setClass("DocLink", # Link documentation among related functions
708  ### The \code{.DocLink} class provides the basis for hooking together  ### The \code{.DocLink} class provides the basis for hooking together
709  ### documentation of related classes/functions/objects. The aim is that  ### documentation of related classes/functions/objects. The aim is that
710  ### documentation sections missing from the child are  ### documentation sections missing from the child are inherited from
711    ### the parent class.
712           representation(name="character", ##<< name of object           representation(name="character", ##<< name of object
713                          created="character", ##<< how created                          created="character", ##<< how created
714                          parent="character", ##<< parent class or NA                          parent="character", ##<< parent class or NA
# Line 705  Line 743 
743      ## "prefix" lines will be used instead.      ## "prefix" lines will be used instead.
744      default.description <- NULL      default.description <- NULL
745      while ( start > last.end+1      while ( start > last.end+1
746             && 1 == length(grep(prefix,code[start-1],perl=TRUE)) ){             && grepl(prefix,code[start-1],perl=TRUE) ){
747        start <- start-1        start <- start-1
748      }      }
749      if ( start < chunks[[k]][1] ){      if ( start < chunks[[k]][1] ){
# Line 732  Line 770 
770        ## If the function definition is not embedded within the call, then        ## If the function definition is not embedded within the call, then
771        ## the parent is that function. Test whether the the third value        ## the parent is that function. Test whether the the third value
772        ## looks like a name and add it to parents if so.        ## looks like a name and add it to parents if so.
773        if ( 1 == length(grep("^[\\._\\w]+$",chars[3],perl=TRUE)) ){        if ( grepl("^[\\._\\w]+$",chars[3],perl=TRUE) ){
774          parent <- chars[3]          parent <- chars[3]
775        }        }
776        res[[object.name]] <- new("DocLink",name=object.name,        res[[object.name]] <- new("DocLink",name=object.name,
# Line 764  Line 802 
802        ## If the function definition is not embedded within the call, then        ## If the function definition is not embedded within the call, then
803        ## the parent is that function. Test whether the the fourth value        ## the parent is that function. Test whether the the fourth value
804        ## looks like a name and add it to parents if so.        ## looks like a name and add it to parents if so.
805        if ( 1 == length(grep("^[\\._\\w]+$",chars[4],perl=TRUE)) ){        if ( grepl("^[\\._\\w]+$",chars[4],perl=TRUE) ){
806          parent <- c(chars[4],parent)          parent <- c(chars[4],parent)
807        }        }
808        res[[object.name]] <- new("DocLink",name=object.name,        res[[object.name]] <- new("DocLink",name=object.name,
# Line 847  Line 885 
885  ### Additional arguments to pass to Parser Functions.  ### Additional arguments to pass to Parser Functions.
886   ){   ){
887    e <- new.env()    e <- new.env()
888    old <- options(keep.source=TRUE)    ## KMP 2011-03-09 fix problem with DocLink when inlinedocs ran on itself
889      ## Error in assignClassDef(Class, classDef, where) :
890      ##   Class "DocLink" has a locked definition in package "inlinedocs"
891      ## Traced to "where" argument in setClassDef which defaults to topenv()
892      ## which in turn is inlinedocs when processing inlinedocs package, hence
893      ## the clash. The following works (under R 2.12.2), so that the topenv()
894      ## now finds e before finding the inlinedocs environment.
895      old <- options(keep.source=TRUE,topLevelEnvironment=e)
896    on.exit(options(old))    on.exit(options(old))
897    exprs <- parse(text=code)    exprs <- parse(text=code)
898    for (i in exprs){    for (i in exprs){
# Line 859  Line 904 
904    
905    docs <- list()    docs <- list()
906    
   # 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  
             }  
         }  
     }  
   }  
907    ## apply parsers in sequence to code and objs    ## apply parsers in sequence to code and objs
908    for(i in seq_along(parsers)){    for(i in seq_along(parsers)){
909      N <- names(parsers[i])      N <- names(parsers[i])
# Line 887  Line 914 
914      }      }
915      p <- parsers[[i]]      p <- parsers[[i]]
916      ## This is the argument list that each parser receives:      ## This is the argument list that each parser receives:
917      L <- p(code=code,objs=objs,docs=docs,...)      L <- p(code=code,objs=objs,docs=docs,env=e,...)
918      docs <- combine(docs,L)      docs <- combine(docs,L)
919    }    }
920      ## post-process to collapse all character vectors
921      for(i in seq_along(docs)){
922        for(j in seq_along(docs[[i]])){
923          if(names(docs[[i]])[j]!=".s3method")
924          docs[[i]][[j]] <- paste(docs[[i]][[j]],collapse="\n")
925        }
926      }
927    if(verbose)cat("\n")    if(verbose)cat("\n")
928    docs    docs
929  ### A list of extracted documentation from code.  ### A list of extracted documentation from code.
# Line 906  Line 940 
940  ### description file.  ### description file.
941  nondesc.parsers <- default.parsers[non.descfile.names]  nondesc.parsers <- default.parsers[non.descfile.names]
942    
943  extract.docs.file <- function  extract.docs.file <- structure(function
944  ### Apply all parsers relevant to extract info from just 1 code file.  ### Apply all parsers relevant to extract info from just 1 code file.
945  (f,  (f,
946  ### File name of R code to read and parse.  ### File name of R code to read and parse.
947   parsers=nondesc.parsers,   parsers=NULL,
948  ### Parser Functions to use to parse the code and extract  ### Parser Functions to use to parse the code and extract
949  ### documentation.  ### documentation.
950   ...   ...
951  ### Other arguments to pass to Parser Functions.  ### Other arguments to pass to Parser Functions.
952   ){   ){
953      if(is.null(parsers))parsers <- nondesc.parsers
954    apply.parsers(readLines(f),parsers,verbose=FALSE,...)    apply.parsers(readLines(f),parsers,verbose=FALSE,...)
955  }  },ex=function(){
956      f <- system.file("silly","R","silly.R",package="inlinedocs")
957      extract.docs.file(f) ##FIXME: warning
958    })

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

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