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

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