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