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