liveBook · Manning

Code generation

As explained in Building User-Friendly DSLs

The automated production of source code or executable artifacts from a higher-level representation.

Code generation turns a higher-level DSL representation into executable JavaScript artifacts. An AST supplies the domain structure, while a template literal supplies the runtime code’s shape. The generator progressively replaces fixed text with expressions that read AST values, so changes in the DSL become changes in the generated runtime. section 1.2.3 section 8.4.1

A practical generation workflow proceeds in small, verifiable steps:

  • Start with textual output matching a reference implementation, such as a Rental class. section 8.4.1
  • Find literal text represented in the AST and replace it with an embedded template expression. section 8.4.1
  • Extract reusable helpers for naming and initialization, such as camelCase, withFirstUpper, and initializationFor. section 8.4.1
  • Dispatch on AST concepts to render values, including numbers and attribute references, while emitting explicit generation-problem markers for unsupported cases. section 8.4.1
  • Run the generator after each change and compare its output with the reference, optionally using Node.js watch mode or nodemon. section 8.4.1

Parameterizing a Rental field

A fixed field such as rentalPeriod = new DateRange() becomes a template expression that obtains the attribute from the record-type AST, converts its name with ccNameOf, and selects initialization from its type or initial value. Mapping initializationFor across the AST attributes then generates the complete field list. section 8.4.1

Figure 8.7 The iterative process to turn an unparameterized template into a parameterized one
figure

The figure provides a visual overview of the feedback loop from an unparameterized reference template to AST-driven generated code. section 8.4.1

How Building User-Friendly DSLs covers it

How deep it goes
Builds from templates through AST parameterization, helper functions, expression dispatch, and diagnostics; it stops short of a complete runtime.
Examples
Uses a Rental class, record-type and attribute ASTs, template helpers, numeric expressions, attribute references, and generator watch commands.
What it assumes
Assumes a reference implementation and AST representation; teaches template parameterization incrementally.
What you can do after
Build it from scratch by parameterizing templates, running the generator, and checking generated output against reference code.
How it connects
Connects abstract syntax trees, projectional editing, domain-specific languages, templates, and runtime code.

Also explained in

Compare how 17 books explain code generation →

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.