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 115 - (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 : tdhock 115 ## TDH 2010-06-18 For item{}s in the documentation list names,
527 :     ## we don't need to have a backslash before, so delete it.
528 :     arg <- gsub("^[\\]+","",arg)
529 : tdhock 87 cur.field <- gsub("...","\\dots",arg,fix=TRUE) ##special case for dots
530 :     payload <- comment
531 :     } else {
532 :     ## this is a describe block, so we need to paste with existing
533 :     ## payload as a new \item.
534 :     if ( first.describe ){
535 :     ## for first item, need to add describe block starter
536 :     if ( "value" == cur.field ){
537 :     payload <- paste(payload,"\n",arg,"{",sep="")
538 :     } else {
539 :     payload <- paste(payload,"\\describe{\n",arg,"{",sep="")
540 :     }
541 :     first.describe <- FALSE
542 :     in.describe <- in.describe+1
543 :     } else {
544 :     ## subsequent item - terminate existing and start new
545 :     payload <- paste(payload,"}\n",arg,"{",sep="")
546 :     }
547 :     if ( nzchar(comment) ){
548 :     payload <- paste(payload,comment,sep="")
549 :     }
550 :     }
551 :     } else if ( in.chunk ){
552 :     if ( 0 == in.describe && !first.describe ){
553 :     ## reached an end to current field, but need to wait if in.describe
554 :     res[[cur.field]] <- end.chunk(cur.field,payload)
555 :     in.chunk <- FALSE
556 :     cur.field <- NULL
557 :     payload <- NULL
558 :     }
559 :     }
560 :     k <- k+1
561 :     }
562 :     ## finishing any existing payload
563 :     if ( 0 < in.describe ){
564 :     if ( "value" != cur.field ){ # value is implicit describe block
565 :     payload <- paste(payload,"}",sep="")
566 :     }
567 :     while ( in.describe>0 ){
568 :     payload <- paste(payload,"}",sep="\n")
569 :     in.describe <- in.describe-1;
570 :     }
571 :     }
572 :     if ( in.chunk ) res[[cur.field]] <- end.chunk(cur.field,payload)
573 :     res
574 :     ### Named list of character strings extracted from comments. For each
575 :     ### name N we will look for N\{...\} in the Rd file and replace it
576 :     ### with the string in this list (implemented in modify.Rd.file).
577 :     }
578 :    
579 :     setClass("DocLink", # Link documentation among related functions
580 :     ### The \code{.DocLink} class provides the basis for hooking together
581 :     ### documentation of related classes/functions/objects. The aim is that
582 :     ### documentation sections missing from the child are
583 :     representation(name="character", ##<< name of object
584 :     created="character", ##<< how created
585 :     parent="character", ##<< parent class or NA
586 :     code="character", ##<< actual source lines
587 :     description="character") ##<< preceding description block
588 :     )
589 :    
590 :     extract.file.parse <- function # File content analysis
591 :     ### Using the base \code{\link{parse}} function, analyse the file to link
592 :     ### preceding "prefix" comments to each active chunk. Those comments form
593 :     ### the default description for that chunk. The analysis also looks for
594 :     ### S4 class "setClass" calls and R.oo setConstructorS3 and setMethodS3
595 :     ### calls in order to link the documentation of those properly.
596 :     (code
597 :     ### Lines of R source code in a character vector - note that any
598 :     ### nested \code{source} statements are \emph{ignored} when scanning
599 :     ### for class definitions.
600 :     ){
601 :     res <- list()
602 :     old.opt <- options(keep.source=TRUE)
603 :     parsed <- try(parse(text=code))
604 :     options(old.opt)
605 :     if ( inherits(parsed,"try-error") ){
606 :     stop("parse failed with error:\n",parsed)
607 :     }
608 :     chunks <- attr(parsed,"srcref")
609 :     last.end <- 0
610 :     for ( k in 1:length(parsed) ){
611 :     start <- chunks[[k]][1]
612 :     ##details<< If the definition chunk does not contain a
613 :     ## description, any immediately preceding sequence consecutive
614 :     ## "prefix" lines will be used instead.
615 :     default.description <- NULL
616 :     while ( start > last.end+1
617 :     && 1 == length(grep(prefix,code[start-1],perl=TRUE)) ){
618 :     start <- start-1
619 :     }
620 :     if ( start < chunks[[k]][1] ){
621 :     default.description <- decomment(code[start:(chunks[[k]][1]-1)])
622 :     } else {
623 :     default.description <- NA_character_;
624 :     }
625 :     ##details<< Class and method definitions can take several forms,
626 :     ## determined by expression type: \describe{
627 :     ## \item{assignment (<-)}{Ordinary assignment of value/function;}
628 :     ## \item{setClass}{Definition of S4 class;}
629 :     ## \item{setConstructorS3}{Definition of S3 class using R.oo package;}
630 :     ## \item{setMethodS3}{Definition of method for S3 class using R.oo package.}}
631 :     ## Additionally, the value may be a name of a function defined elsewhere,
632 :     ## in which case the documentation should be copied from that other definition.
633 :     ## This is handled using the concept of documentation links.
634 :     lang <- parsed[[k]]
635 :     chars <- as.character(lang)
636 :     expr.type <- chars[1]
637 :     parent <- NA_character_
638 :    
639 :     if ( expr.type == "<-" || expr.type == "setConstructorS3" || expr.type == "setClass" ){
640 :     object.name <- chars[2]
641 :     ## If the function definition is not embedded within the call, then
642 :     ## the parent is that function. Test whether the the third value
643 :     ## looks like a name and add it to parents if so.
644 :     if ( 1 == length(grep("^[\\._\\w]+$",chars[3],perl=TRUE)) ){
645 :     parent <- chars[3]
646 :     }
647 :     res[[object.name]] <- new("DocLink",name=object.name,
648 :     created=expr.type,
649 :     parent=parent,
650 :     code=paste(chunks[[k]],sep=""),
651 :     description=default.description)
652 :     } else if ( expr.type == "setMethodS3" ){
653 :     ##details<< The \code{setMethodS3} calls introduce additional
654 :     ## complexity: they will define an additional S3 generic (which
655 :     ## needs documentation to avoid warnings at package build time)
656 :     ## unless one already exists. This also is handled by "linking"
657 :     ## documentation. A previously unseen generic is linked to the
658 :     ## first defining instances, subsequent definitions of that generic
659 :     ## also link back to the first defining instance.
660 :     generic.name <- chars[2]
661 :     object.name <- paste(generic.name,chars[3],sep=".")
662 :     if ( is.null(res[[generic.name]]) ){
663 :     generic.desc <- paste("Generic method behind \\code{\\link{",object.name,"}}",sep="")
664 :     res[[generic.name]] <- new("DocLink",
665 :     name=generic.name,
666 :     created=expr.type,
667 :     parent=object.name,
668 :     code=NA_character_,
669 :     description=generic.desc)
670 :     } else {
671 :     parent <- res[[generic.name]]@parent
672 :     }
673 :     ## If the function definition is not embedded within the call, then
674 :     ## the parent is that function. Test whether the the fourth value
675 :     ## looks like a name and add it to parents if so.
676 :     if ( 1 == length(grep("^[\\._\\w]+$",chars[4],perl=TRUE)) ){
677 :     parent <- c(chars[4],parent)
678 :     }
679 :     res[[object.name]] <- new("DocLink",name=object.name,
680 :     created=expr.type,
681 :     parent=parent,
682 :     code=paste(chunks[[k]],sep=""),
683 :     description=default.description)
684 :     } else {
685 :     ## Not sure what to do with these yet. Need to deal with setMethod, setAs etc.
686 :     }
687 :     }
688 :     invisible(res)
689 :     ### Returns an invisible list of .DocLink objects.
690 :     }
691 :    
692 :     extract.docs.setClass <- function # S4 class inline documentation
693 :     ### Using the same conventions as for functions, definitions of S4 classes
694 :     ### in the form \code{setClass("classname",\dots)} are also located and
695 :     ### scanned for inline comments.
696 : tdhock 93 (doc.link
697 : tdhock 87 ### DocLink object as created by \code{\link{extract.file.parse}}.
698 :     ### Note that \code{source} statements are \emph{ignored} when scanning for
699 :     ### class definitions.
700 : tdhock 93 ){
701 : tdhock 87 chunk.source <- doc.link@code
702 :     ##details<<
703 :     ## Extraction of S4 class documentation is currently limited to expressions
704 :     ## within the source code which have first line starting with
705 :     ## \code{setClass("classname"}. These are located from the source file
706 :     ## (allowing also for white space around the \code{setClass} and \code{(}).
707 :     ## Note that \code{"classname"} must be a quoted character string;
708 :     ## expressions returning such a string are not matched.
709 :     class.name <- doc.link@name
710 :    
711 :     ##details<< For class definitions, the slots (elements of the
712 :     ## \code{representation} list) fill the role of function
713 :     ## arguments, so may be documented by \code{##<<} comments on
714 :     ## the same line or \code{### } comments at the beginning of the
715 :     ## following line.
716 :     f.n <- paste(class.name,"class",sep="-")
717 :     docs <- extract.docs.fun(chunk.source,f.n)
718 :     ##details<<
719 :     ## The class definition skeleton includes an \code{Objects from the Class}
720 :     ## section, to which any \code{##details<<} documentation chunks are
721 :     ## written. It is given a vanilla content if there are no specific
722 :     ## \code{##details<<} documentation chunks.
723 :     if ( is.null(docs[["details"]]) ){
724 :     docs[["details"]] <-
725 :     paste("Objects can be created by calls of the form \\code{new(",
726 :     class.name," ...)}",sep="")
727 :     }
728 :     docs[["section{Objects from the Class}"]] <- docs[["details"]]
729 :     ## seealso has a skeleton line not marked by ~ .. ~, so have to suppress
730 :     if ( is.null(docs[["seealso"]]) ){
731 :     docs[["seealso"]] <- ""
732 :     }
733 :     if ( is.null(docs[["alias"]]) ){
734 :     docs[["alias"]] <- class.name
735 :     }
736 :     if ( is.null(docs[["description"]]) ){
737 :     docs[["description"]] <- doc.link@description
738 :     }
739 :     invisible(docs)
740 :     }
741 : tdhock 105
742 : tdhock 109 apply.parsers <- function
743 :     ### Parse code to r objs, then run all the parsers and return the
744 :     ### documentation list.
745 : tdhock 105 (code,
746 :     ### Character vector of code lines.
747 : tdhock 109 parsers=default.parsers,
748 : tdhock 105 ### List of Parser Functions.
749 : tdhock 109 verbose=FALSE,
750 : tdhock 105 ### Echo names of Parser Functions?
751 :     ...
752 :     ### Additional arguments to pass to Parser Functions.
753 :     ){
754 :     e <- new.env()
755 : tdhock 110 old <- options(keep.source=TRUE)
756 : tdhock 109 on.exit(options(old))
757 : tdhock 110 exprs <- parse(text=code)
758 :     for (i in exprs) eval(i, e)
759 : tdhock 105 objs <- sapply(ls(e),get,e,simplify=FALSE)
760 :    
761 :     docs <- list()
762 : phgrosjean 108
763 :     # PhG: Automatically determine who is S3 methods
764 :     for (name in names(objs)) {
765 :     parts <- strsplit(name, ".", fixed = TRUE)[[1]]
766 :     l <- length(parts)
767 :     if (l > 1) {
768 :     for (i in 1:(l - 1)) {
769 :     # Look for a generic function (known by the system or defined
770 :     # in the package) that matches that part of the function name
771 :     generic <- paste(parts[1:i], collapse = ".")
772 :     if (any(generic %in% utils:::getKnownS3generics()) ||
773 :     utils:::findGeneric(generic, e) != "") {
774 :     object <- paste(parts[(i + 1):l], collapse = ".")
775 :     docs[[name]]$s3method <- c(generic, object)
776 :     break
777 :     }
778 :     }
779 :     }
780 :     }
781 : tdhock 109 ## apply parsers in sequence to code and objs
782 : tdhock 105 for(i in seq_along(parsers)){
783 :     N <- names(parsers[i])
784 :     if(verbose){
785 :     if(is.character(N) && N!=""){
786 :     cat(N," ",sep="")
787 :     }else cat('. ')
788 :     }
789 :     p <- parsers[[i]]
790 :     ## This is the argument list that each parser receives:
791 :     L <- p(code=code,objs=objs,docs=docs,...)
792 :     docs <- combine(docs,L)
793 :     }
794 :     if(verbose)cat("\n")
795 :     docs
796 :     ### A list of extracted documentation from code.
797 :     }
798 : tdhock 109
799 :     extract.docs.file <- function
800 :     ### Apply all parsers relevant to extract info from just 1 code file.
801 :     (f,
802 :     ### File name of R code to read and parse.
803 :     parsers=list(extra.code.docs,default.parsers$parsefun),
804 :     ### Parser Functions to use to parse the code and extract
805 :     ### documentation.
806 :     ...
807 :     ### Other arguments to pass to Parser Functions.
808 :     ){
809 :     apply.parsers(readLines(f),parsers,verbose=FALSE,...)
810 :     }

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