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 212, Wed Mar 9 16:37:25 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 184  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 282  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 290  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 365  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 380  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 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 450  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 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 ( 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 597  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 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 710  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 737  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 769  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 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      ## 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      options(topLevelEnvironment=e)
896    old <- options(keep.source=TRUE)    old <- options(keep.source=TRUE)
897    on.exit(options(old))    on.exit(options(old))
898    exprs <- parse(text=code)    exprs <- parse(text=code)
# Line 864  Line 905 
905    
906    docs <- list()    docs <- list()
907    
   # 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  
             }  
         }  
     }  
   }  
908    ## apply parsers in sequence to code and objs    ## apply parsers in sequence to code and objs
909    for(i in seq_along(parsers)){    for(i in seq_along(parsers)){
910      N <- names(parsers[i])      N <- names(parsers[i])
# Line 892  Line 915 
915      }      }
916      p <- parsers[[i]]      p <- parsers[[i]]
917      ## This is the argument list that each parser receives:      ## This is the argument list that each parser receives:
918      L <- p(code=code,objs=objs,docs=docs,...)      L <- p(code=code,objs=objs,docs=docs,env=e,...)
919      docs <- combine(docs,L)      docs <- combine(docs,L)
920    }    }
921      ## post-process to collapse all character vectors
922      for(i in seq_along(docs)){
923        for(j in seq_along(docs[[i]])){
924          if(names(docs[[i]])[j]!=".s3method")
925          docs[[i]][[j]] <- paste(docs[[i]][[j]],collapse="\n")
926        }
927      }
928    if(verbose)cat("\n")    if(verbose)cat("\n")
929    docs    docs
930  ### A list of extracted documentation from code.  ### A list of extracted documentation from code.
# Line 911  Line 941 
941  ### description file.  ### description file.
942  nondesc.parsers <- default.parsers[non.descfile.names]  nondesc.parsers <- default.parsers[non.descfile.names]
943    
944  extract.docs.file <- function  extract.docs.file <- structure(function
945  ### Apply all parsers relevant to extract info from just 1 code file.  ### Apply all parsers relevant to extract info from just 1 code file.
946  (f,  (f,
947  ### File name of R code to read and parse.  ### File name of R code to read and parse.
948   parsers=nondesc.parsers,   parsers=NULL,
949  ### Parser Functions to use to parse the code and extract  ### Parser Functions to use to parse the code and extract
950  ### documentation.  ### documentation.
951   ...   ...
952  ### Other arguments to pass to Parser Functions.  ### Other arguments to pass to Parser Functions.
953   ){   ){
954      if(is.null(parsers))parsers <- nondesc.parsers
955    apply.parsers(readLines(f),parsers,verbose=FALSE,...)    apply.parsers(readLines(f),parsers,verbose=FALSE,...)
956  }  },ex=function(){
957      f <- system.file("silly","R","silly.R",package="inlinedocs")
958      extract.docs.file(f)
959    })

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

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