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

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

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