liveBook · Manning

Leaf object

As explained in Building User-Friendly DSLs

An AST object that has no child objects connected by outgoing containment relations.

A leaf object is an AST object with no child objects connected by outgoing containment relations. During traversal, it contributes one leaf when its settings contain no nested AST objects. section 3.3.2

A recursive counter can inspect each value as an AST object, reference, array, or other value. For an AST object, it counts leaves in the settings; a zero subtotal means the object itself is a leaf. References and unrelated values contribute zero, while arrays sum their elements. section 3.3.2

Counting AST leaves

Implement numberOfLeaves in ast.js, then call numberOfLeaves(astRoot). For the running rental AST, numberOfLeaves(rental) returns 4. The implementation uses isAstObject, isAstReference, Array.isArray, and a reduce-based sum helper. section 3.3.2

How Building User-Friendly DSLs covers it

How deep it goes
Defines leaves and implements recursive handling for AST objects, references, arrays, and other values.
Examples
Uses a rental AST and numberOfLeaves(rental), which produces four.
What it assumes
Assumes encoded AST values and helper predicates while teaching recursive inspection from the root value.
What you can do after
Build a JavaScript function that counts leaf objects in an encoded AST.
How it connects
Connects leaf objects with abstract syntax trees, recursion, depth-first tree traversal, references, arrays, and reduction.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Building User-Friendly DSLs. The section links point to the parts of the book it draws on.