Skip to main content

Crate hir_lang

Crate hir_lang 

Source
Expand description

§hir_lang

The high-level intermediate representation (HIR) of LexerSketch: the one structured, expression-oriented IR that every forged language lowers into, so that name resolution, type checking, pattern compilation, capabilities, the evaluator, and the lowering to SSA are written once.

The full definition is specs/HIR.md in the LexerSketch plan; this crate implements its node forms, storage, builder, validator, traversal, and debug printer.

§The lazy path

Build bottom-up with a Builder (every node captures the builder’s current origin), finish to validate, then read, walk, or print:

use hir_lang::{Builder, Name, OpKind, Span};
use intern_lang::Interner;

let mut names = Interner::new();
let mut b = Builder::new();

// fn double(n) { n * 2 }
b.set_span(Span::new(10, 11));
let (param, n) = b.local_param(Name::new(names.intern("n")));
b.set_span(Span::new(15, 20));
let use_n = b.use_binder(n);
let two = b.int(2);
let product = b.op(OpKind::Mul, &[use_n, two]);
let body = b.block(&[], Some(product));
let double = b.func(Name::new(names.intern("double")), &[param], body);
let root = b.module(None, &[double]);

let hir = b.finish(root)?;

let mut nodes = 0;
hir_lang::walk(&hir, |_| nodes += 1);
assert_eq!(nodes, 9); // module, fn, param, pattern, block, op, use, path, literal
assert!(hir_lang::print(&hir, &names).contains("(op mul overflow=error"));

§What a Hir guarantees

A Hir exists only after the validator accepted it, and the validator is total: on any arena it accepts or returns a precise HirError, never panics, and runs in linear time. Accepted HIR forms one tree; every id resolves; every binder is bound exactly once and referenced only where it is in scope and reachable across frames; every jump has a target; effect forms sit only in frames that allow them; every op carries exactly the policy fields specs/OPS.md says it consults. Storage is flat, so cloning, comparing, printing, walking, and dropping never recurse, at any depth.

§no_std

The crate needs only alloc. The default std feature is additive.

Structs§

Arg
One argument of a call.
Arm
One arm of a match or one catch clause of a try.
Asm
Structured inline assembly (Zero, Iron).
AsmOperand
One inline-assembly operand: in(reg) x, out("rax") y.
AsmOptions
Inline-assembly options, a bit set.
Attr
An attribute: @inline, #[repr(C)], @budget(cpu = 10, heat = 3).
AttrArg
One attribute argument: key = value, key, or value.
Binder
A binder: one variable, parameter, capture, generic parameter, or label.
BinderId
The id of a Binder: a variable, parameter, capture, generic parameter, or label. Binder ids are unique across a whole Hir.
Block
A block: statements, an optional tail value, an optional label.
Builder
Builds a Hir bottom-up: children first, then the parent that lists them.
Capture
One explicit capture: the outer variable, the closure-local binder it initializes, and the mode.
ClassDef
A class: fields, base classes, interfaces, and members. Also a PHP trait (mixin), whose members are copied into the classes that use it.
Closure
A closure (lambda); see the spec, §8.10.
DefId
A definition in some compilation unit.
Effects
The effects a function, closure, or function type may perform.
Expansion
One expansion: what produced it, where it was invoked, and how it nests.
ExpnId
The id of an expansion record, or ExpnId::ROOT for text written directly in source.
ExprId
The id of an Expr: an expression.
FieldDef
A field of a record, class, or variant.
FieldId
The id of a FieldDef: a field of a record, class, or variant.
FieldInit
One name: value entry of a record literal.
FieldPat
One name: pattern entry of a record pattern.
FloatLit
A floating-point literal, stored as IEEE binary64 bits so that literals compare and hash exactly.
FnDef
A function: signature and optional body.
GenericParam
One generic parameter: its binder, bounds, and optional type and default.
Generics
The generic parameters and predicates of an item.
Hir
A validated HIR: one compilation unit rooted at a module.
Ident
A member name with its own span: field names, named arguments, method names, and attribute names.
ImplDef
An implementation block.
IntLit
An integer literal: magnitude, sign, and optional type suffix.
InterfaceDef
An interface (trait).
Item
A declaration.
ItemId
The id of an Item: a declaration.
List
A run of Ts stored out of line in one of the Hir’s pools.
MapEntry
One entry of an ordered map literal.
MixinRule
One conflict-resolution rule of a mixin use.
MixinUseDef
use A, B { rules } inside a class: copy the members of mixins (PHP traits). resolve-lang expands it after resolution.
Name
A hygienic name: a symbol plus the mark of the expansion that wrote it.
Op
One op instance: the operation and its policy.
Origin
Where a node came from: its source span and the expansion that produced it.
Param
A function or closure parameter.
ParamId
The id of a Param: a function or closure parameter.
PatId
The id of a Pat: a pattern.
Path
A name reference: root, optional qualified self, segments, namespace, and a partial resolution.
PathId
The id of a Path: a name reference with its resolution slot.
Policy
The policy fields of one op instance.
PrintOptions
Options for print_with and print_into.
QSelf
A qualified self type: <T>::a or <T as Tr>::a.
RecordDef
A record (struct).
Segment
One segment of a path: a hygienic name, its generic arguments, and its own origin (what an LSP renames).
SliceRest
The .. part of a slice pattern: an optional pattern for the middle and the elements after it.
Span
A half-open byte range start..end into a single source.
StmtId
The id of a Stmt: a statement inside a block.
SumDef
A sum (enum, tagged union).
Symbol
A small, copyable handle to a string held by an Interner.
TextRef
A run of bytes in the Hir’s text pool: the payload of a string, byte-string, or big-integer literal.
TyId
The id of a Ty: a type term.
UnitId
A compilation unit’s identity, assigned by the host (the LexerSketch engine numbers the files of a session).
Variant
A variant of a sum.
VariantId
The id of a Variant: a variant of a sum.
WherePred
A where predicate: T: A + 'r or 'a: 'b.

