2

Please see the below MWE

generate_summ_code= function(...) {
  code = substitute(list(...))[-1]
  gpd = getParseData(parse(text = deparse(code)), includeText = TRUE)
  print(gpd)
  gpd
}

generate_summ_code(n = n())

If I run that in REPL I get the print out

>    line1 col1 line2 col2 id parent                token terminal  text
> 10     1    1     1    5 10      0                 expr    FALSE n()()
> 6      1    1     1    3  6     10                 expr    FALSE   n()
> 1      1    1     1    1  1      3 SYMBOL_FUNCTION_CALL     TRUE     n
> 3      1    1     1    1  3      6                 expr    FALSE     n
> 2      1    2     1    2  2      6                  '('     TRUE     (
> 4      1    3     1    3  4      6                  ')'     TRUE     )
> 7      1    4     1    4  7     10                  '('     TRUE     (
> 8      1    5     1    5  8     10                  ')'     TRUE     )

However, if I put the code inside a file say code.r and I do

Rscript code.r

or

R -e "source('code.r')"

It just returns NULL. There is nothing in the ?getParseData that indicates that the behaviour should be different?

Is this a bug in Base R?

xiaodai
  • 14,889
  • 18
  • 76
  • 140

1 Answers1

3

The difference is that in interactive mode the keep.source option is set to TRUE, otherwise it is set to FALSE (unless you override it). Therefore, the behaviour of parse differs:

〉getParseData(parse(text = '1 + 1'), includeText = TRUE)
  line1 col1 line2 col2 id parent     token terminal  text
7     1    1     1    5  7      0      expr    FALSE 1 + 1
1     1    1     1    1  1      2 NUM_CONST     TRUE     1
2     1    1     1    1  2      7      expr    FALSE     1
3     1    3     1    3  3      7       '+'     TRUE     +
4     1    5     1    5  4      5 NUM_CONST     TRUE     1
5     1    5     1    5  5      7      expr    FALSE     1
〉getParseData(parse(text = '1 + 1', keep.source = FALSE), includeText = TRUE)
NULL
Konrad Rudolph
  • 530,221
  • 131
  • 937
  • 1,214
  • Yeah. I just figured that independently. Is that documented somewhere or have I just missed it? – xiaodai Jan 27 '20 at 12:22
  • @xiaodai Yes, itʼs in the “description” section of the [`getParseData` documentation](https://stat.ethz.ch/R-manual/R-devel/library/utils/html/getParseData.html). – Konrad Rudolph Jan 27 '20 at 13:30
  • "If the "keep.source" option is TRUE, R's parser will attach detailed information on the object it has parsed. These functions retrieve that information." But it doesn't say that in interactive mode keep.source is set differently. Or is that meant to be "common" knowledge? – xiaodai Jan 27 '20 at 13:38
  • @xiaodai Ah, right. The standard R options are all documented [on the page of the `option` function](https://stat.ethz.ch/R-manual/R-devel/library/base/html/options.html). – Konrad Rudolph Jan 27 '20 at 15:27