Skip to main content

lower_lang/
arch.rs

1//! The archetype catalogue: the semantic forms a construct can be declared as.
2//!
3//! Each variant of [`Arch`] is one archetype from LexerSketch's semantic layer
4//! (ARCHITECTURE §5): binders, scopes, declarations, control, expressions,
5//! patterns, and types. Its fields are [`Pick`]s that say where each part of
6//! the construct sits among the node's children. Flags that a construct
7//! spells with keywords (`mut`, `async`, `static`, `pub`, `...`, `&`) are not
8//! fields: they are read from the node's direct children through the
9//! mapping's [modifier table](crate::MappingBuilder::modifier).
10
11use hir_lang::CaptureMode;
12
13use crate::pick::Pick;
14use crate::template::TemplateId;
15
16/// How a record or variant's field layout is decided.
17///
18/// # Examples
19///
20/// ```
21/// use lower_lang::RecordShape;
22///
23/// assert_eq!(RecordShape::default(), RecordShape::Auto);
24/// ```
25#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
26pub enum RecordShape {
27    /// Named when any field has a name or there are no fields; tuple-like when
28    /// every field is unnamed.
29    #[default]
30    Auto,
31    /// `{ x: T }`.
32    Named,
33    /// `(T, U)`.
34    Tuple,
35    /// No fields at all (`struct S;`, a bare enum variant).
36    Unit,
37}
38
39/// A use of a registered template as a node's archetype, made by
40/// [`MappingBuilder::template_node`](crate::MappingBuilder::template_node).
41///
42/// The template's holes are bound, in declaration order, to picks stored in
43/// the mapping.
44///
45/// # Examples
46///
47/// ```
48/// use lower_lang::{templates, Arch, MappingBuilder, Pick};
49///
50/// let mut b = MappingBuilder::<u8>::new();
51/// let while_loop = b.template(templates::while_loop())?;
52/// b.template_node(4, while_loop, &[Pick::NthNode(0), Pick::NthNode(1), Pick::Absent]);
53/// let mapping = b.build()?;
54/// assert!(matches!(mapping.rule_for(&4), Some(Arch::Template(_))));
55/// # Ok::<(), lower_lang::MappingError>(())
56/// ```
57#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
58pub struct TemplateUse {
59    pub(crate) template: TemplateId,
60    pub(crate) first: u32,
61    pub(crate) len: u32,
62}
63
64impl TemplateUse {
65    /// The template this node instantiates.
66    ///
67    /// # Examples
68    ///
69    /// ```
70    /// use lower_lang::{templates, Arch, MappingBuilder, Pick};
71    ///
72    /// let mut b = MappingBuilder::<u8>::new();
73    /// let t = b.template(templates::logical_and())?;
74    /// b.template_node(1, t, &[Pick::Nth(0), Pick::Nth(2)]);
75    /// let m = b.build()?;
76    /// let Some(Arch::Template(used)) = m.rule_for(&1) else { unreachable!() };
77    /// assert_eq!(used.template(), t);
78    /// # Ok::<(), lower_lang::MappingError>(())
79    /// ```
80    #[must_use]
81    pub const fn template(&self) -> TemplateId {
82        self.template
83    }
84}
85
86/// A semantic archetype: what a syntax node *means*, and where its parts are.
87///
88/// A [`Mapping`](crate::Mapping) maps node kinds to archetypes. Lowering a node
89/// lowers each field in the context the archetype gives it (an `If`'s `cond`
90/// as an expression, a `Fn`'s `params` as parameters) and builds the HIR form.
91/// Fields marked *required* that a node lacks become error nodes plus a
92/// [`MissingField`](crate::ProblemKind::MissingField) problem; the others are
93/// simply left out. List fields take every match of their pick.
94///
95/// The modifiers each archetype reads from its direct children are listed
96/// with it (see [`Modifier`](crate::Modifier)).
97///
98/// # Examples
99///
100/// ```
101/// use lower_lang::{Arch, Pick};
102///
103/// // `if COND BLOCK (else (if_expr | BLOCK))?` with no field labels:
104/// let if_expr: Arch<u16> = Arch::If {
105///     cond: Pick::NthNode(0),
106///     then: Pick::NthNode(1),
107///     else_: Pick::NthNode(2),
108/// };
109/// assert!(matches!(if_expr, Arch::If { .. }));
110/// ```
111#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
112#[non_exhaustive]
113pub enum Arch<K> {
114    // ------------------------------------------------------------ structure
115    /// A module: the root of a file, or a nested module. Declarations among
116    /// `items` become the module's items; everything else (statements and
117    /// expressions) becomes its top-level body, in order (scripts, REPL
118    /// entries, conditional definitions).
119    Module {
120        /// The module's name (nested modules).
121        name: Pick<K>,
122        /// List: declarations and top-level statements.
123        items: Pick<K>,
124    },
125    /// A wrapper with one meaningful child (`expr`, a parenthesized group, a
126    /// statement wrapper): lowered as that child, in the same context.
127    Pass {
128        /// Required: the child.
129        inner: Pick<K>,
130    },
131    /// Several statements, items, or class members from one node
132    /// (`let a = 1, b = 2;`), spliced into the enclosing list.
133    Splice {
134        /// List: the parts, lowered in the enclosing list's context.
135        items: Pick<K>,
136    },
137    /// A construct the language has but does not lower yet: an error node
138    /// plus an [`Unsupported`](crate::ProblemKind::Unsupported) problem.
139    Unsupported,
140
141    // ------------------------------------------------- statements and binders
142    /// `let PAT: TY = INIT else ELSE;` — binds the pattern's names for the
143    /// following statements. Modifiers: `Mut` makes the binders mutable.
144    Let {
145        /// Required: the pattern (an identifier binds it).
146        pat: Pick<K>,
147        /// The annotation.
148        ty: Pick<K>,
149        /// The initializer.
150        init: Pick<K>,
151        /// The diverging `else` of let-else.
152        else_: Pick<K>,
153        /// Whether the binders are mutable without a `Mut` modifier (`var`,
154        /// JavaScript `let`) rather than only with one (`let` / `let mut`).
155        mutable: bool,
156        /// Function-scoped hoisting (JavaScript `var`): the name is declared
157        /// once at the top of the enclosing function (or module body) and this
158        /// statement becomes an assignment. Applies to identifier patterns;
159        /// other patterns lower as an ordinary `let`.
160        hoist: bool,
161    },
162    /// `EXPR;` — an expression evaluated for its effect (never a block tail).
163    ExprStmt {
164        /// Required: the expression.
165        expr: Pick<K>,
166    },
167    /// `defer BODY` — runs when the enclosing block exits.
168    Defer {
169        /// Required: the deferred expression.
170        body: Pick<K>,
171    },
172    /// `static $x = INIT;` — a function-static variable (PHP, C).
173    Static {
174        /// Required: the variable's name.
175        name: Pick<K>,
176        /// The annotation.
177        ty: Pick<K>,
178        /// The initializer.
179        init: Pick<K>,
180    },
181    /// `global $a, $b;` — locals aliasing globals, one statement per name.
182    GlobalDecl {
183        /// List: the names.
184        names: Pick<K>,
185    },
186    /// `use a::b as c;` / `use a::*;` — an import item. Modifiers: `Glob`.
187    Import {
188        /// Required: the imported path (a path node or one name).
189        path: Pick<K>,
190        /// The alias (`as c`).
191        alias: Pick<K>,
192    },
193
194    // ------------------------------------------------------------ declarations
195    /// A function. Modifiers: visibility, `Async`, `Generator`, `Throws`,
196    /// `Unsafe`. In a class, interface, or impl it is a method.
197    Fn {
198        /// Required: the name.
199        name: Pick<K>,
200        /// List: generic parameters.
201        generics: Pick<K>,
202        /// List: parameters.
203        params: Pick<K>,
204        /// The declared return type.
205        ret: Pick<K>,
206        /// The declared thrown type.
207        throws: Pick<K>,
208        /// The body (absent for required, abstract, or foreign functions).
209        body: Pick<K>,
210        /// List: where-clause predicates.
211        where_: Pick<K>,
212    },
213    /// A record (struct) or union. Modifiers: visibility, `Union`.
214    Record {
215        /// Required: the name.
216        name: Pick<K>,
217        /// List: generic parameters.
218        generics: Pick<K>,
219        /// List: the fields.
220        fields: Pick<K>,
221        /// How the field layout is decided.
222        shape: RecordShape,
223    },
224    /// A sum (enum) with variants. Modifiers: visibility.
225    Sum {
226        /// Required: the name.
227        name: Pick<K>,
228        /// List: generic parameters.
229        generics: Pick<K>,
230        /// List: the variants.
231        variants: Pick<K>,
232    },
233    /// An interface or trait. Modifiers: visibility.
234    Interface {
235        /// Required: the name.
236        name: Pick<K>,
237        /// List: generic parameters.
238        generics: Pick<K>,
239        /// List: super-interfaces (types).
240        supers: Pick<K>,
241        /// List: members (methods, constants, associated types).
242        items: Pick<K>,
243    },
244    /// A class. Modifiers: visibility, `Abstract`, `Final`.
245    Class {
246        /// Required: the name.
247        name: Pick<K>,
248        /// List: generic parameters.
249        generics: Pick<K>,
250        /// List: base classes, in method-resolution order (types).
251        bases: Pick<K>,
252        /// List: implemented interfaces (types).
253        interfaces: Pick<K>,
254        /// List: members: fields, methods, constants, static fields, aliases,
255        /// mixin uses.
256        members: Pick<K>,
257        /// A mixin (PHP trait): never instantiated, used by classes.
258        mixin: bool,
259    },
260    /// An implementation block (`impl Tr for T { ... }`).
261    Impl {
262        /// List: generic parameters.
263        generics: Pick<K>,
264        /// The implemented interface (a type).
265        interface: Pick<K>,
266        /// Required: the implementing type.
267        self_ty: Pick<K>,
268        /// List: members.
269        items: Pick<K>,
270    },
271    /// A type alias. Modifiers: visibility.
272    Alias {
273        /// Required: the name.
274        name: Pick<K>,
275        /// List: generic parameters.
276        generics: Pick<K>,
277        /// Required: the aliased type.
278        ty: Pick<K>,
279    },
280    /// An associated type declared by an interface.
281    AssocType {
282        /// Required: the name.
283        name: Pick<K>,
284        /// List: bounds (types).
285        bounds: Pick<K>,
286        /// A default type.
287        default: Pick<K>,
288    },
289    /// A compile-time constant. Modifiers: visibility.
290    Const {
291        /// Required: the name.
292        name: Pick<K>,
293        /// The annotation.
294        ty: Pick<K>,
295        /// The value (absent only in an interface).
296        value: Pick<K>,
297    },
298    /// A global or static variable item. Modifiers: visibility, `Mut`.
299    GlobalVar {
300        /// Required: the name.
301        name: Pick<K>,
302        /// The annotation.
303        ty: Pick<K>,
304        /// The initializer.
305        init: Pick<K>,
306        /// Whether it is assignable without a `Mut` modifier.
307        mutable: bool,
308    },
309    /// A mixin use inside a class (PHP `use T, U;`).
310    MixinUse {
311        /// List: the mixins (types).
312        mixins: Pick<K>,
313    },
314    /// A field of a record, variant, or class. Modifiers: visibility; in a
315    /// class, `Static` makes it a static (global) member instead.
316    FieldDecl {
317        /// The name (absent for a positional field).
318        name: Pick<K>,
319        /// The type.
320        ty: Pick<K>,
321        /// A default value.
322        default: Pick<K>,
323    },
324    /// A variant of a sum.
325    VariantDecl {
326        /// Required: the name.
327        name: Pick<K>,
328        /// List: the fields.
329        fields: Pick<K>,
330        /// An explicit discriminant.
331        discriminant: Pick<K>,
332        /// How the field layout is decided.
333        shape: RecordShape,
334    },
335    /// A generic parameter: a type parameter, a const parameter (with a
336    /// type), or a region (a lifetime-role token).
337    GenericParam {
338        /// Required: the name.
339        name: Pick<K>,
340        /// List: bounds (types).
341        bounds: Pick<K>,
342        /// The type of a const parameter.
343        ty: Pick<K>,
344        /// A default (a type, or a constant for a const parameter).
345        default: Pick<K>,
346    },
347    /// A where-clause predicate: `T: A + B`.
348    WherePred {
349        /// Required: the constrained type.
350        subject: Pick<K>,
351        /// List: the bounds (types).
352        bounds: Pick<K>,
353    },
354    /// A parameter. Modifiers: `Ref` (by reference, PHP `&$x`), `Mut`,
355    /// `Rest` (variadic), `RestNamed`, `NamedOnly`, `PositionalOnly`,
356    /// `Receiver`.
357    Param {
358        /// Required: the pattern (usually one name).
359        pat: Pick<K>,
360        /// The annotation.
361        ty: Pick<K>,
362        /// The default value.
363        default: Pick<K>,
364    },
365    /// An explicit closure capture (PHP `use ($x, &$y)`). Modifiers: `Ref`,
366    /// `Mut`.
367    Capture {
368        /// Required: the captured name.
369        name: Pick<K>,
370    },
371
372    // ------------------------------------------------------------- expressions
373    /// A path: `a::b::c`, `::a`, `self::a`, `super::a`, `Self::a`,
374    /// `<T as Tr>::a`. Leading tokens of `segments` whose kind is in the
375    /// mapping's [root table](crate::MappingBuilder::root) set the root.
376    Path {
377        /// Required (unless qualified): list of segments (names or `Segment`
378        /// nodes).
379        segments: Pick<K>,
380        /// A leading global marker (`::a`).
381        global: Pick<K>,
382        /// The qualified self type (`<T as ...>`).
383        qself: Pick<K>,
384        /// List: the trait segments of a qualified self (`<T as a::Tr>`).
385        qtrait: Pick<K>,
386    },
387    /// A path segment with generic arguments (`Vec::<i32>`).
388    Segment {
389        /// Required: the name.
390        name: Pick<K>,
391        /// List: generic arguments.
392        args: Pick<K>,
393    },
394    /// An associated-type binding in generic arguments: `Item = u8`.
395    AssocBinding {
396        /// Required: the associated type's name.
397        name: Pick<K>,
398        /// Required: its type.
399        ty: Pick<K>,
400    },
401    /// A prefix operator; the operator token's kind is looked up in the
402    /// prefix [operator table](crate::MappingBuilder::prefix_op).
403    Unary {
404        /// Required: the operator token.
405        op: Pick<K>,
406        /// Required: the operand.
407        operand: Pick<K>,
408    },
409    /// A binary operator; the token's kind is looked up in the binary
410    /// operator table. `&&`, `||`, `??`, assignment, and compound assignment
411    /// are operators too.
412    Binary {
413        /// Required: the left operand.
414        lhs: Pick<K>,
415        /// Required: the operator token.
416        op: Pick<K>,
417        /// Required: the right operand.
418        rhs: Pick<K>,
419    },
420    /// A postfix operator; looked up in the postfix operator table.
421    Postfix {
422        /// Required: the operand.
423        operand: Pick<K>,
424        /// Required: the operator token.
425        op: Pick<K>,
426    },
427    /// `TARGET = VALUE` or `TARGET op= VALUE`; a compound operator token is
428    /// looked up in the binary operator table.
429    Assign {
430        /// Required: the place.
431        target: Pick<K>,
432        /// The operator token (absent: plain assignment).
433        op: Pick<K>,
434        /// Required: the value.
435        value: Pick<K>,
436    },
437    /// `$a = &$b`: reference assignment (PHP).
438    RefAssign {
439        /// Required: the place that becomes an alias.
440        target: Pick<K>,
441        /// Required: the aliased place.
442        source: Pick<K>,
443    },
444    /// A call.
445    Call {
446        /// Required: the callee.
447        callee: Pick<K>,
448        /// List: arguments.
449        args: Pick<K>,
450    },
451    /// A call argument: named (`name: value`), spread (`...xs`, modifier
452    /// `Spread`; `**kw`, modifier `SpreadNamed`), or a place (`&$x`, modifier
453    /// `Ref`). Plain expressions in an argument list need no archetype.
454    Arg {
455        /// The argument's name.
456        name: Pick<K>,
457        /// Required: the value.
458        value: Pick<K>,
459    },
460    /// Member access, or a method call when `call` finds something:
461    /// `a.b`, `a.0`, `a.b(x)`.
462    Member {
463        /// Required: the accessed value.
464        base: Pick<K>,
465        /// Required: the member (a name, or a number for tuple fields).
466        member: Pick<K>,
467        /// List: method-call arguments.
468        args: Pick<K>,
469        /// The call marker (such as `(`); `Absent` means never a call.
470        call: Pick<K>,
471    },
472    /// A method call with explicit generic arguments: `x.f::<T>(a)`.
473    MethodCall {
474        /// Required: the receiver.
475        receiver: Pick<K>,
476        /// Required: the method name.
477        method: Pick<K>,
478        /// List: generic arguments.
479        generics: Pick<K>,
480        /// List: arguments.
481        args: Pick<K>,
482    },
483    /// `$o->$name` / `$o->$name(args)`: a member chosen at run time (Mox).
484    DynMember {
485        /// Required: the accessed value.
486        base: Pick<K>,
487        /// Required: the member name, an expression.
488        name: Pick<K>,
489        /// List: method-call arguments.
490        args: Pick<K>,
491        /// The call marker; `Absent` means never a call.
492        call: Pick<K>,
493    },
494    /// `base[index]`.
495    Index {
496        /// Required: the indexed value.
497        base: Pick<K>,
498        /// Required: the index.
499        index: Pick<K>,
500    },
501    /// `$$name`: the variable named at run time (Mox).
502    VarVar {
503        /// Required: the expression naming the variable.
504        inner: Pick<K>,
505    },
506    /// `$a[]`: append position (Mox); only a write target.
507    Append {
508        /// Required: the array.
509        base: Pick<K>,
510    },
511    /// `(a, b)`.
512    Tuple {
513        /// List: elements.
514        elems: Pick<K>,
515    },
516    /// `[a, b]`.
517    Array {
518        /// List: elements.
519        elems: Pick<K>,
520    },
521    /// An ordered map literal: `[k => v, w]` (PHP arrays). Elements that are
522    /// not `MapEntry` nodes take the next index.
523    Map {
524        /// List: entries.
525        entries: Pick<K>,
526    },
527    /// `key => value` inside a map literal.
528    MapEntry {
529        /// The key (absent: next index).
530        key: Pick<K>,
531        /// Required: the value.
532        value: Pick<K>,
533    },
534    /// `Path { x: 1, ..base }` or an anonymous record.
535    RecordLit {
536        /// The record type's path.
537        path: Pick<K>,
538        /// List: field initializers.
539        fields: Pick<K>,
540        /// The `..base` expression.
541        base: Pick<K>,
542    },
543    /// `name: value` (or the shorthand `name`) in a record literal.
544    FieldInit {
545        /// Required: the field name.
546        name: Pick<K>,
547        /// The value (absent: shorthand, the variable of the same name).
548        value: Pick<K>,
549    },
550    /// `[elem; count]`.
551    Repeat {
552        /// Required: the element.
553        elem: Pick<K>,
554        /// Required: the count.
555        count: Pick<K>,
556    },
557    /// `expr as Type`.
558    Cast {
559        /// Required: the converted value.
560        expr: Pick<K>,
561        /// Required: the target type.
562        ty: Pick<K>,
563    },
564    /// `&expr` / `&mut expr`. Modifiers: `Mut`.
565    Borrow {
566        /// Required: the borrowed place.
567        expr: Pick<K>,
568    },
569    /// `*expr`.
570    Deref {
571        /// Required: the dereferenced value.
572        inner: Pick<K>,
573    },
574    /// A block. Modifiers: `Unsafe`.
575    Block {
576        /// List: statements (and local items).
577        stmts: Pick<K>,
578        /// The tail expression (the block's value).
579        tail: Pick<K>,
580        /// A label (`'a: { ... }`).
581        label: Pick<K>,
582        /// Whether a final bare expression (not an expression statement)
583        /// becomes the tail.
584        tail_from_last: bool,
585    },
586    /// `if cond then else`.
587    If {
588        /// Required: the condition.
589        cond: Pick<K>,
590        /// Required: the value when true.
591        then: Pick<K>,
592        /// The value when false.
593        else_: Pick<K>,
594    },
595    /// `match scrutinee { arms }`.
596    Match {
597        /// Required: the matched value.
598        scrutinee: Pick<K>,
599        /// List: arms.
600        arms: Pick<K>,
601    },
602    /// A match arm: `pat if guard => body`.
603    Arm {
604        /// Required: the pattern.
605        pat: Pick<K>,
606        /// The guard.
607        guard: Pick<K>,
608        /// Required: the body.
609        body: Pick<K>,
610    },
611    /// `loop body` — HIR's one loop. `while`, `do-while`, C `for`, and
612    /// `for-each` are [templates](crate::templates).
613    Loop {
614        /// A label.
615        label: Pick<K>,
616        /// Required: the body.
617        body: Pick<K>,
618    },
619    /// `break 'label value`.
620    Break {
621        /// The target label.
622        label: Pick<K>,
623        /// The value.
624        value: Pick<K>,
625    },
626    /// `continue 'label`.
627    Continue {
628        /// The target label.
629        label: Pick<K>,
630    },
631    /// `return value`.
632    Return {
633        /// The value.
634        value: Pick<K>,
635    },
636    /// `throw value`.
637    Throw {
638        /// Required: the raised value.
639        value: Pick<K>,
640    },
641    /// `try body catch... finally...`.
642    Try {
643        /// Required: the protected body.
644        body: Pick<K>,
645        /// List: catch clauses (`Catch` or `Arm` nodes).
646        catches: Pick<K>,
647        /// The `finally` body.
648        finally: Pick<K>,
649    },
650    /// `catch (A | B $e) body`: a type test (or an alternative of several)
651    /// binding `name`. Without types it catches everything.
652    Catch {
653        /// List: the caught types.
654        types: Pick<K>,
655        /// The bound name.
656        name: Pick<K>,
657        /// Required: the handler.
658        body: Pick<K>,
659    },
660    /// `await e`.
661    Await {
662        /// Required: the awaited value.
663        inner: Pick<K>,
664    },
665    /// `yield v`.
666    Yield {
667        /// The yielded value.
668        value: Pick<K>,
669    },
670    /// `spawn e` — starts a task running the callable `e`.
671    Spawn {
672        /// Required: the callable.
673        inner: Pick<K>,
674    },
675    /// A closure. Modifiers: `Async`, `Generator`, `Throws`.
676    Closure {
677        /// List: parameters.
678        params: Pick<K>,
679        /// The return type.
680        ret: Pick<K>,
681        /// List: explicit captures (`Capture` nodes or names).
682        captures: Pick<K>,
683        /// Required: the body.
684        body: Pick<K>,
685        /// How outer variables are captured implicitly; `None` means only the
686        /// explicit captures are visible (PHP `function () use (...)`).
687        implicit: Option<CaptureMode>,
688    },
689    /// A node lowered through a template; see
690    /// [`MappingBuilder::template_node`](crate::MappingBuilder::template_node).
691    Template(TemplateUse),
692
693    // ---------------------------------------------------------------- patterns
694    /// `_` as a node.
695    WildPat,
696    /// `..` (or `rest @ ..`) inside a tuple, constructor, slice, or record
697    /// pattern.
698    RestPat {
699        /// A pattern binding the rest (slices only).
700        bind: Pick<K>,
701    },
702    /// `ref mut x @ sub`. Modifiers: `Ref`, `Mut`.
703    BindPat {
704        /// Required: the bound name.
705        name: Pick<K>,
706        /// A sub-pattern the value must also match.
707        sub: Pick<K>,
708    },
709    /// `(a, b, ..)`.
710    TuplePat {
711        /// List: element patterns (a `RestPat` marks `..`).
712        elems: Pick<K>,
713    },
714    /// `Some(x)`.
715    CtorPat {
716        /// Required: the constructor's path.
717        path: Pick<K>,
718        /// List: element patterns.
719        elems: Pick<K>,
720    },
721    /// `Point { x, y: 0, .. }`.
722    RecordPat {
723        /// The record's path (absent: an anonymous record or object).
724        path: Pick<K>,
725        /// List: field patterns.
726        fields: Pick<K>,
727    },
728    /// `name: pat` (or the shorthand `name`) in a record pattern.
729    FieldPat {
730        /// Required: the field name.
731        name: Pick<K>,
732        /// The pattern (absent: shorthand, binding the field's name).
733        pat: Pick<K>,
734    },
735    /// `a | b`.
736    OrPat {
737        /// List: alternatives.
738        alts: Pick<K>,
739    },
740    /// `lo..hi` / `lo..=hi`. Modifiers: `Inclusive`.
741    RangePat {
742        /// The lower bound.
743        lo: Pick<K>,
744        /// The upper bound.
745        hi: Pick<K>,
746    },
747    /// `&p` / `&mut p`. Modifiers: `Mut`.
748    RefPat {
749        /// Required: the inner pattern.
750        inner: Pick<K>,
751    },
752    /// `[a, b, rest @ .., z]`.
753    SlicePat {
754        /// List: element patterns (a `RestPat` marks `..`).
755        elems: Pick<K>,
756    },
757    /// `e: Type` / `Type e` — a type test, as in `catch` clauses.
758    TypeTestPat {
759        /// Required: the tested type.
760        ty: Pick<K>,
761        /// The pattern the value must then match.
762        pat: Pick<K>,
763    },
764
765    // ------------------------------------------------------------------- types
766    /// `(A, B)`.
767    TupleTy {
768        /// List: element types.
769        elems: Pick<K>,
770    },
771    /// `[T; N]`.
772    ArrayTy {
773        /// Required: the element type.
774        elem: Pick<K>,
775        /// Required: the length.
776        len: Pick<K>,
777    },
778    /// `[T]`.
779    SliceTy {
780        /// Required: the element type.
781        elem: Pick<K>,
782    },
783    /// `&'r mut T`. Modifiers: `Mut`.
784    RefTy {
785        /// Required: the referent type.
786        inner: Pick<K>,
787        /// An explicit region.
788        region: Pick<K>,
789    },
790    /// `*mut T` / `*const T`. Modifiers: `Mut`.
791    PtrTy {
792        /// Required: the pointee type.
793        inner: Pick<K>,
794    },
795    /// `T?`.
796    NullableTy {
797        /// Required: the inner type.
798        inner: Pick<K>,
799    },
800    /// `fn(A, B) -> R`.
801    FnTy {
802        /// List: parameter types.
803        params: Pick<K>,
804        /// The return type (absent: unit).
805        ret: Pick<K>,
806    },
807    /// `dyn A + B`.
808    ObjectTy {
809        /// List: bounds.
810        bounds: Pick<K>,
811    },
812    /// `impl A + B`.
813    ImplTy {
814        /// List: bounds.
815        bounds: Pick<K>,
816    },
817}
818
819impl<K> Arch<K> {
820    /// `Pass { inner: Nth(n) }`: the common wrapper.
821    ///
822    /// # Examples
823    ///
824    /// ```
825    /// use lower_lang::{Arch, Pick};
826    ///
827    /// assert_eq!(Arch::<u8>::pass(1), Arch::Pass { inner: Pick::Nth(1) });
828    /// ```
829    #[must_use]
830    pub const fn pass(n: u16) -> Self {
831        Self::Pass {
832            inner: Pick::Nth(n),
833        }
834    }
835
836    /// The shape of lang-forge's operator nodes: `binary` is `lhs op rhs`.
837    ///
838    /// # Examples
839    ///
840    /// ```
841    /// use lower_lang::{Arch, Pick};
842    ///
843    /// let Arch::Binary { op, .. } = Arch::<u8>::binary() else { unreachable!() };
844    /// assert_eq!(op, Pick::Nth(1));
845    /// ```
846    #[must_use]
847    pub const fn binary() -> Self {
848        Self::Binary {
849            lhs: Pick::Nth(0),
850            op: Pick::Nth(1),
851            rhs: Pick::Nth(2),
852        }
853    }
854
855    /// The shape of lang-forge's `prefix` nodes: `op operand`.
856    ///
857    /// # Examples
858    ///
859    /// ```
860    /// use lower_lang::{Arch, Pick};
861    ///
862    /// let Arch::Unary { operand, .. } = Arch::<u8>::prefix() else { unreachable!() };
863    /// assert_eq!(operand, Pick::Nth(1));
864    /// ```
865    #[must_use]
866    pub const fn prefix() -> Self {
867        Self::Unary {
868            op: Pick::Nth(0),
869            operand: Pick::Nth(1),
870        }
871    }
872
873    /// The archetype's name, as problems and docs spell it.
874    ///
875    /// # Examples
876    ///
877    /// ```
878    /// use lower_lang::Arch;
879    ///
880    /// assert_eq!(Arch::<u8>::binary().name(), "binary");
881    /// assert_eq!(Arch::<u8>::WildPat.name(), "wildcard pattern");
882    /// ```
883    #[must_use]
884    pub const fn name(&self) -> &'static str {
885        match self {
886            Self::Module { .. } => "module",
887            Self::Pass { .. } => "pass",
888            Self::Splice { .. } => "splice",
889            Self::Unsupported => "unsupported",
890            Self::Let { .. } => "let",
891            Self::ExprStmt { .. } => "expression statement",
892            Self::Defer { .. } => "defer",
893            Self::Static { .. } => "static",
894            Self::GlobalDecl { .. } => "global declaration",
895            Self::Import { .. } => "import",
896            Self::Fn { .. } => "function",
897            Self::Record { .. } => "record",
898            Self::Sum { .. } => "sum",
899            Self::Interface { .. } => "interface",
900            Self::Class { .. } => "class",
901            Self::Impl { .. } => "impl",
902            Self::Alias { .. } => "alias",
903            Self::AssocType { .. } => "associated type",
904            Self::Const { .. } => "constant",
905            Self::GlobalVar { .. } => "global variable",
906            Self::MixinUse { .. } => "mixin use",
907            Self::FieldDecl { .. } => "field",
908            Self::VariantDecl { .. } => "variant",
909            Self::GenericParam { .. } => "generic parameter",
910            Self::WherePred { .. } => "where predicate",
911            Self::Param { .. } => "parameter",
912            Self::Capture { .. } => "capture",
913            Self::Path { .. } => "path",
914            Self::Segment { .. } => "path segment",
915            Self::AssocBinding { .. } => "associated-type binding",
916            Self::Unary { .. } => "unary",
917            Self::Binary { .. } => "binary",
918            Self::Postfix { .. } => "postfix",
919            Self::Assign { .. } => "assignment",
920            Self::RefAssign { .. } => "reference assignment",
921            Self::Call { .. } => "call",
922            Self::Arg { .. } => "argument",
923            Self::Member { .. } => "member",
924            Self::MethodCall { .. } => "method call",
925            Self::DynMember { .. } => "dynamic member",
926            Self::Index { .. } => "index",
927            Self::VarVar { .. } => "variable variable",
928            Self::Append { .. } => "append",
929            Self::Tuple { .. } => "tuple",
930            Self::Array { .. } => "array",
931            Self::Map { .. } => "map",
932            Self::MapEntry { .. } => "map entry",
933            Self::RecordLit { .. } => "record literal",
934            Self::FieldInit { .. } => "field initializer",
935            Self::Repeat { .. } => "repeat",
936            Self::Cast { .. } => "cast",
937            Self::Borrow { .. } => "borrow",
938            Self::Deref { .. } => "dereference",
939            Self::Block { .. } => "block",
940            Self::If { .. } => "if",
941            Self::Match { .. } => "match",
942            Self::Arm { .. } => "match arm",
943            Self::Loop { .. } => "loop",
944            Self::Break { .. } => "break",
945            Self::Continue { .. } => "continue",
946            Self::Return { .. } => "return",
947            Self::Throw { .. } => "throw",
948            Self::Try { .. } => "try",
949            Self::Catch { .. } => "catch",
950            Self::Await { .. } => "await",
951            Self::Yield { .. } => "yield",
952            Self::Spawn { .. } => "spawn",
953            Self::Closure { .. } => "closure",
954            Self::Template(_) => "template",
955            Self::WildPat => "wildcard pattern",
956            Self::RestPat { .. } => "rest pattern",
957            Self::BindPat { .. } => "binding pattern",
958            Self::TuplePat { .. } => "tuple pattern",
959            Self::CtorPat { .. } => "constructor pattern",
960            Self::RecordPat { .. } => "record pattern",
961            Self::FieldPat { .. } => "field pattern",
962            Self::OrPat { .. } => "or-pattern",
963            Self::RangePat { .. } => "range pattern",
964            Self::RefPat { .. } => "reference pattern",
965            Self::SlicePat { .. } => "slice pattern",
966            Self::TypeTestPat { .. } => "type-test pattern",
967            Self::TupleTy { .. } => "tuple type",
968            Self::ArrayTy { .. } => "array type",
969            Self::SliceTy { .. } => "slice type",
970            Self::RefTy { .. } => "reference type",
971            Self::PtrTy { .. } => "pointer type",
972            Self::NullableTy { .. } => "nullable type",
973            Self::FnTy { .. } => "function type",
974            Self::ObjectTy { .. } => "object type",
975            Self::ImplTy { .. } => "impl type",
976        }
977    }
978}