flux_driver/collector/
mod.rs

1mod annot_stats;
2mod detached_specs;
3mod extern_specs;
4
5use std::{collections::HashMap, iter};
6
7use annot_stats::Stats;
8use extern_specs::ExternSpecCollector;
9use flux_common::{
10    iter::IterExt,
11    result::{ErrorCollector, ResultExt},
12    tracked_span_assert_eq,
13};
14use flux_config::{self as config, OverflowMode, PartialInferOpts, SmtSolver};
15use flux_errors::{Errors, FluxSession};
16use flux_middle::Specs;
17use flux_syntax::{
18    ParseResult, ParseSess,
19    surface::{self, NodeId, Trusted},
20};
21use rustc_ast::{MetaItemInner, MetaItemKind, tokenstream::TokenStream};
22use rustc_data_structures::fx::FxIndexMap;
23use rustc_errors::ErrorGuaranteed;
24use rustc_hir::{
25    self as hir, Attribute, CRATE_OWNER_ID, EnumDef, ImplItemKind, Item, ItemKind, OwnerId,
26    VariantData,
27    def::DefKind,
28    def_id::{CRATE_DEF_ID, DefId, LocalDefId},
29};
30use rustc_middle::ty::TyCtxt;
31use rustc_span::{Ident, Span, Symbol, SyntaxContext};
32
33use crate::collector::detached_specs::DetachedSpecsCollector;
34type Result<T = ()> = std::result::Result<T, ErrorGuaranteed>;
35
36pub(crate) struct SpecCollector<'sess, 'tcx> {
37    tcx: TyCtxt<'tcx>,
38    parse_sess: ParseSess,
39    specs: Specs,
40    errors: Errors<'sess>,
41    stats: Stats,
42}
43
44macro_rules! attr_name {
45    ($kind:ident) => {{
46        let _ = FluxAttrKind::$kind;
47        stringify!($kind)
48    }};
49}
50
51impl<'tcx> hir::intravisit::Visitor<'tcx> for SpecCollector<'_, 'tcx> {
52    type NestedFilter = rustc_middle::hir::nested_filter::All;
53
54    fn maybe_tcx(&mut self) -> Self::MaybeTyCtxt {
55        self.tcx
56    }
57
58    fn visit_item(&mut self, item: &'tcx Item<'tcx>) {
59        let _ = self.collect_item(item);
60    }
61
62    fn visit_trait_item(&mut self, trait_item: &'tcx rustc_hir::TraitItem<'tcx>) {
63        let _ = self.collect_trait_item(trait_item);
64    }
65
66    fn visit_impl_item(&mut self, impl_item: &'tcx rustc_hir::ImplItem<'tcx>) {
67        let _ = self.collect_impl_item(impl_item);
68    }
69}
70
71impl<'a, 'tcx> SpecCollector<'a, 'tcx> {
72    pub(crate) fn collect(tcx: TyCtxt<'tcx>, sess: &'a FluxSession) -> Result<Specs> {
73        let mut collector = Self {
74            tcx,
75            parse_sess: ParseSess::default(),
76            specs: Specs::default(),
77            errors: Errors::new(sess),
78            stats: Default::default(),
79        };
80
81        let _ = collector.collect_crate();
82        tcx.hir_walk_toplevel_module(&mut collector);
83
84        if config::annots() {
85            collector.stats.save(tcx).unwrap();
86        }
87
88        collector.errors.into_result()?;
89
90        Ok(collector.specs)
91    }
92
93    fn collect_crate(&mut self) -> Result {
94        let mut attrs = self.parse_attrs_and_report_dups(CRATE_DEF_ID)?;
95        DetachedSpecsCollector::collect(self, &mut attrs, CRATE_DEF_ID)?;
96        self.collect_mod(CRATE_OWNER_ID, attrs)
97    }
98
99    fn collect_item(&mut self, item: &'tcx Item<'tcx>) -> Result {
100        let owner_id = item.owner_id;
101
102        let mut attrs = self.parse_attrs_and_report_dups(owner_id.def_id)?;
103
104        // Get the parent module's LocalDefId
105        let module_id = self
106            .tcx
107            .parent_module_from_def_id(owner_id.def_id)
108            .to_local_def_id();
109        DetachedSpecsCollector::collect(self, &mut attrs, module_id)?;
110
111        match &item.kind {
112            ItemKind::Fn { .. } => {
113                if attrs.has_attrs() {
114                    let fn_sig = attrs.fn_sig();
115                    self.check_fn_sig_name(owner_id, fn_sig.as_ref())?;
116                    let node_id = self.next_node_id();
117                    self.insert_item(
118                        owner_id,
119                        surface::Item {
120                            attrs: attrs.into_attr_vec(),
121                            kind: surface::ItemKind::Fn(fn_sig),
122                            node_id,
123                        },
124                    )?;
125                }
126            }
127            ItemKind::Struct(_, _, variant) => {
128                self.collect_struct_def(owner_id, attrs, variant)?;
129            }
130            ItemKind::Union(_, _, variant) => {
131                // currently no refinements on unions
132                tracked_span_assert_eq!(attrs.items().is_empty(), true);
133                self.collect_struct_def(owner_id, attrs, variant)?;
134            }
135            ItemKind::Enum(_, _, enum_def) => {
136                self.collect_enum_def(owner_id, attrs, enum_def)?;
137            }
138            ItemKind::Mod(..) => self.collect_mod(owner_id, attrs)?,
139            ItemKind::TyAlias(..) => self.collect_type_alias(owner_id, attrs)?,
140            ItemKind::Impl(..) => self.collect_impl(owner_id, attrs)?,
141            ItemKind::Trait(..) => self.collect_trait(owner_id, attrs)?,
142            ItemKind::Const(.., body_id) => {
143                // The flux-rs macro puts defs as an outer attribute on a `const _: () = { }`. We
144                // consider these defs to be defined in the parent of the const.
145                self.specs
146                    .flux_items_by_parent
147                    .entry(self.tcx.hir_get_parent_item(item.hir_id()))
148                    .or_default()
149                    .extend(attrs.items());
150
151                if attrs.extern_spec() {
152                    return ExternSpecCollector::collect(self, *body_id);
153                }
154
155                self.collect_constant(owner_id, attrs)?;
156            }
157            _ => {}
158        }
159        hir::intravisit::walk_item(self, item);
160        Ok(())
161    }
162
163    fn collect_trait_item(&mut self, trait_item: &'tcx rustc_hir::TraitItem<'tcx>) -> Result {
164        let owner_id = trait_item.owner_id;
165
166        let mut attrs = self.parse_attrs_and_report_dups(owner_id.def_id)?;
167        if let rustc_hir::TraitItemKind::Fn(_, _) = trait_item.kind
168            && attrs.has_attrs()
169        {
170            let sig = attrs.fn_sig();
171            self.check_fn_sig_name(owner_id, sig.as_ref())?;
172            let node_id = self.next_node_id();
173            self.insert_trait_item(
174                owner_id,
175                surface::TraitItemFn { attrs: attrs.into_attr_vec(), sig, node_id },
176            )?;
177        }
178        hir::intravisit::walk_trait_item(self, trait_item);
179        Ok(())
180    }
181
182    fn collect_impl_item(&mut self, impl_item: &'tcx rustc_hir::ImplItem<'tcx>) -> Result {
183        let owner_id = impl_item.owner_id;
184
185        let mut attrs = self.parse_attrs_and_report_dups(owner_id.def_id)?;
186
187        if let ImplItemKind::Fn(..) = &impl_item.kind
188            && attrs.has_attrs()
189        {
190            let sig = attrs.fn_sig();
191            self.check_fn_sig_name(owner_id, sig.as_ref())?;
192            let node_id = self.next_node_id();
193            self.insert_impl_item(
194                owner_id,
195                surface::ImplItemFn { attrs: attrs.into_attr_vec(), sig, node_id },
196            )?;
197        }
198        hir::intravisit::walk_impl_item(self, impl_item);
199        Ok(())
200    }
201
202    fn collect_mod(&mut self, module_id: OwnerId, mut attrs: FluxAttrs) -> Result {
203        self.specs
204            .flux_items_by_parent
205            .entry(module_id)
206            .or_default()
207            .extend(attrs.items());
208
209        if attrs.has_attrs() {
210            let node_id = self.next_node_id();
211            self.insert_item(
212                module_id,
213                surface::Item {
214                    attrs: attrs.into_attr_vec(),
215                    kind: surface::ItemKind::Mod,
216                    node_id,
217                },
218            )?;
219        }
220
221        Ok(())
222    }
223
224    fn collect_trait(&mut self, owner_id: OwnerId, mut attrs: FluxAttrs) -> Result {
225        if !attrs.has_attrs() {
226            return Ok(());
227        }
228
229        let generics = attrs.generics();
230        let assoc_refinements = attrs.trait_assoc_refts();
231
232        let node_id = self.next_node_id();
233        self.insert_item(
234            owner_id,
235            surface::Item {
236                attrs: attrs.into_attr_vec(),
237                kind: surface::ItemKind::Trait(surface::Trait { generics, assoc_refinements }),
238                node_id,
239            },
240        )
241    }
242
243    fn collect_impl(&mut self, owner_id: OwnerId, mut attrs: FluxAttrs) -> Result {
244        if !attrs.has_attrs() {
245            return Ok(());
246        }
247
248        let generics = attrs.generics();
249        let assoc_refinements = attrs.impl_assoc_refts();
250
251        let node_id = self.next_node_id();
252        self.insert_item(
253            owner_id,
254            surface::Item {
255                attrs: attrs.into_attr_vec(),
256                kind: surface::ItemKind::Impl(surface::Impl { generics, assoc_refinements }),
257                node_id,
258            },
259        )
260    }
261
262    fn collect_type_alias(&mut self, owner_id: OwnerId, mut attrs: FluxAttrs) -> Result {
263        if let Some(ty_alias) = attrs.ty_alias() {
264            let node_id = self.next_node_id();
265            self.insert_item(
266                owner_id,
267                surface::Item {
268                    attrs: attrs.into_attr_vec(),
269                    kind: surface::ItemKind::TyAlias(ty_alias),
270                    node_id,
271                },
272            )?;
273        }
274        Ok(())
275    }
276
277    fn collect_struct_def(
278        &mut self,
279        owner_id: OwnerId,
280        mut attrs: FluxAttrs,
281        data: &VariantData,
282    ) -> Result {
283        let fields: Vec<_> = data
284            .fields()
285            .iter()
286            .take(data.fields().len())
287            .map(|field| self.parse_field(field))
288            .try_collect_exhaust()?;
289
290        // We consider the struct unannotatd if the struct itself doesn't have attrs *and* none of
291        // the fields have attributes.
292        let fields_have_attrs = fields.iter().any(|f| f.is_some());
293        if !attrs.has_attrs() && !fields_have_attrs {
294            return Ok(());
295        }
296
297        let opaque = attrs.opaque();
298        let refined_by = attrs.refined_by();
299        let generics = attrs.generics();
300        let invariants = attrs.invariants();
301
302        // Report an error if the struct is marked as opaque and there's a field with an annotation
303        for (field, hir_field) in iter::zip(&fields, data.fields()) {
304            // The `flux!` macro unconditionally adds a `#[flux_tool::field(..)]` annotations, even
305            // if the struct is opaque so we only consider the field annotated if it's is refined.
306            if opaque
307                && let Some(ty) = field
308                && ty.is_refined()
309            {
310                return Err(self
311                    .errors
312                    .emit(errors::AttrOnOpaque::new(ty.span, hir_field)));
313            }
314        }
315
316        let struct_def = surface::StructDef { generics, refined_by, fields, opaque, invariants };
317        let node_id = self.next_node_id();
318        self.insert_item(
319            owner_id,
320            surface::Item {
321                attrs: attrs.into_attr_vec(),
322                kind: surface::ItemKind::Struct(struct_def),
323                node_id,
324            },
325        )
326    }
327
328    fn parse_constant_spec(&mut self, owner_id: OwnerId, mut attrs: FluxAttrs) -> Result {
329        if let Some(constant) = attrs.constant() {
330            let node_id = self.next_node_id();
331            self.insert_item(
332                owner_id,
333                surface::Item {
334                    attrs: attrs.into_attr_vec(),
335                    kind: surface::ItemKind::Const(constant),
336                    node_id,
337                },
338            )?;
339        }
340        Ok(())
341    }
342
343    fn parse_field(&mut self, field: &rustc_hir::FieldDef) -> Result<Option<surface::Ty>> {
344        let mut attrs = self.parse_attrs_and_report_dups(field.def_id)?;
345        Ok(attrs.field())
346    }
347
348    fn collect_enum_def(
349        &mut self,
350        owner_id: OwnerId,
351        mut attrs: FluxAttrs,
352        enum_def: &EnumDef,
353    ) -> Result {
354        let variants: Vec<_> = enum_def
355            .variants
356            .iter()
357            .take(enum_def.variants.len())
358            .map(|variant| self.parse_variant(variant))
359            .try_collect_exhaust()?;
360
361        // We consider the enum unannotatd if the enum itself doesn't have attrs *and* none of
362        // the variants have attributes.
363        let variants_have_attrs = variants.iter().any(|v| v.is_some());
364        if !attrs.has_attrs() && !variants_have_attrs {
365            return Ok(());
366        }
367
368        let generics = attrs.generics();
369        let refined_by = attrs.refined_by();
370        let reflected = attrs.reflected();
371        let invariants = attrs.invariants();
372
373        // Can't use `refined_by` and `reflected` at the same time
374        if refined_by.is_some() && reflected {
375            let span = self.tcx.def_span(owner_id.to_def_id());
376            return Err(self
377                .errors
378                .emit(errors::ReflectedEnumWithRefinedBy::new(span)));
379        }
380
381        // Report an error if the enum has a refined_by and one of the variants is not annotated
382        for (variant, hir_variant) in iter::zip(&variants, enum_def.variants) {
383            if variant.is_none() && refined_by.is_some() {
384                return Err(self
385                    .errors
386                    .emit(errors::MissingVariant::new(hir_variant.span)));
387            }
388        }
389
390        let enum_def = surface::EnumDef { generics, refined_by, variants, invariants, reflected };
391        let node_id = self.next_node_id();
392        self.insert_item(
393            owner_id,
394            surface::Item {
395                attrs: attrs.into_attr_vec(),
396                kind: surface::ItemKind::Enum(enum_def),
397                node_id,
398            },
399        )
400    }
401
402    fn parse_variant(
403        &mut self,
404        hir_variant: &rustc_hir::Variant,
405    ) -> Result<Option<surface::VariantDef>> {
406        let mut attrs = self.parse_attrs_and_report_dups(hir_variant.def_id)?;
407        Ok(attrs.variant())
408    }
409
410    fn collect_constant(&mut self, owner_id: OwnerId, attrs: FluxAttrs) -> Result {
411        self.parse_constant_spec(owner_id, attrs)
412    }
413
414    fn check_fn_sig_name(&mut self, owner_id: OwnerId, fn_sig: Option<&surface::FnSig>) -> Result {
415        if let Some(fn_sig) = fn_sig
416            && let Some(ident) = fn_sig.ident
417            && let Some(item_ident) = self.tcx.opt_item_ident(owner_id.to_def_id())
418            && ident != item_ident
419        {
420            return Err(self.errors.emit(errors::MismatchedSpecName::new(
421                self.tcx,
422                ident,
423                owner_id.to_def_id(),
424            )));
425        };
426        Ok(())
427    }
428
429    fn parse_attrs_and_report_dups(&mut self, def_id: LocalDefId) -> Result<FluxAttrs> {
430        let attrs = self.parse_flux_attrs(def_id)?;
431        self.report_dups(&attrs)?;
432        Ok(attrs)
433    }
434
435    fn parse_flux_attrs(&mut self, def_id: LocalDefId) -> Result<FluxAttrs> {
436        let def_kind = self.tcx.def_kind(def_id);
437        let hir_id = self.tcx.local_def_id_to_hir_id(def_id);
438        let attrs = self.tcx.hir_attrs(hir_id);
439        let attrs: Vec<_> = attrs
440            .iter()
441            .filter_map(|attr| {
442                if let Attribute::Unparsed(attr_item) = &attr {
443                    match &attr_item.path.segments[..] {
444                        [first, ..] => {
445                            let ident = first.as_str();
446                            if ident == "flux" || ident == "flux_tool" {
447                                Some(attr_item)
448                            } else {
449                                None
450                            }
451                        }
452                        _ => None,
453                    }
454                } else {
455                    None
456                }
457            })
458            .map(|attr_item| self.parse_flux_attr(attr_item, def_kind))
459            .try_collect_exhaust()?;
460
461        Ok(FluxAttrs::new(attrs))
462    }
463
464    fn parse_flux_attr(
465        &mut self,
466        attr_item: &hir::AttrItem,
467        def_kind: DefKind,
468    ) -> Result<FluxAttr> {
469        let invalid_attr_err = |this: &Self| {
470            this.errors
471                .emit(errors::InvalidAttr { span: attr_item_span(attr_item) })
472        };
473
474        let [_, segment] = &attr_item.path.segments[..] else { return Err(invalid_attr_err(self)) };
475
476        let kind = match (segment.as_str(), &attr_item.args) {
477            ("alias", hir::AttrArgs::Delimited(dargs)) => {
478                self.parse(dargs, ParseSess::parse_type_alias, |t| {
479                    FluxAttrKind::TypeAlias(Box::new(t))
480                })?
481            }
482            ("sig" | "spec", hir::AttrArgs::Delimited(dargs)) => {
483                self.parse(dargs, ParseSess::parse_fn_sig, FluxAttrKind::FnSig)?
484            }
485            ("assoc" | "reft", hir::AttrArgs::Delimited(dargs)) => {
486                match def_kind {
487                    DefKind::Trait => {
488                        self.parse(
489                            dargs,
490                            ParseSess::parse_trait_assoc_reft,
491                            FluxAttrKind::TraitAssocReft,
492                        )?
493                    }
494                    DefKind::Impl { .. } => {
495                        self.parse(
496                            dargs,
497                            ParseSess::parse_impl_assoc_reft,
498                            FluxAttrKind::ImplAssocReft,
499                        )?
500                    }
501                    _ => return Err(invalid_attr_err(self)),
502                }
503            }
504            ("qualifiers", hir::AttrArgs::Delimited(dargs)) => {
505                self.parse(dargs, ParseSess::parse_ident_list, FluxAttrKind::QualNames)?
506            }
507            ("reveal", hir::AttrArgs::Delimited(dargs)) => {
508                self.parse(dargs, ParseSess::parse_ident_list, FluxAttrKind::RevealNames)?
509            }
510            ("defs", hir::AttrArgs::Delimited(dargs)) => {
511                self.parse(dargs, ParseSess::parse_flux_item, FluxAttrKind::Items)?
512            }
513            ("refined_by", hir::AttrArgs::Delimited(dargs)) => {
514                self.parse(dargs, ParseSess::parse_refined_by, FluxAttrKind::RefinedBy)?
515            }
516            ("field", hir::AttrArgs::Delimited(dargs)) => {
517                self.parse(dargs, ParseSess::parse_type, FluxAttrKind::Field)?
518            }
519            ("variant", hir::AttrArgs::Delimited(dargs)) => {
520                self.parse(dargs, ParseSess::parse_variant, FluxAttrKind::Variant)?
521            }
522            ("invariant", hir::AttrArgs::Delimited(dargs)) => {
523                self.parse(dargs, ParseSess::parse_expr, FluxAttrKind::Invariant)?
524            }
525            ("constant", hir::AttrArgs::Delimited(dargs)) => {
526                self.parse(dargs, ParseSess::parse_constant_info, FluxAttrKind::Constant)?
527            }
528            ("opts", hir::AttrArgs::Delimited(..)) => {
529                let opts = AttrMap::parse(attr_item)
530                    .emit(&self.errors)?
531                    .try_into_infer_opts()
532                    .emit(&self.errors)?;
533                FluxAttrKind::InferOpts(opts)
534            }
535            ("ignore", hir::AttrArgs::Delimited(dargs)) => {
536                self.parse(dargs, ParseSess::parse_yes_or_no_with_reason, |b| {
537                    FluxAttrKind::Ignore(b.into())
538                })?
539            }
540            ("ignore", hir::AttrArgs::Empty) => FluxAttrKind::Ignore(surface::Ignored::Yes),
541            ("trusted", hir::AttrArgs::Delimited(dargs)) => {
542                self.parse(dargs, ParseSess::parse_yes_or_no_with_reason, |b| {
543                    FluxAttrKind::Trusted(b.into())
544                })?
545            }
546            ("trusted", hir::AttrArgs::Empty) => FluxAttrKind::Trusted(Trusted::Yes),
547            ("trusted_impl", hir::AttrArgs::Delimited(dargs)) => {
548                self.parse(dargs, ParseSess::parse_yes_or_no_with_reason, |b| {
549                    FluxAttrKind::TrustedImpl(b.into())
550                })?
551            }
552            ("proven_externally", hir::AttrArgs::Empty) => FluxAttrKind::ProvenExternally,
553            ("trusted_impl", hir::AttrArgs::Empty) => FluxAttrKind::TrustedImpl(Trusted::Yes),
554            ("opaque", hir::AttrArgs::Empty) => FluxAttrKind::Opaque,
555            ("reflect", hir::AttrArgs::Empty) => FluxAttrKind::Reflect,
556            ("extern_spec", hir::AttrArgs::Empty) => FluxAttrKind::ExternSpec,
557            ("no_panic", hir::AttrArgs::Empty) => FluxAttrKind::NoPanic,
558            ("should_fail", hir::AttrArgs::Empty) => FluxAttrKind::ShouldFail,
559            ("specs", hir::AttrArgs::Delimited(dargs)) => {
560                self.parse(dargs, ParseSess::parse_detached_specs, FluxAttrKind::DetachedSpecs)?
561            }
562            _ => return Err(invalid_attr_err(self)),
563        };
564        if config::annots() {
565            self.stats.add(self.tcx, segment.as_str(), &attr_item.args);
566        }
567        Ok(FluxAttr { kind, span: attr_item_span(attr_item) })
568    }
569
570    fn parse<T>(
571        &mut self,
572        dargs: &rustc_ast::DelimArgs,
573        parser: impl FnOnce(&mut ParseSess, &TokenStream, Span) -> ParseResult<T>,
574        ctor: impl FnOnce(T) -> FluxAttrKind,
575    ) -> Result<FluxAttrKind> {
576        let entire = dargs.dspan.entire().with_ctxt(SyntaxContext::root());
577        parser(&mut self.parse_sess, &dargs.tokens, entire)
578            .map(ctor)
579            .map_err(errors::SyntaxErr::from)
580            .emit(&self.errors)
581    }
582
583    fn report_dups(&mut self, attrs: &FluxAttrs) -> Result {
584        let mut err = None;
585        for (name, dups) in attrs.dups() {
586            for attr in dups {
587                if attr.allow_dups() {
588                    continue;
589                }
590                err.collect(
591                    self.errors
592                        .emit(errors::DuplicatedAttr { span: attr.span, name }),
593                );
594            }
595        }
596        err.into_result()
597    }
598
599    fn insert_item(&mut self, owner_id: OwnerId, item: surface::Item) -> Result {
600        match self.specs.insert_item(owner_id, item) {
601            Some(_) => Err(self.err_multiple_specs(owner_id.to_def_id())),
602            None => Ok(()),
603        }
604    }
605
606    fn insert_trait_item(&mut self, owner_id: OwnerId, item: surface::TraitItemFn) -> Result {
607        match self.specs.insert_trait_item(owner_id, item) {
608            Some(_) => Err(self.err_multiple_specs(owner_id.to_def_id())),
609            None => Ok(()),
610        }
611    }
612
613    fn insert_impl_item(&mut self, owner_id: OwnerId, item: surface::ImplItemFn) -> Result {
614        match self.specs.insert_impl_item(owner_id, item) {
615            Some(_) => Err(self.err_multiple_specs(owner_id.to_def_id())),
616            None => Ok(()),
617        }
618    }
619
620    fn err_multiple_specs(&mut self, def_id: DefId) -> ErrorGuaranteed {
621        let name = self.tcx.def_path_str(def_id);
622        let span = self.tcx.def_span(def_id);
623        let name = Symbol::intern(&name);
624        self.errors
625            .emit(errors::MultipleSpecifications { name, span })
626    }
627
628    fn next_node_id(&mut self) -> NodeId {
629        self.parse_sess.next_node_id()
630    }
631}
632
633#[derive(Debug)]
634struct FluxAttrs {
635    map: FxIndexMap<&'static str, Vec<FluxAttr>>,
636}
637
638#[derive(Debug)]
639struct FluxAttr {
640    kind: FluxAttrKind,
641    span: Span,
642}
643
644#[derive(Debug)]
645enum FluxAttrKind {
646    Trusted(Trusted),
647    TrustedImpl(Trusted),
648    ProvenExternally,
649    Opaque,
650    Reflect,
651    FnSig(surface::FnSig),
652    TraitAssocReft(Vec<surface::TraitAssocReft>),
653    ImplAssocReft(Vec<surface::ImplAssocReft>),
654    RefinedBy(surface::RefineParams),
655    Generics(surface::Generics),
656    QualNames(Vec<Ident>),
657    RevealNames(Vec<Ident>),
658    Items(Vec<surface::FluxItem>),
659    TypeAlias(Box<surface::TyAlias>),
660    Field(surface::Ty),
661    Constant(surface::ConstantInfo),
662    Variant(surface::VariantDef),
663    InferOpts(config::PartialInferOpts),
664    Invariant(surface::Expr),
665    Ignore(surface::Ignored),
666    ShouldFail,
667    ExternSpec,
668    NoPanic,
669    /// See `detachXX.rs`
670    DetachedSpecs(surface::DetachedSpecs),
671}
672
673macro_rules! read_flag {
674    ($self:expr, $kind:ident) => {{ $self.map.get(attr_name!($kind)).is_some() }};
675}
676
677macro_rules! read_attrs {
678    ($self:expr, $kind:ident) => {
679        $self
680            .map
681            .swap_remove(attr_name!($kind))
682            .unwrap_or_else(|| vec![])
683            .into_iter()
684            .filter_map(|attr| if let FluxAttrKind::$kind(v) = attr.kind { Some(v) } else { None })
685            .collect::<Vec<_>>()
686    };
687}
688
689macro_rules! read_attr {
690    ($self:expr, $kind:ident) => {
691        read_attrs!($self, $kind).pop()
692    };
693}
694
695impl FluxAttr {
696    pub fn allow_dups(&self) -> bool {
697        matches!(
698            &self.kind,
699            FluxAttrKind::Invariant(..)
700                | FluxAttrKind::TraitAssocReft(..)
701                | FluxAttrKind::ImplAssocReft(..)
702        )
703    }
704}
705
706impl FluxAttrs {
707    fn new(attrs: Vec<FluxAttr>) -> Self {
708        let mut map: FxIndexMap<&'static str, Vec<FluxAttr>> = Default::default();
709        for attr in attrs {
710            map.entry(attr.kind.name()).or_default().push(attr);
711        }
712        FluxAttrs { map }
713    }
714
715    fn has_attrs(&self) -> bool {
716        !self.map.is_empty()
717    }
718
719    fn dups(&self) -> impl Iterator<Item = (&'static str, &[FluxAttr])> {
720        self.map
721            .iter()
722            .filter(|(_, attrs)| attrs.len() > 1)
723            .map(|(name, attrs)| (*name, &attrs[1..]))
724    }
725
726    fn opaque(&self) -> bool {
727        read_flag!(self, Opaque)
728    }
729
730    fn reflected(&self) -> bool {
731        read_flag!(self, Reflect)
732    }
733
734    fn items(&mut self) -> Vec<surface::FluxItem> {
735        read_attrs!(self, Items).into_iter().flatten().collect()
736    }
737
738    fn fn_sig(&mut self) -> Option<surface::FnSig> {
739        read_attr!(self, FnSig)
740    }
741
742    fn ty_alias(&mut self) -> Option<Box<surface::TyAlias>> {
743        read_attr!(self, TypeAlias)
744    }
745
746    fn refined_by(&mut self) -> Option<surface::RefineParams> {
747        read_attr!(self, RefinedBy)
748    }
749
750    fn generics(&mut self) -> Option<surface::Generics> {
751        read_attr!(self, Generics)
752    }
753
754    fn trait_assoc_refts(&mut self) -> Vec<surface::TraitAssocReft> {
755        read_attrs!(self, TraitAssocReft)
756            .into_iter()
757            .flatten()
758            .collect()
759    }
760
761    fn impl_assoc_refts(&mut self) -> Vec<surface::ImplAssocReft> {
762        read_attrs!(self, ImplAssocReft)
763            .into_iter()
764            .flatten()
765            .collect()
766    }
767
768    fn field(&mut self) -> Option<surface::Ty> {
769        read_attr!(self, Field)
770    }
771
772    fn constant(&mut self) -> Option<surface::ConstantInfo> {
773        read_attr!(self, Constant)
774    }
775
776    fn variant(&mut self) -> Option<surface::VariantDef> {
777        read_attr!(self, Variant)
778    }
779
780    fn invariants(&mut self) -> Vec<surface::Expr> {
781        read_attrs!(self, Invariant)
782    }
783
784    fn extern_spec(&self) -> bool {
785        read_flag!(self, ExternSpec)
786    }
787
788    fn detached_specs(&mut self) -> Option<surface::DetachedSpecs> {
789        read_attr!(self, DetachedSpecs)
790    }
791
792    fn into_attr_vec(self) -> Vec<surface::Attr> {
793        let mut attrs = vec![];
794        for attr in self.map.into_values().flatten() {
795            let attr = match attr.kind {
796                FluxAttrKind::Trusted(trusted) => surface::Attr::Trusted(trusted),
797                FluxAttrKind::TrustedImpl(trusted) => surface::Attr::TrustedImpl(trusted),
798                FluxAttrKind::ProvenExternally => surface::Attr::ProvenExternally,
799                FluxAttrKind::QualNames(names) => surface::Attr::Qualifiers(names),
800                FluxAttrKind::RevealNames(names) => surface::Attr::Reveal(names),
801                FluxAttrKind::InferOpts(opts) => surface::Attr::InferOpts(opts),
802                FluxAttrKind::Ignore(ignored) => surface::Attr::Ignore(ignored),
803                FluxAttrKind::ShouldFail => surface::Attr::ShouldFail,
804                FluxAttrKind::NoPanic => surface::Attr::NoPanic,
805                FluxAttrKind::Opaque
806                | FluxAttrKind::Reflect
807                | FluxAttrKind::FnSig(_)
808                | FluxAttrKind::TraitAssocReft(_)
809                | FluxAttrKind::ImplAssocReft(_)
810                | FluxAttrKind::RefinedBy(_)
811                | FluxAttrKind::Generics(_)
812                | FluxAttrKind::Items(_)
813                | FluxAttrKind::TypeAlias(_)
814                | FluxAttrKind::Field(_)
815                | FluxAttrKind::Constant(_)
816                | FluxAttrKind::Variant(_)
817                | FluxAttrKind::Invariant(_)
818                | FluxAttrKind::ExternSpec
819                | FluxAttrKind::DetachedSpecs(_) => continue,
820            };
821            attrs.push(attr);
822        }
823        attrs
824    }
825}
826
827impl FluxAttrKind {
828    fn name(&self) -> &'static str {
829        match self {
830            FluxAttrKind::Trusted(_) => attr_name!(Trusted),
831            FluxAttrKind::TrustedImpl(_) => attr_name!(TrustedImpl),
832            FluxAttrKind::ProvenExternally => attr_name!(ProvenExternally),
833            FluxAttrKind::Opaque => attr_name!(Opaque),
834            FluxAttrKind::Reflect => attr_name!(Reflect),
835            FluxAttrKind::FnSig(_) => attr_name!(FnSig),
836            FluxAttrKind::TraitAssocReft(_) => attr_name!(TraitAssocReft),
837            FluxAttrKind::ImplAssocReft(_) => attr_name!(ImplAssocReft),
838            FluxAttrKind::RefinedBy(_) => attr_name!(RefinedBy),
839            FluxAttrKind::Generics(_) => attr_name!(Generics),
840            FluxAttrKind::Items(_) => attr_name!(Items),
841            FluxAttrKind::QualNames(_) => attr_name!(QualNames),
842            FluxAttrKind::RevealNames(_) => attr_name!(RevealNames),
843            FluxAttrKind::Field(_) => attr_name!(Field),
844            FluxAttrKind::Constant(_) => attr_name!(Constant),
845            FluxAttrKind::Variant(_) => attr_name!(Variant),
846            FluxAttrKind::TypeAlias(_) => attr_name!(TypeAlias),
847            FluxAttrKind::InferOpts(_) => attr_name!(InferOpts),
848            FluxAttrKind::Ignore(_) => attr_name!(Ignore),
849            FluxAttrKind::Invariant(_) => attr_name!(Invariant),
850            FluxAttrKind::ShouldFail => attr_name!(ShouldFail),
851            FluxAttrKind::ExternSpec => attr_name!(ExternSpec),
852            FluxAttrKind::DetachedSpecs(_) => attr_name!(DetachedSpecs),
853            FluxAttrKind::NoPanic => attr_name!(NoPanic),
854        }
855    }
856}
857
858#[derive(Debug)]
859struct AttrMapValue {
860    setting: Symbol,
861    span: Span,
862}
863
864#[derive(Debug)]
865struct AttrMap {
866    map: HashMap<String, AttrMapValue>,
867}
868
869macro_rules! try_read_setting {
870    ($self:expr, $setting:ident, $type:ident, $cfg:expr) => {{
871        let val =
872            if let Some(AttrMapValue { setting, span }) = $self.map.remove(stringify!($setting)) {
873                let parse_result = setting.as_str().parse::<$type>();
874                if let Ok(val) = parse_result {
875                    Some(val)
876                } else {
877                    return Err(errors::AttrMapErr {
878                        span,
879                        message: format!(
880                            "incorrect type in value for setting `{}`, expected {}",
881                            stringify!($setting),
882                            stringify!($type)
883                        ),
884                    });
885                }
886            } else {
887                None
888            };
889        $cfg.$setting = val;
890    }};
891}
892
893type AttrMapErr<T = ()> = std::result::Result<T, errors::AttrMapErr>;
894
895impl AttrMap {
896    fn parse(attr_item: &hir::AttrItem) -> AttrMapErr<Self> {
897        let mut map = Self { map: HashMap::new() };
898        let err = || {
899            Err(errors::AttrMapErr {
900                span: attr_item_span(attr_item),
901                message: "bad syntax".to_string(),
902            })
903        };
904        let hir::AttrArgs::Delimited(d) = &attr_item.args else { return err() };
905        let Some(items) = MetaItemKind::list_from_tokens(d.tokens.clone()) else { return err() };
906        for item in items {
907            map.parse_entry(&item)?;
908        }
909        Ok(map)
910    }
911
912    fn parse_entry(&mut self, nested_item: &MetaItemInner) -> AttrMapErr {
913        match nested_item {
914            MetaItemInner::MetaItem(item) => {
915                let name = item.name().map(|sym| sym.to_ident_string());
916                let span = item.span;
917                if let Some(name) = name {
918                    if self.map.contains_key(&name) {
919                        return Err(errors::AttrMapErr {
920                            span,
921                            message: format!("duplicated key `{name}`"),
922                        });
923                    }
924
925                    // TODO: support types of values other than strings
926                    let value = item.name_value_literal().ok_or_else(|| {
927                        errors::AttrMapErr { span, message: "unsupported value".to_string() }
928                    })?;
929
930                    let setting = AttrMapValue { setting: value.symbol, span: item.span };
931                    self.map.insert(name, setting);
932                    return Ok(());
933                }
934                Err(errors::AttrMapErr { span, message: "bad setting name".to_string() })
935            }
936            MetaItemInner::Lit(_) => {
937                Err(errors::AttrMapErr {
938                    span: nested_item.span(),
939                    message: "unsupported item".to_string(),
940                })
941            }
942        }
943    }
944
945    fn try_into_infer_opts(&mut self) -> AttrMapErr<PartialInferOpts> {
946        let mut infer_opts = PartialInferOpts::default();
947        try_read_setting!(self, allow_uninterpreted_cast, bool, infer_opts);
948        try_read_setting!(self, check_overflow, OverflowMode, infer_opts);
949        try_read_setting!(self, scrape_quals, bool, infer_opts);
950        try_read_setting!(self, solver, SmtSolver, infer_opts);
951
952        if let Some((name, setting)) = self.map.iter().next() {
953            return Err(errors::AttrMapErr {
954                span: setting.span,
955                message: format!("invalid crate cfg keyword `{name}`"),
956            });
957        }
958
959        Ok(infer_opts)
960    }
961}
962
963fn attr_item_span(attr_item: &hir::AttrItem) -> Span {
964    attr_args_span(&attr_item.args)
965        .map_or(attr_item.path.span, |args_span| attr_item.path.span.to(args_span))
966}
967
968fn attr_args_span(attr_args: &hir::AttrArgs) -> Option<Span> {
969    match attr_args {
970        hir::AttrArgs::Empty => None,
971        hir::AttrArgs::Delimited(args) => Some(args.dspan.entire()),
972        hir::AttrArgs::Eq { eq_span, expr } => Some(eq_span.to(expr.span)),
973    }
974}
975
976mod errors {
977    use flux_errors::E0999;
978    use flux_macros::Diagnostic;
979    use flux_syntax::surface::ExprPath;
980    use itertools::Itertools;
981    use rustc_errors::{Diag, DiagCtxtHandle, Diagnostic, Level};
982    use rustc_hir::def_id::DefId;
983    use rustc_middle::ty::TyCtxt;
984    use rustc_span::{ErrorGuaranteed, Span, Symbol, symbol::Ident};
985
986    #[derive(Diagnostic)]
987    #[diag(driver_duplicated_attr, code = E0999)]
988    pub(super) struct DuplicatedAttr {
989        #[primary_span]
990        pub span: Span,
991        pub name: &'static str,
992    }
993
994    #[derive(Diagnostic)]
995    #[diag(driver_invalid_attr, code = E0999)]
996    pub(super) struct InvalidAttr {
997        #[primary_span]
998        pub span: Span,
999    }
1000
1001    #[derive(Diagnostic)]
1002    #[diag(driver_invalid_attr_map, code = E0999)]
1003    pub(super) struct AttrMapErr {
1004        #[primary_span]
1005        pub span: Span,
1006        pub message: String,
1007    }
1008
1009    #[derive(Diagnostic)]
1010    #[diag(driver_unresolved_specification, code = E0999)]
1011    pub(super) struct UnresolvedSpecification {
1012        #[primary_span]
1013        pub span: Span,
1014        pub ident: Ident,
1015        pub thing: String,
1016    }
1017
1018    impl UnresolvedSpecification {
1019        pub(super) fn new(path: &ExprPath, thing: &str) -> Self {
1020            let span = path.span;
1021            let ident = path
1022                .segments
1023                .last()
1024                .map_or_else(|| Ident::with_dummy_span(Symbol::intern("")), |seg| seg.ident);
1025            Self { span, ident, thing: thing.to_string() }
1026        }
1027    }
1028
1029    #[derive(Diagnostic)]
1030    #[diag(driver_multiple_specifications, code = E0999)]
1031    pub(super) struct MultipleSpecifications {
1032        #[primary_span]
1033        pub span: Span,
1034        pub name: Symbol,
1035    }
1036
1037    pub(super) struct SyntaxErr(flux_syntax::ParseError);
1038
1039    impl From<flux_syntax::ParseError> for SyntaxErr {
1040        fn from(err: flux_syntax::ParseError) -> Self {
1041            SyntaxErr(err)
1042        }
1043    }
1044
1045    impl<'sess> Diagnostic<'sess> for SyntaxErr {
1046        fn into_diag(
1047            self,
1048            dcx: DiagCtxtHandle<'sess>,
1049            level: Level,
1050        ) -> Diag<'sess, ErrorGuaranteed> {
1051            use flux_syntax::ParseErrorKind;
1052            let mut diag = Diag::new(dcx, level, crate::fluent_generated::driver_syntax_err);
1053            diag.code(E0999).span(self.0.span).span_label(
1054                self.0.span,
1055                match &self.0.kind {
1056                    ParseErrorKind::UnexpectedEof => "unexpected end of input".to_string(),
1057                    ParseErrorKind::UnexpectedToken { expected } => {
1058                        match &expected[..] {
1059                            [] => "unexpected token".to_string(),
1060                            [a] => format!("unexpected token, expected `{a}`"),
1061                            [a, b] => format!("unexpected token, expected `{a}` or `{b}`"),
1062                            [prefix @ .., last] => {
1063                                format!(
1064                                    "unexpected token, expected one of {}, or `{last}`",
1065                                    prefix
1066                                        .iter()
1067                                        .format_with(", ", |it, f| f(&format_args!("`{it}`")))
1068                                )
1069                            }
1070                        }
1071                    }
1072                    ParseErrorKind::CannotBeChained => "operator cannot be chained".to_string(),
1073                    ParseErrorKind::InvalidBinding => {
1074                        "identifier must be a mutable reference".to_string()
1075                    }
1076                    ParseErrorKind::InvalidSort => {
1077                        "property parameter sort is inherited from the primitive operator"
1078                            .to_string()
1079                    }
1080                    ParseErrorKind::InvalidDetachedSpec => {
1081                        "detached spec requires an identifier name".to_string()
1082                    }
1083                },
1084            );
1085            diag
1086        }
1087    }
1088
1089    #[derive(Diagnostic)]
1090    #[diag(driver_attr_on_opaque, code = E0999)]
1091    pub(super) struct AttrOnOpaque {
1092        #[primary_span]
1093        span: Span,
1094        #[label]
1095        field_span: Span,
1096    }
1097
1098    impl AttrOnOpaque {
1099        pub(super) fn new(span: Span, field: &rustc_hir::FieldDef) -> Self {
1100            let field_span = field.ident.span;
1101            Self { span, field_span }
1102        }
1103    }
1104
1105    #[derive(Diagnostic)]
1106    #[diag(driver_reflected_enum_with_refined_by, code = E0999)]
1107    pub(super) struct ReflectedEnumWithRefinedBy {
1108        #[primary_span]
1109        #[label]
1110        span: Span,
1111    }
1112    impl ReflectedEnumWithRefinedBy {
1113        pub(super) fn new(span: Span) -> Self {
1114            Self { span }
1115        }
1116    }
1117
1118    #[derive(Diagnostic)]
1119    #[diag(driver_missing_variant, code = E0999)]
1120    #[note]
1121    pub(super) struct MissingVariant {
1122        #[primary_span]
1123        #[label]
1124        span: Span,
1125    }
1126
1127    impl MissingVariant {
1128        pub(super) fn new(span: Span) -> Self {
1129            Self { span }
1130        }
1131    }
1132
1133    #[derive(Diagnostic)]
1134    #[diag(driver_mismatched_spec_name, code = E0999)]
1135    pub(super) struct MismatchedSpecName {
1136        #[primary_span]
1137        #[label]
1138        span: Span,
1139        #[label(driver_item_def_ident)]
1140        item_ident_span: Span,
1141        item_ident: Ident,
1142        def_descr: &'static str,
1143    }
1144
1145    impl MismatchedSpecName {
1146        pub(super) fn new(tcx: TyCtxt, ident: Ident, def_id: DefId) -> Self {
1147            let def_descr = tcx.def_descr(def_id);
1148            let item_ident = tcx.opt_item_ident(def_id).unwrap();
1149            Self { span: ident.span, item_ident_span: item_ident.span, item_ident, def_descr }
1150        }
1151    }
1152}