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 191, Thu Feb 17 14:09:43 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        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    
# Line 46  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 442  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 451  Line 488 
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,...){         title.from.firstline=function(src,...){
491           if(length(src) && grepl("#",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 511  Line 549 
549             }             }
550             list(examples = ex)             list(examples = ex)
551           } else list()           } else list()
552         },         },collapse=function(doc,...){
553         collapse.docs=function(doc,...){           L <- lapply(doc,paste,collapse="\n")
554           list(doc=lapply(doc,paste,collapse="\n"))           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 535  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 565  Line 604 
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 ( grepl("\\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 664  Line 697 
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      },      },
# Line 675  Line 707 
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 852  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 864  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 892  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 911  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.191  
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