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