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(_) | surface::BaseTyKind::Ptr(..) => {
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 if segment.name == sym::ptr {
639 Some(fhir::SortRes::PrimSort(fhir::PrimSort::RawPtr))
640 } else {
641 None
642 }
643 }
644
645 pub(crate) fn finish(self) -> Result {
646 let param_id_gen = IndexGen::new();
647 let mut params = FxIndexMap::default();
648
649 for (node_id, res) in self.path_res_map {
652 let res = res.map_param_id(|param_id| {
653 *params
654 .entry(param_id)
655 .or_insert_with(|| param_id_gen.fresh())
656 });
657 self.resolver.output.expr_path_res_map.insert(node_id, res);
658 }
659
660 for (param_id, param_def) in self.param_defs {
663 let name = match param_def.kind {
664 fhir::ParamKind::Colon => {
665 let Some(name) = params.get(¶m_id) else { continue };
666 *name
667 }
668 fhir::ParamKind::Error => continue,
669 _ => {
670 params
671 .get(¶m_id)
672 .copied()
673 .unwrap_or_else(|| param_id_gen.fresh())
674 }
675 };
676 let output = &mut self.resolver.output;
677 output
678 .param_res_map
679 .insert(param_id, (name, param_def.kind));
680
681 if let Some(scope) = param_def.scope {
682 output
683 .implicit_params
684 .entry(scope)
685 .or_default()
686 .push((param_def.ident, param_id));
687 }
688 }
689 self.errors.to_result()
690 }
691
692 fn resolver_output(&self) -> &ResolverOutput {
693 &self.resolver.output
694 }
695}
696
697impl ScopedVisitor for RefinementResolver<'_, '_, '_> {
698 fn is_box(&self, segment: &surface::PathSegment) -> bool {
699 self.resolver_output()
700 .path_res_map
701 .get(&segment.node_id)
702 .map(|r| r.is_box(self.resolver.genv.tcx()))
703 .unwrap_or(false)
704 }
705
706 fn enter_scope(&mut self, kind: ScopeKind) -> ControlFlow<()> {
707 self.scopes.push(Scope::new(kind));
708 ControlFlow::Continue(())
709 }
710
711 fn exit_scope(&mut self) {
712 self.scopes.pop();
713 }
714
715 fn on_fn_trait_input(&mut self, in_arg: &surface::GenericArg, trait_node_id: NodeId) {
716 let params = ImplicitParamCollector::new(
717 self.resolver.genv.tcx(),
718 &self.resolver.output.path_res_map,
719 ScopeKind::FnTraitInput,
720 )
721 .run(|vis| vis.visit_generic_arg(in_arg));
722 for (ident, kind, node_id) in params {
723 self.define_param(ident, kind, node_id, Some(trait_node_id));
724 }
725 }
726
727 fn on_enum_variant(&mut self, variant: &surface::VariantDef) {
728 let params = ImplicitParamCollector::new(
729 self.resolver.genv.tcx(),
730 &self.resolver.output.path_res_map,
731 ScopeKind::Variant,
732 )
733 .run(|vis| vis.visit_variant(variant));
734 for (ident, kind, node_id) in params {
735 self.define_param(ident, kind, node_id, Some(variant.node_id));
736 }
737 }
738
739 fn on_fn_sig(&mut self, fn_sig: &surface::FnSig) {
740 let params = ImplicitParamCollector::new(
741 self.resolver.genv.tcx(),
742 &self.resolver.output.path_res_map,
743 ScopeKind::FnInput,
744 )
745 .run(|vis| vis.visit_fn_sig(fn_sig));
746 for (ident, kind, param_id) in params {
747 self.define_param(ident, kind, param_id, Some(fn_sig.node_id));
748 }
749 }
750
751 fn on_fn_output(&mut self, output: &surface::FnOutput) {
752 let params = ImplicitParamCollector::new(
753 self.resolver.genv.tcx(),
754 &self.resolver.output.path_res_map,
755 ScopeKind::FnOutput,
756 )
757 .run(|vis| vis.visit_fn_output(output));
758 for (ident, kind, param_id) in params {
759 self.define_param(ident, kind, param_id, Some(output.node_id));
760 }
761 }
762
763 fn on_refine_param(&mut self, param: &surface::RefineParam) {
764 self.define_param(param.ident, fhir::ParamKind::Explicit(param.mode), param.node_id, None);
765 }
766
767 fn on_loc(&mut self, loc: Ident, node_id: NodeId) {
768 self.resolve_ident(loc, node_id);
769 }
770
771 fn on_path(&mut self, path: &surface::ExprPath) {
772 self.resolve_path(path);
773 }
774
775 fn on_base_sort(&mut self, sort: &surface::BaseSort) {
776 match sort {
777 surface::BaseSort::Path(path) => {
778 self.resolve_sort_path(path);
779 }
780 surface::BaseSort::BitVec(_) => {}
781 surface::BaseSort::SortOf(..) => {}
782 surface::BaseSort::Tuple(sorts) => {
783 for sort in sorts {
784 self.on_base_sort(sort);
785 }
786 }
787 }
788 }
789}
790
791struct IllegalBinderVisitor<'a, 'genv, 'tcx> {
792 scopes: Vec<ScopeKind>,
793 resolver: &'a CrateResolver<'genv, 'tcx>,
794 errors: Errors<'genv>,
795}
796
797impl<'a, 'genv, 'tcx> IllegalBinderVisitor<'a, 'genv, 'tcx> {
798 fn new(resolver: &'a mut CrateResolver<'genv, 'tcx>) -> Self {
799 let errors = Errors::new(resolver.genv.sess());
800 Self { scopes: vec![], resolver, errors }
801 }
802
803 fn run(self, f: impl FnOnce(&mut ScopedVisitorWrapper<Self>)) -> Result {
804 let mut vis = self.wrap();
805 f(&mut vis);
806 vis.0.errors.to_result()
807 }
808}
809
810impl ScopedVisitor for IllegalBinderVisitor<'_, '_, '_> {
811 fn is_box(&self, segment: &surface::PathSegment) -> bool {
812 self.resolver
813 .output
814 .path_res_map
815 .get(&segment.node_id)
816 .map(|r| r.is_box(self.resolver.genv.tcx()))
817 .unwrap_or(false)
818 }
819
820 fn enter_scope(&mut self, kind: ScopeKind) -> ControlFlow<()> {
821 self.scopes.push(kind);
822 ControlFlow::Continue(())
823 }
824
825 fn exit_scope(&mut self) {
826 self.scopes.pop();
827 }
828
829 fn on_implicit_param(&mut self, ident: Ident, param_kind: fhir::ParamKind, _: NodeId) {
830 let Some(scope_kind) = self.scopes.last() else { return };
831 let (allowed, bind_kind) = match param_kind {
832 fhir::ParamKind::At => {
833 (
834 matches!(
835 scope_kind,
836 ScopeKind::FnInput | ScopeKind::FnTraitInput | ScopeKind::Variant
837 ),
838 surface::BindKind::At,
839 )
840 }
841 fhir::ParamKind::Pound => {
842 (matches!(scope_kind, ScopeKind::FnOutput), surface::BindKind::Pound)
843 }
844 fhir::ParamKind::Colon
845 | fhir::ParamKind::Loc
846 | fhir::ParamKind::Error
847 | fhir::ParamKind::Explicit(..) => return,
848 };
849 if !allowed {
850 self.errors
851 .emit(errors::IllegalBinder::new(ident.span, bind_kind));
852 }
853 }
854}
855
856mod errors {
857 use flux_errors::E0999;
858 use flux_macros::Diagnostic;
859 use flux_syntax::surface;
860 use itertools::Itertools;
861 use rustc_span::{Span, Symbol, symbol::Ident};
862
863 #[derive(Diagnostic)]
864 #[diag(desugar_duplicate_param, code = E0999)]
865 pub(super) struct DuplicateParam {
866 #[primary_span]
867 #[label]
868 span: Span,
869 name: Symbol,
870 #[label(desugar_first_use)]
871 first_use: Span,
872 }
873
874 impl DuplicateParam {
875 pub(super) fn new(old_ident: Ident, new_ident: Ident) -> Self {
876 debug_assert_eq!(old_ident.name, new_ident.name);
877 Self { span: new_ident.span, name: new_ident.name, first_use: old_ident.span }
878 }
879 }
880
881 #[derive(Diagnostic)]
882 #[diag(desugar_unresolved_sort, code = E0999)]
883 pub(super) struct UnresolvedSort {
884 #[primary_span]
885 #[label]
886 span: Span,
887 name: String,
888 }
889
890 impl UnresolvedSort {
891 pub(super) fn new(path: &surface::SortPath) -> Self {
892 Self {
893 span: path
894 .segments
895 .iter()
896 .map(|ident| ident.span)
897 .reduce(Span::to)
898 .unwrap_or_default(),
899 name: format!("{}", path.segments.iter().format("::")),
900 }
901 }
902 }
903
904 #[derive(Diagnostic)]
905 #[diag(desugar_unresolved_var, code = E0999)]
906 pub(super) struct UnresolvedVar {
907 #[primary_span]
908 #[label]
909 span: Span,
910 var: String,
911 }
912
913 impl UnresolvedVar {
914 pub(super) fn from_path(path: &surface::ExprPath) -> Self {
915 Self {
916 span: path.span,
917 var: format!(
918 "{}",
919 path.segments
920 .iter()
921 .format_with("::", |s, f| f(&s.ident.name))
922 ),
923 }
924 }
925
926 pub(super) fn from_ident(ident: Ident) -> Self {
927 Self { span: ident.span, var: format!("{ident}") }
928 }
929 }
930
931 #[derive(Diagnostic)]
932 #[diag(desugar_invalid_unrefined_param, code = E0999)]
933 pub(super) struct InvalidUnrefinedParam {
934 #[primary_span]
935 #[label]
936 span: Span,
937 var: Ident,
938 }
939
940 impl InvalidUnrefinedParam {
941 pub(super) fn new(var: Ident) -> Self {
942 Self { var, span: var.span }
943 }
944 }
945
946 #[derive(Diagnostic)]
947 #[diag(desugar_illegal_binder, code = E0999)]
948 pub(super) struct IllegalBinder {
949 #[primary_span]
950 #[label]
951 span: Span,
952 kind: &'static str,
953 }
954
955 impl IllegalBinder {
956 pub(super) fn new(span: Span, kind: surface::BindKind) -> Self {
957 Self { span, kind: kind.token_str() }
958 }
959 }
960}