Skip to main content

lower_lang/
lib.rs

1//! # lower_lang
2//!
3//! Lowers a lossless syntax tree into HIR. A language describes what its
4//! constructs *mean* as data — a [`Mapping`] from node kinds to semantic
5//! [archetypes](Arch) (binders, scopes, declarations, control, expressions,
6//! patterns, types), operator tables with their policies, and hygienic
7//! [templates](Template) for sugar — and lower-lang builds the HIR, records
8//! where every node came from, and validates the result.
9//!
10//! ## The lazy path
11//!
12//! Build a mapping once, then [`lower`] any tree of that language:
13//!
14//! ```
15//! use hir_lang::OpKind;
16//! use intern_lang::Interner;
17//! use lower_lang::{lower, Arch, MappingBuilder, OpSpec, Pick, TokenRole};
18//! use syntax_lang::{Element, Node, Span, Token, TokenKind};
19//!
20//! #[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)]
21//! enum K { File, Add, Num, Plus, Space }
22//! impl TokenKind for K {
23//!     fn is_trivia(&self) -> bool { matches!(self, K::Space) }
24//! }
25//!
26//! let mut b = MappingBuilder::new();
27//! b.node(K::File, Arch::Module { name: Pick::Absent, items: Pick::Nodes });
28//! b.node(K::Add, Arch::binary());
29//! b.token(K::Num, TokenRole::Int);
30//! b.binary_op(K::Plus, OpSpec::Op(OpKind::Add));
31//! let mapping = b.build()?;
32//!
33//! // `1 + 2`
34//! let tok = |k, s, e| Element::Token(Token::new(k, Span::new(s, e)));
35//! let add = Node::new(K::Add, vec![
36//!     tok(K::Num, 0, 1), tok(K::Space, 1, 2), tok(K::Plus, 2, 3),
37//!     tok(K::Space, 3, 4), tok(K::Num, 4, 5),
38//! ]);
39//! let file = Node::new(K::File, vec![Element::Node(add)]);
40//!
41//! let mut names = Interner::new();
42//! let out = lower(&file, "1 + 2", &mapping, &mut names).expect("within budget");
43//! assert!(out.problems.is_empty());
44//! assert!(hir_lang::print(&out.hir, &names).contains("(op add overflow=error"));
45//! # Ok::<(), lower_lang::MappingError>(())
46//! ```
47//!
48//! ## What lowering guarantees
49//!
50//! - **It never panics and always returns valid HIR** for any tree, including
51//!   trees full of syntax errors, unmapped kinds, missing parts, and spans
52//!   outside the source: each broken construct becomes an HIR error form and a
53//!   [`Problem`] with its source span, and hir-lang's lenient validation
54//!   repairs and reports everything else. Only an exhausted [`Budget`] (or
55//!   exhausted interner or arena space) stops it.
56//! - **Every HIR node has an origin inside the source**: its own syntax span,
57//!   or, for template output, the span of the node that invoked the template,
58//!   with the template's expansion recorded.
59//! - **Templates are hygienic**: names a template introduces carry its
60//!   expansion's mark and are resolved by construction, so they never capture
61//!   or shadow user names.
62//! - **It is deterministic and iterative**: the same input lowers to the same
63//!   HIR, at any tree depth.
64//!
65//! ## `no_std`
66//!
67//! The crate needs only `alloc`. The default `std` feature is additive.
68
69#![cfg_attr(not(feature = "std"), no_std)]
70#![cfg_attr(docsrs, feature(doc_cfg))]
71#![forbid(unsafe_code)]
72#![deny(missing_docs)]
73#![deny(unused_must_use)]
74#![deny(unused_results)]
75#![deny(clippy::unwrap_used)]
76#![deny(clippy::expect_used)]
77#![deny(clippy::todo)]
78#![deny(clippy::unimplemented)]
79#![deny(clippy::print_stdout)]
80#![deny(clippy::print_stderr)]
81#![deny(clippy::dbg_macro)]
82#![deny(clippy::unreachable)]
83
84extern crate alloc;
85
86mod arch;
87mod lower;
88mod mapping;
89mod pick;
90mod problem;
91mod template;
92pub mod templates;
93
94pub use arch::{Arch, RecordShape, TemplateUse};
95pub use hir_lang::Span;
96pub use lower::{Budget, Lowered, Lowerer};
97pub use mapping::{
98    EffectMode, Escapes, Fixity, IdentPatterns, LangPolicy, Mapping, MappingBuilder, MappingError,
99    Modifier, NameRef, OpSpec, PlaceArgs, TokenRole, TypeName,
100};
101pub use pick::{Labeler, Pick};
102pub use problem::{Context, LowerError, Problem, ProblemKind};
103pub use template::{
104    ArgsHole, ExprHole, HoleKind, LabelHole, LabelRef, MAX_TEMPLATE_SIZE, PatHole, StmtsHole, TArg,
105    TBinder, TExpr, TLabel, TLit, TPat, TStmt, TTy, Template, TemplateBuilder, TemplateError,
106    TemplateId, TyHole,
107};
108
109use intern_lang::Interner;
110use syntax_lang::{Node, TokenKind};
111
112/// Lowers `tree`, parsed from `source`, into a validated HIR unit with the
113/// default [`Budget`], names interned in `names`.
114///
115/// The Tier-1 entry point; use [`Lowerer`] for a budget, a unit id, or field
116/// labels.
117///
118/// # Errors
119///
120/// Only for exhausted resources: [`LowerError::NodeBudget`],
121/// [`LowerError::SymbolSpaceExhausted`], or [`LowerError::Hir`] when hir-lang's
122/// arenas overflow. Problems in the code are never errors; they are in
123/// [`Lowered::problems`], and the HIR is still valid.
124///
125/// # Examples
126///
127/// See the [crate documentation](crate).
128pub fn lower<K>(
129    tree: &Node<K>,
130    source: &str,
131    mapping: &Mapping<K>,
132    names: &mut Interner,
133) -> Result<Lowered, LowerError>
134where
135    K: Copy + Ord + TokenKind,
136{
137    Lowerer::new(mapping).lower(tree, source, names)
138}
139
140/// Compiles and runs the `rust` code blocks in `README.md` and `docs/API.md` as
141/// part of `cargo test`, so the published examples cannot drift from the API.
142#[cfg(doctest)]
143#[doc = include_str!("../README.md")]
144#[doc = include_str!("../docs/API.md")]
145pub struct MarkdownDocTests;