18.2 Abstract Syntact Tree (AST)

  • Expressions are objects that capture the structure of code without evaluating it.
  • Expressions are also called abstract syntax trees (ASTs) because the structure of code is hierarchical and can be naturally represented as a tree.
  • Understanding this tree structure is crucial for inspecting and modifying expressions.
    • Branches = Calls
    • Leaves = Symbols and constants
f(x, "y", 1)

18.2.1 With lobstr::ast():

lobstr::ast(f(x, "y", 1))
#> █─f 
#> ├─x 
#> ├─"y" 
#> └─1
  • Some functions might also contain more calls like the example below:
f(g(1, 2), h(3, 4, i())):

lobstr::ast(f(g(1, 2), h(3, 4, i())))
#> █─f 
#> ├─█─g 
#> │ ├─1 
#> │ └─2 
#> └─█─h 
#>   ├─3 
#>   ├─4 
#>   └─█─i
  • Read the hand-drawn diagrams from left-to-right (ignoring vertical position)
  • Read the lobstr-drawn diagrams from top-to-bottom (ignoring horizontal position).
  • The depth within the tree is determined by the nesting of function calls.
  • Depth also determines evaluation order, as evaluation generally proceeds from deepest-to-shallowest, but this is not guaranteed because of lazy evaluation.