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