nick-ulle/rstatic

How to read in ast for script?

clarkfitzg opened this issue · 4 comments

We often start with something like a parsed script. How to convert this to an AST?

e = parse(text = "x = 1:10
plot(x)")

to_ast(e)
# Error in to_ast.default(e) : Cannot convert 'expression' to an ASTNode.

The approach below works fine to convert each element. Is there something like a c() function for AST objects?

lapply(e, to_ast)

The lapply() is the way to do it.

There's no special expression type/vector like in base R. A list of separate expressions is just stored in a list (including in the $body of Brace objects).

And if you want to combine the lists, you can just use c().

Since using parse() could be a common pattern, e7b3663 adds a to_ast() method to convert expressions to Brace objects.

It could return a list instead, but a Brace object is more convenient for using to_cfg() later. Let's see how well this works for now.

The brace seems like a reasonable approach. Works for me now, thanks!