lower_lang/mapping.rs
1//! The mapping: a language's semantics as data.
2//!
3//! A [`Mapping`] mirrors LexerSketch's LSF2 `[semantics]` sections:
4//! node kinds to [`Arch`]etypes (`[semantics.bind]`), templates
5//! (`[semantics.lower]`), and operators with their policies
6//! (`[semantics.ops]`), plus the token roles, modifiers, and path roots that
7//! the archetypes read. Build one with a [`MappingBuilder`]; it is immutable,
8//! `Send` and `Sync` when `K` is, and lowers any number of trees.
9
10use alloc::boxed::Box;
11use alloc::vec::Vec;
12use core::fmt;
13
14use hir_lang::{DivZero, FloatToInt, Op, OpKind, Overflow, PathRoot, Prim, Shift};
15
16use crate::arch::{Arch, TemplateUse};
17use crate::pick::{KindSets, Pick};
18use crate::template::{HoleKind, NONE, TArg, TNode, Template, TemplateId};
19
20/// What a token means when it is lowered on its own.
21///
22/// # Examples
23///
24/// ```
25/// use lower_lang::{Escapes, TokenRole};
26///
27/// let var = TokenRole::Var { sigil: 1 }; // `$name`, name `name`
28/// let string = TokenRole::Str(Escapes::Standard);
29/// assert_ne!(var, string);
30/// ```
31#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
32#[non_exhaustive]
33pub enum TokenRole {
34 /// An identifier: a name, a variable reference, a binding, or a type name.
35 Name,
36 /// A sigiled variable such as `$x`; the first `sigil` bytes are not part
37 /// of the name.
38 Var {
39 /// Bytes to strip.
40 sigil: u8,
41 },
42 /// A loop label such as `'outer`.
43 Label {
44 /// Bytes to strip.
45 sigil: u8,
46 },
47 /// A region (lifetime) such as `'a`, as a generic parameter or argument.
48 Lifetime {
49 /// Bytes to strip.
50 sigil: u8,
51 },
52 /// An integer literal (`0x`, `0o`, `0b` prefixes and `_` separators
53 /// accepted; a registered suffix sets its type).
54 Int,
55 /// A floating-point literal.
56 Float,
57 /// A number: a float if it has a fraction or an exponent, else an integer.
58 Number,
59 /// A string literal, quotes included in the token.
60 Str(Escapes),
61 /// A character literal, quotes included.
62 Char(Escapes),
63 /// A byte-string literal, quotes (and a leading `b`) included.
64 Bytes(Escapes),
65 /// `true`.
66 True,
67 /// `false`.
68 False,
69 /// `null` / `nil` / `None`-as-keyword.
70 Null,
71 /// `_`: a wildcard pattern, or an inferred type.
72 Wild,
73 /// `..` inside a pattern.
74 Rest,
75 /// A type keyword (`int`, `mixed`, `Self`, `!`).
76 Type(TypeName),
77}
78
79/// How a string or character literal's escapes are decoded.
80///
81/// # Examples
82///
83/// ```
84/// use lower_lang::Escapes;
85///
86/// assert_ne!(Escapes::None, Escapes::Standard);
87/// ```
88#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
89pub enum Escapes {
90 /// Raw: the text between the quotes, unchanged.
91 None,
92 /// Only `\\` and an escaped quote (PHP single-quoted strings).
93 Quotes,
94 /// `\n \r \t \0 \\ \' \" \$ \xHH \u{H..}`; any other escape is reported
95 /// and kept as written.
96 Standard,
97}
98
99/// A type keyword's meaning.
100///
101/// # Examples
102///
103/// ```
104/// use hir_lang::Prim;
105/// use lower_lang::TypeName;
106///
107/// assert_eq!(TypeName::Prim(Prim::I64), TypeName::Prim(Prim::I64));
108/// ```
109#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
110pub enum TypeName {
111 /// A primitive type.
112 Prim(Prim),
113 /// The gradual dynamic type (`mixed`, `any`).
114 Any,
115 /// The type of expressions that never complete (`never`, `!`).
116 Never,
117 /// `Self`.
118 SelfTy,
119 /// A type to infer (`_`, `auto`).
120 Infer,
121}
122
123/// A keyword or symbol that sets a flag on the construct it appears in.
124///
125/// Modifiers are read from the **direct** significant children of the
126/// archetypes that consult them (listed on each [`Arch`] variant), so a token
127/// can be a modifier in one construct and something else elsewhere.
128///
129/// # Examples
130///
131/// ```
132/// use lower_lang::Modifier;
133///
134/// assert_ne!(Modifier::Public, Modifier::Mut);
135/// ```
136#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
137#[non_exhaustive]
138pub enum Modifier {
139 /// `pub`, `public`.
140 Public,
141 /// `protected`.
142 Protected,
143 /// `private`.
144 Private,
145 /// `pub(crate)`, `internal`.
146 Package,
147 /// `mut`, `var`.
148 Mut,
149 /// `&` / `ref`: by reference (parameters, captures, bindings, arguments).
150 Ref,
151 /// `...` / `*` on a parameter: variadic.
152 Rest,
153 /// `**` on a parameter: collects named arguments.
154 RestNamed,
155 /// A `*` marker in a parameter list: the parameters after it are named-only.
156 NamedOnly,
157 /// A `/` marker in a parameter list: the parameters before it are
158 /// positional-only.
159 PositionalOnly,
160 /// `self` as a parameter: the method receiver.
161 Receiver,
162 /// `async`.
163 Async,
164 /// `*` on a function (`function*`), `gen`: a generator.
165 Generator,
166 /// `throws`.
167 Throws,
168 /// `unsafe`.
169 Unsafe,
170 /// `static` on a class member.
171 Static,
172 /// `abstract`.
173 Abstract,
174 /// `final`.
175 Final,
176 /// `*` in an import: a glob.
177 Glob,
178 /// `..=`: an inclusive range pattern.
179 Inclusive,
180 /// `...` on an argument: spread positional arguments.
181 Spread,
182 /// `**` on an argument: spread named arguments.
183 SpreadNamed,
184 /// `union` on a record.
185 Union,
186}
187
188impl Modifier {
189 pub(crate) const fn bit(self) -> u32 {
190 1 << (self as u32)
191 }
192}
193
194/// How a function's effects are decided.
195///
196/// # Examples
197///
198/// ```
199/// use lower_lang::EffectMode;
200///
201/// assert_eq!(EffectMode::default(), EffectMode::Declared);
202/// ```
203#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
204pub enum EffectMode {
205 /// Only what modifiers declare (`async`, `throws`, generator markers).
206 #[default]
207 Declared,
208 /// Declared, plus whatever the body does directly (a `yield` makes a
209 /// generator, as in PHP and Python; a `throw` makes it throwing).
210 Inferred,
211 /// Every function, closure, and module body has the effect (any PHP
212 /// function may throw).
213 Always,
214}
215
216/// How a bare identifier in a `match` arm pattern is lowered.
217///
218/// # Examples
219///
220/// ```
221/// use lower_lang::IdentPatterns;
222///
223/// assert_eq!(IdentPatterns::default(), IdentPatterns::Ident);
224/// ```
225#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
226pub enum IdentPatterns {
227 /// `Pat::Ident`: the resolver decides between a constant or unit variant
228 /// and a new binding (Rust, Kraken).
229 #[default]
230 Ident,
231 /// Always a new binding.
232 Bind,
233}
234
235/// Which call arguments are passed as places, so a by-reference parameter can
236/// alias them.
237///
238/// # Examples
239///
240/// ```
241/// use lower_lang::PlaceArgs;
242///
243/// assert_eq!(PlaceArgs::default(), PlaceArgs::Marked);
244/// ```
245#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
246pub enum PlaceArgs {
247 /// Only arguments with a `Ref` modifier (`f(&$x)` in old PHP, `ref x` in
248 /// C#).
249 #[default]
250 Marked,
251 /// Every argument that is a place (a variable, field, index, ...); the
252 /// callee decides at run time whether to alias it (PHP and Mox, where
253 /// by-reference is declared on the parameter).
254 Places,
255}
256
257/// Language-wide lowering policies.
258///
259/// `#[non_exhaustive]`: start from [`LangPolicy::default`] and assign fields.
260///
261/// # Examples
262///
263/// ```
264/// use hir_lang::Overflow;
265/// use lower_lang::{EffectMode, LangPolicy, PlaceArgs};
266///
267/// // Mox: PHP-like integers, any function may throw, implicit locals.
268/// let mut mox = LangPolicy::default();
269/// mox.overflow = Overflow::Promote;
270/// mox.throws = EffectMode::Always;
271/// mox.yields = EffectMode::Inferred;
272/// mox.implicit_locals = true;
273/// mox.place_args = PlaceArgs::Places;
274/// assert!(mox.implicit_locals);
275/// ```
276#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
277#[non_exhaustive]
278pub struct LangPolicy {
279 /// The overflow policy of every op that consults one (OPS §2).
280 pub overflow: Overflow,
281 /// The division-by-zero policy.
282 pub div_zero: DivZero,
283 /// The shift-amount policy.
284 pub shift: Shift,
285 /// The float-to-integer conversion policy.
286 pub float_to_int: FloatToInt,
287 /// When functions, closures, and module bodies throw.
288 pub throws: EffectMode,
289 /// When they are generators.
290 pub yields: EffectMode,
291 /// When they are async.
292 pub asyncs: EffectMode,
293 /// PHP-style implicit declaration: assigning to a plain variable declares
294 /// it for the whole enclosing function (or module body) unless a
295 /// parameter, `global`, or `static` already does.
296 pub implicit_locals: bool,
297 /// Bare identifiers in `match` arm patterns.
298 pub ident_patterns: IdentPatterns,
299 /// Which arguments are passed as places.
300 pub place_args: PlaceArgs,
301}
302
303impl Default for LangPolicy {
304 fn default() -> Self {
305 Self {
306 overflow: Overflow::Error,
307 div_zero: DivZero::Error,
308 shift: Shift::Error,
309 float_to_int: FloatToInt::Error,
310 throws: EffectMode::Declared,
311 yields: EffectMode::Declared,
312 asyncs: EffectMode::Declared,
313 implicit_locals: false,
314 ident_patterns: IdentPatterns::Ident,
315 place_args: PlaceArgs::Marked,
316 }
317 }
318}
319
320/// A host or intrinsic name stored in a mapping, from
321/// [`MappingBuilder::name`].
322///
323/// # Examples
324///
325/// ```
326/// let mut b = lower_lang::MappingBuilder::<u8>::new();
327/// let concat = b.name("mox.concat");
328/// assert_ne!(concat, b.name("mox.echo"));
329/// ```
330#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
331pub struct NameRef(pub(crate) u32);
332
333/// What an operator token lowers to.
334///
335/// # Examples
336///
337/// ```
338/// use hir_lang::{Op, OpKind, Overflow};
339/// use lower_lang::OpSpec;
340///
341/// let plus = OpSpec::Op(OpKind::Add); // language policy
342/// let wrapping = OpSpec::OpWith(Op::new(OpKind::Add).with_overflow(Overflow::Wrap));
343/// let plus_eq = OpSpec::Compound(OpKind::Add); // `+=`
344/// assert_ne!(plus, wrapping);
345/// assert_ne!(plus, plus_eq);
346/// ```
347#[derive(Clone, Copy, Debug, PartialEq, Eq)]
348#[non_exhaustive]
349pub enum OpSpec {
350 /// An intrinsic op with the language's policies ([`LangPolicy`]).
351 Op(OpKind),
352 /// An intrinsic op with exactly this policy (`[semantics.ops] "/" = { op =
353 /// "div", zero = "trap" }`).
354 OpWith(Op),
355 /// Compound assignment (`+=`) with the language's policies.
356 Compound(OpKind),
357 /// Compound assignment with exactly this policy.
358 CompoundWith(Op),
359 /// Plain assignment (`=` as an operator).
360 Assign,
361 /// Reference assignment (`=&`).
362 RefAssign,
363 /// The operand itself (unary `+`).
364 Identity,
365 /// `&x` / `&mut x` as a prefix operator.
366 Borrow(hir_lang::BorrowKind),
367 /// `*x` as a prefix operator.
368 Deref,
369 /// `await x` (prefix) or `x.await` (postfix).
370 Await,
371 /// A template whose expression holes receive the operands, in order
372 /// (`&&`, `||`, `??`, `x++`).
373 Template(TemplateId),
374 /// A call of a host function with the operands as arguments (Mox `.`
375 /// string concatenation).
376 Extern(NameRef),
377 /// A named backend intrinsic applied to the operands.
378 Intrinsic(NameRef),
379}
380
381/// Ops a compound assignment may use (HIR §8.2).
382const COMPOUND: [OpKind; 11] = [
383 OpKind::Add,
384 OpKind::Sub,
385 OpKind::Mul,
386 OpKind::Div,
387 OpKind::FloorDiv,
388 OpKind::Rem,
389 OpKind::FloorMod,
390 OpKind::And,
391 OpKind::Or,
392 OpKind::Xor,
393 OpKind::Shl,
394];
395
396pub(crate) fn compound_ok(kind: OpKind) -> bool {
397 COMPOUND.contains(&kind) || kind == OpKind::Shr
398}
399
400/// Operator positions, for the tables and errors.
401///
402/// # Examples
403///
404/// ```
405/// use lower_lang::Fixity;
406///
407/// assert_eq!(Fixity::Binary.arity(), 2);
408/// ```
409#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
410pub enum Fixity {
411 /// Before the operand.
412 Prefix,
413 /// Between two operands.
414 Binary,
415 /// After the operand.
416 Postfix,
417}
418
419impl Fixity {
420 /// The number of operands.
421 ///
422 /// # Examples
423 ///
424 /// ```
425 /// assert_eq!(lower_lang::Fixity::Prefix.arity(), 1);
426 /// ```
427 #[must_use]
428 pub const fn arity(self) -> usize {
429 match self {
430 Self::Binary => 2,
431 Self::Prefix | Self::Postfix => 1,
432 }
433 }
434}
435
436/// Why a mapping was refused.
437///
438/// # Examples
439///
440/// ```
441/// use lower_lang::{Arch, MappingBuilder, MappingError, Pick};
442///
443/// let mut b = MappingBuilder::<u8>::new();
444/// b.node(1, Arch::If { cond: Pick::Absent, then: Pick::Nth(1), else_: Pick::Absent });
445/// assert_eq!(b.build().unwrap_err(), MappingError::MissingField { rule: 0, field: "cond" });
446/// ```
447#[derive(Clone, Copy, Debug, PartialEq, Eq)]
448#[non_exhaustive]
449pub enum MappingError {
450 /// Rule `rule` (in registration order) leaves a required field `Absent`.
451 MissingField {
452 /// The rule's registration index.
453 rule: usize,
454 /// The field.
455 field: &'static str,
456 },
457 /// A kind has two entries in a table that allows one (`table` names it:
458 /// "token role", "modifier", "root", "prefix operator", ...).
459 DuplicateKind {
460 /// The table.
461 table: &'static str,
462 /// The later entry's registration index in that table.
463 index: usize,
464 },
465 /// A type name is registered twice.
466 DuplicateTypeName {
467 /// The later entry's registration index.
468 index: usize,
469 },
470 /// A template id that this mapping did not issue (or, inside a template,
471 /// one not registered before it).
472 UnknownTemplate {
473 /// The id's index.
474 template: usize,
475 },
476 /// A node binds a template with the wrong number of picks.
477 HoleCount {
478 /// The rule's registration index.
479 rule: usize,
480 /// The template's hole count.
481 expected: usize,
482 /// The picks given.
483 found: usize,
484 },
485 /// An `apply` inside template `template` passes arguments that do not
486 /// match the applied template's holes (count, or kind, or `Absent` for a
487 /// required hole).
488 ApplyArgs {
489 /// The registering template's index.
490 template: usize,
491 },
492 /// An operator maps to a spec that cannot apply at its position: an op of
493 /// the wrong arity, a compound op HIR does not allow, a policy that does
494 /// not fit its op, assignment outside binary position, identity outside
495 /// unary position, or a template whose holes are not one expression per
496 /// operand.
497 BadOperator {
498 /// The operator's position.
499 fixity: Fixity,
500 /// Its registration index in that table.
501 index: usize,
502 },
503 /// A table outgrew its index type.
504 TooLarge,
505}
506
507impl fmt::Display for MappingError {
508 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
509 match self {
510 Self::MissingField { rule, field } => {
511 write!(f, "rule {rule}: required field `{field}` has no pick")
512 }
513 Self::DuplicateKind { table, index } => {
514 write!(f, "{table} {index}: the kind already has an entry")
515 }
516 Self::DuplicateTypeName { index } => write!(f, "type name {index} is registered twice"),
517 Self::UnknownTemplate { template } => {
518 write!(f, "template {template} is not registered")
519 }
520 Self::HoleCount {
521 rule,
522 expected,
523 found,
524 } => write!(
525 f,
526 "rule {rule}: the template has {expected} holes, {found} picks given"
527 ),
528 Self::ApplyArgs { template } => {
529 write!(
530 f,
531 "template {template}: an `apply` does not match the applied template's holes"
532 )
533 }
534 Self::BadOperator { fixity, index } => {
535 write!(
536 f,
537 "{fixity:?} operator {index} maps to a spec that cannot apply there"
538 )
539 }
540 Self::TooLarge => f.write_str("a mapping table outgrew its index type"),
541 }
542 }
543}
544
545impl core::error::Error for MappingError {}
546
547/// One node rule: an archetype, applied when `when` finds something (or
548/// always, when `when` is `Absent`).
549#[derive(Clone, Copy, Debug)]
550pub(crate) struct Rule<K> {
551 pub(crate) when: Pick<K>,
552 pub(crate) arch: Arch<K>,
553}
554
555/// A language's semantics as data: what each node kind means, what each token
556/// is, which operators map to what, and the templates for sugar.
557///
558/// # Examples
559///
560/// ```
561/// use lower_lang::{Arch, MappingBuilder, Pick, TokenRole};
562///
563/// const IDENT: u8 = 1;
564/// const LET: u8 = 2;
565/// let mut b = MappingBuilder::new();
566/// b.token(IDENT, TokenRole::Name);
567/// b.node(LET, Arch::Let {
568/// pat: Pick::Kind(IDENT),
569/// ty: Pick::Absent,
570/// init: Pick::Back(0),
571/// else_: Pick::Absent,
572/// mutable: false,
573/// hoist: false,
574/// });
575/// let mapping = b.build()?;
576/// assert_eq!(mapping.role_for(&IDENT), Some(TokenRole::Name));
577/// assert!(mapping.rule_for(&LET).is_some());
578/// # Ok::<(), lower_lang::MappingError>(())
579/// ```
580#[derive(Clone, Debug)]
581pub struct Mapping<K> {
582 pub(crate) rules: Vec<Rule<K>>,
583 pub(crate) by_kind: Vec<(K, u32)>,
584 pub(crate) roles: Vec<(K, TokenRole)>,
585 pub(crate) modifiers: Vec<(K, Modifier)>,
586 pub(crate) roots: Vec<(K, PathRoot)>,
587 pub(crate) containers: Vec<K>,
588 pub(crate) skips: Vec<K>,
589 pub(crate) errors: Vec<K>,
590 pub(crate) type_names: Vec<(Box<str>, TypeName)>,
591 pub(crate) suffixes: Vec<(Box<str>, Prim)>,
592 pub(crate) prefix: Vec<(K, OpSpec)>,
593 pub(crate) binary: Vec<(K, OpSpec)>,
594 pub(crate) postfix: Vec<(K, OpSpec)>,
595 pub(crate) templates: Vec<Template>,
596 pub(crate) template_names: Vec<u32>,
597 pub(crate) hole_picks: Vec<Pick<K>>,
598 pub(crate) strings: Vec<Box<str>>,
599 pub(crate) policy: LangPolicy,
600}
601
602fn find<'a, K: Ord, V>(table: &'a [(K, V)], kind: &K) -> Option<&'a V> {
603 table
604 .binary_search_by(|(k, _)| k.cmp(kind))
605 .ok()
606 .and_then(|i| table.get(i))
607 .map(|(_, v)| v)
608}
609
610impl<K: Copy + Ord> Mapping<K> {
611 /// The archetype of the first rule registered for `kind`.
612 ///
613 /// # Examples
614 ///
615 /// ```
616 /// use lower_lang::{Arch, MappingBuilder};
617 ///
618 /// let mut b = MappingBuilder::<u8>::new();
619 /// b.node(3, Arch::binary());
620 /// let m = b.build()?;
621 /// assert_eq!(m.rule_for(&3), Some(&Arch::binary()));
622 /// assert_eq!(m.rule_for(&4), None);
623 /// # Ok::<(), lower_lang::MappingError>(())
624 /// ```
625 #[must_use]
626 pub fn rule_for(&self, kind: &K) -> Option<&Arch<K>> {
627 let (start, _) = self.rule_range(kind);
628 self.by_kind
629 .get(start)
630 .filter(|(k, _)| k == kind)
631 .and_then(|(_, r)| self.rules.get(*r as usize))
632 .map(|r| &r.arch)
633 }
634
635 /// The role of token kind `kind`.
636 ///
637 /// # Examples
638 ///
639 /// See [`Mapping`].
640 #[must_use]
641 pub fn role_for(&self, kind: &K) -> Option<TokenRole> {
642 find(&self.roles, kind).copied()
643 }
644
645 /// The modifier token kind `kind` stands for.
646 ///
647 /// # Examples
648 ///
649 /// ```
650 /// use lower_lang::{MappingBuilder, Modifier};
651 ///
652 /// let mut b = MappingBuilder::<u8>::new();
653 /// b.modifier(9, Modifier::Mut);
654 /// assert_eq!(b.build()?.modifier_for(&9), Some(Modifier::Mut));
655 /// # Ok::<(), lower_lang::MappingError>(())
656 /// ```
657 #[must_use]
658 pub fn modifier_for(&self, kind: &K) -> Option<Modifier> {
659 find(&self.modifiers, kind).copied()
660 }
661
662 /// The registered template `id`.
663 ///
664 /// # Examples
665 ///
666 /// ```
667 /// use lower_lang::{templates, MappingBuilder};
668 ///
669 /// let mut b = MappingBuilder::<u8>::new();
670 /// let id = b.template(templates::coalesce())?;
671 /// let m = b.build()?;
672 /// assert_eq!(m.template(id).map(|t| t.name()), Some("??"));
673 /// # Ok::<(), lower_lang::MappingError>(())
674 /// ```
675 #[must_use]
676 pub fn template(&self, id: TemplateId) -> Option<&Template> {
677 self.templates.get(id.index())
678 }
679
680 /// The language-wide policies.
681 ///
682 /// # Examples
683 ///
684 /// ```
685 /// use lower_lang::{LangPolicy, MappingBuilder};
686 ///
687 /// let m = MappingBuilder::<u8>::new().build()?;
688 /// assert_eq!(*m.policy(), LangPolicy::default());
689 /// # Ok::<(), lower_lang::MappingError>(())
690 /// ```
691 #[must_use]
692 pub const fn policy(&self) -> &LangPolicy {
693 &self.policy
694 }
695
696 /// The rules registered for `kind`, as an index range into `by_kind`.
697 pub(crate) fn rule_range(&self, kind: &K) -> (usize, usize) {
698 let start = self.by_kind.partition_point(|(k, _)| k < kind);
699 let end = start
700 + self
701 .by_kind
702 .get(start..)
703 .map_or(0, |rest| rest.partition_point(|(k, _)| k == kind));
704 (start, end)
705 }
706
707 pub(crate) fn op(&self, fixity: Fixity, kind: &K) -> Option<OpSpec> {
708 let table = match fixity {
709 Fixity::Prefix => &self.prefix,
710 Fixity::Binary => &self.binary,
711 Fixity::Postfix => &self.postfix,
712 };
713 find(table, kind).copied()
714 }
715
716 pub(crate) fn root_for(&self, kind: &K) -> Option<PathRoot> {
717 find(&self.roots, kind).copied()
718 }
719
720 pub(crate) fn is_error(&self, kind: &K) -> bool {
721 self.errors.binary_search(kind).is_ok()
722 }
723
724 pub(crate) fn type_name(&self, text: &str) -> Option<TypeName> {
725 self.type_names
726 .binary_search_by(|(t, _)| (**t).cmp(text))
727 .ok()
728 .and_then(|i| self.type_names.get(i))
729 .map(|(_, n)| *n)
730 }
731}
732
733impl<K: Ord> KindSets<K> for Mapping<K> {
734 fn is_skip(&self, kind: &K) -> bool {
735 self.skips.binary_search(kind).is_ok()
736 }
737 fn is_container(&self, kind: &K) -> bool {
738 self.containers.binary_search(kind).is_ok()
739 }
740}
741
742/// Builds a [`Mapping`]. Every method records; [`build`](Self::build) checks
743/// everything and sorts the tables.
744///
745/// # Examples
746///
747/// A calculator's semantics: statements, `let`, numbers, names, and `+ - * /`.
748///
749/// ```
750/// use hir_lang::OpKind;
751/// use lower_lang::{Arch, MappingBuilder, OpSpec, Pick, TokenRole};
752///
753/// #[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)]
754/// enum K { Program, Let, Binary, Ident, Number, Plus, Star, Eq, Semi }
755///
756/// let mut b = MappingBuilder::new();
757/// b.node(K::Program, Arch::Module { name: Pick::Absent, items: Pick::Nodes });
758/// b.node(K::Let, Arch::Let {
759/// pat: Pick::Kind(K::Ident), ty: Pick::Absent, init: Pick::After(K::Eq),
760/// else_: Pick::Absent, mutable: false, hoist: false,
761/// });
762/// b.node(K::Binary, Arch::binary());
763/// b.token(K::Ident, TokenRole::Name);
764/// b.token(K::Number, TokenRole::Number);
765/// b.binary_op(K::Plus, OpSpec::Op(OpKind::Add));
766/// b.binary_op(K::Star, OpSpec::Op(OpKind::Mul));
767/// b.skip(K::Semi);
768/// let mapping = b.build()?;
769/// # let _ = mapping;
770/// # Ok::<(), lower_lang::MappingError>(())
771/// ```
772#[derive(Clone, Debug)]
773pub struct MappingBuilder<K> {
774 m: Mapping<K>,
775 rule_picks_error: Option<MappingError>,
776}
777
778impl<K: Copy + Ord> Default for MappingBuilder<K> {
779 fn default() -> Self {
780 Self::new()
781 }
782}
783
784impl<K: Copy + Ord> MappingBuilder<K> {
785 /// An empty builder with the default [`LangPolicy`].
786 ///
787 /// # Examples
788 ///
789 /// ```
790 /// let m = lower_lang::MappingBuilder::<u8>::new().build()?;
791 /// assert!(m.rule_for(&0).is_none());
792 /// # Ok::<(), lower_lang::MappingError>(())
793 /// ```
794 #[must_use]
795 pub fn new() -> Self {
796 Self {
797 m: Mapping {
798 rules: Vec::new(),
799 by_kind: Vec::new(),
800 roles: Vec::new(),
801 modifiers: Vec::new(),
802 roots: Vec::new(),
803 containers: Vec::new(),
804 skips: Vec::new(),
805 errors: Vec::new(),
806 type_names: Vec::new(),
807 suffixes: Vec::new(),
808 prefix: Vec::new(),
809 binary: Vec::new(),
810 postfix: Vec::new(),
811 templates: Vec::new(),
812 template_names: Vec::new(),
813 hole_picks: Vec::new(),
814 strings: Vec::new(),
815 policy: LangPolicy::default(),
816 },
817 rule_picks_error: None,
818 }
819 }
820
821 fn add_rule(&mut self, kind: K, when: Pick<K>, arch: Arch<K>) -> &mut Self {
822 match u32::try_from(self.m.rules.len()) {
823 Ok(i) if i < NONE => {
824 self.m.rules.push(Rule { when, arch });
825 self.m.by_kind.push((kind, i));
826 }
827 _ => self.rule_picks_error = Some(MappingError::TooLarge),
828 }
829 self
830 }
831
832 /// Nodes of `kind` mean `arch`.
833 ///
834 /// # Examples
835 ///
836 /// See [`MappingBuilder`].
837 pub fn node(&mut self, kind: K, arch: Arch<K>) -> &mut Self {
838 self.add_rule(kind, Pick::Absent, arch)
839 }
840
841 /// Nodes of `kind` mean `arch` when `when` finds a child; otherwise the
842 /// next rule for `kind` (in registration order) is tried. For grammars
843 /// that put alternatives in one rule (`stmt = "'let' ... | expr ';'"`).
844 /// A node no rule applies to is reported as unmapped.
845 ///
846 /// # Examples
847 ///
848 /// ```
849 /// use lower_lang::{Arch, MappingBuilder, Pick};
850 ///
851 /// const STMT: u8 = 1;
852 /// const LET: u8 = 2;
853 /// let mut b = MappingBuilder::new();
854 /// b.node_when(STMT, Pick::First(LET), Arch::Let {
855 /// pat: Pick::Nth(1), ty: Pick::Absent, init: Pick::Nth(3),
856 /// else_: Pick::Absent, mutable: false, hoist: false,
857 /// });
858 /// b.node(STMT, Arch::ExprStmt { expr: Pick::Nth(0) });
859 /// assert!(b.build().is_ok());
860 /// ```
861 pub fn node_when(&mut self, kind: K, when: Pick<K>, arch: Arch<K>) -> &mut Self {
862 self.add_rule(kind, when, arch)
863 }
864
865 /// Tokens of `kind` mean `role`.
866 ///
867 /// # Examples
868 ///
869 /// See [`Mapping`].
870 pub fn token(&mut self, kind: K, role: TokenRole) -> &mut Self {
871 self.m.roles.push((kind, role));
872 self
873 }
874
875 /// Tokens of `kind` set `modifier` on the construct they appear in.
876 ///
877 /// # Examples
878 ///
879 /// See [`Mapping::modifier_for`].
880 pub fn modifier(&mut self, kind: K, modifier: Modifier) -> &mut Self {
881 self.m.modifiers.push((kind, modifier));
882 self
883 }
884
885 /// Leading tokens of `kind` in a [`Path`](Arch::Path) set its root
886 /// (`self` → `SelfModule`, `super` → `Super(1)` each, `Self` → `SelfType`,
887 /// PHP `parent`/`static` → `ParentType`/`StaticType`, `::` → `Global`).
888 ///
889 /// # Examples
890 ///
891 /// ```
892 /// use hir_lang::PathRoot;
893 ///
894 /// let mut b = lower_lang::MappingBuilder::<u8>::new();
895 /// b.root(5, PathRoot::Super(1));
896 /// assert!(b.build().is_ok());
897 /// ```
898 pub fn root(&mut self, kind: K, root: PathRoot) -> &mut Self {
899 self.m.roots.push((kind, root));
900 self
901 }
902
903 /// Nodes of `kind` are containers: list picks splice their children in
904 /// place (an `args` node inside a `call`, a `params` node inside a `fn`).
905 ///
906 /// # Examples
907 ///
908 /// ```
909 /// let mut b = lower_lang::MappingBuilder::<u8>::new();
910 /// b.container(7);
911 /// assert!(b.build().is_ok());
912 /// ```
913 pub fn container(&mut self, kind: K) -> &mut Self {
914 self.m.containers.push(kind);
915 self
916 }
917
918 /// Tokens (or nodes) of `kind` are punctuation that list picks leave out
919 /// (`,`, `;`, `(`).
920 ///
921 /// # Examples
922 ///
923 /// ```
924 /// let mut b = lower_lang::MappingBuilder::<u8>::new();
925 /// b.skip(8);
926 /// assert!(b.build().is_ok());
927 /// ```
928 pub fn skip(&mut self, kind: K) -> &mut Self {
929 self.m.skips.push(kind);
930 self
931 }
932
933 /// Nodes of `kind` are syntax errors (lang-forge's `ERROR`): they lower to
934 /// error forms with a [`SyntaxError`](crate::ProblemKind::SyntaxError)
935 /// problem, whatever context they appear in.
936 ///
937 /// # Examples
938 ///
939 /// ```
940 /// let mut b = lower_lang::MappingBuilder::<u8>::new();
941 /// b.error(0);
942 /// assert!(b.build().is_ok());
943 /// ```
944 pub fn error(&mut self, kind: K) -> &mut Self {
945 self.m.errors.push(kind);
946 self
947 }
948
949 /// An identifier spelled `text` names this type (`int` → `i64`, `mixed`
950 /// → any).
951 ///
952 /// # Examples
953 ///
954 /// ```
955 /// use hir_lang::Prim;
956 /// use lower_lang::TypeName;
957 ///
958 /// let mut b = lower_lang::MappingBuilder::<u8>::new();
959 /// b.type_name("int", TypeName::Prim(Prim::I64));
960 /// assert!(b.build().is_ok());
961 /// ```
962 pub fn type_name(&mut self, text: &str, name: TypeName) -> &mut Self {
963 self.m.type_names.push((text.into(), name));
964 self
965 }
966
967 /// A numeric literal ending in `suffix` has that type (`10u8`).
968 ///
969 /// # Examples
970 ///
971 /// ```
972 /// use hir_lang::Prim;
973 ///
974 /// let mut b = lower_lang::MappingBuilder::<u8>::new();
975 /// b.suffix("u8", Prim::U8);
976 /// assert!(b.build().is_ok());
977 /// ```
978 pub fn suffix(&mut self, suffix: &str, prim: Prim) -> &mut Self {
979 self.m.suffixes.push((suffix.into(), prim));
980 self
981 }
982
983 /// A prefix operator.
984 ///
985 /// # Examples
986 ///
987 /// ```
988 /// use hir_lang::OpKind;
989 /// use lower_lang::OpSpec;
990 ///
991 /// let mut b = lower_lang::MappingBuilder::<u8>::new();
992 /// b.prefix_op(1, OpSpec::Op(OpKind::Neg));
993 /// assert!(b.build().is_ok());
994 /// ```
995 pub fn prefix_op(&mut self, kind: K, spec: OpSpec) -> &mut Self {
996 self.m.prefix.push((kind, spec));
997 self
998 }
999
1000 /// A binary operator.
1001 ///
1002 /// # Examples
1003 ///
1004 /// See [`MappingBuilder`].
1005 pub fn binary_op(&mut self, kind: K, spec: OpSpec) -> &mut Self {
1006 self.m.binary.push((kind, spec));
1007 self
1008 }
1009
1010 /// A postfix operator.
1011 ///
1012 /// # Examples
1013 ///
1014 /// ```
1015 /// use lower_lang::{templates, OpSpec};
1016 ///
1017 /// let mut b = lower_lang::MappingBuilder::<u8>::new();
1018 /// let inc = b.template(templates::post_increment())?;
1019 /// b.postfix_op(1, OpSpec::Template(inc));
1020 /// assert!(b.build().is_ok());
1021 /// # Ok::<(), lower_lang::MappingError>(())
1022 /// ```
1023 pub fn postfix_op(&mut self, kind: K, spec: OpSpec) -> &mut Self {
1024 self.m.postfix.push((kind, spec));
1025 self
1026 }
1027
1028 /// Stores a host or intrinsic name for [`OpSpec::Extern`] and
1029 /// [`OpSpec::Intrinsic`]; interned per lowering.
1030 ///
1031 /// # Examples
1032 ///
1033 /// See [`NameRef`].
1034 pub fn name(&mut self, text: &str) -> NameRef {
1035 NameRef(self.string(text))
1036 }
1037
1038 fn string(&mut self, text: &str) -> u32 {
1039 let i = self.m.strings.len();
1040 self.m.strings.push(text.into());
1041 u32::try_from(i).unwrap_or_else(|_| {
1042 self.rule_picks_error = Some(MappingError::TooLarge);
1043 0
1044 })
1045 }
1046
1047 /// Sets the language-wide policies.
1048 ///
1049 /// # Examples
1050 ///
1051 /// ```
1052 /// use lower_lang::LangPolicy;
1053 ///
1054 /// let mut policy = LangPolicy::default();
1055 /// policy.implicit_locals = true;
1056 /// let mut b = lower_lang::MappingBuilder::<u8>::new();
1057 /// b.policy(policy);
1058 /// assert!(b.build()?.policy().implicit_locals);
1059 /// # Ok::<(), lower_lang::MappingError>(())
1060 /// ```
1061 pub fn policy(&mut self, policy: LangPolicy) -> &mut Self {
1062 self.m.policy = policy;
1063 self
1064 }
1065
1066 /// Registers a template and returns its id. Templates it
1067 /// [`apply`](crate::TemplateBuilder::apply)s must already be registered,
1068 /// which keeps templates acyclic by construction.
1069 ///
1070 /// # Errors
1071 ///
1072 /// [`MappingError::UnknownTemplate`] if an `apply` names a template not
1073 /// registered before this one; [`MappingError::ApplyArgs`] if its
1074 /// arguments do not match that template's holes.
1075 ///
1076 /// # Examples
1077 ///
1078 /// ```
1079 /// use lower_lang::{templates, MappingBuilder};
1080 ///
1081 /// let mut b = MappingBuilder::<u8>::new();
1082 /// let id = b.template(templates::while_loop())?;
1083 /// assert_eq!(id.index(), 0);
1084 /// # Ok::<(), lower_lang::MappingError>(())
1085 /// ```
1086 pub fn template(&mut self, mut template: Template) -> Result<TemplateId, MappingError> {
1087 let index = self.m.templates.len();
1088 for &node in &template.applies {
1089 let Some(TNode::Apply {
1090 template: callee,
1091 args,
1092 }) = template.node(node).copied()
1093 else {
1094 continue;
1095 };
1096 let callee_t =
1097 self.m
1098 .templates
1099 .get(callee as usize)
1100 .ok_or(MappingError::UnknownTemplate {
1101 template: callee as usize,
1102 })?;
1103 let (start, len) = (args.0 as usize, args.1 as usize);
1104 let given = template
1105 .args
1106 .get(start..start.saturating_add(len))
1107 .ok_or(MappingError::ApplyArgs { template: index })?;
1108 if given.len() != callee_t.holes.len() {
1109 return Err(MappingError::ApplyArgs { template: index });
1110 }
1111 for (arg, hole) in given.iter().zip(&callee_t.holes) {
1112 let fits = match arg.kind() {
1113 Some(kind) => kind == hole.kind,
1114 None => hole.optional,
1115 };
1116 let forwarded_ok = match *arg {
1117 TArg::Stmts(h) => template
1118 .holes
1119 .get(usize::from(h.0))
1120 .is_some_and(|d| d.kind == HoleKind::Stmts),
1121 TArg::Args(h) => template
1122 .holes
1123 .get(usize::from(h.0))
1124 .is_some_and(|d| d.kind == HoleKind::Args),
1125 _ => true,
1126 };
1127 if !fits || !forwarded_ok {
1128 return Err(MappingError::ApplyArgs { template: index });
1129 }
1130 }
1131 }
1132 let id = u32::try_from(index).map_err(|_| MappingError::TooLarge)?;
1133 let base = u32::try_from(self.m.strings.len()).map_err(|_| MappingError::TooLarge)?;
1134 template.text_base = base;
1135 self.m.strings.extend(template.texts.iter().cloned());
1136 let name = template.name.clone();
1137 let name_ref = self.string(&name);
1138 self.m.template_names.push(name_ref);
1139 self.m.templates.push(template);
1140 Ok(TemplateId(id))
1141 }
1142
1143 /// Nodes of `kind` lower through `template`, its holes filled from
1144 /// `holes` (one pick per hole, in the template's hole order).
1145 ///
1146 /// # Examples
1147 ///
1148 /// ```
1149 /// use lower_lang::{templates, MappingBuilder, Pick};
1150 ///
1151 /// const WHILE: u8 = 1;
1152 /// let mut b = MappingBuilder::new();
1153 /// let w = b.template(templates::while_loop())?;
1154 /// // `while COND BLOCK`: holes cond, body, label.
1155 /// b.template_node(WHILE, w, &[Pick::NthNode(0), Pick::NthNode(1), Pick::Absent]);
1156 /// assert!(b.build().is_ok());
1157 /// # Ok::<(), lower_lang::MappingError>(())
1158 /// ```
1159 pub fn template_node(&mut self, kind: K, template: TemplateId, holes: &[Pick<K>]) -> &mut Self {
1160 let first = self.m.hole_picks.len();
1161 self.m.hole_picks.extend_from_slice(holes);
1162 match (u32::try_from(first), u32::try_from(holes.len())) {
1163 (Ok(first), Ok(len)) => self.add_rule(
1164 kind,
1165 Pick::Absent,
1166 Arch::Template(TemplateUse {
1167 template,
1168 first,
1169 len,
1170 }),
1171 ),
1172 _ => {
1173 self.rule_picks_error = Some(MappingError::TooLarge);
1174 self
1175 }
1176 }
1177 }
1178
1179 /// Checks the mapping and returns it.
1180 ///
1181 /// # Errors
1182 ///
1183 /// A [`MappingError`]: a required field without a pick, a kind with two
1184 /// entries in a one-entry table, an unknown template or a wrong number of
1185 /// template picks, or an operator spec that cannot apply where it is
1186 /// registered.
1187 ///
1188 /// # Examples
1189 ///
1190 /// See [`MappingBuilder`].
1191 pub fn build(mut self) -> Result<Mapping<K>, MappingError> {
1192 if let Some(e) = self.rule_picks_error {
1193 return Err(e);
1194 }
1195 let m = &mut self.m;
1196 for (i, rule) in m.rules.iter().enumerate() {
1197 if let Some(field) = missing_field(&rule.arch) {
1198 return Err(MappingError::MissingField { rule: i, field });
1199 }
1200 if let Arch::Template(used) = rule.arch {
1201 let t = m.templates.get(used.template.index()).ok_or(
1202 MappingError::UnknownTemplate {
1203 template: used.template.index(),
1204 },
1205 )?;
1206 if t.holes.len() != used.len as usize {
1207 return Err(MappingError::HoleCount {
1208 rule: i,
1209 expected: t.holes.len(),
1210 found: used.len as usize,
1211 });
1212 }
1213 }
1214 }
1215 for (fixity, table) in [
1216 (Fixity::Prefix, &m.prefix),
1217 (Fixity::Binary, &m.binary),
1218 (Fixity::Postfix, &m.postfix),
1219 ] {
1220 for (index, (_, spec)) in table.iter().enumerate() {
1221 if !op_fits(*spec, fixity, &m.templates) {
1222 return Err(MappingError::BadOperator { fixity, index });
1223 }
1224 }
1225 }
1226 m.by_kind.sort_by_key(|e| e.0);
1227 sort_unique(&mut m.roles, "token role")?;
1228 sort_unique(&mut m.modifiers, "modifier")?;
1229 sort_unique(&mut m.roots, "root")?;
1230 sort_unique(&mut m.prefix, "prefix operator")?;
1231 sort_unique(&mut m.binary, "binary operator")?;
1232 sort_unique(&mut m.postfix, "postfix operator")?;
1233 m.containers.sort();
1234 m.containers.dedup();
1235 m.skips.sort();
1236 m.skips.dedup();
1237 m.errors.sort();
1238 m.errors.dedup();
1239 let mut names: Vec<(usize, &str)> = m
1240 .type_names
1241 .iter()
1242 .enumerate()
1243 .map(|(i, (t, _))| (i, &**t))
1244 .collect();
1245 names.sort_by(|a, b| a.1.cmp(b.1).then(a.0.cmp(&b.0)));
1246 if let Some(w) = names.windows(2).find(|w| w[0].1 == w[1].1) {
1247 return Err(MappingError::DuplicateTypeName { index: w[1].0 });
1248 }
1249 m.type_names.sort_by(|a, b| a.0.cmp(&b.0));
1250 // Longest suffix first, so `i64` wins over a hypothetical `4`.
1251 m.suffixes
1252 .sort_by(|a, b| b.0.len().cmp(&a.0.len()).then(a.0.cmp(&b.0)));
1253 Ok(self.m)
1254 }
1255}
1256
1257/// Sorts a kind-keyed table, refusing a kind with two entries (reported by
1258/// the later entry's registration index).
1259fn sort_unique<K: Ord + Copy, V>(
1260 table: &mut [(K, V)],
1261 name: &'static str,
1262) -> Result<(), MappingError> {
1263 let mut order: Vec<(K, usize)> = table
1264 .iter()
1265 .enumerate()
1266 .map(|(i, (k, _))| (*k, i))
1267 .collect();
1268 order.sort();
1269 if let Some(w) = order.windows(2).find(|w| w[0].0 == w[1].0) {
1270 return Err(MappingError::DuplicateKind {
1271 table: name,
1272 index: w[1].1,
1273 });
1274 }
1275 table.sort_by_key(|e| e.0);
1276 Ok(())
1277}
1278
1279/// Whether `spec` can apply at `fixity`.
1280fn op_fits(spec: OpSpec, fixity: Fixity, templates: &[Template]) -> bool {
1281 let arity = fixity.arity();
1282 match spec {
1283 OpSpec::Op(kind) => kind.arity() == arity,
1284 OpSpec::OpWith(op) => op.kind.arity() == arity && op.policy_matches(),
1285 OpSpec::Compound(kind) => fixity == Fixity::Binary && compound_ok(kind),
1286 OpSpec::CompoundWith(op) => {
1287 fixity == Fixity::Binary && compound_ok(op.kind) && op.policy_matches()
1288 }
1289 OpSpec::Assign | OpSpec::RefAssign => fixity == Fixity::Binary,
1290 OpSpec::Identity | OpSpec::Await => fixity != Fixity::Binary,
1291 OpSpec::Borrow(_) | OpSpec::Deref => fixity == Fixity::Prefix,
1292 OpSpec::Template(id) => templates.get(id.index()).is_some_and(|t| {
1293 t.holes.len() == arity && t.holes.iter().all(|h| h.kind == HoleKind::Expr)
1294 }),
1295 OpSpec::Extern(_) | OpSpec::Intrinsic(_) => true,
1296 }
1297}
1298
1299/// The first required field an archetype leaves `Absent`.
1300fn missing_field<K>(arch: &Arch<K>) -> Option<&'static str> {
1301 let need =
1302 |pairs: &[(&'static str, bool)]| pairs.iter().find(|(_, absent)| *absent).map(|(f, _)| *f);
1303 match arch {
1304 Arch::Module { .. }
1305 | Arch::Splice { .. }
1306 | Arch::Unsupported
1307 | Arch::GlobalDecl { .. }
1308 | Arch::MixinUse { .. }
1309 | Arch::FieldDecl { .. }
1310 | Arch::Tuple { .. }
1311 | Arch::Array { .. }
1312 | Arch::Map { .. }
1313 | Arch::RecordLit { .. }
1314 | Arch::Block { .. }
1315 | Arch::Break { .. }
1316 | Arch::Continue { .. }
1317 | Arch::Return { .. }
1318 | Arch::Yield { .. }
1319 | Arch::Template(_)
1320 | Arch::WildPat
1321 | Arch::RestPat { .. }
1322 | Arch::TuplePat { .. }
1323 | Arch::RecordPat { .. }
1324 | Arch::OrPat { .. }
1325 | Arch::RangePat { .. }
1326 | Arch::SlicePat { .. }
1327 | Arch::TupleTy { .. }
1328 | Arch::FnTy { .. }
1329 | Arch::ObjectTy { .. }
1330 | Arch::ImplTy { .. } => None,
1331 Arch::Pass { inner } => need(&[("inner", inner.is_absent())]),
1332 Arch::Let { pat, .. } => need(&[("pat", pat.is_absent())]),
1333 Arch::ExprStmt { expr } => need(&[("expr", expr.is_absent())]),
1334 Arch::Defer { body } => need(&[("body", body.is_absent())]),
1335 Arch::Static { name, .. }
1336 | Arch::Fn { name, .. }
1337 | Arch::Record { name, .. }
1338 | Arch::Sum { name, .. }
1339 | Arch::Interface { name, .. }
1340 | Arch::Class { name, .. }
1341 | Arch::AssocType { name, .. }
1342 | Arch::Const { name, .. }
1343 | Arch::GlobalVar { name, .. }
1344 | Arch::VariantDecl { name, .. }
1345 | Arch::GenericParam { name, .. }
1346 | Arch::Capture { name }
1347 | Arch::Segment { name, .. }
1348 | Arch::BindPat { name, .. }
1349 | Arch::FieldPat { name, .. }
1350 | Arch::FieldInit { name, .. } => need(&[("name", name.is_absent())]),
1351 Arch::Import { path, .. } => need(&[("path", path.is_absent())]),
1352 Arch::Impl { self_ty, .. } => need(&[("self_ty", self_ty.is_absent())]),
1353 Arch::Alias { name, ty, .. } | Arch::AssocBinding { name, ty } => {
1354 need(&[("name", name.is_absent()), ("ty", ty.is_absent())])
1355 }
1356 Arch::WherePred { subject, .. } => need(&[("subject", subject.is_absent())]),
1357 Arch::Param { pat, .. } => need(&[("pat", pat.is_absent())]),
1358 Arch::Path {
1359 segments, qself, ..
1360 } => need(&[("segments", segments.is_absent() && qself.is_absent())]),
1361 Arch::Unary { op, operand } | Arch::Postfix { operand, op } => {
1362 need(&[("op", op.is_absent()), ("operand", operand.is_absent())])
1363 }
1364 Arch::Binary { lhs, op, rhs } => need(&[
1365 ("lhs", lhs.is_absent()),
1366 ("op", op.is_absent()),
1367 ("rhs", rhs.is_absent()),
1368 ]),
1369 Arch::Assign { target, value, .. } => {
1370 need(&[("target", target.is_absent()), ("value", value.is_absent())])
1371 }
1372 Arch::RefAssign { target, source } => need(&[
1373 ("target", target.is_absent()),
1374 ("source", source.is_absent()),
1375 ]),
1376 Arch::Call { callee, .. } => need(&[("callee", callee.is_absent())]),
1377 Arch::Arg { value, .. } | Arch::MapEntry { value, .. } => {
1378 need(&[("value", value.is_absent())])
1379 }
1380 Arch::Member { base, member, .. } => {
1381 need(&[("base", base.is_absent()), ("member", member.is_absent())])
1382 }
1383 Arch::MethodCall {
1384 receiver, method, ..
1385 } => need(&[
1386 ("receiver", receiver.is_absent()),
1387 ("method", method.is_absent()),
1388 ]),
1389 Arch::DynMember { base, name, .. } => {
1390 need(&[("base", base.is_absent()), ("name", name.is_absent())])
1391 }
1392 Arch::Index { base, index } => {
1393 need(&[("base", base.is_absent()), ("index", index.is_absent())])
1394 }
1395 Arch::VarVar { inner }
1396 | Arch::Deref { inner }
1397 | Arch::Await { inner }
1398 | Arch::Spawn { inner }
1399 | Arch::RefPat { inner }
1400 | Arch::PtrTy { inner }
1401 | Arch::NullableTy { inner }
1402 | Arch::RefTy { inner, .. } => need(&[("inner", inner.is_absent())]),
1403 Arch::Append { base } => need(&[("base", base.is_absent())]),
1404 Arch::Repeat { elem, count } => {
1405 need(&[("elem", elem.is_absent()), ("count", count.is_absent())])
1406 }
1407 Arch::Cast { expr, ty } => need(&[("expr", expr.is_absent()), ("ty", ty.is_absent())]),
1408 Arch::Borrow { expr } => need(&[("expr", expr.is_absent())]),
1409 Arch::If { cond, then, .. } => {
1410 need(&[("cond", cond.is_absent()), ("then", then.is_absent())])
1411 }
1412 Arch::Match { scrutinee, .. } => need(&[("scrutinee", scrutinee.is_absent())]),
1413 Arch::Arm { pat, body, .. } => {
1414 need(&[("pat", pat.is_absent()), ("body", body.is_absent())])
1415 }
1416 Arch::Loop { body, .. }
1417 | Arch::Try { body, .. }
1418 | Arch::Catch { body, .. }
1419 | Arch::Closure { body, .. } => need(&[("body", body.is_absent())]),
1420 Arch::Throw { value } => need(&[("value", value.is_absent())]),
1421 Arch::CtorPat { path, .. } => need(&[("path", path.is_absent())]),
1422 Arch::TypeTestPat { ty, .. } => need(&[("ty", ty.is_absent())]),
1423 Arch::ArrayTy { elem, len } => {
1424 need(&[("elem", elem.is_absent()), ("len", len.is_absent())])
1425 }
1426 Arch::SliceTy { elem } => need(&[("elem", elem.is_absent())]),
1427 }
1428}
1429
1430/// Every [`Modifier`] in bit order, for the scan of a node's children.
1431pub(crate) fn modifier_bits<K: Ord>(map: &Mapping<K>, kind: &K) -> u32 {
1432 find(&map.modifiers, kind).map_or(0, |m| m.bit())
1433}
1434
1435#[cfg(test)]
1436// Builder methods return `&mut Self` for chaining; the tests discard it.
1437#[allow(unused_results)]
1438mod tests {
1439 use super::*;
1440 use crate::templates;
1441
1442 #[test]
1443 fn test_duplicate_roles_are_refused() {
1444 let mut b = MappingBuilder::<u8>::new();
1445 b.token(1, TokenRole::Name).token(1, TokenRole::Int);
1446 assert_eq!(
1447 b.build().err(),
1448 Some(MappingError::DuplicateKind {
1449 table: "token role",
1450 index: 1
1451 })
1452 );
1453 }
1454
1455 #[test]
1456 fn test_operator_specs_are_checked_against_their_position() {
1457 let mut b = MappingBuilder::<u8>::new();
1458 b.binary_op(1, OpSpec::Op(OpKind::Neg));
1459 assert!(matches!(b.build(), Err(MappingError::BadOperator { .. })));
1460
1461 let mut b = MappingBuilder::<u8>::new();
1462 b.binary_op(1, OpSpec::Compound(OpKind::Eq));
1463 assert!(matches!(b.build(), Err(MappingError::BadOperator { .. })));
1464
1465 let mut b = MappingBuilder::<u8>::new();
1466 b.prefix_op(1, OpSpec::Assign);
1467 assert!(matches!(b.build(), Err(MappingError::BadOperator { .. })));
1468
1469 let mut b = MappingBuilder::<u8>::new();
1470 let w = b.template(templates::while_loop()).ok();
1471 if let Some(w) = w {
1472 b.binary_op(1, OpSpec::Template(w));
1473 }
1474 assert!(matches!(b.build(), Err(MappingError::BadOperator { .. })));
1475 }
1476
1477 #[test]
1478 fn test_template_node_checks_hole_count() {
1479 let mut b = MappingBuilder::<u8>::new();
1480 let Ok(w) = b.template(templates::while_loop()) else {
1481 panic!("registers");
1482 };
1483 b.template_node(1, w, &[Pick::Nth(0)]);
1484 assert_eq!(
1485 b.build().err(),
1486 Some(MappingError::HoleCount {
1487 rule: 0,
1488 expected: 3,
1489 found: 1
1490 })
1491 );
1492 }
1493
1494 #[test]
1495 fn test_conditional_rules_keep_registration_order() {
1496 let mut b = MappingBuilder::<u8>::new();
1497 b.node(9, Arch::WildPat);
1498 b.node_when(4, Pick::First(1), Arch::Unsupported);
1499 b.node(4, Arch::WildPat);
1500 let Ok(m) = b.build() else { panic!("valid") };
1501 let (s, e) = m.rule_range(&4);
1502 assert_eq!(e - s, 2);
1503 assert_eq!(m.rule_for(&4), Some(&Arch::Unsupported));
1504 }
1505
1506 #[test]
1507 fn test_duplicate_type_names_are_refused() {
1508 let mut b = MappingBuilder::<u8>::new();
1509 b.type_name("int", TypeName::Any)
1510 .type_name("int", TypeName::Never);
1511 assert_eq!(
1512 b.build().err(),
1513 Some(MappingError::DuplicateTypeName { index: 1 })
1514 );
1515 }
1516}