[Rd] AddComment (gram.y)

Duncan Murdoch murdoch at stats.uwo.ca
Tue Apr 22 00:08:58 CEST 2008

Peter Danenberg wrote:
>> They aren't "cannibalized", they are still there, where the source
>> ref says they are.
> I was thinking along the lines of using parse() to unambiguously
> associate a comment block with a code object; sure, srcref() retains
> them: but that's no different than parsing a text file.
> If I can't associate comment with code in parse(), I don't see how I
> can avoid reimplementing the R parser; at least far enough to identify
> top-level objects (but why stop there?).
> By "cannibalizing", I'm referring to the following; take trivial.R:
>    # Comment relevant to foo
>    foo <- "bar"
> attributes(parse("trivial.R"))$srcref[[1]] returns:
>    foo <- "bar"
> which is consistent with SkipComment.

That's not the way to do it.  Currently there is no easy way to print 
the comments, but one could certainly be written.  If you look at all 
the srcref values, they identify the start and end of the expressions 
that were parsed.  The source outside those identified regions are the 
comments.  (There may also be embedded comments within
those regions, e.g.

  foo <-   # about foo

For example, when I parse your file above and save the srcrefs, I get

 > unclass(srcref[[1]])
[1]  2  4  2 15

This says that everything before line 2, column 4 is whitespace/comment, 
and everything after line 2 column 15 is the same.  If you want to adopt 
a style that says comments precede their target, then you should be 
looking for a comment in line 1.  R can't put a comment in the first few 
chars of a line.  If you want your comments
to follow the object, then look in line 2 after column 15, or in line 3 
or later.

I think a parser modification that returned the location of all # 
markers that start comments would be reasonable, but the parser 
shouldn't decide which expression these
are attached to.  That's not part of the language, that's a convention 
added on top of it.

Duncan Murdoch

More information about the R-devel mailing list