Skip to main content

hir_lang/
lib.rs

1//! # hir_lang
2//!
3//! The high-level intermediate representation (HIR) of LexerSketch: the one
4//! structured, expression-oriented IR that every forged language lowers into,
5//! so that name resolution, type checking, pattern compilation, capabilities,
6//! the evaluator, and the lowering to SSA are written once.
7//!
8//! The full definition is `specs/HIR.md` in the LexerSketch plan; this crate
9//! implements its node forms, storage, builder, validator, traversal, and
10//! debug printer.
11//!
12//! ## The lazy path
13//!
14//! Build bottom-up with a [`Builder`] (every node captures the builder's
15//! current origin), [`finish`](Builder::finish) to validate, then read, walk,
16//! or print:
17//!
18//! ```
19//! use hir_lang::{Builder, Name, OpKind, Span};
20//! use intern_lang::Interner;
21//!
22//! let mut names = Interner::new();
23//! let mut b = Builder::new();
24//!
25//! // fn double(n) { n * 2 }
26//! b.set_span(Span::new(10, 11));
27//! let (param, n) = b.local_param(Name::new(names.intern("n")));
28//! b.set_span(Span::new(15, 20));
29//! let use_n = b.use_binder(n);
30//! let two = b.int(2);
31//! let product = b.op(OpKind::Mul, &[use_n, two]);
32//! let body = b.block(&[], Some(product));
33//! let double = b.func(Name::new(names.intern("double")), &[param], body);
34//! let root = b.module(None, &[double]);
35//!
36//! let hir = b.finish(root)?;
37//!
38//! let mut nodes = 0;
39//! hir_lang::walk(&hir, |_| nodes += 1);
40//! assert_eq!(nodes, 9); // module, fn, param, pattern, block, op, use, path, literal
41//! assert!(hir_lang::print(&hir, &names).contains("(op mul overflow=error"));
42//! # Ok::<(), hir_lang::HirError>(())
43//! ```
44//!
45//! ## What a `Hir` guarantees
46//!
47//! A [`Hir`] exists only after the validator accepted it, and the validator is
48//! total: on any arena it accepts or returns a precise [`HirError`], never
49//! panics, and runs in linear time. Accepted HIR forms one tree; every id
50//! resolves; every binder is bound exactly once and referenced only where it
51//! is in scope and reachable across frames; every jump has a target; effect
52//! forms sit only in frames that allow them; every op carries exactly the
53//! policy fields `specs/OPS.md` says it consults. Storage is flat, so cloning,
54//! comparing, printing, walking, and dropping never recurse, at any depth.
55//!
56//! ## `no_std`
57//!
58//! The crate needs only `alloc`. The default `std` feature is additive.
59
60#![cfg_attr(not(feature = "std"), no_std)]
61#![cfg_attr(docsrs, feature(doc_cfg))]
62#![forbid(unsafe_code)]
63#![deny(missing_docs)]
64#![deny(unused_must_use)]
65#![deny(unused_results)]
66#![deny(clippy::unwrap_used)]
67#![deny(clippy::expect_used)]
68#![deny(clippy::panic)]
69#![deny(clippy::todo)]
70#![deny(clippy::unimplemented)]
71#![deny(clippy::unreachable)]
72#![deny(clippy::print_stdout)]
73#![deny(clippy::print_stderr)]
74#![deny(clippy::dbg_macro)]
75
76extern crate alloc;
77
78mod builder;
79mod canon;
80mod copy;
81mod def;
82mod error;
83mod expr;
84mod hir;
85mod id;
86mod intrinsic;
87mod item;
88mod lit;
89mod name;
90mod ops;
91mod origin;
92mod pat;
93mod print;
94mod store;
95mod ty;
96mod validate;
97mod walk;
98
99pub use builder::Builder;
100pub use def::{Def, DefId, UnitId};
101pub use error::{Capacity, EffectProblem, HirError, JumpProblem, Malformed, Site};
102pub use expr::{
103    Arg, ArgKind, Arm, Block, BorrowKind, Capture, CaptureMode, Closure, DefaultEval, Expr,
104    FieldInit, MapEntry, Member, Stmt,
105};
106pub use hir::Hir;
107pub use id::{
108    BinderId, ExprId, FieldId, IdKind, ItemId, List, NodeRef, ParamId, PatId, PathId, StmtId,
109    TextRef, TyId, VariantId,
110};
111pub use intern_lang::Symbol;
112pub use intrinsic::{Asm, AsmDir, AsmOperand, AsmOptions, Intrinsic, MemOrder, RmwOp};
113pub use item::{
114    Attr, AttrArg, AttrValue, ClassDef, FieldDef, FnDef, GenericParam, Generics, ImplDef,
115    InterfaceDef, Item, ItemKind, MixinAction, MixinRule, MixinUseDef, Param, ParamKind, RecordDef,
116    Shape, SumDef, Variant, Vis, WherePred,
117};
118pub use lit::{FloatLit, IntLit, Lit, Prim};
119pub use name::{Binder, BinderKind, Ns, Path, PathRoot, QSelf, Res, Segment};
120pub use ops::{DivZero, FloatToInt, Op, OpKind, Overflow, Policy, Shift};
121pub use origin::{Expansion, ExpnId, ExpnKind, Ident, Name, Origin};
122pub use pat::{BindMode, FieldPat, Pat, SliceRest};
123pub use print::{PrintOptions, print, print_into, print_with};
124pub use span_lang::Span;
125pub use store::Pooled;
126pub use ty::{Bound, Effects, GenericArg, Ty};
127pub use walk::{Control, Event, Frame};
128
129/// Visits every node of `hir` in canonical preorder, from the root.
130///
131/// The lazy path for analyses that look at nodes one at a time. For enter and
132/// leave events, skipping, or stopping, use [`Hir::walk_from`].
133///
134/// # Examples
135///
136/// ```
137/// use hir_lang::{Builder, NodeRef};
138///
139/// let mut b = Builder::new();
140/// let root = b.module(None, &[]);
141/// let hir = b.finish(root)?;
142/// let mut seen = Vec::new();
143/// hir_lang::walk(&hir, |node| seen.push(node));
144/// assert_eq!(seen, [NodeRef::Item(root)]);
145/// # Ok::<(), hir_lang::HirError>(())
146/// ```
147pub fn walk<F: FnMut(NodeRef)>(hir: &Hir, f: F) {
148    walk::walk_nodes(hir.store(), NodeRef::Item(hir.root()), f);
149}
150
151/// Compiles and runs the `rust` code blocks in `README.md` and `docs/API.md` as
152/// part of `cargo test`, so the published examples cannot drift from the API.
153#[cfg(doctest)]
154#[doc = include_str!("../README.md")]
155#[doc = include_str!("../docs/API.md")]
156pub struct MarkdownDocTests;
157
158#[cfg(test)]
159mod tests {
160    use super::*;
161
162    /// The README states node sizes; keep them from growing unnoticed.
163    #[test]
164    fn test_node_sizes_stay_small() {
165        let sizes = [
166            core::mem::size_of::<Expr>(),
167            core::mem::size_of::<Pat>(),
168            core::mem::size_of::<Ty>(),
169            core::mem::size_of::<Stmt>(),
170            core::mem::size_of::<Path>(),
171            core::mem::size_of::<Item>(),
172            core::mem::size_of::<Origin>(),
173            core::mem::size_of::<Option<ExprId>>(),
174        ];
175        // Paths grew in 0.3 (root, qualified self, partial resolution, a
176        // unit-qualified `DefId`); patterns shrank (range bounds are nodes).
177        assert_eq!(sizes, [40, 32, 24, 20, 40, 72, 12, 4]);
178    }
179}