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 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(box ast::Impl { polarity, defaultness, of_trait, .. }) => {
221 if let &ast::ImplPolarity::Negative(span) = polarity {
222 gate!(
223 &self,
224 negative_impls,
225 span.to(of_trait.as_ref().map_or(span, |t| t.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(_) = 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::BareFn(bare_fn_ty) => {
290 self.check_late_bound_lifetime_defs(&bare_fn_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>, 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!(let_chains, "`let` expressions in this position are unstable");
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!(dyn_star, "`dyn*` trait objects are experimental");
509 gate_all!(const_closures, "const closures are experimental");
510 gate_all!(builtin_syntax, "`builtin #` syntax is unstable");
511 gate_all!(ergonomic_clones, "ergonomic clones are experimental");
512 gate_all!(explicit_tail_calls, "`become` expression is experimental");
513 gate_all!(generic_const_items, "generic const items are experimental");
514 gate_all!(guard_patterns, "guard patterns are experimental", "consider using match arm guards");
515 gate_all!(default_field_values, "default values on fields are experimental");
516 gate_all!(fn_delegation, "functions delegation is not yet fully implemented");
517 gate_all!(postfix_match, "postfix match is experimental");
518 gate_all!(mut_ref, "mutable by-reference bindings are experimental");
519 gate_all!(global_registration, "global registration is experimental");
520 gate_all!(return_type_notation, "return type notation is experimental");
521 gate_all!(pin_ergonomics, "pinned reference syntax is experimental");
522 gate_all!(unsafe_fields, "`unsafe` fields are experimental");
523 gate_all!(unsafe_binders, "unsafe binder types are experimental");
524 gate_all!(contracts, "contracts are incomplete");
525 gate_all!(contracts_internals, "contract internal machinery is for internal use only");
526 gate_all!(where_clause_attrs, "attributes in `where` clause are unstable");
527 gate_all!(super_let, "`super let` is experimental");
528 gate_all!(frontmatter, "frontmatters are 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 if 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 {
640 spans,
641 f1: f1_name,
642 f2: f2_name,
643 });
644 }
645 }
646 }
647}
648
649fn check_new_solver_banned_features(sess: &Session, features: &Features) {
650 if !sess.opts.unstable_opts.next_solver.globally {
651 return;
652 }
653
654 if let Some(gce_span) = features
656 .enabled_lang_features()
657 .iter()
658 .find(|feat| feat.gate_name == sym::generic_const_exprs)
659 .map(|feat| feat.attr_sp)
660 {
661 #[allow(rustc::symbol_intern_string_literal)]
662 sess.dcx().emit_err(errors::IncompatibleFeatures {
663 spans: vec![gce_span],
664 f1: Symbol::intern("-Znext-solver=globally"),
665 f2: sym::generic_const_exprs,
666 });
667 }
668}