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