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

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