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

root@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