From hadley at rice.edu  Thu May 12 21:59:19 2011
From: hadley at rice.edu (Hadley Wickham)
Date: Thu, 12 May 2011 14:59:19 -0500
Subject: [Rd] Recursively parsing srcrefs
In-Reply-To: <4DCC28F6.2090502@gmail.com>
References: <BANLkTikpgh27=EJGnmfrmuQ7QBh1vV-Qkw@mail.gmail.com>
	<4DCC28F6.2090502@gmail.com>
Message-ID: <BANLkTimkrQ3AXViGgnxB6hgVN90abXcL5Q@mail.gmail.com>

>> 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/



[Rd] Recursively parsing srcrefs
Hadley Wickham