Enums§

ArgKind
How an argument is passed.
AsmDir
How an inline-assembly operand is used.
AttrValue
An attribute value.
BindMode
How a binding pattern binds its value.
BinderKind
What a binder names. Each kind has its own binding sites; see the spec, §3.1.
BorrowKind
The kind of a borrow expression.
Bound
A term in bound position: an interface type or a region.
Capacity
What a container overflowed; carried by HirError::CapacityExceeded.
CaptureMode
How a closure captures a variable.
Control
What a walk callback asks for next (only meaningful on Event::Enter).
Def
The definition inside a unit that a DefId names: an item or a variant.
DefaultEval
When parameter defaults are evaluated, and what they can see.
DivZero
What happens on integer division or remainder by zero.
EffectProblem
An effect form outside a frame that allows it; carried by HirError::Effect.
Event
An event of Hir::walk_from.
ExpnKind
What kind of expansion produced some HIR.
Expr
An expression; see the spec, §8. Children are evaluated in the order the fields are listed.
FloatToInt
What happens when a float-to-int conversion meets NaN or an out-of-range value.
Frame
The kind of a frame, as delivered by Event::FrameOpen.
GenericArg
A generic argument in a path segment or method call.
HirError
Why a HIR was rejected by the validator, or a resolution by Hir::resolve.
IdKind
Names an arena: the nine node kinds plus binders and expansions.
Intrinsic
A non-arithmetic intrinsic; operands are Expr::Intrinsic’s args.
ItemKind
What an item declares; see the spec, §10.
JumpProblem
A jump that has no valid target; carried by HirError::Jump.
Lit
A literal value.
Malformed
A structural problem inside one node; carried by HirError::Malformed.
MemOrder
A memory ordering (C++20 / LLVM semantics).
Member
The member a field access names.
MixinAction
What a mixin rule does with a method.
NodeRef
A reference to any tree node: the nine node kinds in one Copy value.
Ns
The namespace a path is looked up in, fixed by the path’s context.
OpKind
An operation from specs/OPS.md. Conversions carry their target type.
Overflow
What happens on integer overflow (add sub mul neg abs, div MIN / -1, int_cast); specs/OPS.md section 2.
ParamKind
How a parameter receives its argument. Parameters appear in this order; Receiver, Rest, and RestNamed at most once each.
Pat
A pattern; see the spec, §6.
PathRoot
Where a path starts.
Prim
A primitive type: the value domains of specs/OPS.md plus isize/usize (target-width integers) and str.
Res
What a path (or its resolved prefix) refers to. Lowering may set it; resolve-lang sets the rest with Hir::resolve.
RmwOp
The operation of an atomic read-modify-write.
Shape
The field layout of a record or variant.
Shift
What happens when a shift amount is at least the bit width, or negative.
Site
Where an error was found: a node, a binder, an expansion record, the root, or a node’s attribute list.
Stmt
A statement inside a block; see the spec, §7.
Ty
A type term. Every annotation slot in HIR is optional, so a dynamic language never creates one; see the spec, §5.
Vis
Visibility of an item or field.

Traits§

Pooled
An element type that lives in one of the Hir’s pools and can therefore appear in a List.

Functions§

print
Prints hir in the debug form, resolving names through names.
print_into
Prints hir into any fmt::Write sink; see print().
print_with
Prints hir with options; see print().
walk
Visits every node of hir in canonical preorder, from the root.