liveBook · Manning

Type computation

As explained in Building User-Friendly DSLs

The process of determining the type produced by an expression from its syntax, operands, and context.

Type computation determines the type an expression would produce. In a DSL, it supports type safety by computing types for subexpressions and combining them with operators, references, and context. section 13.4

A practical implementation follows the expression AST from its leaves upward:

  • Read an attribute reference’s declared type. section 13.1
  • Compute each child expression, then combine the resulting types according to the operator. section 13.1
  • Return a best-effort type when possible; otherwise return the special untype value so errors do not obscure the original problem. section 13.4
  • Use ancestors when the type depends on surrounding context; this is type inference rather than purely local computation. section 13.4 section 13.1

Rental price expression

For a rental-price expression such as rental price − discount of rental price, rental price has type amount and discount has type percentage. The of operation produces amount, and subtracting two amounts produces amount. A recursive typeOf function can implement the same calculation directly on the expression AST. section 13.1

How Building User-Friendly DSLs covers it

How deep it goes
Descends from operator rules and leaf types to recursive AST traversal, ancestor-based inference, best-effort types, and untype.
Examples
Uses a rental-price expression, amount and percentage operands, binary operators, AST diagrams, and JavaScript typeOf listings.
What it assumes
Assumes expression ASTs and DSL expressions, while teaching declared types, operator rules, untype, and ancestor-based inference.
What you can do after
Build it from scratch with a recursive typeOf function that handles AST nodes, operators, references, parentheses, and contextual inference.
How it connects
Connects ASTs, type systems, type safety, type inference, and type checking constraints.

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.