liveBook · Manning

Type inference

As explained in Building User-Friendly DSLs

Type inference is the algorithmic determination of expression or value types from available constraints without requiring every type to be written explicitly.

Type inference computes an AST object’s type from surrounding context, rather than only from the object and its descendants. Ancestors supply that context, letting a type system determine a number’s type from the attribute that contains it. section 13.1 section 13.4

Implement lightweight contextual inference by:

  • Pass an ancestor array through typeOf while traversing AST objects. section 13.1
  • Inspect enclosing objects when a local expression lacks enough type information, such as a Number contained directly in an Attribute. section 13.1
  • Return a sensible best-effort type when possible; otherwise return untype so an uncertain result does not spread mismatches through the expression. section 13.4
  • Keep type logic in the type system, then call it from projection code instead of relying on a fixed AST shape. section 13.1

Rental price expressions

A rental-price expression can combine numeric values with “-” and “of”. When projecting a Number, typeOf receives its ancestors and infers the number type from its containing attribute, allowing the editor to project it without embedding attribute-specific logic. section 13.1

Figure 13.5 The type computation of the rental price expression, in terms of the AST
figure

Inspect the rental-price type computation as an AST to see where ancestor context complements subexpression-based type computation. section 13.1

Constraint-based inference can go further: MPS produces type equalities and inequalities and solves them algorithmically, inferring types where a direct computation would return untype. That power requires more implementation code. section 15.4.2

How Building User-Friendly DSLs covers it

How deep it goes
Implements ancestor-based inference for numbers and defers richer Hindley-Milner-style algorithms.
Examples
Uses rental-price expressions, Number objects, attributes, and the “-” and “of” operators.
What it assumes
Uses AST objects, ancestor traversal, and a typeOf function while defining contextual inference directly.
What you can do after
Build it from scratch by passing AST ancestors into typeOf and centralizing contextual type logic.
How it connects
Connects type computation with AST ancestors, type checking constraints, untype, and type objects.

Also explained in

Compare how 16 books explain type inference →

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.