1use rustc_ast as ast;
2use rustc_ast::visit::{self, AssocCtxt, FnCtxt, FnKind, Visitor};
3use rustc_ast::{NodeId, PatKind, attr, token};
4use rustc_feature::{AttributeGate, BUILTIN_ATTRIBUTE_MAP, BuiltinAttribute, Features};
5use rustc_session::Session;
6use rustc_session::parse::{feature_err, feature_warn};
7use rustc_span::source_map::Spanned;
8use rustc_span::{Span, Symbol, sym};
9use thin_vec::ThinVec;
10
11use crate::errors;
12
13macro_rules! gate {
15 ($visitor:expr, $feature:ident, $span:expr, $explain:expr) => {{
16 if !$visitor.features.$feature() && !$span.allows_unstable(sym::$feature) {
17 #[allow(rustc::untranslatable_diagnostic)] feature_err(&$visitor.sess, sym::$feature, $span, $explain).emit();
19 }
20 }};
21 ($visitor:expr, $feature:ident, $span:expr, $explain:expr, $help:expr) => {{
22 if !$visitor.features.$feature() && !$span.allows_unstable(sym::$feature) {
23 #[allow(rustc::diagnostic_outside_of_impl)]
25 #[allow(rustc::untranslatable_diagnostic)]
26 feature_err(&$visitor.sess, sym::$feature, $span, $explain).with_help($help).emit();
27 }
28 }};
29}
30
31macro_rules! gate_alt {
33 ($visitor:expr, $has_feature:expr, $name:expr, $span:expr, $explain:expr) => {{
34 if !$has_feature && !$span.allows_unstable($name) {
35 #[allow(rustc::untranslatable_diagnostic)] feature_err(&$visitor.sess, $name, $span, $explain).emit();
37 }
38 }};
39 ($visitor:expr, $has_feature:expr, $name:expr, $span:expr, $explain:expr, $notes: expr) => {{
40 if !$has_feature && !$span.allows_unstable($name) {
41 #[allow(rustc::untranslatable_diagnostic)] let mut diag = feature_err(&$visitor.sess, $name, $span, $explain);
43 for note in $notes {
44 diag.note(*note);
45 }
46 diag.emit();
47 }
48 }};
49}
50
51macro_rules! gate_multi {
53 ($visitor:expr, $feature:ident, $spans:expr, $explain:expr) => {{
54 if !$visitor.features.$feature() {
55 let spans: Vec<_> =
56 $spans.filter(|span| !span.allows_unstable(sym::$feature)).collect();
57 if !spans.is_empty() {
58 feature_err(&$visitor.sess, sym::$feature, spans, $explain).emit();
59 }
60 }
61 }};
62}
63
64macro_rules! gate_legacy {
66 ($visitor:expr, $feature:ident, $span:expr, $explain:expr) => {{
67 if !$visitor.features.$feature() && !$span.allows_unstable(sym::$feature) {
68 feature_warn(&$visitor.sess, sym::$feature, $span, $explain);
69 }
70 }};
71}
72
73pub fn check_attribute(attr: &ast::Attribute, sess: &Session, features: &Features) {
74 PostExpansionVisitor { sess, features }.visit_attribute(attr)
75}
76
77struct PostExpansionVisitor<'a> {
78 sess: &'a Session,
79
80 features: &'a Features,
82}
83
84impl<'a> PostExpansionVisitor<'a> {
85 fn check_impl_trait(&self, ty: &ast::Ty, in_associated_ty: bool) {
87 struct ImplTraitVisitor<'a> {
88 vis: &'a PostExpansionVisitor<'a>,
89 in_associated_ty: bool,
90 }
91 impl Visitor<'_> for ImplTraitVisitor<'_> {
92 fn visit_ty(&mut self, ty: &ast::Ty) {
93 if let ast::TyKind::ImplTrait(..) = ty.kind {
94 if self.in_associated_ty {
95 gate!(
96 &self.vis,
97 impl_trait_in_assoc_type,
98 ty.span,
99 "`impl Trait` in associated types is unstable"
100 );
101 } else {
102 gate!(
103 &self.vis,
104 type_alias_impl_trait,
105 ty.span,
106 "`impl Trait` in type aliases is unstable"
107 );
108 }
109 }
110 visit::walk_ty(self, ty);
111 }
112
113 fn visit_anon_const(&mut self, _: &ast::AnonConst) -> Self::Result {
114 }
119 }
120 ImplTraitVisitor { vis: self, in_associated_ty }.visit_ty(ty);
121 }
122
123 fn check_late_bound_lifetime_defs(&self, params: &[ast::GenericParam]) {
124 let non_lt_param_spans = params.iter().filter_map(|param| match param.kind {
127 ast::GenericParamKind::Lifetime { .. } => None,
128 _ => Some(param.ident.span),
129 });
130 gate_multi!(
131 &self,
132 non_lifetime_binders,
133 non_lt_param_spans,
134 crate::fluent_generated::ast_passes_forbidden_non_lifetime_param
135 );
136
137 if self.features.non_lifetime_binders() {
140 let const_param_spans: Vec<_> = params
141 .iter()
142 .filter_map(|param| match param.kind {
143 ast::GenericParamKind::Const { .. } => Some(param.ident.span),
144 _ => None,
145 })
146 .collect();
147
148 if !const_param_spans.is_empty() {
149 self.sess.dcx().emit_err(errors::ForbiddenConstParam { const_param_spans });
150 }
151 }
152
153 for param in params {
154 if !param.bounds.is_empty() {
155 let spans: Vec<_> = param.bounds.iter().map(|b| b.span()).collect();
156 self.sess.dcx().emit_err(errors::ForbiddenBound { spans });
157 }
158 }
159 }
160}
161
162impl<'a> Visitor<'a> for PostExpansionVisitor<'a> {
163 fn visit_attribute(&mut self, attr: &ast::Attribute) {
164 let attr_info = attr.ident().and_then(|ident| BUILTIN_ATTRIBUTE_MAP.get(&ident.name));
165 if let Some(BuiltinAttribute {
167 gate: AttributeGate::Gated { feature, message, check, notes, .. },
168 ..
169 }) = attr_info
170 {
171 gate_alt!(self, check(self.features), *feature, attr.span, *message, *notes);
172 }
173 if attr.has_name(sym::doc) {
175 for meta_item_inner in attr.meta_item_list().unwrap_or_default() {
176 macro_rules! gate_doc { ($($s:literal { $($name:ident => $feature:ident)* })*) => {
177 $($(if meta_item_inner.has_name(sym::$name) {
178 let msg = concat!("`#[doc(", stringify!($name), ")]` is ", $s);
179 gate!(self, $feature, attr.span, msg);
180 })*)*
181 }}
182
183 gate_doc!(
184 "experimental" {
185 cfg => doc_cfg
186 cfg_hide => doc_cfg_hide
187 masked => doc_masked
188 notable_trait => doc_notable_trait
189 }
190 "meant for internal use only" {
191 attribute => rustdoc_internals
192 keyword => rustdoc_internals
193 fake_variadic => rustdoc_internals
194 search_unbox => rustdoc_internals
195 }
196 );
197 }
198 }
199 }
200
201 fn visit_item(&mut self, i: &'a ast::Item) {
202 match &i.kind {
203 ast::ItemKind::ForeignMod(_foreign_module) => {
204 }
206 ast::ItemKind::Struct(..) | ast::ItemKind::Enum(..) | ast::ItemKind::Union(..) => {
207 for attr in attr::filter_by_name(&i.attrs, sym::repr) {
208 for item in attr.meta_item_list().unwrap_or_else(ThinVec::new) {
209 if item.has_name(sym::simd) {
210 gate!(
211 &self,
212 repr_simd,
213 attr.span,
214 "SIMD types are experimental and possibly buggy"
215 );
216 }
217 }
218 }
219 }
220
221 ast::ItemKind::Impl(ast::Impl { of_trait: Some(of_trait), .. }) => {
222 if let ast::ImplPolarity::Negative(span) = of_trait.polarity {
223 gate!(
224 &self,
225 negative_impls,
226 span.to(of_trait.trait_ref.path.span),
227 "negative trait bounds are not fully implemented; \
228 use marker types for now"
229 );
230 }
231
232 if let ast::Defaultness::Default(_) = of_trait.defaultness {
233 gate!(&self, specialization, i.span, "specialization is unstable");
234 }
235 }
236
237 ast::ItemKind::Trait(box ast::Trait { is_auto: ast::IsAuto::Yes, .. }) => {
238 gate!(
239 &self,
240 auto_traits,
241 i.span,
242 "auto traits are experimental and possibly buggy"
243 );
244 }
245
246 ast::ItemKind::TraitAlias(..) => {
247 gate!(&self, trait_alias, i.span, "trait aliases are experimental");
248 }
249
250 ast::ItemKind::MacroDef(_, ast::MacroDef { macro_rules: false, .. }) => {
251 let msg = "`macro` is experimental";
252 gate!(&self, decl_macro, i.span, msg);
253 }
254
255 ast::ItemKind::TyAlias(box ast::TyAlias { ty: Some(ty), .. }) => {
256 self.check_impl_trait(ty, false)
257 }
258
259 _ => {}
260 }
261
262 visit::walk_item(self, i);
263 }
264
265 fn visit_foreign_item(&mut self, i: &'a ast::ForeignItem) {
266 match i.kind {
267 ast::ForeignItemKind::Fn(..) | ast::ForeignItemKind::Static(..) => {
268 let link_name = attr::first_attr_value_str_by_name(&i.attrs, sym::link_name);
269 let links_to_llvm = link_name.is_some_and(|val| val.as_str().starts_with("llvm."));
270 if links_to_llvm {
271 gate!(
272 &self,
273 link_llvm_intrinsics,
274 i.span,
275 "linking to LLVM intrinsics is experimental"
276 );
277 }
278 }
279 ast::ForeignItemKind::TyAlias(..) => {
280 gate!(&self, extern_types, i.span, "extern types are experimental");
281 }
282 ast::ForeignItemKind::MacCall(..) => {}
283 }
284
285 visit::walk_item(self, i)
286 }
287
288 fn visit_ty(&mut self, ty: &'a ast::Ty) {
289 match &ty.kind {
290 ast::TyKind::FnPtr(fn_ptr_ty) => {
291 self.check_late_bound_lifetime_defs(&fn_ptr_ty.generic_params);
293 }
294 ast::TyKind::Never => {
295 gate!(&self, never_type, ty.span, "the `!` type is experimental");
296 }
297 ast::TyKind::Pat(..) => {
298 gate!(&self, pattern_types, ty.span, "pattern types are unstable");
299 }
300 _ => {}
301 }
302 visit::walk_ty(self, ty)
303 }
304
305 fn visit_generics(&mut self, g: &'a ast::Generics) {
306 for predicate in &g.where_clause.predicates {
307 match &predicate.kind {
308 ast::WherePredicateKind::BoundPredicate(bound_pred) => {
309 self.check_late_bound_lifetime_defs(&bound_pred.bound_generic_params);
311 }
312 _ => {}
313 }
314 }
315 visit::walk_generics(self, g);
316 }
317
318 fn visit_fn_ret_ty(&mut self, ret_ty: &'a ast::FnRetTy) {
319 if let ast::FnRetTy::Ty(output_ty) = ret_ty {
320 if let ast::TyKind::Never = output_ty.kind {
321 } else {
323 self.visit_ty(output_ty)
324 }
325 }
326 }
327
328 fn visit_generic_args(&mut self, args: &'a ast::GenericArgs) {
329 if let ast::GenericArgs::Parenthesized(generic_args) = args
333 && let ast::FnRetTy::Ty(ref ty) = generic_args.output
334 && matches!(ty.kind, ast::TyKind::Never)
335 {
336 gate!(&self, never_type, ty.span, "the `!` type is experimental");
337 }
338 visit::walk_generic_args(self, args);
339 }
340
341 fn visit_expr(&mut self, e: &'a ast::Expr) {
342 match e.kind {
343 ast::ExprKind::TryBlock(_) => {
344 gate!(&self, try_blocks, e.span, "`try` expression is experimental");
345 }
346 ast::ExprKind::Lit(token::Lit {
347 kind: token::LitKind::Float | token::LitKind::Integer,
348 suffix,
349 ..
350 }) => match suffix {
351 Some(sym::f16) => {
352 gate!(&self, f16, e.span, "the type `f16` is unstable")
353 }
354 Some(sym::f128) => {
355 gate!(&self, f128, e.span, "the type `f128` is unstable")
356 }
357 _ => (),
358 },
359 _ => {}
360 }
361 visit::walk_expr(self, e)
362 }
363
364 fn visit_pat(&mut self, pattern: &'a ast::Pat) {
365 match &pattern.kind {
366 PatKind::Slice(pats) => {
367 for pat in pats {
368 let inner_pat = match &pat.kind {
369 PatKind::Ident(.., Some(pat)) => pat,
370 _ => pat,
371 };
372 if let PatKind::Range(Some(_), None, Spanned { .. }) = inner_pat.kind {
373 gate!(
374 &self,
375 half_open_range_patterns_in_slices,
376 pat.span,
377 "`X..` patterns in slices are experimental"
378 );
379 }
380 }
381 }
382 PatKind::Box(..) => {
383 gate!(&self, box_patterns, pattern.span, "box pattern syntax is experimental");
384 }
385 _ => {}
386 }
387 visit::walk_pat(self, pattern)
388 }
389
390 fn visit_poly_trait_ref(&mut self, t: &'a ast::PolyTraitRef) {
391 self.check_late_bound_lifetime_defs(&t.bound_generic_params);
392 visit::walk_poly_trait_ref(self, t);
393 }
394
395 fn visit_fn(&mut self, fn_kind: FnKind<'a>, span: Span, _: NodeId) {
396 if let Some(_header) = fn_kind.header() {
397 }
399
400 if let FnKind::Closure(ast::ClosureBinder::For { generic_params, .. }, ..) = fn_kind {
401 self.check_late_bound_lifetime_defs(generic_params);
402 }
403
404 if fn_kind.ctxt() != Some(FnCtxt::Foreign) && fn_kind.decl().c_variadic() {
405 gate!(&self, c_variadic, span, "C-variadic functions are unstable");
406 }
407
408 visit::walk_fn(self, fn_kind)
409 }
410
411 fn visit_assoc_item(&mut self, i: &'a ast::AssocItem, ctxt: AssocCtxt) {
412 let is_fn = match &i.kind {
413 ast::AssocItemKind::Fn(_) => true,
414 ast::AssocItemKind::Type(box ast::TyAlias { ty, .. }) => {
415 if let (Some(_), AssocCtxt::Trait) = (ty, ctxt) {
416 gate!(
417 &self,
418 associated_type_defaults,
419 i.span,
420 "associated type defaults are unstable"
421 );
422 }
423 if let Some(ty) = ty {
424 self.check_impl_trait(ty, true);
425 }
426 false
427 }
428 _ => false,
429 };
430 if let ast::Defaultness::Default(_) = i.kind.defaultness() {
431 gate_alt!(
433 &self,
434 self.features.specialization() || (is_fn && self.features.min_specialization()),
435 sym::specialization,
436 i.span,
437 "specialization is unstable"
438 );
439 }
440 visit::walk_assoc_item(self, i, ctxt)
441 }
442}
443
444pub fn check_crate(krate: &ast::Crate, sess: &Session, features: &Features) {
445 maybe_stage_features(sess, features, krate);
446 check_incompatible_features(sess, features);
447 check_new_solver_banned_features(sess, features);
448
449 let mut visitor = PostExpansionVisitor { sess, features };
450
451 let spans = sess.psess.gated_spans.spans.borrow();
452 macro_rules! gate_all {
453 ($gate:ident, $msg:literal) => {
454 if let Some(spans) = spans.get(&sym::$gate) {
455 for span in spans {
456 gate!(&visitor, $gate, *span, $msg);
457 }
458 }
459 };
460 ($gate:ident, $msg:literal, $help:literal) => {
461 if let Some(spans) = spans.get(&sym::$gate) {
462 for span in spans {
463 gate!(&visitor, $gate, *span, $msg, $help);
464 }
465 }
466 };
467 }
468 gate_all!(
469 if_let_guard,
470 "`if let` guards are experimental",
471 "you can write `if matches!(<expr>, <pattern>)` instead of `if let <pattern> = <expr>`"
472 );
473 gate_all!(
474 async_trait_bounds,
475 "`async` trait bounds are unstable",
476 "use the desugared name of the async trait, such as `AsyncFn`"
477 );
478 gate_all!(async_for_loop, "`for await` loops are experimental");
479 gate_all!(
480 closure_lifetime_binder,
481 "`for<...>` binders for closures are experimental",
482 "consider removing `for<...>`"
483 );
484 gate_all!(more_qualified_paths, "usage of qualified paths in this context is experimental");
485 if let Some(spans) = spans.get(&sym::yield_expr) {
487 for span in spans {
488 if (!visitor.features.coroutines() && !span.allows_unstable(sym::coroutines))
489 && (!visitor.features.gen_blocks() && !span.allows_unstable(sym::gen_blocks))
490 && (!visitor.features.yield_expr() && !span.allows_unstable(sym::yield_expr))
491 {
492 #[allow(rustc::untranslatable_diagnostic)]
493 feature_err(&visitor.sess, sym::yield_expr, *span, "yield syntax is experimental")
496 .emit();
497 }
498 }
499 }
500 gate_all!(gen_blocks, "gen blocks are experimental");
501 gate_all!(const_trait_impl, "const trait impls are experimental");
502 gate_all!(
503 half_open_range_patterns_in_slices,
504 "half-open range patterns in slices are unstable"
505 );
506 gate_all!(associated_const_equality, "associated const equality is incomplete");
507 gate_all!(yeet_expr, "`do yeet` expression is experimental");
508 gate_all!(const_closures, "const closures are experimental");
509 gate_all!(builtin_syntax, "`builtin #` syntax is unstable");
510 gate_all!(ergonomic_clones, "ergonomic clones are experimental");
511 gate_all!(explicit_tail_calls, "`become` expression is experimental");
512 gate_all!(generic_const_items, "generic const items are experimental");
513 gate_all!(guard_patterns, "guard patterns are experimental", "consider using match arm guards");
514 gate_all!(default_field_values, "default values on fields are experimental");
515 gate_all!(fn_delegation, "functions delegation is not yet fully implemented");
516 gate_all!(postfix_match, "postfix match is experimental");
517 gate_all!(mut_ref, "mutable by-reference bindings are experimental");
518 gate_all!(global_registration, "global registration is experimental");
519 gate_all!(return_type_notation, "return type notation is experimental");
520 gate_all!(pin_ergonomics, "pinned reference syntax is experimental");
521 gate_all!(unsafe_fields, "`unsafe` fields are experimental");
522 gate_all!(unsafe_binders, "unsafe binder types are experimental");
523 gate_all!(contracts, "contracts are incomplete");
524 gate_all!(contracts_internals, "contract internal machinery is for internal use only");
525 gate_all!(where_clause_attrs, "attributes in `where` clause are unstable");
526 gate_all!(super_let, "`super let` is experimental");
527 gate_all!(frontmatter, "frontmatters are experimental");
528 gate_all!(coroutines, "coroutine syntax is experimental");
529
530 if !visitor.features.never_patterns() {
531 if let Some(spans) = spans.get(&sym::never_patterns) {
532 for &span in spans {
533 if span.allows_unstable(sym::never_patterns) {
534 continue;
535 }
536 let sm = sess.source_map();
537 if let Ok(snippet) = sm.span_to_snippet(span)
541 && snippet == "!"
542 {
543 #[allow(rustc::untranslatable_diagnostic)] feature_err(sess, sym::never_patterns, span, "`!` patterns are experimental")
545 .emit();
546 } else {
547 let suggestion = span.shrink_to_hi();
548 sess.dcx().emit_err(errors::MatchArmWithNoBody { span, suggestion });
549 }
550 }
551 }
552 }
553
554 if !visitor.features.negative_bounds() {
555 for &span in spans.get(&sym::negative_bounds).iter().copied().flatten() {
556 sess.dcx().emit_err(errors::NegativeBoundUnsupported { span });
557 }
558 }
559
560 macro_rules! gate_all_legacy_dont_use {
565 ($gate:ident, $msg:literal) => {
566 for span in spans.get(&sym::$gate).unwrap_or(&vec![]) {
567 gate_legacy!(&visitor, $gate, *span, $msg);
568 }
569 };
570 }
571
572 gate_all_legacy_dont_use!(box_patterns, "box pattern syntax is experimental");
573 gate_all_legacy_dont_use!(trait_alias, "trait aliases are experimental");
574 gate_all_legacy_dont_use!(decl_macro, "`macro` is experimental");
575 gate_all_legacy_dont_use!(try_blocks, "`try` blocks are unstable");
576 gate_all_legacy_dont_use!(auto_traits, "`auto` traits are unstable");
577
578 visit::walk_crate(&mut visitor, krate);
579}
580
581fn maybe_stage_features(sess: &Session, features: &Features, krate: &ast::Crate) {
582 if sess.opts.unstable_features.is_nightly_build() {
584 return;
585 }
586 if features.enabled_features().is_empty() {
587 return;
588 }
589 let mut errored = false;
590 for attr in krate.attrs.iter().filter(|attr| attr.has_name(sym::feature)) {
591 let mut err = errors::FeatureOnNonNightly {
593 span: attr.span,
594 channel: option_env!("CFG_RELEASE_CHANNEL").unwrap_or("(unknown)"),
595 stable_features: vec![],
596 sugg: None,
597 };
598
599 let mut all_stable = true;
600 for ident in attr.meta_item_list().into_iter().flatten().flat_map(|nested| nested.ident()) {
601 let name = ident.name;
602 let stable_since = features
603 .enabled_lang_features()
604 .iter()
605 .find(|feat| feat.gate_name == name)
606 .map(|feat| feat.stable_since)
607 .flatten();
608 if let Some(since) = stable_since {
609 err.stable_features.push(errors::StableFeature { name, since });
610 } else {
611 all_stable = false;
612 }
613 }
614 if all_stable {
615 err.sugg = Some(attr.span);
616 }
617 sess.dcx().emit_err(err);
618 errored = true;
619 }
620 assert!(errored);
622}
623
624fn check_incompatible_features(sess: &Session, features: &Features) {
625 let enabled_lang_features =
626 features.enabled_lang_features().iter().map(|feat| (feat.gate_name, feat.attr_sp));
627 let enabled_lib_features =
628 features.enabled_lib_features().iter().map(|feat| (feat.gate_name, feat.attr_sp));
629 let enabled_features = enabled_lang_features.chain(enabled_lib_features);
630
631 for (f1, f2) in rustc_feature::INCOMPATIBLE_FEATURES
632 .iter()
633 .filter(|(f1, f2)| features.enabled(*f1) && features.enabled(*f2))
634 {
635 if let Some((f1_name, f1_span)) = enabled_features.clone().find(|(name, _)| name == f1)
636 && let Some((f2_name, f2_span)) = enabled_features.clone().find(|(name, _)| name == f2)
637 {
638 let spans = vec![f1_span, f2_span];
639 sess.dcx().emit_err(errors::IncompatibleFeatures { spans, f1: f1_name, f2: f2_name });
640 }
641 }
642}
643
644fn check_new_solver_banned_features(sess: &Session, features: &Features) {
645 if !sess.opts.unstable_opts.next_solver.globally {
646 return;
647 }
648
649 if let Some(gce_span) = features
651 .enabled_lang_features()
652 .iter()
653 .find(|feat| feat.gate_name == sym::generic_const_exprs)
654 .map(|feat| feat.attr_sp)
655 {
656 #[allow(rustc::symbol_intern_string_literal)]
657 sess.dcx().emit_err(errors::IncompatibleFeatures {
658 spans: vec![gce_span],
659 f1: Symbol::intern("-Znext-solver=globally"),
660 f2: sym::generic_const_exprs,
661 });
662 }
663}