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 395, Tue Feb 11 21:51:01 2014 UTC revision 396, Tue Feb 18 13:07:32 2014 UTC
# Line 1  Line 1 
1  #  #
2    ############################################################
3    sigString <- function(sig){paste(sig,collapse="_")}
4    ############################################################
5    methodDocName=function
6    ### creates the actual *.Rd filename for a method from its signature and the generic it implements
7    (genName,sig){
8      N=paste(genName,"_method__",sigString(sig),sep="")
9      N
10    }
11  # vim:set ff=unix expandtab ts=2 sw=2:  # vim:set ff=unix expandtab ts=2 sw=2:
12    ############################################################
13    setMethod("[",
14        signature(x = "listOfMethods", i = "logical"),
15        function
16        ### overload the [] operator for objects of class "listOfMethods"
17        (x, i, j, ..., drop = TRUE)
18        {
19           fdef <- x@generic
20           object <- new("listOfMethods", arguments = fdef@signature)
21           object@generic <- fdef
22           object@signatures  <- x@signatures[i]
23           object@.Data       <-      x@.Data[i]
24           object@names       <-      x@names[i]
25           #pe(quote(class(object)),environment())
26           object
27    
28        }
29    )
30    ############################################################
31    mmPromptMethods <-  function (genName, filename = NULL, exportedMeths,where)
32      ## this is a copy of R s own promptMehtods functions but
33      ## with an additional argument of the methods to be exported (and documented)
34    {
35    
36        genExported  <- !is.null(exportedMeths)
37    
38        escape <- function(txt) gsub("%", "\\\\%", txt)
39        packageString <- ""
40        fdef <- getGeneric(genName,where=where)
41        if (!isGeneric(f=genName ,where=where,fdef = fdef))
42            stop(gettextf("no generic function found corresponding to %s",
43                sQuote(genName)), domain = NA)
44        methods <- findMethods(fdef,where=where)
45    
46        #where <- .genEnv(fdef, topenv(parent.frame()))
47        #if (!identical(where, .GlobalEnv))
48        #    packageString <- sprintf("in Package \\pkg{%s}",
49        #        getPackageName(where))
50        fullName <- utils:::topicName("methods", genName)
51    
52        n <- length(methods)
53        labels <- character(n)
54        aliases <- character(n)
55        signatures <- findMethodSignatures(methods = methods, target = TRUE)
56        args <- colnames(signatures)
57        for (i in seq_len(n)) {
58            sigi <- signatures[i, ]
59            labels[[i]] <- sprintf("\\code{signature(%s)}", paste(sprintf("%s = \"%s\"",
60                args, escape(sigi)), collapse = ", "))
61            aliases[[i]] <- paste0("\\alias{", utils:::topicName("method",
62                c(genName, signatures[i, ])), "}")
63        }
64        ####
65        if(genExported){
66          exportedSignatures <-findMethodSignatures(methods =exportedMeths, target = TRUE)
67         # #pp("exportedSignatures",environment())
68          n=nrow(exportedSignatures)
69          labels <- character(n)
70          items<- character(n)
71          args <- colnames(exportedSignatures)
72          for (i in seq_len(n)) {
73            sigi <- exportedSignatures[i, ]
74            N <- methodDocName(genName,sigi)
75            labels[[i]] <- sprintf("\\code{signature(%s)}", paste(sprintf("%s = \"%s\"",
76                args, escape(sigi)), collapse = ", "))
77            items[[i]]<- paste0("    \\item{", labels[[i]], "}{\n      \\code{\\link{",N,"}}  \n    }")
78    
79          }
80          des <- paste0(
81            "\\description{\n ~~ Methods for function",
82            " \\code{", genName, "}",
83            sub("^in Package", "in package", packageString),
84            " ~~\n}"
85          )
86    
87          text <- c("\\section{Methods}{\n  \\describe{", items, "\n  }\n}")
88    
89        }else{
90          des <- paste0(
91            "\\description{\n All methods for function",
92            " \\code{", genName, "} ",
93            "are intended for internal use inside the package only. \n}"
94          )
95          #item<-'
96          #All methods for this generic are privat. (not exported into the namespace).
97          #To discourage use outside the package the documentation is truncated.
98          #'
99          #text <- c("\\section{Methods}{\n\\describe{", item, "}\n}")
100          text <- "" #no method section at all
101        }
102        aliasText <- c(paste0("\\alias{", escape(fullName), "}"),
103            escape(aliases))
104        if (identical(filename, FALSE))
105            return(c(aliasText, text))
106        if (is.null(filename) || identical(filename, TRUE))
107            filename <- paste0(fullName, ".Rd")
108        Rdtxt <- list(name = paste0("\\name{", fullName, "}"), type = "\\docType{methods}",
109            aliases = aliasText, title = sprintf("\\title{ ~~ Methods for Function \\code{%s} %s ~~}",
110                genName, packageString), description = des
111            , `section{Methods}` = text,
112            keywords = c("\\keyword{methods}", "\\keyword{ ~~ other possible keyword(s) ~~ }"))
113        if (is.na(filename))
114            return(Rdtxt)
115        cat(unlist(Rdtxt), file = filename, sep = "\n")
116        print(paste("A shell of methods documentation has been written",filename))
117        invisible(filename)
118    }
119    
120    ############################################################
121    removeComma <- function(str){
122      if(grepl(",",str)){
123         str <- strsplit(str,",")[[1]][[1]]
124      }
125      return(str)
126    }
127    ############################################################
128    exported=function
129    ### a helper soon to read the NAMESPACE file, soon to be replaced by Rs own function
130    (pattern,tD){
131      ##pp("tD",environment())
132      #pe(quote(getwd()),environment())
133      # for simpler parsing we dont allow every possible
134      # export statement but assume the form
135      # export(
136      #  firstFunc,
137      #  secondFunc
138      # )
139      ns=readLines(file.path(tD,"NAMESPACE"))
140      if(any(grepl(pattern,ns))){
141        fl=grep(pattern,ns)[[1]]
142        # start search for closing ")" at the opening one and
143        # use only the next ")" if there are several
144        ll= grep("\\)",ns[fl:length(ns)])[[1]]+fl-1
145        if (ll==fl+1){
146          return(NULL)
147        }else{
148          trunks= unlist(lapply(ns[(fl+1):(ll-1)],removeComma))
149          return(trunks)
150        }
151      }else{
152        return(NULL)
153      }
154    }
155    ############################################################
156    exportedFunctions=function
157    ### get the exported functions from the NAMESPACE file
158    (tD){
159      funcNames=exported("export\\(",tD)
160      #pp("funcNames",environment())
161      return(funcNames)
162    }
163    ############################################################
164    exportedGenerics=function
165    ### get the exported generic functions from the NAMESPACE file
166    (tD){
167      # note that there is only a exportMethods statement available
168      funcNames=exported("exportMethods",tD)
169      return(funcNames)
170    }
171    ############################################################
172    exportedClasses=function
173    ### get the exported Classes from the NAMESPACE file
174    (tD){
175      classnames=exported("exportClasses",tD)
176      return(classnames)
177    }
178    ############################################################
179    methodTable <- function(exprs,e){
180      gens=list() ## a list of generic functions that are mentioned in setMethod statements within the code to be documented
181      for ( k in 1:length(exprs)){
182        lang <- exprs[[k]]
183        chars <- as.character(lang)
184        ##pp("chars",environment())
185        expr.type <- chars[[1]]
186        if (expr.type == "setMethod"){
187          NamedArgs=rewriteSetMethodArgs(lang)
188          nameOfGeneric<-NamedArgs[["f"]]
189          methSig <- eval(NamedArgs[["signature"]],e)
190          gens[[nameOfGeneric]] <- unique(c(gens[[nameOfGeneric]],list(methSig)))
191        }
192      }
193      gens
194    }
195    ############################################################
196    allClasses <- function(env){
197      getClasses(where=env)
198    }
199    ############################################################
200    hiddenClasses <- function(env,pkgDir){
201      setdiff(allClasses(env),exportedClasses(pkgDir))
202    }
203    ############################################################
204    # now find all Generics whose src can be found
205    GenHasSrc=function
206    ### This function tells us if we can find a src reference for this generic
207    (genName,e)
208    {!is.null(getSrcref(getGeneric(genName,where=e)))}
209    
210    
211    # we now want to find all Generics that have at least one Method where we can get at the source
212    ############################################################
213    methSrc=function
214    ### get at the src of a method given as  an MethodDefinition object
215    (MethodDefinition){getSrcref(unRematchDefinition(MethodDefinition))}
216    ############################################################
217    methSig=function
218    ### Extract the definition as text from an MethodDefinition object
219    (MethodDefinition){attr(MethodDefinition,"defined")}
220    ############################################################
221    MethodHasSrc=function(MethodDefinition)
222    ### This function tells if we can find a src reference for this method
223    {!is.null(methSrc(MethodDefinition))}
224    ############################################################
225    MethodSignatureHasOnlyExportedClasses=function(MethodDefinition,env,pkgDir)
226    ### check if all the classes in the signature are exported in the NAMESPACE file.
227    ### This information is needed to decide which Methods we want to document in cases
228    ### where the documentations is restricted to the exported NAMESPACE
229    {
230      sigStr=as.character(methSig(MethodDefinition))
231      hiddCls <- hiddenClasses(env,pkgDir)
232      intersection <- intersect(sigStr,hiddCls)
233      res <- (length(intersection)==0)
234      res
235    }
236    ############################################################
237    MethodsWithSrcRefForGen=function
238    ### Not all methods for a Generic are defined in the src we want to document.
239    ### This function helps to find the methods we want.
240    (genName,env){
241      l=findMethods(genName,where=env)[sapply(findMethods(genName,where=env),MethodHasSrc)]
242      #class(l)<-"methods"
243      l
244    }
245    ############################################################
246    GenHasAnyMethodWithSrc=function
247    ### function to check if we have a src reference for any of the methods of this generic
248    ### This helps to decide how the *-methods.Rd file should look like for this generic
249    (genName,env){
250      methDefs <- findMethods(genName,where=env)
251      ##pp("methDefs)
252      any(sapply(
253        methDefs,
254        MethodHasSrc))
255    }
256    ############################################################
257    GenHasAnyExposedMethod=function
258    ### function used to check if a GenericFunction has any method where the whole signature consist of classes exported in the namespace
259    (genName,env,pkgDir){
260      decide=function(MethodDescription){
261        MethodSignatureHasOnlyExportedClasses(MethodDescription,env,pkgDir)
262      }
263      hasExposedMethod <- any(
264          sapply(
265            findMethods(genName,where=env)
266            ,decide
267          )
268      )
269      #pp("genName",environment())
270      #pp("hasExposedMethod",environment())
271      hasExposedMethod
272    }
273    ############################################################
274    documentableMeths<- function(e){
275      # now find out which generics have any documentable methods
276      allGens=as.character(getGenerics(where=e))
277      ##pp("allGens",environment())
278      decide=function(genName){
279        GenHasAnyMethodWithSrc(genName,e)
280      }
281      GensWithDocMethods=allGens[unlist(sapply(allGens,decide))]
282      ##pp("GensWithDocMethods",environment())
283      # now we can make a list of list
284      # containing the Methods we want to documents ordered after the name of there Generics
285      documentableMeths=list()
286      for (genName in GensWithDocMethods){
287            documentableMeths[[genName]]<-MethodsWithSrcRefForGen(genName,e)
288      }
289      documentableMeths
290    }
291    ############################################################
292    exportedDocumentableMeths<- function(e,pkgDir){
293      decide1=function(genName){
294         GenHasAnyExposedMethod(genName,e,pkgDir)
295      }
296      dm <- documentableMeths(e)
297      indices=unlist(sapply(names(dm),decide1))
298      #pp("indices",environment())
299      newGens <- dm[indices]
300      decide2 <-  function(MethodDescription){
301        MethodSignatureHasOnlyExportedClasses(MethodDescription,e,pkgDir)
302      }
303      for (genName in names(newGens)){
304         allMeths=newGens[[genName]]
305         newGens[[genName]] <- allMeths[sapply(allMeths,decide2)]
306      }
307      newGens
308    
309    }
310    ############################################################
311    getMethodName <- function(doc.link,e){
312      method.name<- doc.link@name
313      method.name
314    }
315    ############################################################
316    getMethodSrc <- function(doc.link,e){
317      chunk.source <- doc.link@code
318      method.name<- doc.link@name
319      old.opt <- options(keep.source=TRUE)
320      parsed <- try(parse(text=chunk.source))
321      options(old.opt)
322      if ( inherits(parsed,"try-error") ){
323        stop("parse failed with error:\n",parsed)
324      }
325      lp <- length(parsed)
326      ##pp("lp",environment())
327      ##pp("parsed",environment())
328      if(lp!=1){
329        stop("extract.docs.setMethod:the expected code should be a lingle setMethod expression")
330      }
331    
332    
333      NamedArgs=rewriteSetMethodArgs(parsed[[1]])
334      #pp("NamedArgs",environment())
335      s <- NamedArgs[["signature"]]
336      #pp("s",environment())
337      methodDef=getMethod(
338          f=NamedArgs[["f"]],
339          signature=eval(NamedArgs[["signature"]]),
340          where=e
341        )
342      #pp("methodDef",environment())
343      src=as.character(getSrcref(unRematchDefinition(methodDef)))
344      src
345    }
346     rewriteSetMethodArgs=function(lang){
347       ### Since we do not know if the arguments in the call to setMethod are given with
348       ### keywords, partially matching keywords as an ordered list or any
349       ### combination of it, we use the same function as R  (match.arg )
350       ### to rewrite our argumentlist to a (pair)list from which
351       ### we can extract the information easily
352       KeyWords=c("f","signature","definition","where")
353       NamedArgs=list() # the new argument list
354       args=lang[2:length(lang)]
355       argNames=names(args)
356       if(is.null(argNames)){
357         # in the  special case keyword=value pairs are not given at all
358         # we determine them by position
359         for (i in seq_along(args)){
360            #pp("i",environment())
361            NamedArgs[[KeyWords[[i]] ]] <- args[[i]]
362         }
363       }else{
364         # at least some keyword=value pairs are given
365         # we determine them by match arg or by position
366         for (i in seq_along(args)){
367            argName=argNames[[i]]
368            if(argNames[[i]]==""){ # no keyword=value given for this arg
369              NamedArgs[[KeyWords[[i]]]] <- args[[i]] #determining the keyword  by position
370            }else{
371             newName=try(match.arg(argNames[[i]],KeyWords))
372             if (class(newName)=="try-error") {
373               stop(paste("could not match the argument with name : " ,argNames[[i]]," to a formal argument of setMethod",sep=""))
374             }else{
375              NamedArgs[[newName]] <- args[[i]]
376            }
377           }
378         }
379       }
380       #NN <- names(NamedArgs)
381       ##pp("lang",environment())
382       ##pp("args",environment())
383       ##pp("argNames",environment())
384       ##pp("NN",environment())
385       NamedArgs
386     }
387  do.not.generate <- structure(function  do.not.generate <- structure(function
388  ### Make a Parser Function used to indicate that certain Rd files  ### Make a Parser Function used to indicate that certain Rd files
389  ### should not be generated.  ### should not be generated.
# Line 61  Line 445 
445    
446  ### combine NULL objects.  ### combine NULL objects.
447  combine.NULL<-function(x,y){  combine.NULL<-function(x,y){
448        if ((class(x) == "NULL")& (class(y) == "NULL")){
449            # print(paste("mm x=",x))
450            # print(paste("mm class(x)=",class(x)))
451            return(NULL)
452        }
453      if (class(x) == "NULL"){      if (class(x) == "NULL"){
454          # print(paste("mm x=",x))          # print(paste("mm x=",x))
455          # print(paste("mm class(x)=",class(x)))          # print(paste("mm class(x)=",class(x)))
# Line 166  Line 555 
555  }  }
556    
557  ### For each function in the package, do something.  ### For each function in the package, do something.
558  forfun <- function(FUN)forall(FUN,is.function)  forfun<- function
559    ### For each object in the package that satisfies the criterion
560  forGeneric<- function(  ### checked by subfun, parse source using FUN and return the resulting
561    FUN  ### Function to apply to each method in the package (usually FUN is a parser)  ### documentation list.
562    ,  (FUN
563    env  ### Function to apply to each function in the package.
   ,  
   gens  
564    ){    ){
565      #pe(quote(getwd()),environment())    FUN <- FUN
   force(FUN)  
566          f <- function(objs,docs,...){          f <- function(objs,docs,...){
567      genericFuncNames=names(gens)      if(length(objs)==0)return(list())
568        objs <- objs[sapply(objs,is.function)]
569            L <- list()            L <- list()
     for(genName in genericFuncNames){  
       fg=gens[[genName]]  
       meths=findMethods(fg,where=env)  
       signatureStrings=names(meths)  
       pp("signatureStrings",environment())  
570              on.exit(cat(sprintf("Parser Function failed on %s\n",N)))              on.exit(cat(sprintf("Parser Function failed on %s\n",N)))
571        for ( sig in signatureStrings){      for(N in names(objs)){
572                method <- meths[[sig]]        o <- objs[[N]]
573          src=getSource(method)        L[[N]] <- FUN(src=getSource(o),
574          N <- paste(genName,"-method-#",sig,sep="")                      name=N,objs=objs,o=o,docs=docs,doc=docs[[N]],...)
         L[[N]]  <-  FUN(src=src,objs=meths,name=N,...)  
575        }        }
576              on.exit()## remove warning message              on.exit()## remove warning message
     }  
577      L      L
578    }    }
579      class(f) <- c("allfun","function")
580    f    f
581    ### A Parser Function.
582  }  }
583    
584  kill.prefix.whitespace <- function  kill.prefix.whitespace <- function
# Line 557  Line 939 
939    list()    list()
940  }  }
941    
942  definition.from.source=function(doc,src,...){  definition.from.source=function(doc,src,...)
943    ### small helper to extract the definition of a doc entry from a bit of src code
944    {
945    def <- doc$definition    def <- doc$definition
946    is.empty <- function(x)is.null(x)||x==""    is.empty <- function(x)is.null(x)||x==""
947    if(is.empty(def) && !is.empty(src))    if(is.empty(def) && !is.empty(src))
# Line 565  Line 949 
949    else list()    else list()
950  }  }
951  ## title from first line of function def  ## title from first line of function def
952  title.from.firstline=function(src,...){  title.from.firstline=function
953    ### extract the title from the first line of a function definition
954    (src,...){
955    first <- src[1]    first <- src[1]
956    if(!is.character(first))return(list())    if(!is.character(first))return(list())
957    if(!grepl("#",first))return(list())    if(!grepl("#",first))return(list())
958    list(title=gsub("[^#]*#\\s*(.*)","\\1",first,perl=TRUE))    list(title=gsub("[^#]*#\\s*(.*)","\\1",first,perl=TRUE))
959  }  }
960  ############  ############
961  mm.examples.from.testfile=function(name,...){  mm.examples.from.testfile=function
962    pp("name",environment())  ### extract examples from external files
963    tsubdir <- getOption("inlinedocs.exampleDir")  (name,inlinedocs.exampleDir,inlinedocs.exampleTrunk,...){
964    trunk<- getOption("inlinedocs.exampleRegExpression")    tsubdir <-inlinedocs.exampleDir
965    if (is.null(tsubdir)) return(list())# do nothing    trunk<- inlinedocs.exampleTrunk
966    #pe(quote(getwd()),environment())    if (is.null(tsubdir)) {
967    #pp("tsubdir",environment())      return(list())# do nothing
968    p <- paste(trunk,name,"\\.R$",sep="")    }
969    #pp("p",environment())    p <- paste(trunk,name,".R",sep="")
970    allfiles=dir(tsubdir)    allfiles=dir(tsubdir)
971    #pp("allfiles",environment())    L<- allfiles[grepl(pattern=p,allfiles,fixed=TRUE)]
   L<- allfiles[grepl(pattern=p,allfiles)]  
   #pp("L",environment())  
972    path=function(l){file.path(tsubdir,l)}    path=function(l){file.path(tsubdir,l)}
973    paths=lapply(L,path)    paths=lapply(L,path)
974    print(lapply(paths,file.exists))    print(lapply(paths,file.exists))
975    
976      res=list()
977    if(length(L)>0){    if(length(L)>0){
978      exampleTexts= lapply(paths,readLines)      exampleTexts= lapply(paths,readLines)
     #pp("exampleTexts",environment())  
979      combinedText <- unlist(exampleTexts)      combinedText <- unlist(exampleTexts)
980        res[["examples"]]=combinedText
981        ##pp("res",environment())
982    
       return(list(examples=combinedText))  
       #pp("combinedTexts",environment())  
   }  
   else{  
     list()  
983    }    }
984      res
985  }  }
986  ### Parsers for each function that are constructed automatically. This  ### Parsers for each function that are constructed automatically. This
987  ### 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
# Line 625  Line 1007 
1007         definition.from.source=definition.from.source         definition.from.source=definition.from.source
1008         )         )
1009    
1010  extract.docs<-function(parsed,objs,on){  extract.docs<-function
1011    #pp("on",environment())  ### produce doc link instances
1012    (parsed,objs,on){
1013      ##pp("on",environment())
1014    extract.docs.try <-function(o,on)    extract.docs.try <-function(o,on)
1015      {      {
1016        ## Note: we could use parsed information here too, but that        ## Note: we could use parsed information here too, but that
# Line 673  Line 1057 
1057    }    }
1058    
1059  inherit.docs <- function(  inherit.docs <- function(
1060    ### recursively add documentation inherited from doc.link parents
1061    parsed, ##<< a list of doc.link objects    parsed, ##<< a list of doc.link objects
1062    res,    ##<< the list of documentation to be extended    res,    ##<< the list of documentation to be extended
1063    childName      ##<< the name of the object who possibly inherits    childName      ##<< the name of the object who possibly inherits
1064    ){    ){
1065    in.res <- res[[childName]] #start with the present    in.res <- res[[childName]] #start with the present
1066    #pp("in.res",environment())    ##pp("in.res",environment())
1067    childsDocLink <-parsed[[childName]]    childsDocLink <-parsed[[childName]]
1068    if ( !is.null(childsDocLink) ){    if ( !is.null(childsDocLink) ){
1069      for ( parent in childsDocLink@parent ){      for ( parent in childsDocLink@parent ){
1070        if ( !is.na(parent) ){        if ( !is.na(parent) ){
1071          #pp("parent",environment())          ##pp("parent",environment())
1072          #pe(quote(names(res)),environment())          #pe(quote(names(res)),environment())
1073          #pe(quote(parent %in% names(res)),environment())          #pe(quote(parent %in% names(res)),environment())
1074          if ( is.null(in.res) ){          if ( is.null(in.res) ){
# Line 702  Line 1087 
1087    invisible(in.res)    invisible(in.res)
1088    ### the possibly extended list of documentation    ### the possibly extended list of documentation
1089  }  }
1090    
1091    
1092    extra.method.docs <- function
1093    ### can be used in the parser list of package.skeleton.dx(). TODO:
1094    (code,
1095    ### Code lines in a character vector containing multiple R objects to
1096    ### parse for documentation.
1097    objs,
1098    ### The objects defined in the code.
1099    env,
1100    ### The environment they inhibit (needed to pass on)
1101    inlinedocs.exampleDir,
1102    ### A string pointing to the location where inlinedocs should search for external examples
1103    inlinedocs.exampleTrunk,
1104    ### A string used to identify the files containing external examples in the example directory. All file names of external examples have to start with this string
1105    ...
1106    ### ignored
1107     ){
1108      doc.names <- names(objs)
1109      parsed <- extract.file.parse(code,env)
1110      res=list()
1111      for ( nn in names(parsed) ){
1112        dL=parsed[[nn]]
1113        if ( dL@created == "setMethod" ){
1114          S4Method.docs <- extract.docs.setMethod(dL,env,inlinedocs.exampleDir,inlinedocs.exampleTrunk)
1115          docname <- dL@name
1116          if ( is.null(res[[docname]]) ){
1117            res[[docname]] <- S4Method.docs
1118            doc.names <- c(doc.names,docname)
1119          } else {
1120            stop(nn," appears as both S4 method and some other definition")
1121          }
1122        }
1123      }
1124      all.done <- FALSE
1125      while ( !all.done ){
1126        res1 <- sapply(doc.names,inherit.docs,parsed=parsed,res=res,simplify=FALSE)
1127        all.done <- identical(res1,res)
1128        res <- res1
1129      }
1130      res
1131    ### named list of lists, one for each object to document.
1132    }
1133    
1134    
1135    
1136  extra.class.docs <- function # Extract documentation from code chunks  extra.class.docs <- function # Extract documentation from code chunks
1137  ### Parse R code to extract inline documentation from comments around  ### Parse R code to extract inline documentation from comments around
1138  ### each class  ### each class
# Line 774  Line 1205 
1205    res    res
1206  ### named list of lists, one for each object to document.  ### named list of lists, one for each object to document.
1207  }  }
 forMethod.parsers<-  
   list(  
     prefixed.lines=prefixed.lines,  
     extract.xxx.chunks=extract.xxx.chunks,  
     title.from.firstline=title.from.firstline,  
     mm.examples.from.testfile  
   )  
1208  ### List of Parser Functions that can be applied to any object.  ### List of Parser Functions that can be applied to any object.
1209  forall.parsers <-  forall.parsers <-
1210    list(## Fill in author from DESCRIPTION and titles.    list(## Fill in author from DESCRIPTION and titles.
# Line 852  Line 1276 
1276  ### List of parsers to use by default with package.skeleton.dx.  ### List of parsers to use by default with package.skeleton.dx.
1277  default.parsers <-  default.parsers <-
1278    c(    c(
     extra.code.docs=extra.code.docs, ## TODO: cleanup!  
1279      extra.class.docs=extra.class.docs, ## TODO: cleanup!      extra.class.docs=extra.class.docs, ## TODO: cleanup!
1280        extra.method.docs=extra.method.docs, ## TODO: cleanup!
1281        extra.code.docs=extra.code.docs, ## TODO: cleanup!
1282      sapply(forfun.parsers,forfun),      sapply(forfun.parsers,forfun),
1283      edit.package.file=function(desc,...){      edit.package.file=function(desc,...){
1284        in.details <- setdiff(colnames(desc),"Description")        in.details <- setdiff(colnames(desc),"Description")
# Line 997  Line 1422 
1422                                  code=paste(chunks[[k]],sep=""),                                  code=paste(chunks[[k]],sep=""),
1423                                  description=default.description)                                  description=default.description)
1424      } else if (expr.type == "setMethod" ) {      } else if (expr.type == "setMethod" ) {
       pp("lang",environment())  
       pp("chars",environment())  
1425    
1426        ## Since we do not know if the arguments in the call to setMethod are given with        NamedArgs=rewriteSetMethodArgs(lang)
       ## keywords, partially matching keywords as an ordered list ore any  
       ## combination of it, we use the same function as R  (match.arg )  
       ## to rewrite our argumentlist to a (pair)list from which  
       ## we can extract the information easily  
       KeyWords=c("f","signature","definition","where")  
       NamedArgs=list() # the new argument list  
       args=lang[2:length(lang)]  
       argNames=names(args)  
       pp("args",environment())  
       pp("argNames",environment())  
       for (i in seq_along(lang[2:length(lang)])){  
          argName=argNames[[i]]  
          if(argNames[[i]]==""){ # no keyword=value given for this arg  
            NamedArgs[[KeyWords[[i]]]] <- args[[i]] #determining the keyword  by position  
          }else{  
           newName=try(match.arg(argNames[[i]],KeyWords))  
           if (class(newName)=="try-error") {  
             stop(paste("could not match the argument with name : " ,argNames[[i]]," to a formal argument of setMethod",sep=""))  
           }else{  
            NamedArgs[[newName]] <- args[[i]]  
          }  
         }  
       }  
       pp("NamedArgs",environment())  
1427        genName=NamedArgs[["f"]]        genName=NamedArgs[["f"]]
1428        sigexp=NamedArgs[["signature"]]        sigexp=NamedArgs[["signature"]]
       pp("sigexp",environment())  
1429        sig=eval(sigexp,env)        sig=eval(sigexp,env)
1430        pp("sig",environment())        N <- methodDocName(genName,sig)
       sigString <- paste(sig,collapse="#")  
       N=paste(genName,"-method-#",sigString,sep="")  
1431        object.name <- N        object.name <- N
       pp("object.name",environment())  
1432    
1433        ## If the function definition is not embedded within the call, then        ## If the function definition is not embedded within the call, then
1434        ## the parent is that function. Test whether the value for "definition"        ## the parent is that function. Test whether the value for "definition"
# Line 1114  Line 1509 
1509    }    }
1510    invisible(docs)    invisible(docs)
1511  }  }
1512    extract.docs.setMethod<- function # S4 mehtod inline documentation
1513    ### Using the same conventions as for functions, definitions of S4 methods
1514    ### in the form \code{setMethod(\dots)} are also located and
1515    ### scanned for inline comments.
1516    
1517    (doc.link,
1518    ### DocLink object as created by \code{extract.file.parse}.
1519     env,
1520     ### environment to find method source
1521    inlinedocs.exampleDir,
1522    ### A string pointing to the location where inlinedocs should search for external examples
1523    inlinedocs.exampleTrunk
1524    ### A regular expression used to identify the files containing external examples in the example directory
1525     ){
1526      funcSource=getMethodSrc(doc.link,env)
1527      method.name=getMethodName(doc.link,env)
1528      ##pp("funcSource",environment())
1529      docs=list()
1530      docs<- combine(docs,prefixed.lines(funcSource))
1531      ##pp("docs",environment())
1532      docs <- combine(docs,extract.xxx.chunks(funcSource,method.name))
1533      ##pp("docs",environment())
1534      docs <- combine(docs,title.from.firstline(funcSource,method.name))
1535      ##pp("docs",environment())
1536      docs <- combine(docs,mm.examples.from.testfile(method.name,inlinedocs.exampleDir,inlinedocs.exampleTrunk))
1537      docs
1538    }
1539  createObjects <- function(code){  createObjects <- function(code){
1540    # this is factored out to make writing tests easier    ### the function creates the environment object lists and expression by parsing all the code files
1541    # since we often need the objects and the environment    ### Is is factored out to make writing tests easier
1542    # they inhabit    ### since we often need the objects and the environment
1543      ### they inhabit
1544    e <- new.env()    e <- new.env()
1545    ## KMP 2011-03-09 fix problem with DocLink when inlinedocs ran on itself    ## KMP 2011-03-09 fix problem with DocLink when inlinedocs ran on itself
1546    ## Error in assignClassDef(Class, classDef, where) :    ## Error in assignClassDef(Class, classDef, where) :
# Line 1126  Line 1549 
1549    ## which in turn is inlinedocs when processing inlinedocs package, hence    ## which in turn is inlinedocs when processing inlinedocs package, hence
1550    ## the clash. The following works (under R 2.12.2), so that the topenv()    ## the clash. The following works (under R 2.12.2), so that the topenv()
1551    ## now finds e before finding the inlinedocs environment.    ## now finds e before finding the inlinedocs environment.
1552    old <- options(keep.source=TRUE,topLevelEnvironment=e)  
1553      #old <- options(keep.source=TRUE,topLevelEnvironment=e)
1554      old <- options(topLevelEnvironment=e)
1555    on.exit(options(old))    on.exit(options(old))
1556    exprs <- parse(text=code)    exprs <- parse(text=code,keep.source=TRUE)
1557    ## TDH 2011-04-07 set this so that no warnings about creating a fake    ## TDH 2011-04-07 set this so that no warnings about creating a fake
1558    ## package when we try to process S4 classes defined in code    ## package when we try to process S4 classes defined in code
1559    e$.packageName <- "inlinedocs.processor"    e$.packageName <- "inlinedocs.processor"
# Line 1149  Line 1574 
1574  ### List of Parser Functions.  ### List of Parser Functions.
1575   verbose=FALSE,   verbose=FALSE,
1576  ### Echo names of Parser Functions?  ### Echo names of Parser Functions?
1577    inlinedocs.exampleDir,
1578    ### A string pointing to the location where inlinedocs should search for external examples
1579    inlinedocs.exampleTrunk,
1580    ### A string used to identify the files containing external examples in the example directory. All file names of external examples have to start with this string
1581   ...   ...
1582  ### Additional arguments to pass to Parser Functions.  ### Additional arguments to pass to Parser Functions.
1583   ){   ){
1584  #  #####################################    l=createObjects(code)# note that ls will not find S4 classes nor methods for generic functions
 #  e <- new.env()  
 #  ## KMP 2011-03-09 fix problem with DocLink when inlinedocs ran on itself  
 #  ## Error in assignClassDef(Class, classDef, where) :  
 #  ##   Class "DocLink" has a locked definition in package "inlinedocs"  
 #  ## Traced to "where" argument in setClassDef which defaults to topenv()  
 #  ## which in turn is inlinedocs when processing inlinedocs package, hence  
 #  ## the clash. The following works (under R 2.12.2), so that the topenv()  
 #  ## now finds e before finding the inlinedocs environment.  
 #  old <- options(keep.source=TRUE,topLevelEnvironment=e)  
 #  on.exit(options(old))  
 #  exprs <- parse(text=code)  
 #  ## TDH 2011-04-07 set this so that no warnings about creating a fake  
 #  ## package when we try to process S4 classes defined in code  
 #  e$.packageName <- "inlinedocs.processor"  
 #  for (i in exprs){  
 #      eval(i, e)  
 #  }  
 #  objs <- sapply(ls(e),get,e,simplify=FALSE) # note that ls will not find S4 classes nor methods for generic functions  
   l=createObjects(code)  
1585    objs=l[["objs"]]    objs=l[["objs"]]
1586    e=l[["env"]]    e=l[["env"]]
1587    exprs=l[["exprs"]]    exprs=l[["exprs"]]
   # since th method definitions do not appear in ls() so are not represented in obs  
   # so we have to find them in the parsed code  
   glo=list()  
   for ( k in 1:length(exprs)){  
     lang <- exprs[[k]]  
     chars <- as.character(lang)  
     #pp("chars",environment())  
     expr.type <- chars[[1]]  
     object.name <- chars[[2]]  
     if (expr.type == "setMethod"){glo=c(glo,object.name)}  
   }  
   gloFuncs=unlist(sapply(glo,getGeneric,where=e))  
   #####################################  
1588    docs <- list()    docs <- list()
   # now find generic Functions that are defined in the code  
   # since those lead to entries in objs we can find them  
   pe(quote(length(names(objs))),environment())  
   if (length(names(objs))!=0){  
     definedGenerics=objs[sapply(names(objs),isGeneric,e)]  
   }else{  
     definedGenerics=list()  
   }  
   #gens=unique(c(definedGenerics,gloFuncs))  
   gens=definedGenerics  
   #gens=gloFuncs  
   # gens=glo  
   pp("gens",environment())  
   
1589    
1590    ## apply parsers in sequence to code and objs    ## apply parsers in sequence to code and objs
1591    if(verbose)cat("Applying parsers:\n")    if(verbose)cat("Applying parsers:\n")
# Line 1215  Line 1598 
1598      }      }
1599      p <- parsers[[i]]      p <- parsers[[i]]
1600      ## This is the argument list that each parser receives:      ## This is the argument list that each parser receives:
1601      L <- p(code=code,objs=objs,docs=docs,env=e,...)      L <- p(
1602            code=code,
1603            objs=objs,
1604            docs=docs,
1605            env=e,
1606            inlinedocs.exampleDir=inlinedocs.exampleDir,
1607            inlinedocs.exampleTrunk=inlinedocs.exampleTrunk,
1608            ...
1609            )
1610      docs <- combine(docs,L)      docs <- combine(docs,L)
1611    }    }
1612    ## post-process to collapse all character vectors    ## post-process to collapse all character vectors
# Line 1226  Line 1617 
1617      }      }
1618   }   }
1619    if(verbose)cat("\n")    if(verbose)cat("\n")
   ## mm I added a second parser loop here for my method parsers  
   ## It would perhaps be possible to integrate the new parsers in the  
   ## main loop above  
   docs2 <- list()  
   parsersForMethods=sapply(forMethod.parsers,forGeneric,env=e,gens=gens)  
   for(i in seq_along(parsersForMethods)){  
     N <- names(parsersForMethods[[i]])  
     p <- parsersForMethods[[i]]  
     cat(" this is parser:",N,"\n",sep="")  
     L <- p(code=code,objs=objs,docs=docs2,env=e,...)  
     #pp("L",environment())  
     docs2 <- combine(docs2,L)  
   }  
1620    
1621    return(list(docs=combine(docs,docs2),env=e,objs=objs,gens=gens))    return(list(docs=docs,env=e,objs=objs,exprs=exprs))
1622  ### A list of extracted documentation from code.  ### A list of extracted documentation from code.
1623  }  }
1624    
# Line 1262  Line 1640 
1640   parsers=NULL,   parsers=NULL,
1641  ### Parser Functions to use to parse the code and extract  ### Parser Functions to use to parse the code and extract
1642  ### documentation.  ### documentation.
1643    inlinedocs.exampleDir=file.path("..","..","inst","tests"),
1644    ### A string pointing to the location where inlinedocs should search for external examples
1645    inlinedocs.exampleTrunk="example.",
1646    ### A string used to identify the files containing external examples in the example directory. All file names of external examples have to start with this string
1647   ...   ...
1648  ### Other arguments to pass to Parser Functions.  ### Other arguments to pass to Parser Functions.
1649   ){   ){
1650    if(is.null(parsers))parsers <- nondesc.parsers    if(is.null(parsers))parsers <- nondesc.parsers
1651    apply.parsers(readLines(f),parsers,verbose=FALSE,...)[["docs"]]    apply.parsers(
1652            readLines(f),
1653            parsers,
1654            verbose=FALSE,
1655            inlinedocs.exampleDir,
1656            inlinedocs.exampleTrunk,
1657            ...
1658            )[["docs"]]
1659  },ex=function(){  },ex=function(){
1660    f <- system.file("silly","R","silly.R",package="inlinedocs")    f <- system.file("silly","R","silly.R",package="inlinedocs")
1661    extract.docs.file(f)    extract.docs.file(f)

Legend:
Removed from v.395  
changed lines
  Added in v.396

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