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

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