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_where_predicate_kind(&mut self, kind: &'a ast::WherePredicateKind) {
305 if let ast::WherePredicateKind::BoundPredicate(bound) = kind {
306 self.check_late_bound_lifetime_defs(&bound.bound_generic_params);
308 }
309 visit::walk_where_predicate_kind(self, kind);
310 }
311
312 fn visit_fn_ret_ty(&mut self, ret_ty: &'a ast::FnRetTy) {
313 if let ast::FnRetTy::Ty(output_ty) = ret_ty {
314 if let ast::TyKind::Never = output_ty.kind {
315 } else {
317 self.visit_ty(output_ty)
318 }
319 }
320 }
321
322 fn visit_generic_args(&mut self, args: &'a ast::GenericArgs) {
323 if let ast::GenericArgs::Parenthesized(generic_args) = args
327 && let ast::FnRetTy::Ty(ref ty) = generic_args.output
328 && matches!(ty.kind, ast::TyKind::Never)
329 {
330 gate!(&self, never_type, ty.span, "the `!` type is experimental");
331 }
332 visit::walk_generic_args(self, args);
333 }
334
335 fn visit_expr(&mut self, e: &'a ast::Expr) {
336 match e.kind {
337 ast::ExprKind::TryBlock(_, None) => {
338 gate!(&self, try_blocks, e.span, "`try` expression is experimental");
339 }
340 ast::ExprKind::TryBlock(_, Some(_)) => {
341 gate!(
342 &self,
343 try_blocks_heterogeneous,
344 e.span,
345 "`try bikeshed` expression is experimental"
346 );
347 }
348 ast::ExprKind::Lit(token::Lit {
349 kind: token::LitKind::Float | token::LitKind::Integer,
350 suffix,
351 ..
352 }) => match suffix {
353 Some(sym::f16) => {
354 gate!(&self, f16, e.span, "the type `f16` is unstable")
355 }
356 Some(sym::f128) => {
357 gate!(&self, f128, e.span, "the type `f128` is unstable")
358 }
359 _ => (),
360 },
361 _ => {}
362 }
363 visit::walk_expr(self, e)
364 }
365
366 fn visit_pat(&mut self, pattern: &'a ast::Pat) {
367 match &pattern.kind {
368 PatKind::Slice(pats) => {
369 for pat in pats {
370 let inner_pat = match &pat.kind {
371 PatKind::Ident(.., Some(pat)) => pat,
372 _ => pat,
373 };
374 if let PatKind::Range(Some(_), None, Spanned { .. }) = inner_pat.kind {
375 gate!(
376 &self,
377 half_open_range_patterns_in_slices,
378 pat.span,
379 "`X..` patterns in slices are experimental"
380 );
381 }
382 }
383 }
384 PatKind::Box(..) => {
385 gate!(&self, box_patterns, pattern.span, "box pattern syntax is experimental");
386 }
387 _ => {}
388 }
389 visit::walk_pat(self, pattern)
390 }
391
392 fn visit_poly_trait_ref(&mut self, t: &'a ast::PolyTraitRef) {
393 self.check_late_bound_lifetime_defs(&t.bound_generic_params);
394 visit::walk_poly_trait_ref(self, t);
395 }
396
397 fn visit_fn(&mut self, fn_kind: FnKind<'a>, _: &AttrVec, span: Span, _: NodeId) {
398 if let Some(_header) = fn_kind.header() {
399 }
401
402 if let FnKind::Closure(ast::ClosureBinder::For { generic_params, .. }, ..) = fn_kind {
403 self.check_late_bound_lifetime_defs(generic_params);
404 }
405
406 if fn_kind.ctxt() != Some(FnCtxt::Foreign) && fn_kind.decl().c_variadic() {
407 gate!(&self, c_variadic, span, "C-variadic functions are unstable");
408 }
409
410 visit::walk_fn(self, fn_kind)
411 }
412
413 fn visit_assoc_item(&mut self, i: &'a ast::AssocItem, ctxt: AssocCtxt) {
414 let is_fn = match &i.kind {
415 ast::AssocItemKind::Fn(_) => true,
416 ast::AssocItemKind::Type(box ast::TyAlias { ty, .. }) => {
417 if let (Some(_), AssocCtxt::Trait) = (ty, ctxt) {
418 gate!(
419 &self,
420 associated_type_defaults,
421 i.span,
422 "associated type defaults are unstable"
423 );
424 }
425 if let Some(ty) = ty {
426 self.check_impl_trait(ty, true);
427 }
428 false
429 }
430 _ => false,
431 };
432 if let ast::Defaultness::Default(_) = i.kind.defaultness() {
433 gate_alt!(
435 &self,
436 self.features.specialization() || (is_fn && self.features.min_specialization()),
437 sym::specialization,
438 i.span,
439 "specialization is unstable"
440 );
441 }
442 visit::walk_assoc_item(self, i, ctxt)
443 }
444}
445
446pub fn check_crate(krate: &ast::Crate, sess: &Session, features: &Features) {
447 maybe_stage_features(sess, features, krate);
448 check_incompatible_features(sess, features);
449 check_new_solver_banned_features(sess, features);
450
451 let mut visitor = PostExpansionVisitor { sess, features };
452
453 let spans = sess.psess.gated_spans.spans.borrow();
454 macro_rules! gate_all {
455 ($gate:ident, $msg:literal) => {
456 if let Some(spans) = spans.get(&sym::$gate) {
457 for span in spans {
458 gate!(&visitor, $gate, *span, $msg);
459 }
460 }
461 };
462 ($gate:ident, $msg:literal, $help:literal) => {
463 if let Some(spans) = spans.get(&sym::$gate) {
464 for span in spans {
465 gate!(&visitor, $gate, *span, $msg, $help);
466 }
467 }
468 };
469 }
470 gate_all!(
471 if_let_guard,
472 "`if let` guards are experimental",
473 "you can write `if matches!(<expr>, <pattern>)` instead of `if let <pattern> = <expr>`"
474 );
475 gate_all!(
476 async_trait_bounds,
477 "`async` trait bounds are unstable",
478 "use the desugared name of the async trait, such as `AsyncFn`"
479 );
480 gate_all!(async_for_loop, "`for await` loops are experimental");
481 gate_all!(
482 closure_lifetime_binder,
483 "`for<...>` binders for closures are experimental",
484 "consider removing `for<...>`"
485 );
486 gate_all!(more_qualified_paths, "usage of qualified paths in this context is experimental");
487 if let Some(spans) = spans.get(&sym::yield_expr) {
489 for span in spans {
490 if (!visitor.features.coroutines() && !span.allows_unstable(sym::coroutines))
491 && (!visitor.features.gen_blocks() && !span.allows_unstable(sym::gen_blocks))
492 && (!visitor.features.yield_expr() && !span.allows_unstable(sym::yield_expr))
493 {
494 #[allow(rustc::untranslatable_diagnostic)]
495 feature_err(&visitor.sess, sym::yield_expr, *span, "yield syntax is experimental")
498 .emit();
499 }
500 }
501 }
502 gate_all!(gen_blocks, "gen blocks are experimental");
503 gate_all!(const_trait_impl, "const trait impls are experimental");
504 gate_all!(
505 half_open_range_patterns_in_slices,
506 "half-open range patterns in slices are unstable"
507 );
508 gate_all!(associated_const_equality, "associated const equality is incomplete");
509 gate_all!(yeet_expr, "`do yeet` expression is experimental");
510 gate_all!(const_closures, "const closures are experimental");
511 gate_all!(builtin_syntax, "`builtin #` syntax is unstable");
512 gate_all!(ergonomic_clones, "ergonomic clones are experimental");
513 gate_all!(explicit_tail_calls, "`become` expression is experimental");
514 gate_all!(generic_const_items, "generic const items are experimental");
515 gate_all!(guard_patterns, "guard patterns are experimental", "consider using match arm guards");
516 gate_all!(default_field_values, "default values on fields are experimental");
517 gate_all!(fn_delegation, "functions delegation is not yet fully implemented");
518 gate_all!(postfix_match, "postfix match is experimental");
519 gate_all!(mut_ref, "mutable by-reference bindings are experimental");
520 gate_all!(min_generic_const_args, "unbraced const blocks as const args are experimental");
521 gate_all!(global_registration, "global registration is experimental");
522 gate_all!(return_type_notation, "return type notation is experimental");
523 gate_all!(pin_ergonomics, "pinned reference syntax is experimental");
524 gate_all!(unsafe_fields, "`unsafe` fields are experimental");
525 gate_all!(unsafe_binders, "unsafe binder types are experimental");
526 gate_all!(contracts, "contracts are incomplete");
527 gate_all!(contracts_internals, "contract internal machinery is for internal use only");
528 gate_all!(where_clause_attrs, "attributes in `where` clause are unstable");
529 gate_all!(super_let, "`super let` is experimental");
530 gate_all!(frontmatter, "frontmatters are experimental");
531 gate_all!(coroutines, "coroutine syntax is experimental");
532
533 if !visitor.features.never_patterns() {
534 if let Some(spans) = spans.get(&sym::never_patterns) {
535 for &span in spans {
536 if span.allows_unstable(sym::never_patterns) {
537 continue;
538 }
539 let sm = sess.source_map();
540 if let Ok(snippet) = sm.span_to_snippet(span)
544 && snippet == "!"
545 {
546 #[allow(rustc::untranslatable_diagnostic)] feature_err(sess, sym::never_patterns, span, "`!` patterns are experimental")
548 .emit();
549 } else {
550 let suggestion = span.shrink_to_hi();
551 sess.dcx().emit_err(errors::MatchArmWithNoBody { span, suggestion });
552 }
553 }
554 }
555 }
556
557 if !visitor.features.negative_bounds() {
558 for &span in spans.get(&sym::negative_bounds).iter().copied().flatten() {
559 sess.dcx().emit_err(errors::NegativeBoundUnsupported { span });
560 }
561 }
562
563 macro_rules! gate_all_legacy_dont_use {
568 ($gate:ident, $msg:literal) => {
569 for span in spans.get(&sym::$gate).unwrap_or(&vec![]) {
570 gate_legacy!(&visitor, $gate, *span, $msg);
571 }
572 };
573 }
574
575 gate_all_legacy_dont_use!(box_patterns, "box pattern syntax is experimental");
576 gate_all_legacy_dont_use!(trait_alias, "trait aliases are experimental");
577 gate_all_legacy_dont_use!(decl_macro, "`macro` is experimental");
578 gate_all_legacy_dont_use!(try_blocks, "`try` blocks are unstable");
579 gate_all_legacy_dont_use!(auto_traits, "`auto` traits are unstable");
580
581 visit::walk_crate(&mut visitor, krate);
582}
583
584fn maybe_stage_features(sess: &Session, features: &Features, krate: &ast::Crate) {
585 if sess.opts.unstable_features.is_nightly_build() {
587 return;
588 }
589 if features.enabled_features().is_empty() {
590 return;
591 }
592 let mut errored = false;
593 for attr in krate.attrs.iter().filter(|attr| attr.has_name(sym::feature)) {
594 let mut err = errors::FeatureOnNonNightly {
596 span: attr.span,
597 channel: option_env!("CFG_RELEASE_CHANNEL").unwrap_or("(unknown)"),
598 stable_features: vec![],
599 sugg: None,
600 };
601
602 let mut all_stable = true;
603 for ident in attr.meta_item_list().into_iter().flatten().flat_map(|nested| nested.ident()) {
604 let name = ident.name;
605 let stable_since = features
606 .enabled_lang_features()
607 .iter()
608 .find(|feat| feat.gate_name == name)
609 .map(|feat| feat.stable_since)
610 .flatten();
611 if let Some(since) = stable_since {
612 err.stable_features.push(errors::StableFeature { name, since });
613 } else {
614 all_stable = false;
615 }
616 }
617 if all_stable {
618 err.sugg = Some(attr.span);
619 }
620 sess.dcx().emit_err(err);
621 errored = true;
622 }
623 assert!(errored);
625}
626
627fn check_incompatible_features(sess: &Session, features: &Features) {
628 let enabled_features = features.enabled_features_iter_stable_order();
629
630 for (f1, f2) in rustc_feature::INCOMPATIBLE_FEATURES
631 .iter()
632 .filter(|(f1, f2)| features.enabled(*f1) && features.enabled(*f2))
633 {
634 if let Some((f1_name, f1_span)) = enabled_features.clone().find(|(name, _)| name == f1)
635 && let Some((f2_name, f2_span)) = enabled_features.clone().find(|(name, _)| name == f2)
636 {
637 let spans = vec![f1_span, f2_span];
638 sess.dcx().emit_err(errors::IncompatibleFeatures { spans, f1: f1_name, f2: f2_name });
639 }
640 }
641}
642
643fn check_new_solver_banned_features(sess: &Session, features: &Features) {
644 if !sess.opts.unstable_opts.next_solver.globally {
645 return;
646 }
647
648 if let Some(gce_span) = features
650 .enabled_lang_features()
651 .iter()
652 .find(|feat| feat.gate_name == sym::generic_const_exprs)
653 .map(|feat| feat.attr_sp)
654 {
655 #[allow(rustc::symbol_intern_string_literal)]
656 sess.dcx().emit_err(errors::IncompatibleFeatures {
657 spans: vec![gce_span],
658 f1: Symbol::intern("-Znext-solver=globally"),
659 f2: sym::generic_const_exprs,
660 });
661 }
662}