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

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