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