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

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