1mod enter;
13mod finish;
14mod token;
15mod tpl;
16
17use alloc::collections::BTreeMap;
18use alloc::string::String;
19use alloc::vec::Vec;
20
21use hir_lang::{
22 Arg, ArgKind, BinderId, BinderKind, Builder, Capture, Effects, Expr, ExprId, FieldInit,
23 FieldPat, GenericArg, GenericParam, Hir, HirError, Item, ItemId, ItemKind, List, MapEntry,
24 Name, NodeRef, Ns, Origin, Param, ParamKind, Pat, PatId, Path, PathId, Res, Segment, Site,
25 Span, Stmt, StmtId, Ty, TyId, UnitId, VariantId, WherePred,
26};
27use intern_lang::{Interner, Symbol};
28use syntax_lang::{Element, Node, TokenKind};
29
30use crate::arch::Arch;
31use crate::mapping::{EffectMode, Mapping, OpSpec, TokenRole};
32use crate::pick::{self, Kid, Labeler, Pick};
33use crate::problem::{Context, LowerError, Problem, ProblemKind};
34use crate::template::TemplateId;
35
36pub(crate) type AttrRange = (u32, u32);
38
39#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
54#[non_exhaustive]
55pub struct Budget {
56 pub max_nodes: u64,
60 pub max_expansion_depth: u32,
66}
67
68impl Default for Budget {
69 fn default() -> Self {
70 Self {
71 max_nodes: 1 << 24,
72 max_expansion_depth: 64,
73 }
74 }
75}
76
77#[derive(Clone, Debug)]
86#[non_exhaustive]
87pub struct Lowered {
88 pub hir: Hir,
90 pub problems: Vec<Problem>,
92}
93
94impl Lowered {
95 #[must_use]
116 pub fn has_problems(&self) -> bool {
117 !self.problems.is_empty()
118 }
119}
120
121pub struct Lowerer<'m, K> {
148 mapping: &'m Mapping<K>,
149 budget: Budget,
150 unit: UnitId,
151 labeler: Option<&'m dyn Labeler<K>>,
152}
153
154impl<'m, K> Lowerer<'m, K>
155where
156 K: Copy + Ord + TokenKind,
157{
158 #[must_use]
165 pub fn new(mapping: &'m Mapping<K>) -> Self {
166 Self {
167 mapping,
168 budget: Budget::default(),
169 unit: UnitId::default(),
170 labeler: None,
171 }
172 }
173
174 #[must_use]
180 pub fn with_budget(mut self, budget: Budget) -> Self {
181 self.budget = budget;
182 self
183 }
184
185 #[must_use]
191 pub fn with_unit(mut self, unit: UnitId) -> Self {
192 self.unit = unit;
193 self
194 }
195
196 #[must_use]
216 pub fn with_labeler(mut self, labeler: &'m dyn Labeler<K>) -> Self {
217 self.labeler = Some(labeler);
218 self
219 }
220
221 pub fn lower(
235 &self,
236 tree: &Node<K>,
237 source: &str,
238 names: &mut Interner,
239 ) -> Result<Lowered, LowerError> {
240 Run::new(self, source, names)?.run(tree)
241 }
242}
243
244#[derive(Clone, Copy, Debug, PartialEq, Eq)]
248pub(crate) struct PatSite {
249 pub(crate) param: bool,
251 pub(crate) mutable: bool,
253 pub(crate) arm: bool,
256 pub(crate) bound: bool,
258 pub(crate) persist: bool,
261}
262
263impl PatSite {
264 pub(crate) const LOCAL: Self = Self {
265 param: false,
266 mutable: false,
267 arm: false,
268 bound: false,
269 persist: false,
270 };
271 pub(crate) const ARM: Self = Self {
272 param: false,
273 mutable: false,
274 arm: true,
275 bound: false,
276 persist: false,
277 };
278}
279
280#[derive(Clone, Copy, Debug)]
283pub(crate) struct Persist {
284 pub(crate) tmp: BinderId,
285 pub(crate) sym: Symbol,
286 pub(crate) span: Span,
287}
288
289#[derive(Clone, Copy, Debug)]
291pub(crate) enum Piece {
292 Text(hir_lang::TextRef, Span),
294 Expr,
296}
297
298#[derive(Clone, Copy, Debug, PartialEq, Eq)]
300pub(crate) enum Want {
301 Root,
303 Expr,
305 Stmt,
308 Member,
310 Pat(PatSite),
312 Ty,
314 Path(Ns),
316 Segment,
318 Param,
320 Arg,
322 Arm,
324 Capture,
326 Field,
328 Rule,
330 Variant,
332 Generic,
334 GArg,
336 Where,
338 Entry,
340 Init,
342 FieldPat(PatSite),
344}
345
346impl Want {
347 pub(crate) const fn context(self) -> Context {
348 match self {
349 Self::Root | Self::Stmt => Context::Statement,
350 Self::Expr => Context::Expression,
351 Self::Member => Context::Member,
352 Self::Pat(_) | Self::FieldPat(_) => Context::Pattern,
353 Self::Ty => Context::Type,
354 Self::Path(_) => Context::Path,
355 Self::Segment => Context::Segment,
356 Self::Param => Context::Parameter,
357 Self::Arg => Context::Argument,
358 Self::Arm => Context::Arm,
359 Self::Capture => Context::Capture,
360 Self::Field => Context::Field,
361 Self::Rule => Context::Member,
362 Self::Variant => Context::Variant,
363 Self::Generic | Self::GArg | Self::Where => Context::Generic,
364 Self::Entry | Self::Init => Context::Entry,
365 }
366 }
367
368 pub(crate) const fn takes_expr(self) -> bool {
370 matches!(
371 self,
372 Self::Expr | Self::Stmt | Self::Arg | Self::Entry | Self::GArg
373 )
374 }
375}
376
377#[derive(Clone, Copy, Debug)]
379pub(crate) enum Val {
380 Err,
383 Expr(ExprId),
384 Stmt(StmtId),
385 Item(ItemId),
386 Spill(u32, u32),
389 Pat(PatId),
390 Rest(Option<PatId>),
392 Ty(TyId),
393 Path(PathId),
394 Seg(Segment),
395 Param(Param, Span, AttrRange),
398 Marker(ParamKind),
400 Arg(Arg),
401 Arm(hir_lang::Arm),
402 Cap(Capture),
403 Field(hir_lang::FieldId, bool),
405 Variant(VariantId),
406 Generic(GenericParam),
407 GArg(GenericArg),
408 Where(WherePred),
409 Entry(MapEntry),
410 Init(FieldInit),
411 FieldPat(FieldPat),
412 Rule(hir_lang::MixinRule),
413}
414
415#[derive(Clone, Copy, Debug)]
418pub(crate) struct Slot {
419 pub(crate) v: Val,
420 pub(crate) span: Span,
421 pub(crate) place: bool,
422}
423
424#[derive(Clone, Copy)]
426pub(crate) enum Task<'t, K> {
427 Elem(&'t Element<K>, Want),
429 Node(&'t Node<K>, Want),
431 Finish,
433 Mark,
436}
437
438#[derive(Clone, Copy, Debug)]
440pub(crate) enum Build {
441 Arch,
443 Op(OpSpec),
445 Compound { spec: OpSpec, nodes_at: u64 },
449 Template {
451 id: TemplateId,
452 label: Option<BinderId>,
453 nodes_at: u64,
454 },
455 RootWrap,
457 HoistedLet { name: Symbol, name_span: Span },
459}
460
461#[derive(Clone, Copy, Debug)]
463pub(crate) struct Frame<K> {
464 pub(crate) arch: Arch<K>,
465 pub(crate) build: Build,
466 pub(crate) want: Want,
467 pub(crate) span: Span,
468 pub(crate) vals_base: usize,
469 pub(crate) counts_base: usize,
470 pub(crate) nfields: usize,
471 pub(crate) spill_base: usize,
472 pub(crate) label_mark: usize,
473 pub(crate) mods: u32,
474 pub(crate) fx: bool,
475 pub(crate) or: bool,
476 pub(crate) name: Option<(Symbol, Span)>,
479 pub(crate) alias: Option<(Symbol, Span)>,
481 pub(crate) binder: Option<BinderId>,
483 pub(crate) index: Option<u32>,
485 pub(crate) flag: bool,
488 pub(crate) path_root: hir_lang::PathRoot,
490 pub(crate) attrs: AttrRange,
492 pub(crate) aux: (u32, u32),
495 pub(crate) loop_mark: usize,
498}
499
500#[derive(Clone, Copy, Debug)]
503pub(crate) struct Fx {
504 pub(crate) declared: Effects,
505 pub(crate) inferred: Effects,
506 pub(crate) hoist_base: usize,
507 pub(crate) decl_base: usize,
508 pub(crate) recv: Recv,
510 pub(crate) recv_captured: bool,
513 pub(crate) loop_base: usize,
516}
517
518#[derive(Clone, Copy, Debug, PartialEq, Eq)]
520pub(crate) enum Recv {
521 None,
524 Visible,
526 Hidden,
530}
531
532#[derive(Clone, Copy, Debug)]
535pub(crate) struct LoopEntry {
536 pub(crate) label: Option<BinderId>,
537 pub(crate) span: Span,
538}
539
540pub(crate) struct Run<'a, 't, K> {
542 pub(crate) m: &'a Mapping<K>,
543 pub(crate) src: &'t str,
544 pub(crate) labeler: Option<&'a dyn Labeler<K>>,
545 pub(crate) names: &'a mut Interner,
546 pub(crate) b: Builder,
547 pub(crate) nodes: u64,
548 pub(crate) budget: Budget,
549 pub(crate) syms: Vec<Symbol>,
550 pub(crate) empty: Symbol,
551 pub(crate) sym_failed: bool,
552 pub(crate) tasks: Vec<Task<'t, K>>,
553 pub(crate) vals: Vec<Slot>,
554 pub(crate) frames: Vec<Frame<K>>,
555 pub(crate) counts: Vec<usize>,
556 pub(crate) spill: Vec<Slot>,
557 pub(crate) kids: Vec<Kid<'t, K>>,
558 pub(crate) kids2: Vec<Kid<'t, K>>,
559 pub(crate) sel: Vec<&'t Element<K>>,
560 pub(crate) labels: BTreeMap<Symbol, Vec<BinderId>>,
561 pub(crate) label_log: Vec<Symbol>,
562 pub(crate) fx: Vec<Fx>,
563 pub(crate) hoist: Vec<(Symbol, Span)>,
564 pub(crate) declared: Vec<Symbol>,
565 pub(crate) or_depth: u32,
566 pub(crate) or_map: BTreeMap<Symbol, BinderId>,
567 pub(crate) problems: Vec<Problem>,
568 pub(crate) text: Vec<u8>,
569 pub(crate) scratch: String,
570 pub(crate) bufs: Vec<Vec<Slot>>,
571 pub(crate) tpl_scratch: tpl::TplScratch,
572 pub(crate) lists: Lists,
573 pub(crate) tfields: Vec<(Pick<K>, Want, bool)>,
574 pub(crate) attr_elems: Vec<&'t Element<K>>,
576 pub(crate) attr_pool: Vec<hir_lang::Attr>,
578 pub(crate) pending_attrs: AttrRange,
580 pub(crate) persist: Vec<Persist>,
582 pub(crate) persist_marks: Vec<(u32, u32)>,
584 pub(crate) pieces: Vec<Piece>,
586 pub(crate) hoist_sym: Symbol,
588 pub(crate) compound_sym: Symbol,
590 pub(crate) place_sym: Symbol,
592 pub(crate) recv_sym: Option<Symbol>,
594 pub(crate) level_sym: Symbol,
597 pub(crate) loops: Vec<LoopEntry>,
600}
601
602#[derive(Default)]
604pub(crate) struct Lists {
605 pub(crate) exprs: Vec<ExprId>,
606 pub(crate) tys: Vec<TyId>,
607 pub(crate) args: Vec<Arg>,
608 pub(crate) arms: Vec<hir_lang::Arm>,
609 pub(crate) stmts: Vec<StmtId>,
610 pub(crate) params: Vec<hir_lang::ParamId>,
611 pub(crate) gargs: Vec<GenericArg>,
612}
613
614impl<'a, 't, K> Run<'a, 't, K>
615where
616 K: Copy + Ord + TokenKind,
617{
618 fn new(
619 cfg: &Lowerer<'a, K>,
620 src: &'t str,
621 names: &'a mut Interner,
622 ) -> Result<Self, LowerError> {
623 let empty = names
624 .try_intern("")
625 .map_err(|_| LowerError::SymbolSpaceExhausted)?;
626 let hoist_sym = names
627 .try_intern("hoist")
628 .map_err(|_| LowerError::SymbolSpaceExhausted)?;
629 let compound_sym = names
630 .try_intern("compound")
631 .map_err(|_| LowerError::SymbolSpaceExhausted)?;
632 let place_sym = names
633 .try_intern("p")
634 .map_err(|_| LowerError::SymbolSpaceExhausted)?;
635 let level_sym = names
636 .try_intern("break_level")
637 .map_err(|_| LowerError::SymbolSpaceExhausted)?;
638 let mut syms = Vec::with_capacity(cfg.mapping.strings.len());
639 for s in &cfg.mapping.strings {
640 syms.push(
641 names
642 .try_intern(s)
643 .map_err(|_| LowerError::SymbolSpaceExhausted)?,
644 );
645 }
646 let recv_sym = cfg
648 .mapping
649 .policy
650 .implicit_receiver
651 .and_then(|r| syms.get(r.0 as usize).copied());
652 Ok(Self {
653 m: cfg.mapping,
654 src,
655 labeler: cfg.labeler,
656 names,
657 b: Builder::for_unit(cfg.unit),
658 nodes: 0,
659 budget: cfg.budget,
660 syms,
661 empty,
662 sym_failed: false,
663 tasks: Vec::new(),
664 vals: Vec::new(),
665 frames: Vec::new(),
666 counts: Vec::new(),
667 spill: Vec::new(),
668 kids: Vec::new(),
669 kids2: Vec::new(),
670 sel: Vec::new(),
671 labels: BTreeMap::new(),
672 label_log: Vec::new(),
673 fx: Vec::new(),
674 hoist: Vec::new(),
675 declared: Vec::new(),
676 or_depth: 0,
677 or_map: BTreeMap::new(),
678 problems: Vec::new(),
679 text: Vec::new(),
680 scratch: String::new(),
681 bufs: Vec::new(),
682 tpl_scratch: tpl::TplScratch::default(),
683 lists: Lists::default(),
684 tfields: Vec::new(),
685 attr_elems: Vec::new(),
686 attr_pool: Vec::new(),
687 pending_attrs: (0, 0),
688 persist: Vec::new(),
689 persist_marks: Vec::new(),
690 pieces: Vec::new(),
691 hoist_sym,
692 compound_sym,
693 place_sym,
694 recv_sym,
695 level_sym,
696 loops: Vec::new(),
697 })
698 }
699
700 fn run(mut self, tree: &'t Node<K>) -> Result<Lowered, LowerError> {
701 self.tasks.push(Task::Node(tree, Want::Root));
702 while let Some(task) = self.tasks.pop() {
703 match task {
704 Task::Elem(Element::Node(n), want) => self.lower_node(n, want),
705 Task::Elem(Element::Token(t), want) => self.lower_token(t, want),
706 Task::Node(n, want) => self.lower_node(n, want),
707 Task::Finish => self.finish(),
708 Task::Mark => {
709 let depth = u32::try_from(self.frames.len()).unwrap_or(u32::MAX);
710 let len = u32::try_from(self.persist.len()).unwrap_or(u32::MAX);
711 self.persist_marks.push((depth, len));
712 }
713 }
714 if self.nodes > self.budget.max_nodes {
715 return Err(LowerError::NodeBudget {
716 limit: self.budget.max_nodes,
717 });
718 }
719 if self.sym_failed {
720 return Err(LowerError::SymbolSpaceExhausted);
721 }
722 }
723 let root = match self.vals.pop().map(|s| s.v) {
724 Some(Val::Item(root)) => root,
725 _ => {
726 self.b.set_origin(Origin::new(tree.span()));
727 self.b.module(None, &[])
728 }
729 };
730 let (hir, errors) = self.b.finish_lenient(root).map_err(LowerError::Hir)?;
731 let mut problems = self.problems;
732 problems.reserve(errors.len());
733 for e in errors {
734 let span = hir_span(&hir, &e);
735 problems.push(Problem {
736 kind: ProblemKind::Hir(e),
737 span,
738 });
739 }
740 problems.sort_by_key(|p| p.span.start());
741 Ok(Lowered { hir, problems })
742 }
743
744 fn lower_node(&mut self, node: &'t Node<K>, want: Want) {
747 let span = node.span();
748 if self.m.is_error(node.kind()) {
749 self.report(ProblemKind::SyntaxError, span);
750 let v = self.error_val(want, span);
751 self.push(v, span);
752 return;
753 }
754 let mut attrs = core::mem::take(&mut self.attr_elems);
755 pick::collect_kids(node, self.labeler, self.m, &mut self.kids, Some(&mut attrs));
756 self.pending_attrs = (0, 0);
757 if !attrs.is_empty() {
758 self.pending_attrs = self.lower_attrs(&attrs);
759 }
760 self.attr_elems = attrs;
761 let (start, end) = self.m.rule_range(node.kind());
762 let mut chosen = None;
763 for &(_, rule) in self.m.by_kind.get(start..end).unwrap_or(&[]) {
764 let Some(rule) = self.m.rules.get(rule as usize) else {
765 continue;
766 };
767 if rule.when.is_absent() || pick::single(rule.when, &self.kids, self.m).is_some() {
768 chosen = Some(rule.arch);
769 break;
770 }
771 }
772 match chosen {
773 Some(arch) => self.enter(node, arch, want),
774 None => {
775 self.report(ProblemKind::Unmapped, span);
776 let v = self.error_val(want, span);
777 self.push(v, span);
778 }
779 }
780 if self.pending_attrs.1 > 0 {
783 self.pending_attrs = (0, 0);
784 self.report(ProblemKind::MisplacedAttribute, span);
785 }
786 }
787
788 pub(crate) fn push(&mut self, v: Val, span: Span) {
790 self.vals.push(Slot {
791 v,
792 span,
793 place: false,
794 });
795 }
796
797 pub(crate) fn push_place(&mut self, v: Val, span: Span, place: bool) {
799 self.vals.push(Slot { v, span, place });
800 }
801
802 pub(crate) fn plan(&mut self, mut frame: Frame<K>, fields: &[(Pick<K>, Want, bool)]) {
808 let counts_base = self.counts.len();
809 self.sel.clear();
810 for &(p, _, many) in fields {
811 let before = self.sel.len();
812 if many {
813 pick::list(p, &self.kids, self.m, &mut self.sel);
814 } else if let Some(e) = pick::single(p, &self.kids, self.m) {
815 self.sel.push(e);
816 }
817 self.counts.push(self.sel.len() - before);
818 }
819 self.drop_shared_children(fields, counts_base);
820 frame.counts_base = counts_base;
821 frame.nfields = fields.len();
822 frame.vals_base = self.vals.len();
823 frame.spill_base = self.spill.len();
824 self.open(frame);
825 self.tasks.push(Task::Finish);
826 let mut end = self.sel.len();
827 for (i, &(_, want, _)) in fields.iter().enumerate().rev() {
828 let n = self.counts.get(counts_base + i).copied().unwrap_or(0);
829 let start = end.saturating_sub(n);
830 if let Some(slice) = self.sel.get(start..end) {
831 for &e in slice.iter().rev() {
832 self.tasks.push(Task::Elem(e, want));
833 }
834 }
835 end = start;
836 }
837 self.sel.clear();
838 }
839
840 fn drop_shared_children(&mut self, fields: &[(Pick<K>, Want, bool)], counts_base: usize) {
845 let mut offset = 0;
846 for (i, &(_, _, many)) in fields.iter().enumerate() {
847 let c = self.counts.get(counts_base + i).copied().unwrap_or(0);
848 if !many && c == 1 {
849 if let Some(&e) = self.sel.get(offset) {
850 let earlier = self.sel.get(..offset).unwrap_or(&[]);
851 if earlier.iter().any(|&x| core::ptr::eq(x, e)) {
852 let _ = self.sel.remove(offset);
853 if let Some(slot) = self.counts.get_mut(counts_base + i) {
854 *slot = 0;
855 }
856 self.report(ProblemKind::AmbiguousChild, e.span());
857 continue;
858 }
859 }
860 }
861 offset += c;
862 }
863 }
864
865 pub(crate) fn plan_marked(&mut self, mut frame: Frame<K>, fields: &[(Pick<K>, Want, bool)]) {
869 let counts_base = self.counts.len();
870 self.sel.clear();
871 for &(p, _, many) in fields {
872 let before = self.sel.len();
873 if many {
874 pick::list(p, &self.kids, self.m, &mut self.sel);
875 } else if let Some(e) = pick::single(p, &self.kids, self.m) {
876 self.sel.push(e);
877 }
878 self.counts.push(self.sel.len() - before);
879 }
880 self.drop_shared_children(fields, counts_base);
881 frame.counts_base = counts_base;
882 frame.nfields = fields.len();
883 frame.vals_base = self.vals.len();
884 frame.spill_base = self.spill.len();
885 self.open(frame);
886 self.tasks.push(Task::Finish);
887 self.tasks.push(Task::Mark);
888 let mut end = self.sel.len();
889 for i in (0..fields.len()).rev() {
890 let n = self.counts.get(counts_base + i).copied().unwrap_or(0);
891 let start = end.saturating_sub(n);
892 if let Some(slice) = self.sel.get(start..end) {
893 let want = fields.get(i).map_or(Want::Expr, |f| f.1);
894 for &e in slice.iter().rev() {
895 self.tasks.push(Task::Elem(e, want));
896 }
897 }
898 self.tasks.push(Task::Mark);
899 end = start;
900 }
901 self.sel.clear();
902 }
903
904 pub(crate) fn frame(&self, arch: Arch<K>, want: Want, span: Span) -> Frame<K> {
906 Frame {
907 arch,
908 build: Build::Arch,
909 want,
910 span,
911 vals_base: 0,
912 counts_base: 0,
913 nfields: 0,
914 spill_base: 0,
915 label_mark: self.label_log.len(),
916 mods: 0,
917 fx: false,
918 or: false,
919 name: None,
920 alias: None,
921 binder: None,
922 index: None,
923 flag: false,
924 path_root: hir_lang::PathRoot::Relative,
925 attrs: (0, 0),
926 aux: (0, 0),
927 loop_mark: self.loops.len(),
928 }
929 }
930
931 pub(crate) fn open(&mut self, mut frame: Frame<K>) {
934 frame.attrs = core::mem::take(&mut self.pending_attrs);
935 self.frames.push(frame);
936 }
937
938 pub(crate) fn field_range(&self, f: &Frame<K>, i: usize) -> (usize, usize) {
940 let counts = self
941 .counts
942 .get(f.counts_base..f.counts_base + f.nfields)
943 .unwrap_or(&[]);
944 let start = f.vals_base + counts.iter().take(i).sum::<usize>();
945 let len = counts.get(i).copied().unwrap_or(0);
946 (start, start + len)
947 }
948
949 pub(crate) fn one(&self, f: &Frame<K>, i: usize) -> Val {
951 self.slot(f, i).map_or(Val::Err, |s| s.v)
952 }
953
954 pub(crate) fn slot(&self, f: &Frame<K>, i: usize) -> Option<Slot> {
956 let (s, e) = self.field_range(f, i);
957 if s < e {
958 self.vals.get(s).copied()
959 } else {
960 None
961 }
962 }
963
964 pub(crate) fn present(&self, f: &Frame<K>, i: usize) -> bool {
966 let (s, e) = self.field_range(f, i);
967 s < e
968 }
969
970 pub(crate) fn many(&mut self, f: &Frame<K>, i: usize) -> Vec<Slot> {
972 let mut out = self.bufs.pop().unwrap_or_default();
973 out.clear();
974 let (s, e) = self.field_range(f, i);
975 for j in s..e {
976 match self.vals.get(j).copied() {
977 Some(Slot {
978 v: Val::Spill(ss, sl),
979 ..
980 }) => {
981 let (ss, sl) = (ss as usize, sl as usize);
982 if let Some(run) = self.spill.get(ss..ss.saturating_add(sl)) {
983 out.extend_from_slice(run);
984 }
985 }
986 Some(Slot { v: Val::Err, .. }) | None => {}
987 Some(slot) => out.push(slot),
988 }
989 }
990 out
991 }
992
993 pub(crate) fn give(&mut self, mut buf: Vec<Slot>) {
995 buf.clear();
996 self.bufs.push(buf);
997 }
998
999 pub(crate) fn report(&mut self, kind: ProblemKind, span: Span) {
1002 self.problems.push(Problem { kind, span });
1003 }
1004
1005 pub(crate) fn missing_expr(&mut self, field: &'static str, span: Span) -> ExprId {
1007 self.report(ProblemKind::MissingField { field }, span);
1008 self.err_expr(span)
1009 }
1010
1011 pub(crate) fn at(&mut self, span: Span) {
1014 self.b.set_origin(Origin::new(span));
1015 }
1016
1017 pub(crate) fn ex(&mut self, e: Expr) -> ExprId {
1018 self.nodes += 1;
1019 self.b.expr(e)
1020 }
1021
1022 pub(crate) fn st(&mut self, s: Stmt) -> StmtId {
1023 self.nodes += 1;
1024 self.b.stmt(s)
1025 }
1026
1027 pub(crate) fn pt(&mut self, p: Pat) -> PatId {
1028 self.nodes += 1;
1029 self.b.pat(p)
1030 }
1031
1032 pub(crate) fn ty(&mut self, t: Ty) -> TyId {
1033 self.nodes += 1;
1034 self.b.ty(t)
1035 }
1036
1037 pub(crate) fn it(&mut self, i: Item) -> ItemId {
1038 self.nodes += 1;
1039 self.b.item(i)
1040 }
1041
1042 pub(crate) fn path(&mut self, p: Path) -> PathId {
1043 self.nodes += 1;
1044 self.b.path(p)
1045 }
1046
1047 pub(crate) fn binder(&mut self, name: Name, kind: BinderKind, mutable: bool) -> BinderId {
1048 self.nodes += 1;
1049 self.b
1050 .binder(hir_lang::Binder::new(name, kind).with_mutable(mutable))
1051 }
1052
1053 pub(crate) fn list<T: hir_lang::Pooled>(&mut self, items: &[T]) -> List<T> {
1054 self.nodes += items.len() as u64;
1055 self.b.list(items)
1056 }
1057
1058 pub(crate) fn err_expr(&mut self, span: Span) -> ExprId {
1059 self.at(span);
1060 self.ex(Expr::Err)
1061 }
1062
1063 pub(crate) fn name_path(&mut self, sym: Symbol, span: Span, ns: Ns) -> PathId {
1065 self.at(span);
1066 let seg = Segment::new(Name::new(sym), Origin::new(span));
1067 let segs = self.list(&[seg]);
1068 self.path(Path::new(segs, ns))
1069 }
1070
1071 pub(crate) fn name_expr(&mut self, sym: Symbol, span: Span) -> ExprId {
1072 let p = self.name_path(sym, span, Ns::Value);
1073 self.ex(Expr::Path(p))
1074 }
1075
1076 pub(crate) fn error_val(&mut self, want: Want, span: Span) -> Val {
1080 self.at(span);
1081 match want {
1082 Want::Root => {
1083 self.nodes += 1;
1085 Val::Item(self.b.module(None, &[]))
1086 }
1087 Want::Member => Val::Item(self.it(Item::new(None, ItemKind::Err))),
1088 Want::Expr => Val::Expr(self.ex(Expr::Err)),
1089 Want::Stmt => Val::Stmt(self.st(Stmt::Err)),
1090 Want::Pat(_) => Val::Pat(self.pt(Pat::Err)),
1091 Want::Ty => Val::Ty(self.ty(Ty::Err)),
1092 Want::Path(_) => {
1093 let mut p = Path::new(List::EMPTY, Ns::Value);
1094 p.res = Res::Err;
1095 Val::Path(self.path(p))
1096 }
1097 Want::Param => {
1098 let pat = self.pt(Pat::Err);
1099 Val::Param(Param::new(pat), span, (0, 0))
1100 }
1101 Want::Arg => {
1102 let e = self.ex(Expr::Err);
1103 Val::Arg(Arg::positional(e))
1104 }
1105 Want::Entry => {
1106 let e = self.ex(Expr::Err);
1107 Val::Entry(MapEntry {
1108 key: None,
1109 value: e,
1110 })
1111 }
1112 Want::GArg => {
1113 let t = self.ty(Ty::Err);
1114 Val::GArg(GenericArg::Ty(t))
1115 }
1116 Want::Segment
1117 | Want::Arm
1118 | Want::Capture
1119 | Want::Field
1120 | Want::Variant
1121 | Want::Generic
1122 | Want::Where
1123 | Want::Init
1124 | Want::Rule
1125 | Want::FieldPat(_) => Val::Err,
1126 }
1127 }
1128
1129 pub(crate) fn not_here(&mut self, want: Want, span: Span) {
1132 self.report(
1133 ProblemKind::NotAllowedHere {
1134 expected: want.context(),
1135 },
1136 span,
1137 );
1138 let v = self.error_val(want, span);
1139 self.push(v, span);
1140 }
1141
1142 pub(crate) fn adapt_expr(&mut self, e: ExprId, place: bool, want: Want, span: Span) -> Val {
1144 match want {
1145 Want::Expr | Want::Stmt => Val::Expr(e),
1146 Want::Arg => Val::Arg(Arg {
1147 kind: ArgKind::Positional,
1148 value: e,
1149 place: place && self.m.policy.place_args == crate::PlaceArgs::Places,
1150 }),
1151 Want::Entry => Val::Entry(MapEntry {
1152 key: None,
1153 value: e,
1154 }),
1155 Want::GArg => Val::GArg(GenericArg::Const(e)),
1156 _ => {
1157 self.report(
1161 ProblemKind::NotAllowedHere {
1162 expected: want.context(),
1163 },
1164 span,
1165 );
1166 self.error_val(want, span)
1167 }
1168 }
1169 }
1170
1171 pub(crate) fn text_of(&mut self, span: Span) -> &'t str {
1176 let (s, e) = (span.start().to_usize(), span.end().to_usize());
1177 match self.src.get(s..e) {
1178 Some(t) => t,
1179 None => {
1180 self.report(ProblemKind::BadSpan, span);
1181 ""
1182 }
1183 }
1184 }
1185
1186 pub(crate) fn intern(&mut self, s: &str) -> Symbol {
1187 match self.names.try_intern(s) {
1188 Ok(sym) => sym,
1189 Err(_) => {
1190 self.sym_failed = true;
1191 self.empty
1192 }
1193 }
1194 }
1195
1196 pub(crate) fn sym(&self, i: u32) -> Symbol {
1198 self.syms.get(i as usize).copied().unwrap_or(self.empty)
1199 }
1200
1201 pub(crate) fn name_of(&mut self, elem: &'t Element<K>) -> Option<(Symbol, Span)> {
1204 let mut cur = elem;
1205 loop {
1206 match cur {
1207 Element::Token(t) => {
1208 let span = t.span();
1209 let strip = match self.m.role_for(t.kind()) {
1210 Some(TokenRole::Name) | None => 0,
1211 Some(
1212 TokenRole::Var { sigil }
1213 | TokenRole::Label { sigil }
1214 | TokenRole::Lifetime { sigil },
1215 ) => usize::from(sigil),
1216 Some(_) => return None,
1217 };
1218 let text = self.text_of(span);
1219 let name = text.get(strip..).unwrap_or("");
1220 return Some((self.intern(name), span));
1221 }
1222 Element::Node(n) => {
1223 pick::collect_kids(n, self.labeler, self.m, &mut self.kids2, None);
1224 let arch = self.m.rule_for(n.kind()).copied();
1225 let inner = match arch {
1226 Some(Arch::Pass { inner } | Arch::Segment { name: inner, .. }) => {
1227 pick::single(inner, &self.kids2, self.m)
1228 }
1229 Some(Arch::Path { segments, .. }) => {
1230 let mut out = Vec::new();
1231 pick::list(segments, &self.kids2, self.m, &mut out);
1232 if out.len() == 1 {
1233 out.first().copied()
1234 } else {
1235 None
1236 }
1237 }
1238 _ => None,
1239 };
1240 cur = inner?;
1241 }
1242 }
1243 }
1244 }
1245
1246 pub(crate) fn mods(&self, arch: &Arch<K>) -> u32 {
1249 if self.m.modifiers.is_empty() && self.m.arch_modifiers.is_empty() {
1250 return 0;
1251 }
1252 let name = (!self.m.arch_modifiers.is_empty()).then(|| arch.lsf_name());
1255 let mut bits = 0;
1256 for kid in &self.kids {
1257 match kid.elem {
1258 Element::Token(t) => {
1259 bits |= crate::mapping::modifier_bits(self.m, t.kind(), name);
1260 }
1261 Element::Node(n) => {
1262 if crate::pick::KindSets::is_container(self.m, n.kind()) {
1263 for c in n.child_tokens() {
1264 bits |= crate::mapping::modifier_bits(self.m, c.kind(), name);
1265 }
1266 }
1267 }
1268 }
1269 }
1270 bits
1271 }
1272
1273 pub(crate) fn push_label(&mut self, sym: Symbol, b: BinderId) {
1276 self.labels.entry(sym).or_default().push(b);
1277 self.label_log.push(sym);
1278 }
1279
1280 pub(crate) fn pop_labels(&mut self, mark: usize) {
1281 while self.label_log.len() > mark {
1282 if let Some(sym) = self.label_log.pop() {
1283 if let Some(stack) = self.labels.get_mut(&sym) {
1284 let _ = stack.pop();
1285 }
1286 }
1287 }
1288 }
1289
1290 pub(crate) fn find_label(&self, sym: Symbol) -> Option<BinderId> {
1291 self.labels.get(&sym).and_then(|s| s.last().copied())
1292 }
1293
1294 pub(crate) fn push_fx(&mut self, declared: Effects) {
1295 self.fx.push(Fx {
1296 declared,
1297 inferred: Effects::NONE,
1298 hoist_base: self.hoist.len(),
1299 decl_base: self.declared.len(),
1300 recv: Recv::None,
1301 recv_captured: false,
1302 loop_base: self.loops.len(),
1303 });
1304 }
1305
1306 pub(crate) fn recv_state(&self) -> Recv {
1308 self.fx.last().map_or(Recv::None, |f| f.recv)
1309 }
1310
1311 pub(crate) fn set_recv(&mut self, recv: Recv) {
1313 if let Some(top) = self.fx.last_mut() {
1314 top.recv = recv;
1315 }
1316 }
1317
1318 pub(crate) fn infer(&mut self, effect: Effects) {
1320 if let Some(top) = self.fx.last_mut() {
1321 top.inferred = top.inferred.union(effect);
1322 }
1323 }
1324
1325 pub(crate) fn hoist_name(&mut self, sym: Symbol, span: Span) {
1326 if !self.fx.is_empty() {
1327 self.hoist.push((sym, span));
1328 }
1329 }
1330
1331 pub(crate) fn declare_name(&mut self, sym: Symbol) {
1332 if !self.fx.is_empty() {
1333 self.declared.push(sym);
1334 }
1335 }
1336
1337 pub(crate) fn pop_fx(&mut self, span: Span) -> (Effects, Vec<StmtId>) {
1341 let Some(fx) = self.fx.pop() else {
1342 return (Effects::NONE, Vec::new());
1343 };
1344 let policy = self.m.policy;
1345 let mut effects = fx.declared;
1346 for (mode, flag) in [
1347 (policy.throws, Effects::THROWS),
1348 (policy.yields, Effects::YIELD),
1349 (policy.asyncs, Effects::ASYNC),
1350 ] {
1351 let add = match mode {
1352 EffectMode::Declared => false,
1353 EffectMode::Inferred => fx.inferred.contains(flag),
1354 EffectMode::Always => true,
1355 };
1356 if add {
1357 effects = effects.union(flag);
1358 }
1359 }
1360 let mut stmts = Vec::new();
1361 if self.hoist.len() > fx.hoist_base {
1362 let mut names: Vec<(Symbol, Span)> = self.hoist.split_off(fx.hoist_base);
1363 let mut declared: Vec<Symbol> = self.declared.split_off(fx.decl_base);
1364 declared.sort();
1365 names.sort_by(|a, b| a.0.cmp(&b.0).then(a.1.start().cmp(&b.1.start())));
1366 names.dedup_by(|later, first| later.0 == first.0);
1367 names.retain(|(s, _)| declared.binary_search(s).is_err());
1368 names.sort_by_key(|(_, sp)| sp.start());
1369 for (sym, sp) in names {
1370 self.at(sp);
1371 let b = self.binder(Name::new(sym), BinderKind::Local, true);
1372 let pat = self.pt(Pat::Bind {
1373 binder: b,
1374 mode: hir_lang::BindMode::Value,
1375 sub: None,
1376 });
1377 stmts.push(self.st(Stmt::Let {
1378 pat,
1379 ty: None,
1380 init: None,
1381 else_: None,
1382 }));
1383 }
1384 self.at(span);
1385 } else {
1386 self.hoist.truncate(fx.hoist_base);
1387 self.declared.truncate(fx.decl_base);
1388 }
1389 (effects, stmts)
1390 }
1391
1392 pub(crate) fn persist_binder(&mut self, sym: Symbol, span: Span) -> BinderId {
1398 let expn = self.b.expansion(hir_lang::Expansion {
1399 kind: hir_lang::ExpnKind::Desugar,
1400 name: self.hoist_sym,
1401 call_site: span,
1402 parent: hir_lang::ExpnId::ROOT,
1403 def_site: hir_lang::ExpnId::ROOT,
1404 });
1405 self.at(span);
1406 let tmp = self.binder(Name::marked(sym, expn), BinderKind::Local, true);
1407 self.hoist_name(sym, span);
1408 self.persist.push(Persist { tmp, sym, span });
1409 tmp
1410 }
1411
1412 pub(crate) fn persist_assigns(&mut self, binds: &[Persist], out: &mut Vec<StmtId>) {
1414 for p in binds {
1415 let target = self.name_expr(p.sym, p.span);
1416 self.at(p.span);
1417 let value = self.b.use_binder(p.tmp);
1418 self.nodes += 2;
1419 let assign = self.ex(Expr::Assign {
1420 target,
1421 op: None,
1422 value,
1423 });
1424 out.push(self.st(Stmt::Expr(assign)));
1425 }
1426 }
1427
1428 pub(crate) fn with_assigns(&mut self, binds: &[Persist], body: ExprId, span: Span) -> ExprId {
1430 if binds.is_empty() {
1431 return body;
1432 }
1433 let mut stmts = Vec::with_capacity(binds.len());
1434 self.persist_assigns(binds, &mut stmts);
1435 self.at(span);
1436 let list = self.list(&stmts);
1437 self.ex(Expr::Block(hir_lang::Block {
1438 stmts: list,
1439 tail: Some(body),
1440 label: None,
1441 is_unsafe: false,
1442 }))
1443 }
1444
1445 fn lower_attrs(&mut self, elems: &[&'t Element<K>]) -> AttrRange {
1450 let start = u32::try_from(self.attr_pool.len()).unwrap_or(u32::MAX);
1451 let mut kids = Vec::new();
1452 let mut arg_kids = Vec::new();
1453 let mut args_sel: Vec<&'t Element<K>> = Vec::new();
1454 for &e in elems {
1455 let Element::Node(n) = e else { continue };
1456 let Some(Arch::Attr { name, args }) = self.m.rule_for(n.kind()).copied() else {
1457 continue;
1458 };
1459 pick::collect_kids(n, self.labeler, self.m, &mut kids, None);
1460 let Some(name_elem) = pick::single(name, &kids, self.m) else {
1461 self.report(ProblemKind::MissingField { field: "name" }, e.span());
1462 continue;
1463 };
1464 let name_span = name_elem.span();
1465 let sym = match name_elem {
1466 Element::Token(_) => self.name_of(name_elem).map(|(s, _)| s),
1467 Element::Node(_) => {
1468 let text = self.text_of(name_span).trim();
1469 Some(self.intern(text))
1470 }
1471 }
1472 .unwrap_or(self.empty);
1473 args_sel.clear();
1474 pick::list(args, &kids, self.m, &mut args_sel);
1475 let mut out_args: Vec<hir_lang::AttrArg> = Vec::new();
1476 for &a in &args_sel {
1477 let arg_rule = match a {
1478 Element::Node(an) => self.m.rule_for(an.kind()).copied(),
1479 Element::Token(_) => None,
1480 };
1481 if let (Some(Arch::AttrArg { key, value }), Element::Node(an)) = (arg_rule, a) {
1482 pick::collect_kids(an, self.labeler, self.m, &mut arg_kids, None);
1483 let key = pick::single(key, &arg_kids, self.m)
1484 .and_then(|k| self.name_of(k))
1485 .map(|(s, sp)| hir_lang::Ident::new(s, sp));
1486 let value = pick::single(value, &arg_kids, self.m);
1487 let value = match value {
1488 Some(v) => match self.attr_value(v) {
1489 Some(v) => Some(v),
1490 None => continue,
1491 },
1492 None => None,
1493 };
1494 if key.is_none() && value.is_none() {
1495 continue;
1496 }
1497 out_args.push(hir_lang::AttrArg { key, value });
1498 } else if let Some(v) = self.attr_value(a) {
1499 out_args.push(hir_lang::AttrArg {
1500 key: None,
1501 value: Some(v),
1502 });
1503 }
1504 }
1505 let list = self.list(&out_args);
1506 self.attr_pool.push(hir_lang::Attr {
1507 name: hir_lang::Ident::new(sym, name_span),
1508 args: list,
1509 });
1510 }
1511 let end = u32::try_from(self.attr_pool.len()).unwrap_or(u32::MAX);
1512 (start, end.saturating_sub(start))
1513 }
1514
1515 fn attr_value(&mut self, e: &'t Element<K>) -> Option<hir_lang::AttrValue> {
1518 match e {
1519 Element::Token(t) => {
1520 let span = t.span();
1521 match self.m.role_for(t.kind()) {
1522 Some(TokenRole::Name | TokenRole::Var { .. }) => {
1523 let (sym, _) = self.token_name(span, TokenRole::Name);
1524 Some(hir_lang::AttrValue::Name(hir_lang::Ident::new(sym, span)))
1525 }
1526 Some(
1527 role @ (TokenRole::Int
1528 | TokenRole::Float
1529 | TokenRole::Number
1530 | TokenRole::Str(_)
1531 | TokenRole::RawStr
1532 | TokenRole::Heredoc(_)
1533 | TokenRole::Char(_)
1534 | TokenRole::Bytes(_)
1535 | TokenRole::True
1536 | TokenRole::False
1537 | TokenRole::Null),
1538 ) => match self.token_lit(role, span, false) {
1539 token::Decoded::Lit(l) => Some(hir_lang::AttrValue::Lit(l)),
1540 token::Decoded::Bad => None,
1541 },
1542 _ => {
1543 self.report(ProblemKind::AttributeArgument, span);
1544 None
1545 }
1546 }
1547 }
1548 Element::Node(n) => {
1549 let span = n.span();
1550 match self.m.rule_for(n.kind()).copied() {
1551 Some(Arch::Path { .. } | Arch::Segment { .. }) => {
1552 let text = self.text_of(span).trim();
1553 let sym = self.intern(text);
1554 Some(hir_lang::AttrValue::Name(hir_lang::Ident::new(sym, span)))
1555 }
1556 Some(Arch::Pass { .. }) => match self.name_of(e) {
1557 Some((sym, sp)) => {
1558 Some(hir_lang::AttrValue::Name(hir_lang::Ident::new(sym, sp)))
1559 }
1560 None => {
1561 self.report(ProblemKind::AttributeArgument, span);
1562 None
1563 }
1564 },
1565 Some(Arch::Unary { op, operand }) => {
1566 let mut kids = Vec::new();
1567 pick::collect_kids(n, self.labeler, self.m, &mut kids, None);
1568 let op_tok = pick::single(op, &kids, self.m);
1569 let neg = match op_tok {
1570 Some(Element::Token(t)) => {
1571 let text = if self.m.has_op_text() {
1572 self.text_of(t.span())
1573 } else {
1574 ""
1575 };
1576 matches!(
1577 self.m.op(crate::mapping::Fixity::Prefix, t.kind(), text),
1578 Some(OpSpec::Op(hir_lang::OpKind::Neg))
1579 )
1580 }
1581 _ => false,
1582 };
1583 let num = match pick::single(operand, &kids, self.m) {
1584 Some(Element::Token(t)) => Some(*t),
1585 _ => None,
1586 };
1587 match (
1588 neg,
1589 num.and_then(|t| self.m.role_for(t.kind()).map(|r| (t, r))),
1590 ) {
1591 (
1592 true,
1593 Some((
1594 t,
1595 role @ (TokenRole::Int | TokenRole::Float | TokenRole::Number),
1596 )),
1597 ) => match self.token_lit(role, t.span(), true) {
1598 token::Decoded::Lit(l) => Some(hir_lang::AttrValue::Lit(l)),
1599 token::Decoded::Bad => None,
1600 },
1601 _ => {
1602 self.report(ProblemKind::AttributeArgument, span);
1603 None
1604 }
1605 }
1606 }
1607 _ => {
1608 self.report(ProblemKind::AttributeArgument, span);
1609 None
1610 }
1611 }
1612 }
1613 }
1614 }
1615
1616 pub(crate) fn attach_attrs(&mut self, v: &mut Val, attrs: AttrRange, span: Span) {
1618 let (s, l) = (attrs.0 as usize, attrs.1 as usize);
1619 let Some(list) = self.attr_pool.get(s..s.saturating_add(l)) else {
1620 return;
1621 };
1622 let list: Vec<hir_lang::Attr> = list.to_vec();
1623 let node = match *v {
1624 Val::Item(i) => Some(NodeRef::Item(i)),
1625 Val::Expr(e) => Some(NodeRef::Expr(e)),
1626 Val::Stmt(st) => Some(NodeRef::Stmt(st)),
1627 Val::Pat(p) => Some(NodeRef::Pat(p)),
1628 Val::Ty(t) => Some(NodeRef::Ty(t)),
1629 Val::Path(p) => Some(NodeRef::Path(p)),
1630 Val::Field(f, _) => Some(NodeRef::Field(f)),
1631 Val::Variant(var) => Some(NodeRef::Variant(var)),
1632 Val::Arg(a) => Some(NodeRef::Expr(a.value)),
1633 Val::Param(p, sp, _) => {
1634 *v = Val::Param(p, sp, attrs);
1635 return;
1636 }
1637 Val::Spill(ss, sl) => {
1638 let (ss, sl) = (ss as usize, sl as usize);
1639 let nodes: Vec<NodeRef> = self
1640 .spill
1641 .get(ss..ss.saturating_add(sl))
1642 .unwrap_or(&[])
1643 .iter()
1644 .filter_map(|slot| match slot.v {
1645 Val::Item(i) => Some(NodeRef::Item(i)),
1646 Val::Stmt(st) => Some(NodeRef::Stmt(st)),
1647 Val::Expr(e) => Some(NodeRef::Expr(e)),
1648 _ => None,
1649 })
1650 .collect();
1651 for n in nodes {
1652 self.b.attach(n, &list);
1653 }
1654 return;
1655 }
1656 _ => None,
1657 };
1658 match node {
1659 Some(n) => self.b.attach(n, &list),
1660 None => self.report(ProblemKind::MisplacedAttribute, span),
1661 }
1662 }
1663
1664 pub(crate) fn wrap_hoisted(&mut self, hoisted: &[StmtId], body: ExprId, span: Span) -> ExprId {
1666 if hoisted.is_empty() {
1667 return body;
1668 }
1669 self.at(span);
1670 let stmts = self.list(hoisted);
1671 self.ex(Expr::Block(hir_lang::Block {
1672 stmts,
1673 tail: Some(body),
1674 label: None,
1675 is_unsafe: false,
1676 }))
1677 }
1678}
1679
1680fn hir_span(hir: &Hir, e: &HirError) -> Span {
1683 match e.node() {
1684 Some(n) => hir.origin(n).span,
1685 None => match e {
1686 HirError::BinderBoundTwice { binder, .. }
1687 | HirError::BinderKind { binder, .. }
1688 | HirError::DuplicateBinding { binder, .. } => hir.binder_origin(*binder).span,
1689 HirError::Dangling {
1690 site: Site::Binder(b),
1691 ..
1692 } => hir.binder_origin(*b).span,
1693 HirError::Dangling {
1694 site: Site::Expansion(x),
1695 ..
1696 }
1697 | HirError::ExpansionOrder { expn: x } => {
1698 hir.expansion(*x).map_or(Span::empty(0), |x| x.call_site)
1699 }
1700 _ => hir.origin(NodeRef::Item(hir.root())).span,
1701 },
1702 }
1703}