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 109 - (view) (download)

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

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