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

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