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 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 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 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 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 for (field, hir_field) in iter::zip(&fields, data.fields()) {
304 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 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 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 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 ("should_fail", hir::AttrArgs::Empty) => FluxAttrKind::ShouldFail,
558 ("specs", hir::AttrArgs::Delimited(dargs)) => {
559 self.parse(dargs, ParseSess::parse_detached_specs, FluxAttrKind::DetachedSpecs)?
560 }
561 _ => return Err(invalid_attr_err(self)),
562 };
563 if config::annots() {
564 self.stats.add(self.tcx, segment.as_str(), &attr_item.args);
565 }
566 Ok(FluxAttr { kind, span: attr_item_span(attr_item) })
567 }
568
569 fn parse<T>(
570 &mut self,
571 dargs: &rustc_ast::DelimArgs,
572 parser: impl FnOnce(&mut ParseSess, &TokenStream, Span) -> ParseResult<T>,
573 ctor: impl FnOnce(T) -> FluxAttrKind,
574 ) -> Result<FluxAttrKind> {
575 let entire = dargs.dspan.entire().with_ctxt(SyntaxContext::root());
576 parser(&mut self.parse_sess, &dargs.tokens, entire)
577 .map(ctor)
578 .map_err(errors::SyntaxErr::from)
579 .emit(&self.errors)
580 }
581
582 fn report_dups(&mut self, attrs: &FluxAttrs) -> Result {
583 let mut err = None;
584 for (name, dups) in attrs.dups() {
585 for attr in dups {
586 if attr.allow_dups() {
587 continue;
588 }
589 err.collect(
590 self.errors
591 .emit(errors::DuplicatedAttr { span: attr.span, name }),
592 );
593 }
594 }
595 err.into_result()
596 }
597
598 fn insert_item(&mut self, owner_id: OwnerId, item: surface::Item) -> Result {
599 match self.specs.insert_item(owner_id, item) {
600 Some(_) => Err(self.err_multiple_specs(owner_id.to_def_id())),
601 None => Ok(()),
602 }
603 }
604
605 fn insert_trait_item(&mut self, owner_id: OwnerId, item: surface::TraitItemFn) -> Result {
606 match self.specs.insert_trait_item(owner_id, item) {
607 Some(_) => Err(self.err_multiple_specs(owner_id.to_def_id())),
608 None => Ok(()),
609 }
610 }
611
612 fn insert_impl_item(&mut self, owner_id: OwnerId, item: surface::ImplItemFn) -> Result {
613 match self.specs.insert_impl_item(owner_id, item) {
614 Some(_) => Err(self.err_multiple_specs(owner_id.to_def_id())),
615 None => Ok(()),
616 }
617 }
618
619 fn err_multiple_specs(&mut self, def_id: DefId) -> ErrorGuaranteed {
620 let name = self.tcx.def_path_str(def_id);
621 let span = self.tcx.def_span(def_id);
622 let name = Symbol::intern(&name);
623 self.errors
624 .emit(errors::MultipleSpecifications { name, span })
625 }
626
627 fn next_node_id(&mut self) -> NodeId {
628 self.parse_sess.next_node_id()
629 }
630}
631
632#[derive(Debug)]
633struct FluxAttrs {
634 map: FxIndexMap<&'static str, Vec<FluxAttr>>,
635}
636
637#[derive(Debug)]
638struct FluxAttr {
639 kind: FluxAttrKind,
640 span: Span,
641}
642
643#[derive(Debug)]
644enum FluxAttrKind {
645 Trusted(Trusted),
646 TrustedImpl(Trusted),
647 ProvenExternally,
648 Opaque,
649 Reflect,
650 FnSig(surface::FnSig),
651 TraitAssocReft(Vec<surface::TraitAssocReft>),
652 ImplAssocReft(Vec<surface::ImplAssocReft>),
653 RefinedBy(surface::RefineParams),
654 Generics(surface::Generics),
655 QualNames(Vec<Ident>),
656 RevealNames(Vec<Ident>),
657 Items(Vec<surface::FluxItem>),
658 TypeAlias(Box<surface::TyAlias>),
659 Field(surface::Ty),
660 Constant(surface::ConstantInfo),
661 Variant(surface::VariantDef),
662 InferOpts(config::PartialInferOpts),
663 Invariant(surface::Expr),
664 Ignore(surface::Ignored),
665 ShouldFail,
666 ExternSpec,
667 DetachedSpecs(surface::DetachedSpecs),
669}
670
671macro_rules! read_flag {
672 ($self:expr, $kind:ident) => {{ $self.map.get(attr_name!($kind)).is_some() }};
673}
674
675macro_rules! read_attrs {
676 ($self:expr, $kind:ident) => {
677 $self
678 .map
679 .swap_remove(attr_name!($kind))
680 .unwrap_or_else(|| vec![])
681 .into_iter()
682 .filter_map(|attr| if let FluxAttrKind::$kind(v) = attr.kind { Some(v) } else { None })
683 .collect::<Vec<_>>()
684 };
685}
686
687macro_rules! read_attr {
688 ($self:expr, $kind:ident) => {
689 read_attrs!($self, $kind).pop()
690 };
691}
692
693impl FluxAttr {
694 pub fn allow_dups(&self) -> bool {
695 matches!(
696 &self.kind,
697 FluxAttrKind::Invariant(..)
698 | FluxAttrKind::TraitAssocReft(..)
699 | FluxAttrKind::ImplAssocReft(..)
700 )
701 }
702}
703
704impl FluxAttrs {
705 fn new(attrs: Vec<FluxAttr>) -> Self {
706 let mut map: FxIndexMap<&'static str, Vec<FluxAttr>> = Default::default();
707 for attr in attrs {
708 map.entry(attr.kind.name()).or_default().push(attr);
709 }
710 FluxAttrs { map }
711 }
712
713 fn has_attrs(&self) -> bool {
714 !self.map.is_empty()
715 }
716
717 fn dups(&self) -> impl Iterator<Item = (&'static str, &[FluxAttr])> {
718 self.map
719 .iter()
720 .filter(|(_, attrs)| attrs.len() > 1)
721 .map(|(name, attrs)| (*name, &attrs[1..]))
722 }
723
724 fn opaque(&self) -> bool {
725 read_flag!(self, Opaque)
726 }
727
728 fn reflected(&self) -> bool {
729 read_flag!(self, Reflect)
730 }
731
732 fn items(&mut self) -> Vec<surface::FluxItem> {
733 read_attrs!(self, Items).into_iter().flatten().collect()
734 }
735
736 fn fn_sig(&mut self) -> Option<surface::FnSig> {
737 read_attr!(self, FnSig)
738 }
739
740 fn ty_alias(&mut self) -> Option<Box<surface::TyAlias>> {
741 read_attr!(self, TypeAlias)
742 }
743
744 fn refined_by(&mut self) -> Option<surface::RefineParams> {
745 read_attr!(self, RefinedBy)
746 }
747
748 fn generics(&mut self) -> Option<surface::Generics> {
749 read_attr!(self, Generics)
750 }
751
752 fn trait_assoc_refts(&mut self) -> Vec<surface::TraitAssocReft> {
753 read_attrs!(self, TraitAssocReft)
754 .into_iter()
755 .flatten()
756 .collect()
757 }
758
759 fn impl_assoc_refts(&mut self) -> Vec<surface::ImplAssocReft> {
760 read_attrs!(self, ImplAssocReft)
761 .into_iter()
762 .flatten()
763 .collect()
764 }
765
766 fn field(&mut self) -> Option<surface::Ty> {
767 read_attr!(self, Field)
768 }
769
770 fn constant(&mut self) -> Option<surface::ConstantInfo> {
771 read_attr!(self, Constant)
772 }
773
774 fn variant(&mut self) -> Option<surface::VariantDef> {
775 read_attr!(self, Variant)
776 }
777
778 fn invariants(&mut self) -> Vec<surface::Expr> {
779 read_attrs!(self, Invariant)
780 }
781
782 fn extern_spec(&self) -> bool {
783 read_flag!(self, ExternSpec)
784 }
785
786 fn detached_specs(&mut self) -> Option<surface::DetachedSpecs> {
787 read_attr!(self, DetachedSpecs)
788 }
789
790 fn into_attr_vec(self) -> Vec<surface::Attr> {
791 let mut attrs = vec![];
792 for attr in self.map.into_values().flatten() {
793 let attr = match attr.kind {
794 FluxAttrKind::Trusted(trusted) => surface::Attr::Trusted(trusted),
795 FluxAttrKind::TrustedImpl(trusted) => surface::Attr::TrustedImpl(trusted),
796 FluxAttrKind::ProvenExternally => surface::Attr::ProvenExternally,
797 FluxAttrKind::QualNames(names) => surface::Attr::Qualifiers(names),
798 FluxAttrKind::RevealNames(names) => surface::Attr::Reveal(names),
799 FluxAttrKind::InferOpts(opts) => surface::Attr::InferOpts(opts),
800 FluxAttrKind::Ignore(ignored) => surface::Attr::Ignore(ignored),
801 FluxAttrKind::ShouldFail => surface::Attr::ShouldFail,
802 FluxAttrKind::Opaque
803 | FluxAttrKind::Reflect
804 | FluxAttrKind::FnSig(_)
805 | FluxAttrKind::TraitAssocReft(_)
806 | FluxAttrKind::ImplAssocReft(_)
807 | FluxAttrKind::RefinedBy(_)
808 | FluxAttrKind::Generics(_)
809 | FluxAttrKind::Items(_)
810 | FluxAttrKind::TypeAlias(_)
811 | FluxAttrKind::Field(_)
812 | FluxAttrKind::Constant(_)
813 | FluxAttrKind::Variant(_)
814 | FluxAttrKind::Invariant(_)
815 | FluxAttrKind::ExternSpec
816 | FluxAttrKind::DetachedSpecs(_) => continue,
817 };
818 attrs.push(attr);
819 }
820 attrs
821 }
822}
823
824impl FluxAttrKind {
825 fn name(&self) -> &'static str {
826 match self {
827 FluxAttrKind::Trusted(_) => attr_name!(Trusted),
828 FluxAttrKind::TrustedImpl(_) => attr_name!(TrustedImpl),
829 FluxAttrKind::ProvenExternally => attr_name!(ProvenExternally),
830 FluxAttrKind::Opaque => attr_name!(Opaque),
831 FluxAttrKind::Reflect => attr_name!(Reflect),
832 FluxAttrKind::FnSig(_) => attr_name!(FnSig),
833 FluxAttrKind::TraitAssocReft(_) => attr_name!(TraitAssocReft),
834 FluxAttrKind::ImplAssocReft(_) => attr_name!(ImplAssocReft),
835 FluxAttrKind::RefinedBy(_) => attr_name!(RefinedBy),
836 FluxAttrKind::Generics(_) => attr_name!(Generics),
837 FluxAttrKind::Items(_) => attr_name!(Items),
838 FluxAttrKind::QualNames(_) => attr_name!(QualNames),
839 FluxAttrKind::RevealNames(_) => attr_name!(RevealNames),
840 FluxAttrKind::Field(_) => attr_name!(Field),
841 FluxAttrKind::Constant(_) => attr_name!(Constant),
842 FluxAttrKind::Variant(_) => attr_name!(Variant),
843 FluxAttrKind::TypeAlias(_) => attr_name!(TypeAlias),
844 FluxAttrKind::InferOpts(_) => attr_name!(InferOpts),
845 FluxAttrKind::Ignore(_) => attr_name!(Ignore),
846 FluxAttrKind::Invariant(_) => attr_name!(Invariant),
847 FluxAttrKind::ShouldFail => attr_name!(ShouldFail),
848 FluxAttrKind::ExternSpec => attr_name!(ExternSpec),
849 FluxAttrKind::DetachedSpecs(_) => attr_name!(DetachedSpecs),
850 }
851 }
852}
853
854#[derive(Debug)]
855struct AttrMapValue {
856 setting: Symbol,
857 span: Span,
858}
859
860#[derive(Debug)]
861struct AttrMap {
862 map: HashMap<String, AttrMapValue>,
863}
864
865macro_rules! try_read_setting {
866 ($self:expr, $setting:ident, $type:ident, $cfg:expr) => {{
867 let val =
868 if let Some(AttrMapValue { setting, span }) = $self.map.remove(stringify!($setting)) {
869 let parse_result = setting.as_str().parse::<$type>();
870 if let Ok(val) = parse_result {
871 Some(val)
872 } else {
873 return Err(errors::AttrMapErr {
874 span,
875 message: format!(
876 "incorrect type in value for setting `{}`, expected {}",
877 stringify!($setting),
878 stringify!($type)
879 ),
880 });
881 }
882 } else {
883 None
884 };
885 $cfg.$setting = val;
886 }};
887}
888
889type AttrMapErr<T = ()> = std::result::Result<T, errors::AttrMapErr>;
890
891impl AttrMap {
892 fn parse(attr_item: &hir::AttrItem) -> AttrMapErr<Self> {
893 let mut map = Self { map: HashMap::new() };
894 let err = || {
895 Err(errors::AttrMapErr {
896 span: attr_item_span(attr_item),
897 message: "bad syntax".to_string(),
898 })
899 };
900 let hir::AttrArgs::Delimited(d) = &attr_item.args else { return err() };
901 let Some(items) = MetaItemKind::list_from_tokens(d.tokens.clone()) else { return err() };
902 for item in items {
903 map.parse_entry(&item)?;
904 }
905 Ok(map)
906 }
907
908 fn parse_entry(&mut self, nested_item: &MetaItemInner) -> AttrMapErr {
909 match nested_item {
910 MetaItemInner::MetaItem(item) => {
911 let name = item.name().map(|sym| sym.to_ident_string());
912 let span = item.span;
913 if let Some(name) = name {
914 if self.map.contains_key(&name) {
915 return Err(errors::AttrMapErr {
916 span,
917 message: format!("duplicated key `{name}`"),
918 });
919 }
920
921 let value = item.name_value_literal().ok_or_else(|| {
923 errors::AttrMapErr { span, message: "unsupported value".to_string() }
924 })?;
925
926 let setting = AttrMapValue { setting: value.symbol, span: item.span };
927 self.map.insert(name, setting);
928 return Ok(());
929 }
930 Err(errors::AttrMapErr { span, message: "bad setting name".to_string() })
931 }
932 MetaItemInner::Lit(_) => {
933 Err(errors::AttrMapErr {
934 span: nested_item.span(),
935 message: "unsupported item".to_string(),
936 })
937 }
938 }
939 }
940
941 fn try_into_infer_opts(&mut self) -> AttrMapErr<PartialInferOpts> {
942 let mut infer_opts = PartialInferOpts::default();
943 try_read_setting!(self, allow_uninterpreted_cast, bool, infer_opts);
944 try_read_setting!(self, check_overflow, OverflowMode, infer_opts);
945 try_read_setting!(self, scrape_quals, bool, infer_opts);
946 try_read_setting!(self, solver, SmtSolver, infer_opts);
947
948 if let Some((name, setting)) = self.map.iter().next() {
949 return Err(errors::AttrMapErr {
950 span: setting.span,
951 message: format!("invalid crate cfg keyword `{name}`"),
952 });
953 }
954
955 Ok(infer_opts)
956 }
957}
958
959fn attr_item_span(attr_item: &hir::AttrItem) -> Span {
960 attr_args_span(&attr_item.args)
961 .map_or(attr_item.path.span, |args_span| attr_item.path.span.to(args_span))
962}
963
964fn attr_args_span(attr_args: &hir::AttrArgs) -> Option<Span> {
965 match attr_args {
966 hir::AttrArgs::Empty => None,
967 hir::AttrArgs::Delimited(args) => Some(args.dspan.entire()),
968 hir::AttrArgs::Eq { eq_span, expr } => Some(eq_span.to(expr.span)),
969 }
970}
971
972mod errors {
973 use flux_errors::E0999;
974 use flux_macros::Diagnostic;
975 use flux_syntax::surface::ExprPath;
976 use itertools::Itertools;
977 use rustc_errors::{Diag, DiagCtxtHandle, Diagnostic, Level};
978 use rustc_hir::def_id::DefId;
979 use rustc_middle::ty::TyCtxt;
980 use rustc_span::{ErrorGuaranteed, Span, Symbol, symbol::Ident};
981
982 #[derive(Diagnostic)]
983 #[diag(driver_duplicated_attr, code = E0999)]
984 pub(super) struct DuplicatedAttr {
985 #[primary_span]
986 pub span: Span,
987 pub name: &'static str,
988 }
989
990 #[derive(Diagnostic)]
991 #[diag(driver_invalid_attr, code = E0999)]
992 pub(super) struct InvalidAttr {
993 #[primary_span]
994 pub span: Span,
995 }
996
997 #[derive(Diagnostic)]
998 #[diag(driver_invalid_attr_map, code = E0999)]
999 pub(super) struct AttrMapErr {
1000 #[primary_span]
1001 pub span: Span,
1002 pub message: String,
1003 }
1004
1005 #[derive(Diagnostic)]
1006 #[diag(driver_unresolved_specification, code = E0999)]
1007 pub(super) struct UnresolvedSpecification {
1008 #[primary_span]
1009 pub span: Span,
1010 pub ident: Ident,
1011 pub thing: String,
1012 }
1013
1014 impl UnresolvedSpecification {
1015 pub(super) fn new(path: &ExprPath, thing: &str) -> Self {
1016 let span = path.span;
1017 let ident = path
1018 .segments
1019 .last()
1020 .map_or_else(|| Ident::with_dummy_span(Symbol::intern("")), |seg| seg.ident);
1021 Self { span, ident, thing: thing.to_string() }
1022 }
1023 }
1024
1025 #[derive(Diagnostic)]
1026 #[diag(driver_multiple_specifications, code = E0999)]
1027 pub(super) struct MultipleSpecifications {
1028 #[primary_span]
1029 pub span: Span,
1030 pub name: Symbol,
1031 }
1032
1033 pub(super) struct SyntaxErr(flux_syntax::ParseError);
1034
1035 impl From<flux_syntax::ParseError> for SyntaxErr {
1036 fn from(err: flux_syntax::ParseError) -> Self {
1037 SyntaxErr(err)
1038 }
1039 }
1040
1041 impl<'sess> Diagnostic<'sess> for SyntaxErr {
1042 fn into_diag(
1043 self,
1044 dcx: DiagCtxtHandle<'sess>,
1045 level: Level,
1046 ) -> Diag<'sess, ErrorGuaranteed> {
1047 use flux_syntax::ParseErrorKind;
1048 let mut diag = Diag::new(dcx, level, crate::fluent_generated::driver_syntax_err);
1049 diag.code(E0999).span(self.0.span).span_label(
1050 self.0.span,
1051 match &self.0.kind {
1052 ParseErrorKind::UnexpectedEof => "unexpected end of input".to_string(),
1053 ParseErrorKind::UnexpectedToken { expected } => {
1054 match &expected[..] {
1055 [] => "unexpected token".to_string(),
1056 [a] => format!("unexpected token, expected `{a}`"),
1057 [a, b] => format!("unexpected token, expected `{a}` or `{b}`"),
1058 [prefix @ .., last] => {
1059 format!(
1060 "unexpected token, expected one of {}, or `{last}`",
1061 prefix
1062 .iter()
1063 .format_with(", ", |it, f| f(&format_args!("`{it}`")))
1064 )
1065 }
1066 }
1067 }
1068 ParseErrorKind::CannotBeChained => "operator cannot be chained".to_string(),
1069 ParseErrorKind::InvalidBinding => {
1070 "identifier must be a mutable reference".to_string()
1071 }
1072 ParseErrorKind::InvalidSort => {
1073 "property parameter sort is inherited from the primitive operator"
1074 .to_string()
1075 }
1076 ParseErrorKind::InvalidDetachedSpec => {
1077 "detached spec requires an identifier name".to_string()
1078 }
1079 },
1080 );
1081 diag
1082 }
1083 }
1084
1085 #[derive(Diagnostic)]
1086 #[diag(driver_attr_on_opaque, code = E0999)]
1087 pub(super) struct AttrOnOpaque {
1088 #[primary_span]
1089 span: Span,
1090 #[label]
1091 field_span: Span,
1092 }
1093
1094 impl AttrOnOpaque {
1095 pub(super) fn new(span: Span, field: &rustc_hir::FieldDef) -> Self {
1096 let field_span = field.ident.span;
1097 Self { span, field_span }
1098 }
1099 }
1100
1101 #[derive(Diagnostic)]
1102 #[diag(driver_reflected_enum_with_refined_by, code = E0999)]
1103 pub(super) struct ReflectedEnumWithRefinedBy {
1104 #[primary_span]
1105 #[label]
1106 span: Span,
1107 }
1108 impl ReflectedEnumWithRefinedBy {
1109 pub(super) fn new(span: Span) -> Self {
1110 Self { span }
1111 }
1112 }
1113
1114 #[derive(Diagnostic)]
1115 #[diag(driver_missing_variant, code = E0999)]
1116 #[note]
1117 pub(super) struct MissingVariant {
1118 #[primary_span]
1119 #[label]
1120 span: Span,
1121 }
1122
1123 impl MissingVariant {
1124 pub(super) fn new(span: Span) -> Self {
1125 Self { span }
1126 }
1127 }
1128
1129 #[derive(Diagnostic)]
1130 #[diag(driver_mismatched_spec_name, code = E0999)]
1131 pub(super) struct MismatchedSpecName {
1132 #[primary_span]
1133 #[label]
1134 span: Span,
1135 #[label(driver_item_def_ident)]
1136 item_ident_span: Span,
1137 item_ident: Ident,
1138 def_descr: &'static str,
1139 }
1140
1141 impl MismatchedSpecName {
1142 pub(super) fn new(tcx: TyCtxt, ident: Ident, def_id: DefId) -> Self {
1143 let def_descr = tcx.def_descr(def_id);
1144 let item_ident = tcx.opt_item_ident(def_id).unwrap();
1145 Self { span: ident.span, item_ident_span: item_ident.span, item_ident, def_descr }
1146 }
1147 }
1148}