Yuku

Semantic Analysis

Semantic analysis builds a model of a program’s scopes, symbols, and references, with each reference resolved to the symbol it names, and reports the early errors that need scopes, such as redeclarations. From JavaScript, see semantic analysis.

var tree = try parser.parse(allocator, source, .{});
defer tree.deinit();

const semantic = try parser.semantic.analyze(&tree, .{ .check = true });
pub fn analyze(tree: *ast.Tree, options: AnalyzeOptions) error{OutOfMemory}!Semantic // .{ .check: bool }
pub fn check(tree: *ast.Tree) error{OutOfMemory}!void
  • .check = true appends the early errors to tree.diagnostics in the same walk, and .check = false skips their cost.
  • check reports the same errors faster, without the model.
  • The model lives in the tree’s arena and describes the tree as parsed. Analyze again after a transform with .check = false, since the errors are already reported.
  • The semantic traverser runs hooks of your own during the analysis.

The model

semantic.symbolOf(node)             // ?SymbolId, what a node declares or refers to
semantic.referenceOf(node)          // ?ReferenceId, at an identifier
semantic.scopeOf(node)              // ScopeId, the scope a node creates, or the innermost around it
semantic.parentOf(node)             // ?ast.NodeIndex
semantic.ancestors(node)            // the node, then each parent up to the root

semantic.symbol(id)                 // also reference(id) and scopes.get(id)
semantic.decls(symbol)              // each declaration's name node, in source order
semantic.uses(symbol)               // each ReferenceId to it, in source order

semantic.bindings(scope)            // an iterator over the symbols a scope declares, in no order
semantic.binding(scope, "x")        // ?SymbolId, declared there or a var hoisting through
semantic.lookup(scope, "x", .value) // ?SymbolId, as the name resolves from the scope
semantic.member(ns, "x", .value)    // ?SymbolId, ns.x of a namespace or enum, across merged bodies

semantic.symbols                    // every Symbol, indexed by SymbolId, also references
semantic.scopes.list                // every Scope, indexed by ScopeId
semantic.scopes.ancestors(id)       // a scope, then each parent

The types are in parser.semantic. Ids are dense, with symbols ordered by first declaration and references by position.

pub const Symbol = struct {
    name: ast.String,
    flags: Flags,   // see Symbols
    scope: ScopeId, // where it lands, the hoist target for a var
};

pub const Reference = struct {
    name: ast.String,
    scope: ScopeId,
    node: ast.NodeIndex, // an identifier_reference, jsx_identifier, or identifier_name
    symbol: SymbolId,    // .none for a global or undeclared name
    flags: Flags,        // .write, .space, and .type_position
};

pub const Scope = struct {
    node: ast.NodeIndex,
    parent: ScopeId,       // .none at the root
    hoist_target: ScopeId,
    kind: Kind,            // .global, .module, .function, .function_body, .block, .class,
                           // .static_block, .expression_name, or .ts_module
    flags: Flags,          // .strict
};

ScopeId.root is the global scope, and semantic.scopeOf(tree.root) the scope of top-level code, the module scope in a module. A JSX component tag and a type predicate’s parameter are references too, so a rename sees every use.

const name = try tree.addString("renamed");
for (semantic.decls(symbol)) |node| tree.setName(node, name);
for (semantic.uses(symbol)) |id| tree.setName(semantic.reference(id).node, name);

An enum member is also read as E.member, a member access rather than a reference, so a rename of one is incomplete.

for (semantic.symbols, 0..) |symbol, i| {
    const id: parser.semantic.SymbolId = @fromBackingInt(@intCast(i));
    if (semantic.uses(id).len == 0) std.debug.print("unused {s}\n", .{tree.string(symbol.name)});
}

for (semantic.references) |reference| {
    if (reference.symbol == .none) std.debug.print("undeclared {s}\n", .{tree.string(reference.name)});
}

Scopes

The scope tree follows the specification.

  • A catch clause shares its scope with its body, unless its parameter has a default value or a computed key.
  • A named function or class expression has a scope of its own for its name.
  • A function body scopes its let and const apart from the parameters, as TypeScript does.
  • A class decorator sees the scope around its class, and a member decorator sees the class scope.
  • Strict mode comes from modules, classes, and "use strict" directives.
  • In sloppy JavaScript, a plain function declared in a block or an if clause binds where a var of its name would, unless that var would be an error, as engines run it (Annex B).

Symbols

symbol.flags records its declaration kinds and modifiers.

KindsModifiers
function_scoped_var, block_scoped_var, function, class, regular_enum, const_enum, value_module, interface, type_alias, type_parameter, namespace_module, import, type_importconst_var, ambient, parameter, catch_var, exported, is_default, enum_member
symbol.flags.intersects(Symbol.value_space) // also variable, any_import, type_space, and namespace_space
symbol.flags.visibleIn(.type)               // whether a reference in a space binds to it, always for an import
symbol.flags.isHoistingVar()
symbol.flags.toString()

One rule decides merging and redeclaration. Each declaration kind has an exclusion mask in Symbol.Excludes, and a new declaration conflicts with a symbol whose flags intersect it, or merges into it otherwise. Function overloads, a class and an interface, and a namespace and an enum merge this way, and a namespace or enum declared in several blocks sees the members of the others. A conflicting declaration is still one of the symbol’s decls.

Declaration spaces

A name resolves in one space, and a binding outside that space does not shadow it, as in TypeScript.

type T = string;
function f() {
  const T = 1;
  let x: T; // the outer type T
  T;        // the inner const T
}
SpaceFor
.valueRuntime uses
.typeAnnotations
.namespaceThe head of a dotted name, such as ns in ns.T
.typeofA value in a type, such as x in typeof x
.anyAlias positions, such as export { x }

lookup resolves by scope alone, without the position rules a reference follows, such as an infer type parameter being visible only in its true branch.

Module records

module_record.collect lists a module’s imports and exports, as the specification’s ImportEntry and ExportEntry records with the symbol behind each, static ones first and then dynamic ones, each in source order.

const records = try parser.semantic.module_record.collect(&tree, &semantic);
pub const Import = struct {
    kind: Kind,               // .named, .namespace, .side_effect, .import_equals, .dynamic,
                              // .require, or .augmentation
    name: ast.String,         // the imported name, "default" for a default import
    symbol: SymbolId,         // the binding it declares, .none if it declares none
    specifier: ast.String,
    type_only: bool,
    phase: ?ast.ImportPhase,  // .source or .@"defer"
    node: ast.NodeIndex,
    scope: ScopeId,           // the body of an augmentation
};

pub const Export = struct {
    kind: Kind,               // .named, .re_export, .namespace, .star, .equals, or .global
    name: ast.String,
    symbol: SymbolId,         // the binding it exports, .none for a re-export
    from_name: ast.String,    // the name a re_export takes
    specifier: ast.String,
    type_only: bool,
    node: ast.NodeIndex,
};

records.flags // .uses_require, .uses_module, .uses_exports, and .uses_import_meta
  • A dynamic import() or require() counts when its specifier is a string, or a template with no substitutions.
  • An augmentation is a declare module "m" block in a module, which merges its body’s declarations into m.
  • A declaration file that is a module with no export statement exports every declaration but its imports, as in TypeScript.
  • flags record free uses, so a local require does not count.