[Rd] Recursively parsing srcrefs

Hadley Wickham hadley at rice.edu
Thu May 12 21:59:19 CEST 2011


>> Is it possible to "recursively" parse srcrefs to match the recursive
>> structure of the underlying code?  I'm interested in this because it's
>
> I don't understand what you mean by that.  It is certainly possible to walk
> through nested srcrefs, to zoom in on a particular location; that's what
> findLineNum() does.

Does the example below not help?  Given the whole function, I want to
be able to walk down the call tree, finding the matching src refs as I
go.  i.e. given f, how do I get f_inside?

f <- function(x = T) {
  # This is a comment
  if (x)                  return(4)
  if (emergency_status()) return(T)
}

f_inside <- parse(text = "
  # This is a comment
  if (x)                  return(4)
  if (emergency_status()) return(T)
")

findLineNum doesn't quite do what I want - it works on the text of the
srcref, not on the parse tree.

Here's another go at explaining what I want:

h <- quote(
  1 # one
  + # plus
  2 # two
)

h[[1]] extracts +.  What can I do to extract "+ # plus" (on an object
created in the appropriate manner to keep the srcref)?  Is that even
possible?

My eventual goal is something like

f <- function(x) {
  # This is my function
  T
}

g <- fix_logical_abbreviations(f)

which would be equivalent to

g <- function(x) {
  # This is my function
  TRUE
}


> That last display looks like a bug indeed.  I'll take a look.

The key seems to be a leading newline:

parse(text = "\nx")
parse(text = "x")

Hadley


-- 
Assistant Professor / Dobelman Family Junior Chair
Department of Statistics / Rice University
http://had.co.nz/



More information about the R-devel mailing list