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