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 356 - (view) (download)

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

root@r-forge.r-project.org
ViewVC Help
Powered by ViewVC 1.0.0  
Thanks to:
Vienna University of Economics and Business Powered By FusionForge