SCM

SCM Repository

[inlinedocs] Annotation of /pkg/inlinedocs/R/parsers.R
ViewVC logotype

Annotation of /pkg/inlinedocs/R/parsers.R

Parent Directory Parent Directory | Revision Log Revision Log


Revision 152 - (view) (download)

1 : tdhock 110 ### combine lists or character strings
2 :     combine <- function(x,y)UseMethod("combine")
3 :    
4 :     ### combine character strings by pasting them together
5 :     combine.character <- function(x,y)
6 :     paste(x,y,sep="\n")
7 :    
8 :     ### combine lists by adding elements or adding to existing elements
9 :     combine.list <- function(x,y){
10 :     toadd <- !names(y)%in%names(x)
11 :     toup <- names(y)[names(y)%in%names(x)]
12 :     x[names(y)[toadd]] <- y[toadd]
13 :     for(up in toup)x[[up]] <- combine(x[[up]],y[[up]])
14 :     return(x)
15 :     ### A list, same type as x, but with added elements from y.
16 :     }
17 :    
18 :     ### Prefix for code comments used with grep and gsub.
19 :     prefix <- "^[ \t]*###[ \t]"
20 :    
21 :     decomment <- function
22 :     ### Remove comment prefix and join lines of code to form a
23 :     ### documentation string.
24 :     (comments
25 :     ### Character vector of prefixed comment lines.
26 :     ){
27 :     paste(gsub(prefix,"",comments),collapse="\n")
28 :     ### String without prefixes or newlines.
29 :     }
30 :    
31 : tdhock 138 ### For each object in the package that satisfies the criterion#
32 :     ## checked by subfun, parse source using FUN and return the resulting
33 : tdhock 87 ### documentation list.
34 :     forall <- function
35 :     (FUN,
36 :     ### Function to apply to each element in the package.
37 :     subfun=function(x)TRUE
38 :     ### Function to select subsets of elements of the package, such as
39 :     ### is.function. subfun(x)==TRUE means FUN will be applied to x and
40 :     ### the result will be returned.
41 :     ){
42 : tdhock 138 FUN <- FUN
43 :     f <- function(objs,docs,...){
44 : tdhock 87 objs <- objs[sapply(objs,subfun)]
45 :     L <- list()
46 : tdhock 93 for(N in names(docs)){
47 : tdhock 87 o <- objs[[N]]
48 : tdhock 89 L[[N]] <- FUN(src=attr(o,"source"),
49 :     name=N,objs=objs,o=o,docs=docs,doc=docs[[N]],...)
50 : tdhock 87 }
51 :     L
52 :     }
53 : tdhock 138 class(f) <- c("allfun","function")
54 :     f
55 : tdhock 87 ### A Parser Function.
56 :     }
57 :    
58 : tdhock 138 ### Print method for functions constructed using forall.
59 :     print.allfun <- function(x,...){
60 :     e <- environment(x)
61 :     cat("Function to apply to every element.\nselector:")
62 :     print(e$subfun)
63 :     cat("processor:")
64 :     print(e$FUN)
65 :     }
66 :    
67 : tdhock 87 ### For each function in the package, do something.
68 :     forfun <- function(FUN)forall(FUN,is.function)
69 :    
70 : tdhock 138 examples.after.return <- function
71 :     ### Get examples from inline definitions after return()
72 :     ### PhG: this does not work well! Think of these situations:
73 :     ### 1) You have multiple return() in the code of your function,
74 :     ### 2) You have return() appearing is some example code, ...
75 :     ### I can hardly propose a hack here. The whole code of the function
76 :     ### must be parsed, and one must determine which one is the last line
77 :     ### of code that is actually executed.
78 :     ###
79 :     ### I make two propositions here
80 :     ### 1) to keep the same mechanism that has the advantage of simplicity
81 :     ### but to use a special tag
82 :     ### ##examples<< or #{{{examples to separate
83 :     ### function code from examples explicitly, and
84 :     ### 2) to place the example in an "ex" attribute
85 :     ### attached to the function
86 :     ### (see next parser). That solution will be also interesting for
87 :     ### documenting datasets, something not done yet by inlinedocs!
88 :     (src,name="",...) {
89 :     ## Look for the examples mark
90 :     m <- grep("^\\s*(##examples<<|#\\{\\{\\{examples)", src)
91 :     if (!length(m)) return(list())
92 :     if (length(m) > 1)
93 :     warning("More than one examples tag for ", name,
94 :     ". Taking the last one")
95 :     m <- m[length(m)]
96 :     ## Look for the lines containing return value comments just before
97 :     r <- grep("\\s*### ", src[1:(m-1)])
98 :     if (!length(r)) {
99 :     value <- NULL
100 :     } else {
101 :     ## Only take consecutive lines before the mark
102 :     keep <- rev((m - rev(r)) == 1:length(r))
103 :     if (!any(keep)) {
104 :     value <- NULL
105 :     } else {
106 :     value <- decomment(src[r[keep]])
107 :     }
108 :     }
109 :     ## Collect now the example code beneath the mark
110 :     ex <- src[(m + 1):(length(src) - 1)]
111 :     ## Possibly eliminate a #}}} tag
112 :     ex <- ex[!grepl("#}}}", ex)]
113 :     ## Eliminate leading tabulations or four spaces
114 :     prefixes <- gsub("(\\s*).*","\\1",ex,perl=TRUE)[grep("\\w",ex)]
115 :     FIND <- prefixes[which.min(nchar(prefixes))]
116 :     ex <- sub(FIND,"",ex)
117 :     ## Add an empty line before and after example
118 :     ex <- c("", ex, "")
119 :     ## Return examples and value
120 :     list(examples = paste(ex, collapse = "\n"), value = value)
121 :     }
122 :    
123 :     prefixed.lines <- function(src,...){
124 :     ### The primary mechanism of inline documentation is via consecutive
125 :     ### groups of lines matching the specified prefix regular expression
126 :     ### "\code{^### }" (i.e. lines beginning with "\code{### }") are
127 :     ### collected as follows into documentation sections:\describe{
128 :     ### \item{description}{group starting at line 2 in the code}
129 :     ### \item{arguments}{group following each function argument}
130 :     ### \item{value}{group ending at the penultimate line of the code}}
131 :     ### These may be added to by use of the \code{##<<} constructs
132 :     ### described below.
133 :     clines <- grep(prefix,src)
134 :     if(length(clines)==0)return(list())
135 :     bounds <- which(diff(clines)!=1)
136 :     starts <- c(1,bounds+1)
137 :     ends <- c(bounds,length(clines))
138 :     ## detect body of function using paren matching
139 :     f <- function(ch)cumsum(nchar(gsub(sprintf("[^%s]",ch),"",src)))
140 :     parens <- f("(")-f(")")
141 :     body.begin <- which(diff(parens)<0 & parens[-1]==0)+2
142 :     is.arg <- function(){
143 :     0 == length(grep("^\\s*#",src[start-1],perl=TRUE)) &&
144 :     start<=body.begin
145 :     }
146 :     res <- list()
147 :     for(i in seq_along(starts)){
148 :     start <- clines[starts[i]]
149 :     end <- clines[ends[i]]
150 :     lab <- if(end+1==length(src))"value"
151 :     else if(start==2)"description"
152 :     else if(is.arg()){
153 :     ##twutz: strip leading white spaces and brackets and ,
154 :     arg <- gsub("^[ \t(,]*", "", src[start - 1])
155 :     arg <- gsub("^([^=,]*)[=,].*", "\\1", arg)
156 :     ##twutz: remove trailing whitespaces
157 :     arg <- gsub("^([^ \t]*)([ \t]+)$","\\1",arg)
158 :     arg <- gsub("...", "\\dots", arg, fix = TRUE)
159 :     paste("item{",arg,"}",sep="")
160 :     } else {
161 :     next;
162 :     }
163 :     res[[lab]] <- decomment(src[start:end])
164 :     }
165 :     res
166 :     }
167 :    
168 : tdhock 99 ### Parsers for each object/function that are constructed
169 :     ### automatically. This is a named list, each element is a list of 2
170 :     ### elements: forfun/forall, then a parser function for an individual
171 :     ### object.
172 : tdhock 138 forfun.parsers <-
173 :     list(prefixed.lines=prefixed.lines,
174 :     examples.after.return=examples.after.return,
175 :     ## Extract lots of info from normal functions.
176 :     parsefun=function(src,name,...){
177 : tdhock 89 extract.docs.fun(src,name)
178 : tdhock 138 },
179 :     ## title from first line of function def
180 :     title.from.firstline=function(src,name,code,...){
181 :     if(length(grep("#",src[1]))){
182 :     list(title=gsub("[^#]*#\\s*(.*)","\\1",src[1],perl=TRUE))
183 :     } else list()
184 :     },
185 : tdhock 116 ## PhG: it is tests/FUN.R!!! I would like more flexibility here
186 :     ## please, let me choose which dir to use for examples!
187 :     ## Get examples for FUN from the file tests/FUN.R
188 : tdhock 138 examples.from.testfile=function(name,...){
189 : phgrosjean 108 tsubdir <- getOption("inlinedocs.exdir")
190 : tdhock 116 if (is.null(tsubdir)) tsubdir <- "tests" # Default value
191 :     tfile <- file.path("..",tsubdir,paste(name,".R",sep=""))
192 : tdhock 89 if(file.exists(tfile))
193 :     list(examples=paste(readLines(tfile),collapse="\n"))
194 :     else list()
195 : tdhock 138 },
196 :     definition.from.source=function(doc,src,...){
197 :     def <- doc$definition
198 : tdhock 144 is.empty <- function(x)is.null(x)||x==""
199 :     if(is.empty(def) && !is.empty(src))
200 : tdhock 142 list(definition=paste(src,collapse="\n"))
201 : tdhock 138 else list()
202 :     })
203 :    
204 :     ### List of Parser Functions that can be applied to any object.
205 :     forall.parsers <-
206 :     list(## Fill in author from DESCRIPTION and titles.
207 :     author.from.description=function(desc,...){
208 :     list(author=desc[,"Maintainer"])
209 :     },
210 :     ## The format section sometimes causes problems, so erase it.
211 :     erase.format=function(...){
212 :     list(format="")
213 :     },
214 :     ## Convert the function name to a title.
215 :     title.from.name=function(name,doc,...){
216 :     if("title"%in%names(doc))list() else
217 :     list(title=gsub("[._]"," ",name))
218 :     },
219 : tdhock 116 ## PhG: here is what I propose for examples code in the 'ex' attribute
220 : tdhock 138 examples.in.attr = function (name, o, ...) {
221 : tdhock 116 ex <- attr(o, "ex")
222 :     if (!is.null(ex)) {
223 :     ## Special case for code contained in a function
224 :     if (inherits(ex, "function")) {
225 :     ## If source is available, start from there
226 :     src <- attr(ex, "source")
227 :     if (!is.null(src)) {
228 :     ex <- src
229 :     } else { ## Use the body of the function
230 :     ex <- deparse(body(ex))
231 :     }
232 :     ## Eliminate leading and trailing code
233 :     ex <- ex[-c(1, length(ex))]
234 : tdhock 138 ## Eliminate leading tabulations or 2/4 spaces
235 :     ex <- sub("^\t| | ", "", ex)
236 : tdhock 116 ## Add an empty line before and after example
237 :     ex <- c("", ex, "")
238 :     }
239 :     list(examples = paste(ex, collapse = "\n"))
240 :     } else list()
241 : tdhock 128 })
242 : tdhock 87
243 : tdhock 89 ### List of parser functions that operate on single objects. This list
244 : tdhock 128 ### is useful for testing these functions.
245 : tdhock 138 lonely <- c(forall.parsers,forfun.parsers)
246 : tdhock 128 attr(lonely,"ex") <- function(){
247 :     lonely$parsefun(attr(extract.docs.file,"source"),"extract.docs.file")
248 :     }
249 : tdhock 87
250 : tdhock 109 extra.code.docs <- function # Extract documentation from code chunks
251 : tdhock 87 ### Parse R code to extract inline documentation from comments around
252 :     ### each function. These are not able to be retreived simply by
253 :     ### looking at the "source" attribute. This is a Parser Function that
254 : tdhock 106 ### can be used in the parser list of package.skeleton.dx(). TODO:
255 : phgrosjean 108 ### Modularize this into separate Parsers Functions for S4 classes,
256 :     ### prefixes, ##<<blocks, etc. Right now it is not very clean!
257 : tdhock 87 (code,
258 :     ### Code lines in a character vector containing multiple R objects to
259 :     ### parse for documentation.
260 :     objs,
261 :     ### The objects defined in the code.
262 :     ...
263 :     ### ignored
264 :     ){
265 :     parsed <- extract.file.parse(code)
266 :     extract.docs.try <- function(o,on)
267 :     {
268 :     ## Note: we could use parsed information here too, but that
269 :     ## would produce different results for setMethodS3 etc.
270 :     doc <- list()
271 :     if ( !is.null(parsed[[on]]) ){
272 :     if ( !is.na(parsed[[on]]@code[1]) ){ # no code given for generics
273 :     doc$definition <- paste(parsed[[on]]@code,collapse="\n")
274 :     }
275 :     if(!"description"%in%names(doc) && !is.na(parsed[[on]]@description) ){
276 :     doc$description <- parsed[[on]]@description
277 :     }
278 :     if ( "setMethodS3" == parsed[[on]]@created ){
279 : phgrosjean 108 # PhG: this may be wrong! It does not catch correctly how the method
280 : tdhock 138 # must be splitted in case of methods containing dots. for instance,
281 :     # as.data.frame.matrix must be split into: m1 = as.data.frame and
282 :     # m2 = matrix... here you got m1 = as, and m2 = data.frame.matrix!!!
283 : phgrosjean 108 pattern <- "^([^\\.]+)\\.(.*)$"
284 : tdhock 87 doc$s3method=c(m1 <- gsub(pattern,"\\1",on,perl=TRUE),
285 :     m2 <- gsub(pattern,"\\2",on,perl=TRUE))
286 :     if ( 0 < length(grep("\\W",m1,perl=TRUE)) ){
287 : phgrosjean 108 m1 <- paste("`",m1,"`",sep="")
288 : tdhock 87 }
289 :     cat("S3method(",m1,",",m2,")\n",sep="")
290 :     }
291 :     }
292 :     if("title" %in% names(doc) && !"description" %in% names(doc) ){
293 :     ## For short functions having both would duplicate, but a
294 :     ## description is required. Therefore automatically copy title
295 :     ## across to avoid errors at package build time.
296 :     doc$description <- doc$title
297 :     }
298 :     doc
299 :     }
300 :     extract.docs <- function(on){
301 :     res <- try({o <- objs[[on]]
302 :     extract.docs.try(o, on)},FALSE)
303 :     if(class(res)=="try-error"){
304 :     cat("Failed to extract docs for: ",on,"\n\n")
305 :     list()
306 :     } else if(0 == length(res) && inherits(objs[[on]],"standardGeneric")){
307 :     NULL
308 :     } else if(0 == length(res) && "function" %in% class(o)
309 :     && 1 == length(osource <- attr(o,"source"))
310 :     && 1 == length(grep(paste("UseMethod(",on,")",sep="\""),osource))
311 :     ){
312 :     ## phew - this should only pick up R.oo S3 generic definitions like:
313 :     ## attr(*, "source")= chr "function(...) UseMethod(\"select\")"
314 :     NULL
315 :     } else res
316 :     }
317 :     doc.names <- names(objs)
318 :     res <- sapply(doc.names,extract.docs,simplify=FALSE)
319 :     ## Special processing for S4 classes as they do not appear in normal ls()
320 :     for ( nn in names(parsed) ){
321 :     if ( parsed[[nn]]@created == "setClass" ){
322 :     S4class.docs <- extract.docs.setClass(parsed[[nn]])
323 :     docname <- paste(nn,"class",sep="-")
324 :     if ( is.null(res[[docname]]) ){
325 :     res[[docname]] <- S4class.docs
326 :     doc.names <- c(doc.names,docname)
327 :     } else {
328 :     stop(nn," appears as both S4 class and some other definition")
329 :     }
330 :     }
331 :     }
332 :     inherit.docs <- function(on){
333 :     in.res <- res[[on]]
334 :     if ( !is.null(parsed[[on]]) ){
335 :     for ( parent in parsed[[on]]@parent ){
336 :     if ( !is.na(parent) ){
337 :     if ( is.null(in.res) ){
338 :     in.res <- res[[parent]]
339 :     } else if ( parent %in% names(res) ){
340 :     parent.docs <- res[[parent]]
341 :     for ( nn in names(parent.docs) ){
342 :     if ( !nn %in% names(in.res) ){
343 :     in.res[[nn]] <- parent.docs[[nn]]
344 :     }
345 :     }
346 :     }
347 :     }
348 :     }
349 :     }
350 :     invisible(in.res)
351 :     }
352 :     all.done <- FALSE
353 :     while ( !all.done ){
354 :     res1 <- sapply(doc.names,inherit.docs,simplify=FALSE)
355 :     all.done <- identical(res1,res)
356 :     res <- res1
357 :     }
358 :     ## now strip out any generics (which have value NULL in res):
359 :     res.not.null <- sapply(res,function(x){!is.null(x)})
360 :     if ( 0 < length(res.not.null) && length(res.not.null) < length(res) ){
361 :     res <- res[res.not.null]
362 :     }
363 :     res
364 :     ### named list of lists, one for each object to document.
365 :     }
366 :    
367 : tdhock 89 ### List of parsers to use by default with package.skeleton.dx.
368 : tdhock 109 default.parsers <-
369 : tdhock 138 c(extra.code.docs=extra.code.docs, ## TODO: cleanup!
370 :     sapply(forfun.parsers,forfun),
371 :     sapply(forall.parsers,forall),
372 : tdhock 109 edit.package.file=function(desc,...){
373 :     in.details <- setdiff(colnames(desc),"Description")
374 :     details <- paste(paste(in.details,": \\tab ",desc[,in.details],"\\cr",
375 :     sep=""),collapse="\n")
376 :     L <-
377 :     list(list(title=desc[,"Title"],
378 :     description=desc[,"Description"],
379 :     `tabular{ll}`=details,
380 :     author=desc[,"Maintainer"]))
381 :     names(L) <- paste(desc[,"Package"],"-package",sep="")
382 :     L
383 :     })
384 : tdhock 87
385 :     extract.docs.fun <- function # Extract documentation from a function
386 :     ### Given source code of a function, return a list describing inline
387 :     ### documentation in that source code.
388 :     (code,
389 :     ### The function to examine.
390 :     name.fun
391 :     ### The name of the function/chunk to use in warning messages.
392 : tdhock 95 ){
393 : tdhock 87 res <- list()
394 :     ##details<< For simple functions/arguments, the argument may also be
395 :     ## documented by appending \code{##<<} comments on the same line as the
396 :     ## argument name. Mixing this mechanism with \code{###} comment lines for
397 :     ## the same argument is likely to lead to confusion, as the \code{###}
398 :     ## lines are processed first.
399 :     #arg.pat <- paste("^[^=,#]*?([\\w\\.]+)\\s*([=,].*|\\)\\s*)?",
400 :     # "<<\\s*(\\S.*?)\\s*$",
401 :     # sep="##") # paste avoids embedded trigger fooling the system
402 :     #tw: removed first comma
403 :     arg.pat <- paste("^[^=#]*?([\\w\\.]+)\\s*([=,].*|\\)\\s*)?",
404 :     "<<\\s*(\\S.*?)\\s*$",
405 :     sep="##") # paste avoids embedded trigger fooling the system
406 :    
407 :     skeleton.fields <- c("alias","details","keyword","references","author",
408 :     "note","seealso","value","title","description",
409 :     "describe","end")
410 :     ##details<< Additionally, consecutive sections of \code{##} comment
411 :     ## lines beginning with \code{##}\emph{xxx}\code{<<} (where
412 :     ## \emph{xxx} is one of the fields: \code{alias}, \code{details},
413 :     ## \code{keyword}, \code{references}, \code{author}, \code{note},
414 :     ## \code{seealso}, \code{value}, \code{title} or \code{description})
415 :     ## are accumulated and inserted in the relevant part of the .Rd
416 :     ## file.
417 :     ##
418 :     ## For \code{value}, \code{title}, \code{description} and function
419 :     ## arguments, these \emph{append} to any text from "prefix"
420 :     ## (\code{^### }) comment lines, irrespective of the order in the
421 :     ## source.
422 :     ##
423 :     ## When documenting S4 classes, documentation from \code{details}
424 :     ## sections will appear under a section \code{Objects from the Class}. That
425 :     ## section typically includes information about construction methods
426 :     ## as well as other description of class objects (but note that the
427 :     ## class Slots are documented in a separate section).
428 :    
429 :     ## but this should not appear, because separated by a blank line
430 :     extra.regexp <- paste("^\\s*##(",paste(skeleton.fields,collapse="|"),
431 :     ")<<\\s*(.*)$",sep="")
432 :     cont.re <- "^\\s*##\\s*"
433 :     in.describe <- 0
434 :     first.describe <- FALSE
435 :     k <- 1
436 :     in.chunk <- FALSE
437 :     end.chunk <- function(field,payload)
438 :     {
439 :     if ( "alias" == field ){
440 :     ##note<< \code{alias} extras are automatically split at new lines.
441 :     payload <- gsub("\\n+","\\}\n\\\\alias\\{",payload,perl=TRUE)
442 :     chunk.sep <- "}\n\\alias{"
443 :     } else if ( "keyword" == field ){
444 :     ##keyword<< documentation utilities
445 :     ##note<< \code{keyword} extras are automatically split at white space,
446 :     ## as all the valid keywords are single words.
447 :     payload <- gsub("\\s+","\\}\n\\\\keyword\\{",payload,perl=TRUE)
448 :     chunk.sep <- "}\n\\keyword{"
449 :     } else if ( "title" == field ){
450 :     chunk.sep <- " "
451 :     } else if ( "description" == field ){
452 :     chunk.sep <- "\n"
453 :     } else {
454 :     ##details<< Each separate extra section appears as a new
455 :     ## paragraph except that: \itemize{\item empty sections (no
456 :     ## matter how many lines) are ignored;\item \code{alias} and
457 :     ## \code{keyword} sections have special rules;\item
458 :     ## \code{description} should be brief, so all such sections
459 :     ## are concatenated as one paragraph;\item \code{title} should
460 :     ## be one line, so any extra \code{title} sections are
461 :     ## concatenated as a single line with spaces separating the
462 :     ## sections.}
463 :     chunk.sep <- "\n\n"
464 :     }
465 :     chunk.res <- NULL
466 :     if ( 0 == length(grep("^\\s*$",payload,perl=TRUE)) )
467 :     chunk.res <-
468 :     if ( is.null(res[[field]]) ) payload
469 :     else paste(res[[field]], payload, sep=chunk.sep)
470 :     invisible(chunk.res)
471 :     }
472 :     while ( k <= length(code) ){
473 :     line <- code[k]
474 :     if ( 0 < length(grep(extra.regexp,line,perl=TRUE) ) ){
475 :     ## we have a new extra chunk - first get field name and any payload
476 :     new.field <- gsub(extra.regexp,"\\1",line,perl=TRUE)
477 :     new.contents <- gsub(extra.regexp,"\\2",line,perl=TRUE)
478 :    
479 :     ##details<< As a special case, the construct \code{##describe<<} causes
480 :     ## similar processing to the main function arguments to be
481 :     ## applied in order to construct a describe block within the
482 :     ## documentation, for example to describe the members of a
483 :     ## list. All subsequent "same line" \code{##<<} comments go into that
484 :     ## block until terminated by a subsequent \code{##}\emph{xxx}\code{<<} line.
485 :     if ( "describe" == new.field ){
486 :     ##details<< Such regions may be nested, but not in such a way
487 :     ## that the first element in a \code{describe} is another \code{describe}.
488 :     ## Thus there must be at least one \code{##<<} comment between each
489 :     ## pair of \code{##describe<<} comments.
490 :     if ( first.describe ){
491 :     stop("consecutive ##describe<< at line",k,"in",name.fun)
492 :     } else {
493 :     if ( nzchar(new.contents) ){
494 :     if ( is.null(payload) || 0 == nzchar(payload) ){
495 :     payload <- new.contents
496 :     } else {
497 :     payload <- paste(payload,new.contents,sep="\n\n")
498 :     }
499 :     }
500 :     first.describe <- TRUE
501 :     }
502 :     } else if ( "end" == new.field ){
503 :     ##details<< When nested \code{describe} blocks are used, a comment-only
504 :     ## line with \code{##end<<} terminates the current level only; any
505 :     ## other valid \code{##}\emph{xxx}\code{<<} line terminates
506 :     ## all open describe blocks.
507 :     if ( in.describe>0 ){
508 :     ## terminate current \item and \describe block only
509 :     if ( "value" == cur.field && 1 == in.describe ){
510 :     payload <- paste(payload,"}",sep="")
511 :     } else {
512 :     payload <- paste(payload,"}\n}",sep="")
513 :     }
514 :     in.describe <- in.describe-1;
515 :     } else {
516 :     warning("mismatched ##end<< at line ",k," in ",name.fun)
517 :     }
518 :     if ( nzchar(new.contents) ){
519 :     if ( nzchar(payload) ){
520 :     payload <- paste(payload,new.contents,sep="\n")
521 :     } else {
522 :     payload <- new.contents
523 :     }
524 :     }
525 :     } else {
526 :     ## terminate all open \describe blocks (+1 because of open item)
527 :     if ( 0 < in.describe ){
528 :     if ( "value" != cur.field ){ # value is implicit describe block
529 :     payload <- paste(payload,"}",sep="")
530 :     }
531 :     while ( in.describe>0 ){
532 :     payload <- paste(payload,"}",sep="\n")
533 :     in.describe <- in.describe-1;
534 :     }
535 :     }
536 :     ## finishing any existing payload
537 :     if ( in.chunk ) res[[cur.field]] <- end.chunk(cur.field,payload)
538 :     in.chunk <- TRUE
539 :     cur.field <- new.field
540 :     payload <- new.contents
541 :     ##note<< The "value" section of a .Rd file is implicitly a describe
542 :     ## block and \code{##}\code{value}\code{<<} acts accordingly. Therefore
543 :     ## it automatically enables the describe block itemization (##<< after
544 :     ## list entries).
545 :     if ( "value" == new.field ){
546 :     first.describe <- TRUE;
547 :     }
548 :     }
549 :     } else if ( in.chunk && 0<length(grep(cont.re,line,perl=TRUE)) ){
550 :     ## append this line to current chunk
551 :     if ( 0 == length(grep(prefix,line,perl=TRUE)) ){
552 :     ##describe<< Any lines with "\code{### }" at the left hand
553 :     ## margin within the included chunks are handled separately,
554 :     ## so if they appear in the documentation they will appear
555 :     ## before the \code{##}\emph{xxx}\code{<}\code{<} chunks.
556 :     ### This one should not appear.
557 :     stripped <- gsub(cont.re,"",line,perl=TRUE)
558 :     if ( nzchar(payload) ){
559 :     payload <- paste(payload,stripped,sep="\n")
560 :     } else {
561 :     payload <- stripped
562 :     }
563 :     }
564 :     } else if ( 0 < length(grep(arg.pat,line,perl=TRUE)) ){
565 :     not.describe <- (0==in.describe && !first.describe)
566 :     if ( in.chunk && not.describe){
567 :     res[[cur.field]] <- end.chunk(cur.field,payload)
568 :     }
569 :     comment <- gsub(arg.pat,"\\3",line,perl=TRUE);
570 :     arg <- gsub(arg.pat,"\\\\item\\{\\1\\}",line,perl=TRUE)
571 :     in.chunk <- TRUE
572 :     if ( not.describe ){
573 : tdhock 115 ## TDH 2010-06-18 For item{}s in the documentation list names,
574 :     ## we don't need to have a backslash before, so delete it.
575 :     arg <- gsub("^[\\]+","",arg)
576 : tdhock 87 cur.field <- gsub("...","\\dots",arg,fix=TRUE) ##special case for dots
577 :     payload <- comment
578 :     } else {
579 :     ## this is a describe block, so we need to paste with existing
580 :     ## payload as a new \item.
581 :     if ( first.describe ){
582 :     ## for first item, need to add describe block starter
583 :     if ( "value" == cur.field ){
584 :     payload <- paste(payload,"\n",arg,"{",sep="")
585 :     } else {
586 :     payload <- paste(payload,"\\describe{\n",arg,"{",sep="")
587 :     }
588 :     first.describe <- FALSE
589 :     in.describe <- in.describe+1
590 :     } else {
591 :     ## subsequent item - terminate existing and start new
592 :     payload <- paste(payload,"}\n",arg,"{",sep="")
593 :     }
594 :     if ( nzchar(comment) ){
595 :     payload <- paste(payload,comment,sep="")
596 :     }
597 :     }
598 :     } else if ( in.chunk ){
599 :     if ( 0 == in.describe && !first.describe ){
600 :     ## reached an end to current field, but need to wait if in.describe
601 :     res[[cur.field]] <- end.chunk(cur.field,payload)
602 :     in.chunk <- FALSE
603 :     cur.field <- NULL
604 :     payload <- NULL
605 :     }
606 :     }
607 :     k <- k+1
608 :     }
609 :     ## finishing any existing payload
610 :     if ( 0 < in.describe ){
611 :     if ( "value" != cur.field ){ # value is implicit describe block
612 :     payload <- paste(payload,"}",sep="")
613 :     }
614 :     while ( in.describe>0 ){
615 :     payload <- paste(payload,"}",sep="\n")
616 :     in.describe <- in.describe-1;
617 :     }
618 :     }
619 :     if ( in.chunk ) res[[cur.field]] <- end.chunk(cur.field,payload)
620 :     res
621 :     ### Named list of character strings extracted from comments. For each
622 :     ### name N we will look for N\{...\} in the Rd file and replace it
623 :     ### with the string in this list (implemented in modify.Rd.file).
624 :     }
625 :    
626 :     setClass("DocLink", # Link documentation among related functions
627 :     ### The \code{.DocLink} class provides the basis for hooking together
628 :     ### documentation of related classes/functions/objects. The aim is that
629 :     ### documentation sections missing from the child are
630 :     representation(name="character", ##<< name of object
631 :     created="character", ##<< how created
632 :     parent="character", ##<< parent class or NA
633 :     code="character", ##<< actual source lines
634 :     description="character") ##<< preceding description block
635 :     )
636 :    
637 :     extract.file.parse <- function # File content analysis
638 :     ### Using the base \code{\link{parse}} function, analyse the file to link
639 :     ### preceding "prefix" comments to each active chunk. Those comments form
640 :     ### the default description for that chunk. The analysis also looks for
641 :     ### S4 class "setClass" calls and R.oo setConstructorS3 and setMethodS3
642 :     ### calls in order to link the documentation of those properly.
643 :     (code
644 :     ### Lines of R source code in a character vector - note that any
645 :     ### nested \code{source} statements are \emph{ignored} when scanning
646 :     ### for class definitions.
647 :     ){
648 :     res <- list()
649 :     old.opt <- options(keep.source=TRUE)
650 :     parsed <- try(parse(text=code))
651 :     options(old.opt)
652 :     if ( inherits(parsed,"try-error") ){
653 :     stop("parse failed with error:\n",parsed)
654 :     }
655 :     chunks <- attr(parsed,"srcref")
656 :     last.end <- 0
657 :     for ( k in 1:length(parsed) ){
658 :     start <- chunks[[k]][1]
659 :     ##details<< If the definition chunk does not contain a
660 :     ## description, any immediately preceding sequence consecutive
661 :     ## "prefix" lines will be used instead.
662 :     default.description <- NULL
663 :     while ( start > last.end+1
664 :     && 1 == length(grep(prefix,code[start-1],perl=TRUE)) ){
665 :     start <- start-1
666 :     }
667 :     if ( start < chunks[[k]][1] ){
668 :     default.description <- decomment(code[start:(chunks[[k]][1]-1)])
669 :     } else {
670 :     default.description <- NA_character_;
671 :     }
672 :     ##details<< Class and method definitions can take several forms,
673 :     ## determined by expression type: \describe{
674 :     ## \item{assignment (<-)}{Ordinary assignment of value/function;}
675 :     ## \item{setClass}{Definition of S4 class;}
676 :     ## \item{setConstructorS3}{Definition of S3 class using R.oo package;}
677 :     ## \item{setMethodS3}{Definition of method for S3 class using R.oo package.}}
678 :     ## Additionally, the value may be a name of a function defined elsewhere,
679 :     ## in which case the documentation should be copied from that other definition.
680 :     ## This is handled using the concept of documentation links.
681 :     lang <- parsed[[k]]
682 :     chars <- as.character(lang)
683 :     expr.type <- chars[1]
684 :     parent <- NA_character_
685 :    
686 :     if ( expr.type == "<-" || expr.type == "setConstructorS3" || expr.type == "setClass" ){
687 :     object.name <- chars[2]
688 :     ## If the function definition is not embedded within the call, then
689 :     ## the parent is that function. Test whether the the third value
690 :     ## looks like a name and add it to parents if so.
691 :     if ( 1 == length(grep("^[\\._\\w]+$",chars[3],perl=TRUE)) ){
692 :     parent <- chars[3]
693 :     }
694 :     res[[object.name]] <- new("DocLink",name=object.name,
695 :     created=expr.type,
696 :     parent=parent,
697 :     code=paste(chunks[[k]],sep=""),
698 :     description=default.description)
699 :     } else if ( expr.type == "setMethodS3" ){
700 :     ##details<< The \code{setMethodS3} calls introduce additional
701 :     ## complexity: they will define an additional S3 generic (which
702 :     ## needs documentation to avoid warnings at package build time)
703 :     ## unless one already exists. This also is handled by "linking"
704 :     ## documentation. A previously unseen generic is linked to the
705 :     ## first defining instances, subsequent definitions of that generic
706 :     ## also link back to the first defining instance.
707 :     generic.name <- chars[2]
708 :     object.name <- paste(generic.name,chars[3],sep=".")
709 :     if ( is.null(res[[generic.name]]) ){
710 :     generic.desc <- paste("Generic method behind \\code{\\link{",object.name,"}}",sep="")
711 :     res[[generic.name]] <- new("DocLink",
712 :     name=generic.name,
713 :     created=expr.type,
714 :     parent=object.name,
715 :     code=NA_character_,
716 :     description=generic.desc)
717 :     } else {
718 :     parent <- res[[generic.name]]@parent
719 :     }
720 :     ## If the function definition is not embedded within the call, then
721 :     ## the parent is that function. Test whether the the fourth value
722 :     ## looks like a name and add it to parents if so.
723 :     if ( 1 == length(grep("^[\\._\\w]+$",chars[4],perl=TRUE)) ){
724 :     parent <- c(chars[4],parent)
725 :     }
726 :     res[[object.name]] <- new("DocLink",name=object.name,
727 :     created=expr.type,
728 :     parent=parent,
729 :     code=paste(chunks[[k]],sep=""),
730 :     description=default.description)
731 :     } else {
732 :     ## Not sure what to do with these yet. Need to deal with setMethod, setAs etc.
733 :     }
734 :     }
735 :     invisible(res)
736 :     ### Returns an invisible list of .DocLink objects.
737 :     }
738 :    
739 :     extract.docs.setClass <- function # S4 class inline documentation
740 :     ### Using the same conventions as for functions, definitions of S4 classes
741 :     ### in the form \code{setClass("classname",\dots)} are also located and
742 :     ### scanned for inline comments.
743 : tdhock 93 (doc.link
744 : tdhock 87 ### DocLink object as created by \code{\link{extract.file.parse}}.
745 :     ### Note that \code{source} statements are \emph{ignored} when scanning for
746 :     ### class definitions.
747 : tdhock 93 ){
748 : tdhock 87 chunk.source <- doc.link@code
749 :     ##details<<
750 :     ## Extraction of S4 class documentation is currently limited to expressions
751 :     ## within the source code which have first line starting with
752 :     ## \code{setClass("classname"}. These are located from the source file
753 :     ## (allowing also for white space around the \code{setClass} and \code{(}).
754 :     ## Note that \code{"classname"} must be a quoted character string;
755 :     ## expressions returning such a string are not matched.
756 :     class.name <- doc.link@name
757 :    
758 :     ##details<< For class definitions, the slots (elements of the
759 :     ## \code{representation} list) fill the role of function
760 :     ## arguments, so may be documented by \code{##<<} comments on
761 :     ## the same line or \code{### } comments at the beginning of the
762 :     ## following line.
763 :     f.n <- paste(class.name,"class",sep="-")
764 :     docs <- extract.docs.fun(chunk.source,f.n)
765 : tdhock 138 ## also apply source parsing functions that I separated out into
766 :     ## separate functions
767 :     docs <- combine(docs,lonely$prefixed.lines(chunk.source))
768 :     docs$title <- lonely$title.from.firstline(chunk.source)
769 : tdhock 87 ##details<<
770 :     ## The class definition skeleton includes an \code{Objects from the Class}
771 :     ## section, to which any \code{##details<<} documentation chunks are
772 :     ## written. It is given a vanilla content if there are no specific
773 :     ## \code{##details<<} documentation chunks.
774 :     if ( is.null(docs[["details"]]) ){
775 :     docs[["details"]] <-
776 :     paste("Objects can be created by calls of the form \\code{new(",
777 :     class.name," ...)}",sep="")
778 :     }
779 :     docs[["section{Objects from the Class}"]] <- docs[["details"]]
780 :     ## seealso has a skeleton line not marked by ~ .. ~, so have to suppress
781 :     if ( is.null(docs[["seealso"]]) ){
782 :     docs[["seealso"]] <- ""
783 :     }
784 :     if ( is.null(docs[["alias"]]) ){
785 :     docs[["alias"]] <- class.name
786 :     }
787 :     if ( is.null(docs[["description"]]) ){
788 :     docs[["description"]] <- doc.link@description
789 :     }
790 :     invisible(docs)
791 :     }
792 : tdhock 105
793 : tdhock 109 apply.parsers <- function
794 :     ### Parse code to r objs, then run all the parsers and return the
795 :     ### documentation list.
796 : tdhock 105 (code,
797 :     ### Character vector of code lines.
798 : tdhock 109 parsers=default.parsers,
799 : tdhock 105 ### List of Parser Functions.
800 : tdhock 109 verbose=FALSE,
801 : tdhock 105 ### Echo names of Parser Functions?
802 :     ...
803 :     ### Additional arguments to pass to Parser Functions.
804 :     ){
805 :     e <- new.env()
806 : tdhock 110 old <- options(keep.source=TRUE)
807 : tdhock 109 on.exit(options(old))
808 : tdhock 110 exprs <- parse(text=code)
809 : tdhock 152 for (i in exprs){
810 :     tryCatch(eval(i, e),error=function(e){
811 :     ##print(e)
812 :     })
813 :     }
814 : tdhock 105 objs <- sapply(ls(e),get,e,simplify=FALSE)
815 :    
816 :     docs <- list()
817 : phgrosjean 108
818 :     # PhG: Automatically determine who is S3 methods
819 :     for (name in names(objs)) {
820 :     parts <- strsplit(name, ".", fixed = TRUE)[[1]]
821 :     l <- length(parts)
822 :     if (l > 1) {
823 :     for (i in 1:(l - 1)) {
824 :     # Look for a generic function (known by the system or defined
825 :     # in the package) that matches that part of the function name
826 :     generic <- paste(parts[1:i], collapse = ".")
827 :     if (any(generic %in% utils:::getKnownS3generics()) ||
828 :     utils:::findGeneric(generic, e) != "") {
829 :     object <- paste(parts[(i + 1):l], collapse = ".")
830 :     docs[[name]]$s3method <- c(generic, object)
831 :     break
832 :     }
833 :     }
834 :     }
835 :     }
836 : tdhock 109 ## apply parsers in sequence to code and objs
837 : tdhock 105 for(i in seq_along(parsers)){
838 :     N <- names(parsers[i])
839 :     if(verbose){
840 :     if(is.character(N) && N!=""){
841 :     cat(N," ",sep="")
842 :     }else cat('. ')
843 :     }
844 :     p <- parsers[[i]]
845 :     ## This is the argument list that each parser receives:
846 :     L <- p(code=code,objs=objs,docs=docs,...)
847 :     docs <- combine(docs,L)
848 :     }
849 :     if(verbose)cat("\n")
850 :     docs
851 :     ### A list of extracted documentation from code.
852 :     }
853 : tdhock 109
854 : tdhock 138 ### Names of Parser Functions that operate on the desc arg.
855 :     descfile.names <- c("author.from.description","edit.package.file")
856 :    
857 :     ### Names of Parser Functions that do NOT use the desc arg.
858 :     non.descfile.names <-
859 :     names(default.parsers)[!names(default.parsers)%in%descfile.names]
860 :    
861 : tdhock 118 ### Parsers that operate only on R code, independently of the
862 :     ### description file.
863 : tdhock 138 nondesc.parsers <- default.parsers[non.descfile.names]
864 : tdhock 118
865 : tdhock 109 extract.docs.file <- function
866 :     ### Apply all parsers relevant to extract info from just 1 code file.
867 :     (f,
868 :     ### File name of R code to read and parse.
869 : tdhock 118 parsers=nondesc.parsers,
870 : tdhock 109 ### Parser Functions to use to parse the code and extract
871 :     ### documentation.
872 :     ...
873 :     ### Other arguments to pass to Parser Functions.
874 :     ){
875 :     apply.parsers(readLines(f),parsers,verbose=FALSE,...)
876 :     }

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