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

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