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

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