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

1 : tdhock 87 ### For each object in the package that satisfies the criterion
2 :     ### checked by subfun, parse source using FUN and return the resulting
3 :     ### documentation list.
4 :     forall <- function
5 :     (FUN,
6 :     ### Function to apply to each element in the package.
7 :     subfun=function(x)TRUE
8 :     ### Function to select subsets of elements of the package, such as
9 :     ### is.function. subfun(x)==TRUE means FUN will be applied to x and
10 :     ### the result will be returned.
11 :     ){
12 :     function(objs,docs,...){
13 :     objs <- objs[sapply(objs,subfun)]
14 :     L <- list()
15 : tdhock 93 for(N in names(docs)){
16 : tdhock 87 o <- objs[[N]]
17 : tdhock 89 L[[N]] <- FUN(src=attr(o,"source"),
18 :     name=N,objs=objs,o=o,docs=docs,doc=docs[[N]],...)
19 : tdhock 87 }
20 :     L
21 :     }
22 :     ### A Parser Function.
23 :     }
24 :    
25 :     ### For each function in the package, do something.
26 :     forfun <- function(FUN)forall(FUN,is.function)
27 :    
28 : tdhock 99 ### Parsers for each object/function that are constructed
29 :     ### automatically. This is a named list, each element is a list of 2
30 :     ### elements: forfun/forall, then a parser function for an individual
31 :     ### object.
32 : tdhock 89 forall.parsers <-
33 :     list(## Extract lots of info from normal functions.
34 :     parsefun=list(forfun,function(src,name,...){
35 :     extract.docs.fun(src,name)
36 :     }),
37 :     ## Fill in author from DESCRIPTION and titles.
38 :     author.from.description=list(forall,function(desc,...){
39 :     list(author=desc[,"Maintainer"])
40 :     }),
41 :     ## The format section sometimes causes problems, so erase it.
42 :     erase.format=list(forall,function(...){
43 :     list(format="")
44 :     }),
45 :     ## Convert the function name to a title.
46 :     title.from.name=list(forall,function(name,doc,...){
47 :     if("title"%in%names(doc))list() else
48 :     list(title=gsub("[._]"," ",name))
49 :     }),
50 :     ## Get examples for FUN from the file test/FUN.R
51 :     examples.from.testfile=list(forfun,function(name,...){
52 :     tfile <- file.path("..","tests",paste(name,".R",sep=""))
53 :     if(file.exists(tfile))
54 :     list(examples=paste(readLines(tfile),collapse="\n"))
55 :     else list()
56 :     }),
57 :     ## Get examples from inline definitions after return()
58 : tdhock 96 examples.after.return=list(forfun,function(name,src,...){
59 :     coll <- paste(src,collapse="\n")
60 :     thispre <- gsub("^[\\^]","",prefix)
61 :     FIND <- paste("(return|UseMethod)[(][^\\n]*\\n",thispre,sep="")
62 :     m <- regexpr(FIND,coll)
63 :     if(m[1]==-1)return(list())
64 :     after <- substr(coll,m[1],nchar(coll))
65 :     FIND <-
66 :     paste("[^\\n]*",# rest of the return line
67 :     "((?:\\n###[^\\n]*)+)",#comment value lines \\1
68 :     "([\\w\\W]*)[}]",#examples \\2
69 :     sep="")
70 : tdhock 104 SEP <- "-/-/-/-/-=====-----"
71 : tdhock 96 REP <- paste("\\1",SEP,"\\2",sep="")
72 :     r <- strsplit(gsub(FIND,REP,after,perl=TRUE),split=SEP)[[1]]
73 :     l <- strsplit(r,split="\n")
74 : tdhock 97 excode <- c(l[[2]],"")
75 : tdhock 103 if(length(l)<2||paste(excode,collapse="")=="")return(list())
76 : tdhock 96 prefixes <- gsub("(\\s*).*","\\1",excode,perl=TRUE)[grep("\\w",excode)]
77 :     FIND <- prefixes[which.min(nchar(prefixes))]
78 : tdhock 97 list(examples=paste(sub(FIND,"",excode),collapse="\n"),
79 :     value=decomment(l[[1]][-1]))
80 : tdhock 89 }))
81 : tdhock 87
82 : tdhock 89 ### List of parser functions that operate on single objects. This list
83 :     ### is useful for testing these functions, ie
84 : tdhock 99 ### lonely$parsefun(attr(extract.docs.file,"source"),"extract.docs.file")
85 : tdhock 89 lonely <- sapply(forall.parsers,function(L)L[[2]])
86 : tdhock 87
87 :     extract.docs.file <- function # Extract documentation from a file
88 :     ### Parse R code to extract inline documentation from comments around
89 :     ### each function. These are not able to be retreived simply by
90 :     ### looking at the "source" attribute. This is a Parser Function that
91 : tdhock 106 ### can be used in the parser list of package.skeleton.dx(). TODO:
92 :     ### Modularize this into separate Parser Functions for S4 classes,
93 :     ### prefixes, ##<< blocks, etc. Right now it is not very clean!
94 : tdhock 87 (code,
95 :     ### Code lines in a character vector containing multiple R objects to
96 :     ### parse for documentation.
97 :     objs,
98 :     ### The objects defined in the code.
99 :     ...
100 :     ### ignored
101 :     ){
102 :     parsed <- extract.file.parse(code)
103 :     extract.docs.try <- function(o,on)
104 :     {
105 :     ## Note: we could use parsed information here too, but that
106 :     ## would produce different results for setMethodS3 etc.
107 :     doc <- list()
108 :     if ( !is.null(parsed[[on]]) ){
109 :     if ( !is.na(parsed[[on]]@code[1]) ){ # no code given for generics
110 :     doc$definition <- paste(parsed[[on]]@code,collapse="\n")
111 :     }
112 :     if(!"description"%in%names(doc) && !is.na(parsed[[on]]@description) ){
113 :     doc$description <- parsed[[on]]@description
114 :     }
115 :     if ( "setMethodS3" == parsed[[on]]@created ){
116 :     pattern <- "^([^\\.]+)\\.(.*)$"
117 :     doc$s3method=c(m1 <- gsub(pattern,"\\1",on,perl=TRUE),
118 :     m2 <- gsub(pattern,"\\2",on,perl=TRUE))
119 :     if ( 0 < length(grep("\\W",m1,perl=TRUE)) ){
120 :     m1 <- paste("`",m1,"`",sep="")
121 :     }
122 :     cat("S3method(",m1,",",m2,")\n",sep="")
123 :     }
124 :     }
125 :     if("title" %in% names(doc) && !"description" %in% names(doc) ){
126 :     ## For short functions having both would duplicate, but a
127 :     ## description is required. Therefore automatically copy title
128 :     ## across to avoid errors at package build time.
129 :     doc$description <- doc$title
130 :     }
131 :     doc
132 :     }
133 :     extract.docs <- function(on){
134 :     res <- try({o <- objs[[on]]
135 :     extract.docs.try(o, on)},FALSE)
136 :     if(class(res)=="try-error"){
137 :     cat("Failed to extract docs for: ",on,"\n\n")
138 :     list()
139 :     } else if(0 == length(res) && inherits(objs[[on]],"standardGeneric")){
140 :     NULL
141 :     } else if(0 == length(res) && "function" %in% class(o)
142 :     && 1 == length(osource <- attr(o,"source"))
143 :     && 1 == length(grep(paste("UseMethod(",on,")",sep="\""),osource))
144 :     ){
145 :     ## phew - this should only pick up R.oo S3 generic definitions like:
146 :     ## attr(*, "source")= chr "function(...) UseMethod(\"select\")"
147 :     NULL
148 :     } else res
149 :     }
150 :     doc.names <- names(objs)
151 :     res <- sapply(doc.names,extract.docs,simplify=FALSE)
152 :     ## Special processing for S4 classes as they do not appear in normal ls()
153 :     for ( nn in names(parsed) ){
154 :     if ( parsed[[nn]]@created == "setClass" ){
155 :     S4class.docs <- extract.docs.setClass(parsed[[nn]])
156 :     docname <- paste(nn,"class",sep="-")
157 :     if ( is.null(res[[docname]]) ){
158 :     res[[docname]] <- S4class.docs
159 :     doc.names <- c(doc.names,docname)
160 :     } else {
161 :     stop(nn," appears as both S4 class and some other definition")
162 :     }
163 :     }
164 :     }
165 :     inherit.docs <- function(on){
166 :     in.res <- res[[on]]
167 :     if ( !is.null(parsed[[on]]) ){
168 :     for ( parent in parsed[[on]]@parent ){
169 :     if ( !is.na(parent) ){
170 :     if ( is.null(in.res) ){
171 :     in.res <- res[[parent]]
172 :     } else if ( parent %in% names(res) ){
173 :     parent.docs <- res[[parent]]
174 :     for ( nn in names(parent.docs) ){
175 :     if ( !nn %in% names(in.res) ){
176 :     in.res[[nn]] <- parent.docs[[nn]]
177 :     }
178 :     }
179 :     }
180 :     }
181 :     }
182 :     }
183 :     invisible(in.res)
184 :     }
185 :     all.done <- FALSE
186 :     while ( !all.done ){
187 :     res1 <- sapply(doc.names,inherit.docs,simplify=FALSE)
188 :     all.done <- identical(res1,res)
189 :     res <- res1
190 :     }
191 :     ## now strip out any generics (which have value NULL in res):
192 :     res.not.null <- sapply(res,function(x){!is.null(x)})
193 :     if ( 0 < length(res.not.null) && length(res.not.null) < length(res) ){
194 :     res <- res[res.not.null]
195 :     }
196 :     res
197 :     ### named list of lists, one for each object to document.
198 :     }
199 :    
200 : tdhock 89 ### List of parsers to use by default with package.skeleton.dx.
201 : tdhock 93 default.parsers <- c(extract.docs.file=extract.docs.file,
202 :     sapply(forall.parsers,function(L)L[[1]](L[[2]])))
203 : tdhock 87
204 :     extract.docs.fun <- function # Extract documentation from a function
205 :     ### Given source code of a function, return a list describing inline
206 :     ### documentation in that source code.
207 :     (code,
208 :     ### The function to examine.
209 :     name.fun
210 :     ### The name of the function/chunk to use in warning messages.
211 : tdhock 95 ){
212 : tdhock 87 res <- list()
213 :     clines <- grep(prefix,code)
214 :     if(length(grep("#",code[1]))){
215 :     res$title <- gsub("[^#]*#\\s*(.*)","\\1",code[1],perl=TRUE)
216 :     }
217 :     if(length(clines) > 0){
218 :     ##details<<
219 :     ## The primary mechanism is that consecutive groups of lines matching
220 :     ## the specified prefix regular expression "\code{^### }" (i.e. lines
221 :     ## beginning with "\code{### }") are collected
222 :     ## as follows into documentation sections:\describe{
223 :     ## \item{description}{group starting at line 2 in the code}
224 :     ## \item{arguments}{group following each function argument}
225 :     ## \item{value}{group ending at the penultimate line of the code}}
226 :     ## These may be added to by use of the \code{##<<} constructs described
227 :     ## below.
228 :     bounds <- which(diff(clines)!=1)
229 :     starts <- c(1,bounds+1)
230 :     ends <- c(bounds,length(clines))
231 :     for(i in seq_along(starts)){
232 :     start <- clines[starts[i]]
233 :     end <- clines[ends[i]]
234 :     lab <- if(end+1==length(code))"value"
235 :     else if(start==2)"description"
236 :     else if ( 0 == length(grep("^\\s*#",code[start-1],perl=TRUE)) ){
237 :     #arg <- gsub("^[ (]*","",code[start-1])
238 :     #arg <- gsub("^([^=,]*)[=,].*","\\1",arg)
239 :     #arg <- gsub("...","\\dots",arg,fix=TRUE) ##special case for dots
240 :     arg <- gsub("^[ \t(,]*", "", code[start - 1]) #twutz: strip leading white spaces and brackets and ,
241 :     arg <- gsub("^([^=,]*)[=,].*", "\\1", arg)
242 :     arg <- gsub("^([^ \t]*)([ \t]+)$","\\1",arg) #twutz: remove trailing whitespaces
243 :     arg <- gsub("...", "\\dots", arg, fix = TRUE)
244 :     paste("item{",arg,"}",sep="")
245 :     } else {
246 :     next;
247 :     }
248 :     res[[lab]] <- decomment(code[start:end])
249 :     }
250 :     }
251 :     ##details<< For simple functions/arguments, the argument may also be
252 :     ## documented by appending \code{##<<} comments on the same line as the
253 :     ## argument name. Mixing this mechanism with \code{###} comment lines for
254 :     ## the same argument is likely to lead to confusion, as the \code{###}
255 :     ## lines are processed first.
256 :     #arg.pat <- paste("^[^=,#]*?([\\w\\.]+)\\s*([=,].*|\\)\\s*)?",
257 :     # "<<\\s*(\\S.*?)\\s*$",
258 :     # sep="##") # paste avoids embedded trigger fooling the system
259 :     #tw: removed first comma
260 :     arg.pat <- paste("^[^=#]*?([\\w\\.]+)\\s*([=,].*|\\)\\s*)?",
261 :     "<<\\s*(\\S.*?)\\s*$",
262 :     sep="##") # paste avoids embedded trigger fooling the system
263 :    
264 :     skeleton.fields <- c("alias","details","keyword","references","author",
265 :     "note","seealso","value","title","description",
266 :     "describe","end")
267 :     ##details<< Additionally, consecutive sections of \code{##} comment
268 :     ## lines beginning with \code{##}\emph{xxx}\code{<<} (where
269 :     ## \emph{xxx} is one of the fields: \code{alias}, \code{details},
270 :     ## \code{keyword}, \code{references}, \code{author}, \code{note},
271 :     ## \code{seealso}, \code{value}, \code{title} or \code{description})
272 :     ## are accumulated and inserted in the relevant part of the .Rd
273 :     ## file.
274 :     ##
275 :     ## For \code{value}, \code{title}, \code{description} and function
276 :     ## arguments, these \emph{append} to any text from "prefix"
277 :     ## (\code{^### }) comment lines, irrespective of the order in the
278 :     ## source.
279 :     ##
280 :     ## When documenting S4 classes, documentation from \code{details}
281 :     ## sections will appear under a section \code{Objects from the Class}. That
282 :     ## section typically includes information about construction methods
283 :     ## as well as other description of class objects (but note that the
284 :     ## class Slots are documented in a separate section).
285 :    
286 :     ## but this should not appear, because separated by a blank line
287 :     extra.regexp <- paste("^\\s*##(",paste(skeleton.fields,collapse="|"),
288 :     ")<<\\s*(.*)$",sep="")
289 :     cont.re <- "^\\s*##\\s*"
290 :     in.describe <- 0
291 :     first.describe <- FALSE
292 :     k <- 1
293 :     in.chunk <- FALSE
294 :     end.chunk <- function(field,payload)
295 :     {
296 :     if ( "alias" == field ){
297 :     ##note<< \code{alias} extras are automatically split at new lines.
298 :     payload <- gsub("\\n+","\\}\n\\\\alias\\{",payload,perl=TRUE)
299 :     chunk.sep <- "}\n\\alias{"
300 :     } else if ( "keyword" == field ){
301 :     ##keyword<< documentation utilities
302 :     ##note<< \code{keyword} extras are automatically split at white space,
303 :     ## as all the valid keywords are single words.
304 :     payload <- gsub("\\s+","\\}\n\\\\keyword\\{",payload,perl=TRUE)
305 :     chunk.sep <- "}\n\\keyword{"
306 :     } else if ( "title" == field ){
307 :     chunk.sep <- " "
308 :     } else if ( "description" == field ){
309 :     chunk.sep <- "\n"
310 :     } else {
311 :     ##details<< Each separate extra section appears as a new
312 :     ## paragraph except that: \itemize{\item empty sections (no
313 :     ## matter how many lines) are ignored;\item \code{alias} and
314 :     ## \code{keyword} sections have special rules;\item
315 :     ## \code{description} should be brief, so all such sections
316 :     ## are concatenated as one paragraph;\item \code{title} should
317 :     ## be one line, so any extra \code{title} sections are
318 :     ## concatenated as a single line with spaces separating the
319 :     ## sections.}
320 :     chunk.sep <- "\n\n"
321 :     }
322 :     chunk.res <- NULL
323 :     if ( 0 == length(grep("^\\s*$",payload,perl=TRUE)) )
324 :     chunk.res <-
325 :     if ( is.null(res[[field]]) ) payload
326 :     else paste(res[[field]], payload, sep=chunk.sep)
327 :     invisible(chunk.res)
328 :     }
329 :     while ( k <= length(code) ){
330 :     line <- code[k]
331 :     if ( 0 < length(grep(extra.regexp,line,perl=TRUE) ) ){
332 :     ## we have a new extra chunk - first get field name and any payload
333 :     new.field <- gsub(extra.regexp,"\\1",line,perl=TRUE)
334 :     new.contents <- gsub(extra.regexp,"\\2",line,perl=TRUE)
335 :    
336 :     ##details<< As a special case, the construct \code{##describe<<} causes
337 :     ## similar processing to the main function arguments to be
338 :     ## applied in order to construct a describe block within the
339 :     ## documentation, for example to describe the members of a
340 :     ## list. All subsequent "same line" \code{##<<} comments go into that
341 :     ## block until terminated by a subsequent \code{##}\emph{xxx}\code{<<} line.
342 :     if ( "describe" == new.field ){
343 :     ##details<< Such regions may be nested, but not in such a way
344 :     ## that the first element in a \code{describe} is another \code{describe}.
345 :     ## Thus there must be at least one \code{##<<} comment between each
346 :     ## pair of \code{##describe<<} comments.
347 :     if ( first.describe ){
348 :     stop("consecutive ##describe<< at line",k,"in",name.fun)
349 :     } else {
350 :     if ( nzchar(new.contents) ){
351 :     if ( is.null(payload) || 0 == nzchar(payload) ){
352 :     payload <- new.contents
353 :     } else {
354 :     payload <- paste(payload,new.contents,sep="\n\n")
355 :     }
356 :     }
357 :     first.describe <- TRUE
358 :     }
359 :     } else if ( "end" == new.field ){
360 :     ##details<< When nested \code{describe} blocks are used, a comment-only
361 :     ## line with \code{##end<<} terminates the current level only; any
362 :     ## other valid \code{##}\emph{xxx}\code{<<} line terminates
363 :     ## all open describe blocks.
364 :     if ( in.describe>0 ){
365 :     ## terminate current \item and \describe block only
366 :     if ( "value" == cur.field && 1 == in.describe ){
367 :     payload <- paste(payload,"}",sep="")
368 :     } else {
369 :     payload <- paste(payload,"}\n}",sep="")
370 :     }
371 :     in.describe <- in.describe-1;
372 :     } else {
373 :     warning("mismatched ##end<< at line ",k," in ",name.fun)
374 :     }
375 :     if ( nzchar(new.contents) ){
376 :     if ( nzchar(payload) ){
377 :     payload <- paste(payload,new.contents,sep="\n")
378 :     } else {
379 :     payload <- new.contents
380 :     }
381 :     }
382 :     } else {
383 :     ## terminate all open \describe blocks (+1 because of open item)
384 :     if ( 0 < in.describe ){
385 :     if ( "value" != cur.field ){ # value is implicit describe block
386 :     payload <- paste(payload,"}",sep="")
387 :     }
388 :     while ( in.describe>0 ){
389 :     payload <- paste(payload,"}",sep="\n")
390 :     in.describe <- in.describe-1;
391 :     }
392 :     }
393 :     ## finishing any existing payload
394 :     if ( in.chunk ) res[[cur.field]] <- end.chunk(cur.field,payload)
395 :     in.chunk <- TRUE
396 :     cur.field <- new.field
397 :     payload <- new.contents
398 :     ##note<< The "value" section of a .Rd file is implicitly a describe
399 :     ## block and \code{##}\code{value}\code{<<} acts accordingly. Therefore
400 :     ## it automatically enables the describe block itemization (##<< after
401 :     ## list entries).
402 :     if ( "value" == new.field ){
403 :     first.describe <- TRUE;
404 :     }
405 :     }
406 :     } else if ( in.chunk && 0<length(grep(cont.re,line,perl=TRUE)) ){
407 :     ## append this line to current chunk
408 :     if ( 0 == length(grep(prefix,line,perl=TRUE)) ){
409 :     ##describe<< Any lines with "\code{### }" at the left hand
410 :     ## margin within the included chunks are handled separately,
411 :     ## so if they appear in the documentation they will appear
412 :     ## before the \code{##}\emph{xxx}\code{<}\code{<} chunks.
413 :     ### This one should not appear.
414 :     stripped <- gsub(cont.re,"",line,perl=TRUE)
415 :     if ( nzchar(payload) ){
416 :     payload <- paste(payload,stripped,sep="\n")
417 :     } else {
418 :     payload <- stripped
419 :     }
420 :     }
421 :     } else if ( 0 < length(grep(arg.pat,line,perl=TRUE)) ){
422 :     not.describe <- (0==in.describe && !first.describe)
423 :     if ( in.chunk && not.describe){
424 :     res[[cur.field]] <- end.chunk(cur.field,payload)
425 :     }
426 :     comment <- gsub(arg.pat,"\\3",line,perl=TRUE);
427 :     arg <- gsub(arg.pat,"\\\\item\\{\\1\\}",line,perl=TRUE)
428 :     in.chunk <- TRUE
429 :     if ( not.describe ){
430 :     cur.field <- gsub("...","\\dots",arg,fix=TRUE) ##special case for dots
431 :     payload <- comment
432 :     } else {
433 :     ## this is a describe block, so we need to paste with existing
434 :     ## payload as a new \item.
435 :     if ( first.describe ){
436 :     ## for first item, need to add describe block starter
437 :     if ( "value" == cur.field ){
438 :     payload <- paste(payload,"\n",arg,"{",sep="")
439 :     } else {
440 :     payload <- paste(payload,"\\describe{\n",arg,"{",sep="")
441 :     }
442 :     first.describe <- FALSE
443 :     in.describe <- in.describe+1
444 :     } else {
445 :     ## subsequent item - terminate existing and start new
446 :     payload <- paste(payload,"}\n",arg,"{",sep="")
447 :     }
448 :     if ( nzchar(comment) ){
449 :     payload <- paste(payload,comment,sep="")
450 :     }
451 :     }
452 :     } else if ( in.chunk ){
453 :     if ( 0 == in.describe && !first.describe ){
454 :     ## reached an end to current field, but need to wait if in.describe
455 :     res[[cur.field]] <- end.chunk(cur.field,payload)
456 :     in.chunk <- FALSE
457 :     cur.field <- NULL
458 :     payload <- NULL
459 :     }
460 :     }
461 :     k <- k+1
462 :     }
463 :     ## finishing any existing payload
464 :     if ( 0 < in.describe ){
465 :     if ( "value" != cur.field ){ # value is implicit describe block
466 :     payload <- paste(payload,"}",sep="")
467 :     }
468 :     while ( in.describe>0 ){
469 :     payload <- paste(payload,"}",sep="\n")
470 :     in.describe <- in.describe-1;
471 :     }
472 :     }
473 :     if ( in.chunk ) res[[cur.field]] <- end.chunk(cur.field,payload)
474 :     res
475 :     ### Named list of character strings extracted from comments. For each
476 :     ### name N we will look for N\{...\} in the Rd file and replace it
477 :     ### with the string in this list (implemented in modify.Rd.file).
478 :     }
479 :    
480 :     setClass("DocLink", # Link documentation among related functions
481 :     ### The \code{.DocLink} class provides the basis for hooking together
482 :     ### documentation of related classes/functions/objects. The aim is that
483 :     ### documentation sections missing from the child are
484 :     representation(name="character", ##<< name of object
485 :     created="character", ##<< how created
486 :     parent="character", ##<< parent class or NA
487 :     code="character", ##<< actual source lines
488 :     description="character") ##<< preceding description block
489 :     )
490 :    
491 :     extract.file.parse <- function # File content analysis
492 :     ### Using the base \code{\link{parse}} function, analyse the file to link
493 :     ### preceding "prefix" comments to each active chunk. Those comments form
494 :     ### the default description for that chunk. The analysis also looks for
495 :     ### S4 class "setClass" calls and R.oo setConstructorS3 and setMethodS3
496 :     ### calls in order to link the documentation of those properly.
497 :     (code
498 :     ### Lines of R source code in a character vector - note that any
499 :     ### nested \code{source} statements are \emph{ignored} when scanning
500 :     ### for class definitions.
501 :     ){
502 :     res <- list()
503 :     old.opt <- options(keep.source=TRUE)
504 :     parsed <- try(parse(text=code))
505 :     options(old.opt)
506 :     if ( inherits(parsed,"try-error") ){
507 :     stop("parse failed with error:\n",parsed)
508 :     }
509 :     chunks <- attr(parsed,"srcref")
510 :     last.end <- 0
511 :     for ( k in 1:length(parsed) ){
512 :     start <- chunks[[k]][1]
513 :     ##details<< If the definition chunk does not contain a
514 :     ## description, any immediately preceding sequence consecutive
515 :     ## "prefix" lines will be used instead.
516 :     default.description <- NULL
517 :     while ( start > last.end+1
518 :     && 1 == length(grep(prefix,code[start-1],perl=TRUE)) ){
519 :     start <- start-1
520 :     }
521 :     if ( start < chunks[[k]][1] ){
522 :     default.description <- decomment(code[start:(chunks[[k]][1]-1)])
523 :     } else {
524 :     default.description <- NA_character_;
525 :     }
526 :     ##details<< Class and method definitions can take several forms,
527 :     ## determined by expression type: \describe{
528 :     ## \item{assignment (<-)}{Ordinary assignment of value/function;}
529 :     ## \item{setClass}{Definition of S4 class;}
530 :     ## \item{setConstructorS3}{Definition of S3 class using R.oo package;}
531 :     ## \item{setMethodS3}{Definition of method for S3 class using R.oo package.}}
532 :     ## Additionally, the value may be a name of a function defined elsewhere,
533 :     ## in which case the documentation should be copied from that other definition.
534 :     ## This is handled using the concept of documentation links.
535 :     lang <- parsed[[k]]
536 :     chars <- as.character(lang)
537 :     expr.type <- chars[1]
538 :     parent <- NA_character_
539 :    
540 :     if ( expr.type == "<-" || expr.type == "setConstructorS3" || expr.type == "setClass" ){
541 :     object.name <- chars[2]
542 :     ## If the function definition is not embedded within the call, then
543 :     ## the parent is that function. Test whether the the third value
544 :     ## looks like a name and add it to parents if so.
545 :     if ( 1 == length(grep("^[\\._\\w]+$",chars[3],perl=TRUE)) ){
546 :     parent <- chars[3]
547 :     }
548 :     res[[object.name]] <- new("DocLink",name=object.name,
549 :     created=expr.type,
550 :     parent=parent,
551 :     code=paste(chunks[[k]],sep=""),
552 :     description=default.description)
553 :     } else if ( expr.type == "setMethodS3" ){
554 :     ##details<< The \code{setMethodS3} calls introduce additional
555 :     ## complexity: they will define an additional S3 generic (which
556 :     ## needs documentation to avoid warnings at package build time)
557 :     ## unless one already exists. This also is handled by "linking"
558 :     ## documentation. A previously unseen generic is linked to the
559 :     ## first defining instances, subsequent definitions of that generic
560 :     ## also link back to the first defining instance.
561 :     generic.name <- chars[2]
562 :     object.name <- paste(generic.name,chars[3],sep=".")
563 :     if ( is.null(res[[generic.name]]) ){
564 :     generic.desc <- paste("Generic method behind \\code{\\link{",object.name,"}}",sep="")
565 :     res[[generic.name]] <- new("DocLink",
566 :     name=generic.name,
567 :     created=expr.type,
568 :     parent=object.name,
569 :     code=NA_character_,
570 :     description=generic.desc)
571 :     } else {
572 :     parent <- res[[generic.name]]@parent
573 :     }
574 :     ## If the function definition is not embedded within the call, then
575 :     ## the parent is that function. Test whether the the fourth value
576 :     ## looks like a name and add it to parents if so.
577 :     if ( 1 == length(grep("^[\\._\\w]+$",chars[4],perl=TRUE)) ){
578 :     parent <- c(chars[4],parent)
579 :     }
580 :     res[[object.name]] <- new("DocLink",name=object.name,
581 :     created=expr.type,
582 :     parent=parent,
583 :     code=paste(chunks[[k]],sep=""),
584 :     description=default.description)
585 :     } else {
586 :     ## Not sure what to do with these yet. Need to deal with setMethod, setAs etc.
587 :     }
588 :     }
589 :     invisible(res)
590 :     ### Returns an invisible list of .DocLink objects.
591 :     }
592 :    
593 :     extract.docs.setClass <- function # S4 class inline documentation
594 :     ### Using the same conventions as for functions, definitions of S4 classes
595 :     ### in the form \code{setClass("classname",\dots)} are also located and
596 :     ### scanned for inline comments.
597 : tdhock 93 (doc.link
598 : tdhock 87 ### DocLink object as created by \code{\link{extract.file.parse}}.
599 :     ### Note that \code{source} statements are \emph{ignored} when scanning for
600 :     ### class definitions.
601 : tdhock 93 ){
602 : tdhock 87 chunk.source <- doc.link@code
603 :     ##details<<
604 :     ## Extraction of S4 class documentation is currently limited to expressions
605 :     ## within the source code which have first line starting with
606 :     ## \code{setClass("classname"}. These are located from the source file
607 :     ## (allowing also for white space around the \code{setClass} and \code{(}).
608 :     ## Note that \code{"classname"} must be a quoted character string;
609 :     ## expressions returning such a string are not matched.
610 :     class.name <- doc.link@name
611 :    
612 :     ##details<< For class definitions, the slots (elements of the
613 :     ## \code{representation} list) fill the role of function
614 :     ## arguments, so may be documented by \code{##<<} comments on
615 :     ## the same line or \code{### } comments at the beginning of the
616 :     ## following line.
617 :     f.n <- paste(class.name,"class",sep="-")
618 :     docs <- extract.docs.fun(chunk.source,f.n)
619 :     ##details<<
620 :     ## The class definition skeleton includes an \code{Objects from the Class}
621 :     ## section, to which any \code{##details<<} documentation chunks are
622 :     ## written. It is given a vanilla content if there are no specific
623 :     ## \code{##details<<} documentation chunks.
624 :     if ( is.null(docs[["details"]]) ){
625 :     docs[["details"]] <-
626 :     paste("Objects can be created by calls of the form \\code{new(",
627 :     class.name," ...)}",sep="")
628 :     }
629 :     docs[["section{Objects from the Class}"]] <- docs[["details"]]
630 :     ## seealso has a skeleton line not marked by ~ .. ~, so have to suppress
631 :     if ( is.null(docs[["seealso"]]) ){
632 :     docs[["seealso"]] <- ""
633 :     }
634 :     if ( is.null(docs[["alias"]]) ){
635 :     docs[["alias"]] <- class.name
636 :     }
637 :     if ( is.null(docs[["description"]]) ){
638 :     docs[["description"]] <- doc.link@description
639 :     }
640 :     invisible(docs)
641 :     }
642 : tdhock 105
643 :     extract.docs.code <- function
644 :     ### Write code to a file and parse it to r objs, then run all the
645 :     ### parsers and return the documentation list.
646 :     (code,
647 :     ### Character vector of code lines.
648 :     parsers,
649 :     ### List of Parser Functions.
650 :     verbose=TRUE,
651 :     ### Echo names of Parser Functions?
652 :     ...
653 :     ### Additional arguments to pass to Parser Functions.
654 :     ){
655 :     code.file <- tempfile()
656 :     writeLines(code,code.file)
657 :     e <- new.env()
658 :     old <- options(keep.source.pkgs=TRUE)
659 :     tryCatch(suppressWarnings(sys.source(code.file,e)),error=function(e){
660 :     stop("source ",code.file," failed with error:\n",e)
661 :     })
662 :     options(old)
663 :     objs <- sapply(ls(e),get,e,simplify=FALSE)
664 :    
665 :     ## apply parsers in sequence to code and objs
666 :     docs <- list()
667 :     for(i in seq_along(parsers)){
668 :     N <- names(parsers[i])
669 :     if(verbose){
670 :     if(is.character(N) && N!=""){
671 :     cat(N," ",sep="")
672 :     }else cat('. ')
673 :     }
674 :     p <- parsers[[i]]
675 :     ## This is the argument list that each parser receives:
676 :     L <- p(code=code,objs=objs,docs=docs,...)
677 :     docs <- combine(docs,L)
678 :     }
679 :     if(verbose)cat("\n")
680 :     docs
681 :     ### A list of extracted documentation from code.
682 :     }

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