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

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