1use std::ops::ControlFlow;
2
3use flux_common::index::IndexGen;
4use flux_errors::Errors;
5use flux_middle::{
6 ResolverOutput,
7 fhir::{self, PartialRes, Res},
8};
9use flux_syntax::{
10 surface::{self, FluxItem, Ident, NodeId, visit::Visitor as _},
11 symbols::sym,
12 walk_list,
13};
14use rustc_data_structures::{
15 fx::{FxIndexMap, FxIndexSet, IndexEntry},
16 unord::UnordMap,
17};
18use rustc_hash::FxHashMap;
19use rustc_hir::def::{
20 DefKind,
21 Namespace::{TypeNS, ValueNS},
22};
23use rustc_middle::ty::TyCtxt;
24use rustc_span::{ErrorGuaranteed, Symbol};
25
26use super::{CrateResolver, Segment};
27
28type Result<T = ()> = std::result::Result<T, ErrorGuaranteed>;
29
30#[derive(Clone, Copy, PartialEq, Eq, Debug)]
31pub(crate) enum ScopeKind {
32 FnInput,
33 FnOutput,
34 Variant,
35 Misc,
36 FnTraitInput,
37}
38
39impl ScopeKind {
40 fn is_barrier(self) -> bool {
41 matches!(self, ScopeKind::FnInput | ScopeKind::Variant)
42 }
43}
44
45#[derive(Debug, Clone, Copy)]
47struct ParamRes(fhir::ParamKind, NodeId);
48
49impl ParamRes {
50 fn kind(self) -> fhir::ParamKind {
51 self.0
52 }
53
54 fn param_id(self) -> NodeId {
55 self.1
56 }
57}
58
59pub(crate) trait ScopedVisitor: Sized {
60 fn is_box(&self, segment: &surface::PathSegment) -> bool;
61 fn enter_scope(&mut self, kind: ScopeKind) -> ControlFlow<()>;
62 fn exit_scope(&mut self) {}
63
64 fn wrap(self) -> ScopedVisitorWrapper<Self> {
65 ScopedVisitorWrapper(self)
66 }
67
68 fn on_implicit_param(&mut self, _ident: Ident, _kind: fhir::ParamKind, _node_id: NodeId) {}
69 fn on_generic_param(&mut self, _param: &surface::GenericParam) {}
70 fn on_refine_param(&mut self, _param: &surface::RefineParam) {}
71 fn on_enum_variant(&mut self, _variant: &surface::VariantDef) {}
72 fn on_fn_trait_input(&mut self, _in_arg: &surface::GenericArg, _node_id: NodeId) {}
73 fn on_fn_sig(&mut self, _fn_sig: &surface::FnSig) {}
74 fn on_fn_output(&mut self, _output: &surface::FnOutput) {}
75 fn on_loc(&mut self, _loc: Ident, _node_id: NodeId) {}
76 fn on_path(&mut self, _path: &surface::ExprPath) {}
77 fn on_base_sort(&mut self, _sort: &surface::BaseSort) {}
78}
79
80pub(crate) struct ScopedVisitorWrapper<V>(V);
81
82impl<V: ScopedVisitor> ScopedVisitorWrapper<V> {
83 fn with_scope(&mut self, kind: ScopeKind, f: impl FnOnce(&mut Self)) {
84 let scope = self.0.enter_scope(kind);
85 if let ControlFlow::Continue(_) = scope {
86 f(self);
87 self.0.exit_scope();
88 }
89 }
90}
91
92impl<V> std::ops::Deref for ScopedVisitorWrapper<V> {
93 type Target = V;
94
95 fn deref(&self) -> &Self::Target {
96 &self.0
97 }
98}
99impl<V> std::ops::DerefMut for ScopedVisitorWrapper<V> {
100 fn deref_mut(&mut self) -> &mut Self::Target {
101 &mut self.0
102 }
103}
104
105impl<V: ScopedVisitor> surface::visit::Visitor for ScopedVisitorWrapper<V> {
106 fn visit_trait_assoc_reft(&mut self, assoc_reft: &surface::TraitAssocReft) {
107 self.with_scope(ScopeKind::Misc, |this| {
108 surface::visit::walk_trait_assoc_reft(this, assoc_reft);
109 });
110 }
111
112 fn visit_impl_assoc_reft(&mut self, assoc_reft: &surface::ImplAssocReft) {
113 self.with_scope(ScopeKind::Misc, |this| {
114 surface::visit::walk_impl_assoc_reft(this, assoc_reft);
115 });
116 }
117
118 fn visit_qualifier(&mut self, qualifier: &surface::Qualifier) {
119 self.with_scope(ScopeKind::Misc, |this| {
120 surface::visit::walk_qualifier(this, qualifier);
121 });
122 }
123
124 fn visit_defn(&mut self, defn: &surface::SpecFunc) {
125 self.with_scope(ScopeKind::Misc, |this| {
126 surface::visit::walk_defn(this, defn);
127 });
128 }
129
130 fn visit_primop_prop(&mut self, prop: &surface::PrimOpProp) {
131 self.with_scope(ScopeKind::Misc, |this| {
132 surface::visit::walk_primop_prop(this, prop);
133 });
134 }
135
136 fn visit_generic_param(&mut self, param: &surface::GenericParam) {
137 self.on_generic_param(param);
138 surface::visit::walk_generic_param(self, param);
139 }
140
141 fn visit_refine_param(&mut self, param: &surface::RefineParam) {
142 self.on_refine_param(param);
143 surface::visit::walk_refine_param(self, param);
144 }
145
146 fn visit_ty_alias(&mut self, ty_alias: &surface::TyAlias) {
147 self.with_scope(ScopeKind::Misc, |this| {
148 surface::visit::walk_ty_alias(this, ty_alias);
149 });
150 }
151
152 fn visit_struct_def(&mut self, struct_def: &surface::StructDef) {
153 self.with_scope(ScopeKind::Misc, |this| {
154 surface::visit::walk_struct_def(this, struct_def);
155 });
156 }
157
158 fn visit_enum_def(&mut self, enum_def: &surface::EnumDef) {
159 self.with_scope(ScopeKind::Misc, |this| {
160 surface::visit::walk_enum_def(this, enum_def);
161 });
162 }
163
164 fn visit_variant(&mut self, variant: &surface::VariantDef) {
165 self.with_scope(ScopeKind::Variant, |this| {
166 this.on_enum_variant(variant);
167 surface::visit::walk_variant(this, variant);
168 });
169 }
170
171 fn visit_trait_ref(&mut self, trait_ref: &surface::TraitRef) {
172 match trait_ref.as_fn_trait_ref() {
173 Some((in_arg, out_arg)) => {
174 self.with_scope(ScopeKind::FnTraitInput, |this| {
175 this.on_fn_trait_input(in_arg, trait_ref.node_id);
176 surface::visit::walk_generic_arg(this, in_arg);
177 this.with_scope(ScopeKind::Misc, |this| {
178 surface::visit::walk_generic_arg(this, out_arg);
179 });
180 });
181 }
182 None => {
183 self.with_scope(ScopeKind::Misc, |this| {
184 surface::visit::walk_trait_ref(this, trait_ref);
185 });
186 }
187 }
188 }
189
190 fn visit_variant_ret(&mut self, ret: &surface::VariantRet) {
191 self.with_scope(ScopeKind::Misc, |this| {
192 surface::visit::walk_variant_ret(this, ret);
193 });
194 }
195
196 fn visit_generics(&mut self, generics: &surface::Generics) {
197 self.with_scope(ScopeKind::Misc, |this| {
198 surface::visit::walk_generics(this, generics);
199 });
200 }
201
202 fn visit_fn_sig(&mut self, fn_sig: &surface::FnSig) {
203 self.with_scope(ScopeKind::FnInput, |this| {
204 this.on_fn_sig(fn_sig);
205 surface::visit::walk_fn_sig(this, fn_sig);
206 });
207 }
208
209 fn visit_fn_output(&mut self, output: &surface::FnOutput) {
210 self.with_scope(ScopeKind::FnOutput, |this| {
211 this.on_fn_output(output);
212 surface::visit::walk_fn_output(this, output);
213 });
214 }
215
216 fn visit_fn_input(&mut self, arg: &surface::FnInput) {
217 match arg {
218 surface::FnInput::Constr(bind, _, _, node_id) => {
219 self.on_implicit_param(*bind, fhir::ParamKind::Colon, *node_id);
220 }
221 surface::FnInput::StrgRef(loc, _, node_id) => {
222 self.on_implicit_param(*loc, fhir::ParamKind::Loc, *node_id);
223 }
224 surface::FnInput::Ty(bind, ty, node_id) => {
225 if let &Some(bind) = bind {
226 let param_kind = if let surface::TyKind::Base(_) = &ty.kind {
227 fhir::ParamKind::Colon
228 } else {
229 fhir::ParamKind::Error
230 };
231 self.on_implicit_param(bind, param_kind, *node_id);
232 }
233 }
234 }
235 surface::visit::walk_fn_input(self, arg);
236 }
237
238 fn visit_ensures(&mut self, constraint: &surface::Ensures) {
239 if let surface::Ensures::Type(loc, _, node_id) = constraint {
240 self.on_loc(*loc, *node_id);
241 }
242 surface::visit::walk_ensures(self, constraint);
243 }
244
245 fn visit_refine_arg(&mut self, arg: &surface::RefineArg) {
246 match arg {
247 surface::RefineArg::Bind(ident, kind, _, node_id) => {
248 let kind = match kind {
249 surface::BindKind::At => fhir::ParamKind::At,
250 surface::BindKind::Pound => fhir::ParamKind::Pound,
251 };
252 self.on_implicit_param(*ident, kind, *node_id);
253 }
254 surface::RefineArg::Abs(..) => {
255 self.with_scope(ScopeKind::Misc, |this| {
256 surface::visit::walk_refine_arg(this, arg);
257 });
258 }
259 surface::RefineArg::Expr(expr) => self.visit_expr(expr),
260 }
261 }
262
263 fn visit_path(&mut self, path: &surface::Path) {
264 for arg in &path.refine {
265 self.with_scope(ScopeKind::Misc, |this| this.visit_refine_arg(arg));
266 }
267 walk_list!(self, visit_path_segment, &path.segments);
268 }
269
270 fn visit_path_segment(&mut self, segment: &surface::PathSegment) {
271 let is_box = self.is_box(segment);
272 for (i, arg) in segment.args.iter().enumerate() {
273 if is_box && i == 0 {
274 self.visit_generic_arg(arg);
275 } else {
276 self.with_scope(ScopeKind::Misc, |this| this.visit_generic_arg(arg));
277 }
278 }
279 }
280
281 fn visit_ty(&mut self, ty: &surface::Ty) {
282 let node_id = ty.node_id;
283 match &ty.kind {
284 surface::TyKind::Exists { bind, .. } => {
285 self.with_scope(ScopeKind::Misc, |this| {
286 let param = surface::RefineParam {
287 ident: *bind,
288 mode: None,
289 sort: surface::Sort::Infer,
290 node_id,
291 span: bind.span,
292 };
293 this.on_refine_param(¶m);
294 surface::visit::walk_ty(this, ty);
295 });
296 }
297 surface::TyKind::GeneralExists { .. } => {
298 self.with_scope(ScopeKind::Misc, |this| {
299 surface::visit::walk_ty(this, ty);
300 });
301 }
302 surface::TyKind::Array(..) => {
303 self.with_scope(ScopeKind::Misc, |this| {
304 surface::visit::walk_ty(this, ty);
305 });
306 }
307 _ => surface::visit::walk_ty(self, ty),
308 }
309 }
310
311 fn visit_bty(&mut self, bty: &surface::BaseTy) {
312 match &bty.kind {
313 surface::BaseTyKind::Slice(_) => {
314 self.with_scope(ScopeKind::Misc, |this| {
315 surface::visit::walk_bty(this, bty);
316 });
317 }
318 surface::BaseTyKind::Path(..) => {
319 surface::visit::walk_bty(self, bty);
320 }
321 }
322 }
323
324 fn visit_path_expr(&mut self, path: &surface::ExprPath) {
325 self.on_path(path);
326 }
327
328 fn visit_base_sort(&mut self, bsort: &surface::BaseSort) {
329 self.on_base_sort(bsort);
330 surface::visit::walk_base_sort(self, bsort);
331 }
332}
333
334struct ImplicitParamCollector<'a, 'tcx> {
335 tcx: TyCtxt<'tcx>,
336 path_res_map: &'a UnordMap<surface::NodeId, fhir::PartialRes>,
337 kind: ScopeKind,
338 params: Vec<(Ident, fhir::ParamKind, NodeId)>,
339}
340
341impl<'a, 'tcx> ImplicitParamCollector<'a, 'tcx> {
342 fn new(
343 tcx: TyCtxt<'tcx>,
344 path_res_map: &'a UnordMap<surface::NodeId, fhir::PartialRes>,
345 kind: ScopeKind,
346 ) -> Self {
347 Self { tcx, path_res_map, kind, params: vec![] }
348 }
349
350 fn run(
351 self,
352 f: impl FnOnce(&mut ScopedVisitorWrapper<Self>),
353 ) -> Vec<(Ident, fhir::ParamKind, NodeId)> {
354 let mut wrapped = self.wrap();
355 f(&mut wrapped);
356 wrapped.0.params
357 }
358}
359
360impl ScopedVisitor for ImplicitParamCollector<'_, '_> {
361 fn is_box(&self, segment: &surface::PathSegment) -> bool {
362 self.path_res_map
363 .get(&segment.node_id)
364 .map(|r| r.is_box(self.tcx))
365 .unwrap_or(false)
366 }
367
368 fn enter_scope(&mut self, kind: ScopeKind) -> ControlFlow<()> {
369 if self.kind == kind { ControlFlow::Continue(()) } else { ControlFlow::Break(()) }
370 }
371
372 fn on_implicit_param(&mut self, ident: Ident, param: fhir::ParamKind, node_id: NodeId) {
373 self.params.push((ident, param, node_id));
374 }
375}
376
377struct Scope {
378 kind: ScopeKind,
379 bindings: FxIndexMap<Ident, ParamRes>,
380}
381
382impl Scope {
383 fn new(kind: ScopeKind) -> Self {
384 Self { kind, bindings: Default::default() }
385 }
386}
387
388#[derive(Clone, Copy)]
389struct ParamDef {
390 ident: Ident,
391 kind: fhir::ParamKind,
392 scope: Option<NodeId>,
393}
394
395pub(crate) struct RefinementResolver<'a, 'genv, 'tcx> {
396 scopes: Vec<Scope>,
397 sort_params: FxIndexSet<Symbol>,
398 param_defs: FxIndexMap<NodeId, ParamDef>,
399 resolver: &'a mut CrateResolver<'genv, 'tcx>,
400 path_res_map: FxHashMap<NodeId, PartialRes<NodeId>>,
401 errors: Errors<'genv>,
402}
403
404impl<'a, 'genv, 'tcx> RefinementResolver<'a, 'genv, 'tcx> {
405 fn for_flux_item(resolver: &'a mut CrateResolver<'genv, 'tcx>, item: &FluxItem) -> Self {
406 let sort_params = match item {
407 FluxItem::FuncDef(defn) => &defn.sort_vars[..],
408 FluxItem::SortDecl(sort_decl) => &sort_decl.sort_vars[..],
409 FluxItem::Qualifier(_) | FluxItem::PrimOpProp(_) => &[],
410 };
411 Self::new(resolver, sort_params.iter().map(|ident| ident.name).collect())
412 }
413
414 fn for_rust_item(resolver: &'a mut CrateResolver<'genv, 'tcx>) -> Self {
415 Self::new(resolver, Default::default())
416 }
417
418 pub(crate) fn resolve_flux_item(
419 resolver: &'a mut CrateResolver<'genv, 'tcx>,
420 item: &FluxItem,
421 ) -> Result {
422 Self::for_flux_item(resolver, item).run(|r| r.visit_flux_item(item))
423 }
424
425 pub(crate) fn resolve_item(
426 resolver: &'a mut CrateResolver<'genv, 'tcx>,
427 item: &surface::Item,
428 ) -> Result {
429 IllegalBinderVisitor::new(resolver).run(|vis| vis.visit_item(item))?;
430 Self::for_rust_item(resolver).run(|vis| vis.visit_item(item))
431 }
432
433 pub(crate) fn resolve_trait_item(
434 resolver: &'a mut CrateResolver<'genv, 'tcx>,
435 item: &surface::TraitItemFn,
436 ) -> Result {
437 IllegalBinderVisitor::new(resolver).run(|vis| vis.visit_trait_item(item))?;
438 Self::for_rust_item(resolver).run(|vis| vis.visit_trait_item(item))
439 }
440
441 pub(crate) fn resolve_impl_item(
442 resolver: &'a mut CrateResolver<'genv, 'tcx>,
443 item: &surface::ImplItemFn,
444 ) -> Result {
445 IllegalBinderVisitor::new(resolver).run(|vis| vis.visit_impl_item(item))?;
446 Self::for_rust_item(resolver).run(|vis| vis.visit_impl_item(item))
447 }
448
449 fn new(resolver: &'a mut CrateResolver<'genv, 'tcx>, sort_params: FxIndexSet<Symbol>) -> Self {
450 let errors = Errors::new(resolver.genv.sess());
451 Self {
452 resolver,
453 sort_params,
454 param_defs: Default::default(),
455 scopes: Default::default(),
456 path_res_map: Default::default(),
457 errors,
458 }
459 }
460
461 fn run(self, f: impl FnOnce(&mut ScopedVisitorWrapper<Self>)) -> Result {
462 let mut wrapper = self.wrap();
463 f(&mut wrapper);
464 wrapper.0.finish()
465 }
466
467 fn define_param(
468 &mut self,
469 ident: Ident,
470 kind: fhir::ParamKind,
471 param_id: NodeId,
472 scope: Option<NodeId>,
473 ) {
474 self.param_defs
475 .insert(param_id, ParamDef { ident, kind, scope });
476
477 let scope = self.scopes.last_mut().unwrap();
478 match scope.bindings.entry(ident) {
479 IndexEntry::Occupied(entry) => {
480 let param_def = self.param_defs[&entry.get().param_id()];
481 self.errors
482 .emit(errors::DuplicateParam::new(param_def.ident, ident));
483 }
484 IndexEntry::Vacant(entry) => {
485 entry.insert(ParamRes(kind, param_id));
486 }
487 }
488 }
489
490 fn find(&mut self, ident: Ident) -> Option<ParamRes> {
491 for scope in self.scopes.iter().rev() {
492 if let Some(res) = scope.bindings.get(&ident) {
493 return Some(*res);
494 }
495
496 if scope.kind.is_barrier() {
497 return None;
498 }
499 }
500 None
501 }
502
503 fn resolve_path(&mut self, path: &surface::ExprPath) {
504 if let [segment] = &path.segments[..]
505 && let Some(res) = self.try_resolve_param(segment.ident)
506 {
507 self.path_res_map.insert(path.node_id, PartialRes::new(res));
508 return;
509 }
510 if let Some(res) = self.try_resolve_expr_with_ribs(&path.segments) {
511 self.path_res_map.insert(path.node_id, res);
512 return;
513 }
514 if let [segment] = &path.segments[..]
515 && let Some(res) = self.try_resolve_global_func(segment.ident)
516 {
517 self.path_res_map.insert(path.node_id, PartialRes::new(res));
518 return;
519 }
520
521 self.errors.emit(errors::UnresolvedVar::from_path(path));
522 }
523
524 fn resolve_ident(&mut self, ident: Ident, node_id: NodeId) {
525 if let Some(res) = self.try_resolve_param(ident) {
526 self.path_res_map.insert(node_id, PartialRes::new(res));
527 return;
528 }
529 if let Some(res) = self.try_resolve_expr_with_ribs(&[ident]) {
530 self.path_res_map.insert(node_id, res);
531 return;
532 }
533 if let Some(res) = self.try_resolve_global_func(ident) {
534 self.path_res_map.insert(node_id, PartialRes::new(res));
535 return;
536 }
537 self.errors.emit(errors::UnresolvedVar::from_ident(ident));
538 }
539
540 fn try_resolve_expr_with_ribs<S: Segment>(
541 &mut self,
542 segments: &[S],
543 ) -> Option<PartialRes<NodeId>> {
544 if let Some(partial_res) = self.resolver.resolve_path_with_ribs(segments, ValueNS) {
545 return Some(partial_res.map_param_id(|p| p));
546 }
547
548 self.resolver
549 .resolve_path_with_ribs(segments, TypeNS)
550 .map(|r| r.map_param_id(|p| p))
551 }
552
553 fn try_resolve_param(&mut self, ident: Ident) -> Option<Res<NodeId>> {
554 let res = self.find(ident)?;
555
556 if let fhir::ParamKind::Error = res.kind() {
557 self.errors.emit(errors::InvalidUnrefinedParam::new(ident));
558 }
559 Some(Res::Param(res.kind(), res.param_id()))
560 }
561
562 fn try_resolve_global_func(&mut self, ident: Ident) -> Option<Res<NodeId>> {
563 let kind = self.resolver.func_decls.get(&ident.name)?;
564 Some(Res::GlobalFunc(*kind))
565 }
566
567 fn resolve_sort_path(&mut self, path: &surface::SortPath) {
568 let res = self
569 .try_resolve_sort_param(path)
570 .or_else(|| self.try_resolve_sort_with_ribs(path))
571 .or_else(|| self.try_resolve_user_sort(path))
572 .or_else(|| self.try_resolve_prim_sort(path));
573
574 if let Some(res) = res {
575 self.resolver
576 .output
577 .sort_path_res_map
578 .insert(path.node_id, res);
579 } else {
580 self.errors.emit(errors::UnresolvedSort::new(path));
581 }
582 }
583
584 fn try_resolve_sort_param(&self, path: &surface::SortPath) -> Option<fhir::SortRes> {
585 let [segment] = &path.segments[..] else { return None };
586 self.sort_params
587 .get_index_of(&segment.name)
588 .map(fhir::SortRes::SortParam)
589 }
590
591 fn try_resolve_sort_with_ribs(&mut self, path: &surface::SortPath) -> Option<fhir::SortRes> {
592 let partial_res = self
593 .resolver
594 .resolve_path_with_ribs(&path.segments, TypeNS)?;
595 match (partial_res.base_res(), partial_res.unresolved_segments()) {
596 (fhir::Res::Def(DefKind::Struct | DefKind::Enum, def_id), 0) => {
597 Some(fhir::SortRes::Adt(def_id))
598 }
599 (fhir::Res::Def(DefKind::TyParam, def_id), 0) => Some(fhir::SortRes::TyParam(def_id)),
600 (fhir::Res::SelfTyParam { trait_ }, 0) => {
601 Some(fhir::SortRes::SelfParam { trait_id: trait_ })
602 }
603 (fhir::Res::SelfTyParam { trait_ }, 1) => {
604 let ident = *path.segments.last().unwrap();
605 Some(fhir::SortRes::SelfParamAssoc { trait_id: trait_, ident })
606 }
607 (fhir::Res::SelfTyAlias { alias_to, .. }, 0) => {
608 Some(fhir::SortRes::SelfAlias { alias_to })
609 }
610 _ => None,
611 }
612 }
613
614 fn try_resolve_user_sort(&self, path: &surface::SortPath) -> Option<fhir::SortRes> {
615 let [segment] = &path.segments[..] else { return None };
616 self.resolver
617 .sort_decls
618 .get(&segment.name)
619 .map(|decl| fhir::SortRes::User(*decl))
620 }
621
622 fn try_resolve_prim_sort(&self, path: &surface::SortPath) -> Option<fhir::SortRes> {
623 let [segment] = &path.segments[..] else { return None };
624 if segment.name == sym::int {
625 Some(fhir::SortRes::PrimSort(fhir::PrimSort::Int))
626 } else if segment.name == sym::bool {
627 Some(fhir::SortRes::PrimSort(fhir::PrimSort::Bool))
628 } else if segment.name == sym::char {
629 Some(fhir::SortRes::PrimSort(fhir::PrimSort::Char))
630 } else if segment.name == sym::real {
631 Some(fhir::SortRes::PrimSort(fhir::PrimSort::Real))
632 } else if segment.name == sym::Set {
633 Some(fhir::SortRes::PrimSort(fhir::PrimSort::Set))
634 } else if segment.name == sym::Map {
635 Some(fhir::SortRes::PrimSort(fhir::PrimSort::Map))
636 } else if segment.name == sym::str {
637 Some(fhir::SortRes::PrimSort(fhir::PrimSort::Str))
638 } else {
639 None
640 }
641 }
642
643 pub(crate) fn finish(self) -> Result {
644 let param_id_gen = IndexGen::new();
645 let mut params = FxIndexMap::default();
646
647 for (node_id, res) in self.path_res_map {
650 let res = res.map_param_id(|param_id| {
651 *params
652 .entry(param_id)
653 .or_insert_with(|| param_id_gen.fresh())
654 });
655 self.resolver.output.expr_path_res_map.insert(node_id, res);
656 }
657
658 for (param_id, param_def) in self.param_defs {
661 let name = match param_def.kind {
662 fhir::ParamKind::Colon => {
663 let Some(name) = params.get(¶m_id) else { continue };
664 *name
665 }
666 fhir::ParamKind::Error => continue,
667 _ => {
668 params
669 .get(¶m_id)
670 .copied()
671 .unwrap_or_else(|| param_id_gen.fresh())
672 }
673 };
674 let output = &mut self.resolver.output;
675 output
676 .param_res_map
677 .insert(param_id, (name, param_def.kind));
678
679 if let Some(scope) = param_def.scope {
680 output
681 .implicit_params
682 .entry(scope)
683 .or_default()
684 .push((param_def.ident, param_id));
685 }
686 }
687 self.errors.into_result()
688 }
689
690 fn resolver_output(&self) -> &ResolverOutput {
691 &self.resolver.output
692 }
693}
694
695impl ScopedVisitor for RefinementResolver<'_, '_, '_> {
696 fn is_box(&self, segment: &surface::PathSegment) -> bool {
697 self.resolver_output()
698 .path_res_map
699 .get(&segment.node_id)
700 .map(|r| r.is_box(self.resolver.genv.tcx()))
701 .unwrap_or(false)
702 }
703
704 fn enter_scope(&mut self, kind: ScopeKind) -> ControlFlow<()> {
705 self.scopes.push(Scope::new(kind));
706 ControlFlow::Continue(())
707 }
708
709 fn exit_scope(&mut self) {
710 self.scopes.pop();
711 }
712
713 fn on_fn_trait_input(&mut self, in_arg: &surface::GenericArg, trait_node_id: NodeId) {
714 let params = ImplicitParamCollector::new(
715 self.resolver.genv.tcx(),
716 &self.resolver.output.path_res_map,
717 ScopeKind::FnTraitInput,
718 )
719 .run(|vis| vis.visit_generic_arg(in_arg));
720 for (ident, kind, node_id) in params {
721 self.define_param(ident, kind, node_id, Some(trait_node_id));
722 }
723 }
724
725 fn on_enum_variant(&mut self, variant: &surface::VariantDef) {
726 let params = ImplicitParamCollector::new(
727 self.resolver.genv.tcx(),
728 &self.resolver.output.path_res_map,
729 ScopeKind::Variant,
730 )
731 .run(|vis| vis.visit_variant(variant));
732 for (ident, kind, node_id) in params {
733 self.define_param(ident, kind, node_id, Some(variant.node_id));
734 }
735 }
736
737 fn on_fn_sig(&mut self, fn_sig: &surface::FnSig) {
738 let params = ImplicitParamCollector::new(
739 self.resolver.genv.tcx(),
740 &self.resolver.output.path_res_map,
741 ScopeKind::FnInput,
742 )
743 .run(|vis| vis.visit_fn_sig(fn_sig));
744 for (ident, kind, param_id) in params {
745 self.define_param(ident, kind, param_id, Some(fn_sig.node_id));
746 }
747 }
748
749 fn on_fn_output(&mut self, output: &surface::FnOutput) {
750 let params = ImplicitParamCollector::new(
751 self.resolver.genv.tcx(),
752 &self.resolver.output.path_res_map,
753 ScopeKind::FnOutput,
754 )
755 .run(|vis| vis.visit_fn_output(output));
756 for (ident, kind, param_id) in params {
757 self.define_param(ident, kind, param_id, Some(output.node_id));
758 }
759 }
760
761 fn on_refine_param(&mut self, param: &surface::RefineParam) {
762 self.define_param(param.ident, fhir::ParamKind::Explicit(param.mode), param.node_id, None);
763 }
764
765 fn on_loc(&mut self, loc: Ident, node_id: NodeId) {
766 self.resolve_ident(loc, node_id);
767 }
768
769 fn on_path(&mut self, path: &surface::ExprPath) {
770 self.resolve_path(path);
771 }
772
773 fn on_base_sort(&mut self, sort: &surface::BaseSort) {
774 match sort {
775 surface::BaseSort::Path(path) => {
776 self.resolve_sort_path(path);
777 }
778 surface::BaseSort::BitVec(_) => {}
779 surface::BaseSort::SortOf(..) => {}
780 }
781 }
782}
783
784struct IllegalBinderVisitor<'a, 'genv, 'tcx> {
785 scopes: Vec<ScopeKind>,
786 resolver: &'a CrateResolver<'genv, 'tcx>,
787 errors: Errors<'genv>,
788}
789
790impl<'a, 'genv, 'tcx> IllegalBinderVisitor<'a, 'genv, 'tcx> {
791 fn new(resolver: &'a mut CrateResolver<'genv, 'tcx>) -> Self {
792 let errors = Errors::new(resolver.genv.sess());
793 Self { scopes: vec![], resolver, errors }
794 }
795
796 fn run(self, f: impl FnOnce(&mut ScopedVisitorWrapper<Self>)) -> Result {
797 let mut vis = self.wrap();
798 f(&mut vis);
799 vis.0.errors.into_result()
800 }
801}
802
803impl ScopedVisitor for IllegalBinderVisitor<'_, '_, '_> {
804 fn is_box(&self, segment: &surface::PathSegment) -> bool {
805 self.resolver
806 .output
807 .path_res_map
808 .get(&segment.node_id)
809 .map(|r| r.is_box(self.resolver.genv.tcx()))
810 .unwrap_or(false)
811 }
812
813 fn enter_scope(&mut self, kind: ScopeKind) -> ControlFlow<()> {
814 self.scopes.push(kind);
815 ControlFlow::Continue(())
816 }
817
818 fn exit_scope(&mut self) {
819 self.scopes.pop();
820 }
821
822 fn on_implicit_param(&mut self, ident: Ident, param_kind: fhir::ParamKind, _: NodeId) {
823 let Some(scope_kind) = self.scopes.last() else { return };
824 let (allowed, bind_kind) = match param_kind {
825 fhir::ParamKind::At => {
826 (
827 matches!(
828 scope_kind,
829 ScopeKind::FnInput | ScopeKind::FnTraitInput | ScopeKind::Variant
830 ),
831 surface::BindKind::At,
832 )
833 }
834 fhir::ParamKind::Pound => {
835 (matches!(scope_kind, ScopeKind::FnOutput), surface::BindKind::Pound)
836 }
837 fhir::ParamKind::Colon
838 | fhir::ParamKind::Loc
839 | fhir::ParamKind::Error
840 | fhir::ParamKind::Explicit(..) => return,
841 };
842 if !allowed {
843 self.errors
844 .emit(errors::IllegalBinder::new(ident.span, bind_kind));
845 }
846 }
847}
848
849mod errors {
850 use flux_errors::E0999;
851 use flux_macros::Diagnostic;
852 use flux_syntax::surface;
853 use itertools::Itertools;
854 use rustc_span::{Span, Symbol, symbol::Ident};
855
856 #[derive(Diagnostic)]
857 #[diag(desugar_duplicate_param, code = E0999)]
858 pub(super) struct DuplicateParam {
859 #[primary_span]
860 #[label]
861 span: Span,
862 name: Symbol,
863 #[label(desugar_first_use)]
864 first_use: Span,
865 }
866
867 impl DuplicateParam {
868 pub(super) fn new(old_ident: Ident, new_ident: Ident) -> Self {
869 debug_assert_eq!(old_ident.name, new_ident.name);
870 Self { span: new_ident.span, name: new_ident.name, first_use: old_ident.span }
871 }
872 }
873
874 #[derive(Diagnostic)]
875 #[diag(desugar_unresolved_sort, code = E0999)]
876 pub(super) struct UnresolvedSort {
877 #[primary_span]
878 #[label]
879 span: Span,
880 name: String,
881 }
882
883 impl UnresolvedSort {
884 pub(super) fn new(path: &surface::SortPath) -> Self {
885 Self {
886 span: path
887 .segments
888 .iter()
889 .map(|ident| ident.span)
890 .reduce(Span::to)
891 .unwrap_or_default(),
892 name: format!("{}", path.segments.iter().format("::")),
893 }
894 }
895 }
896
897 #[derive(Diagnostic)]
898 #[diag(desugar_unresolved_var, code = E0999)]
899 pub(super) struct UnresolvedVar {
900 #[primary_span]
901 #[label]
902 span: Span,
903 var: String,
904 }
905
906 impl UnresolvedVar {
907 pub(super) fn from_path(path: &surface::ExprPath) -> Self {
908 Self {
909 span: path.span,
910 var: format!(
911 "{}",
912 path.segments
913 .iter()
914 .format_with("::", |s, f| f(&s.ident.name))
915 ),
916 }
917 }
918
919 pub(super) fn from_ident(ident: Ident) -> Self {
920 Self { span: ident.span, var: format!("{ident}") }
921 }
922 }
923
924 #[derive(Diagnostic)]
925 #[diag(desugar_invalid_unrefined_param, code = E0999)]
926 pub(super) struct InvalidUnrefinedParam {
927 #[primary_span]
928 #[label]
929 span: Span,
930 var: Ident,
931 }
932
933 impl InvalidUnrefinedParam {
934 pub(super) fn new(var: Ident) -> Self {
935 Self { var, span: var.span }
936 }
937 }
938
939 #[derive(Diagnostic)]
940 #[diag(desugar_illegal_binder, code = E0999)]
941 pub(super) struct IllegalBinder {
942 #[primary_span]
943 #[label]
944 span: Span,
945 kind: &'static str,
946 }
947
948 impl IllegalBinder {
949 pub(super) fn new(span: Span, kind: surface::BindKind) -> Self {
950 Self { span, kind: kind.token_str() }
951 }
952 }
953}