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 if !self.features.staged_api() {
184 if attr.has_name(sym::unstable)
185 || attr.has_name(sym::stable)
186 || attr.has_name(sym::rustc_const_unstable)
187 || attr.has_name(sym::rustc_const_stable)
188 || attr.has_name(sym::rustc_default_body_unstable)
189 {
190 self.sess.dcx().emit_err(errors::StabilityOutsideStd { span: attr.span });
191 }
192 }
193 }
194
195 fn visit_item(&mut self, i: &'a ast::Item) {
196 match &i.kind {
197 ast::ItemKind::ForeignMod(_foreign_module) => {
198 }
200 ast::ItemKind::Struct(..) | ast::ItemKind::Enum(..) | ast::ItemKind::Union(..) => {
201 for attr in attr::filter_by_name(&i.attrs, sym::repr) {
202 for item in attr.meta_item_list().unwrap_or_else(ThinVec::new) {
203 if item.has_name(sym::simd) {
204 gate!(
205 &self,
206 repr_simd,
207 attr.span,
208 "SIMD types are experimental and possibly buggy"
209 );
210 }
211 }
212 }
213 }
214
215 ast::ItemKind::Impl(box ast::Impl { polarity, defaultness, of_trait, .. }) => {
216 if let &ast::ImplPolarity::Negative(span) = polarity {
217 gate!(
218 &self,
219 negative_impls,
220 span.to(of_trait.as_ref().map_or(span, |t| t.path.span)),
221 "negative trait bounds are not fully implemented; \
222 use marker types for now"
223 );
224 }
225
226 if let ast::Defaultness::Default(_) = defaultness {
227 gate!(&self, specialization, i.span, "specialization is unstable");
228 }
229 }
230
231 ast::ItemKind::Trait(box ast::Trait { is_auto: ast::IsAuto::Yes, .. }) => {
232 gate!(
233 &self,
234 auto_traits,
235 i.span,
236 "auto traits are experimental and possibly buggy"
237 );
238 }
239
240 ast::ItemKind::TraitAlias(..) => {
241 gate!(&self, trait_alias, i.span, "trait aliases are experimental");
242 }
243
244 ast::ItemKind::MacroDef(ast::MacroDef { macro_rules: false, .. }) => {
245 let msg = "`macro` is experimental";
246 gate!(&self, decl_macro, i.span, msg);
247 }
248
249 ast::ItemKind::TyAlias(box ast::TyAlias { ty: Some(ty), .. }) => {
250 self.check_impl_trait(ty, false)
251 }
252
253 _ => {}
254 }
255
256 visit::walk_item(self, i);
257 }
258
259 fn visit_foreign_item(&mut self, i: &'a ast::ForeignItem) {
260 match i.kind {
261 ast::ForeignItemKind::Fn(..) | ast::ForeignItemKind::Static(..) => {
262 let link_name = attr::first_attr_value_str_by_name(&i.attrs, sym::link_name);
263 let links_to_llvm = link_name.is_some_and(|val| val.as_str().starts_with("llvm."));
264 if links_to_llvm {
265 gate!(
266 &self,
267 link_llvm_intrinsics,
268 i.span,
269 "linking to LLVM intrinsics is experimental"
270 );
271 }
272 }
273 ast::ForeignItemKind::TyAlias(..) => {
274 gate!(&self, extern_types, i.span, "extern types are experimental");
275 }
276 ast::ForeignItemKind::MacCall(..) => {}
277 }
278
279 visit::walk_item(self, i)
280 }
281
282 fn visit_ty(&mut self, ty: &'a ast::Ty) {
283 match &ty.kind {
284 ast::TyKind::BareFn(bare_fn_ty) => {
285 self.check_late_bound_lifetime_defs(&bare_fn_ty.generic_params);
287 }
288 ast::TyKind::Never => {
289 gate!(&self, never_type, ty.span, "the `!` type is experimental");
290 }
291 ast::TyKind::Pat(..) => {
292 gate!(&self, pattern_types, ty.span, "pattern types are unstable");
293 }
294 _ => {}
295 }
296 visit::walk_ty(self, ty)
297 }
298
299 fn visit_generics(&mut self, g: &'a ast::Generics) {
300 for predicate in &g.where_clause.predicates {
301 match &predicate.kind {
302 ast::WherePredicateKind::BoundPredicate(bound_pred) => {
303 self.check_late_bound_lifetime_defs(&bound_pred.bound_generic_params);
305 }
306 _ => {}
307 }
308 }
309 visit::walk_generics(self, g);
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(_) => {
338 gate!(&self, try_blocks, e.span, "`try` expression is experimental");
339 }
340 ast::ExprKind::Lit(token::Lit { kind: token::LitKind::Float, suffix, .. }) => {
341 match suffix {
342 Some(sym::f16) => {
343 gate!(&self, f16, e.span, "the type `f16` is unstable")
344 }
345 Some(sym::f128) => {
346 gate!(&self, f128, e.span, "the type `f128` is unstable")
347 }
348 _ => (),
349 }
350 }
351 _ => {}
352 }
353 visit::walk_expr(self, e)
354 }
355
356 fn visit_pat(&mut self, pattern: &'a ast::Pat) {
357 match &pattern.kind {
358 PatKind::Slice(pats) => {
359 for pat in pats {
360 let inner_pat = match &pat.kind {
361 PatKind::Ident(.., Some(pat)) => pat,
362 _ => pat,
363 };
364 if let PatKind::Range(Some(_), None, Spanned { .. }) = inner_pat.kind {
365 gate!(
366 &self,
367 half_open_range_patterns_in_slices,
368 pat.span,
369 "`X..` patterns in slices are experimental"
370 );
371 }
372 }
373 }
374 PatKind::Box(..) => {
375 gate!(&self, box_patterns, pattern.span, "box pattern syntax is experimental");
376 }
377 _ => {}
378 }
379 visit::walk_pat(self, pattern)
380 }
381
382 fn visit_poly_trait_ref(&mut self, t: &'a ast::PolyTraitRef) {
383 self.check_late_bound_lifetime_defs(&t.bound_generic_params);
384 visit::walk_poly_trait_ref(self, t);
385 }
386
387 fn visit_fn(&mut self, fn_kind: FnKind<'a>, span: Span, _: NodeId) {
388 if let Some(_header) = fn_kind.header() {
389 }
391
392 if let FnKind::Closure(ast::ClosureBinder::For { generic_params, .. }, ..) = fn_kind {
393 self.check_late_bound_lifetime_defs(generic_params);
394 }
395
396 if fn_kind.ctxt() != Some(FnCtxt::Foreign) && fn_kind.decl().c_variadic() {
397 gate!(&self, c_variadic, span, "C-variadic functions are unstable");
398 }
399
400 visit::walk_fn(self, fn_kind)
401 }
402
403 fn visit_assoc_item(&mut self, i: &'a ast::AssocItem, ctxt: AssocCtxt) {
404 let is_fn = match &i.kind {
405 ast::AssocItemKind::Fn(_) => true,
406 ast::AssocItemKind::Type(box ast::TyAlias { ty, .. }) => {
407 if let (Some(_), AssocCtxt::Trait) = (ty, ctxt) {
408 gate!(
409 &self,
410 associated_type_defaults,
411 i.span,
412 "associated type defaults are unstable"
413 );
414 }
415 if let Some(ty) = ty {
416 self.check_impl_trait(ty, true);
417 }
418 false
419 }
420 _ => false,
421 };
422 if let ast::Defaultness::Default(_) = i.kind.defaultness() {
423 gate_alt!(
425 &self,
426 self.features.specialization() || (is_fn && self.features.min_specialization()),
427 sym::specialization,
428 i.span,
429 "specialization is unstable"
430 );
431 }
432 visit::walk_assoc_item(self, i, ctxt)
433 }
434}
435
436pub fn check_crate(krate: &ast::Crate, sess: &Session, features: &Features) {
437 maybe_stage_features(sess, features, krate);
438 check_incompatible_features(sess, features);
439 check_new_solver_banned_features(sess, features);
440
441 let mut visitor = PostExpansionVisitor { sess, features };
442
443 let spans = sess.psess.gated_spans.spans.borrow();
444 macro_rules! gate_all {
445 ($gate:ident, $msg:literal) => {
446 if let Some(spans) = spans.get(&sym::$gate) {
447 for span in spans {
448 gate!(&visitor, $gate, *span, $msg);
449 }
450 }
451 };
452 ($gate:ident, $msg:literal, $help:literal) => {
453 if let Some(spans) = spans.get(&sym::$gate) {
454 for span in spans {
455 gate!(&visitor, $gate, *span, $msg, $help);
456 }
457 }
458 };
459 }
460 gate_all!(
461 if_let_guard,
462 "`if let` guards are experimental",
463 "you can write `if matches!(<expr>, <pattern>)` instead of `if let <pattern> = <expr>`"
464 );
465 gate_all!(let_chains, "`let` expressions in this position are unstable");
466 gate_all!(
467 async_trait_bounds,
468 "`async` trait bounds are unstable",
469 "use the desugared name of the async trait, such as `AsyncFn`"
470 );
471 gate_all!(async_for_loop, "`for await` loops are experimental");
472 gate_all!(
473 closure_lifetime_binder,
474 "`for<...>` binders for closures are experimental",
475 "consider removing `for<...>`"
476 );
477 gate_all!(more_qualified_paths, "usage of qualified paths in this context is experimental");
478 if let Some(spans) = spans.get(&sym::yield_expr) {
480 for span in spans {
481 if (!visitor.features.coroutines() && !span.allows_unstable(sym::coroutines))
482 && (!visitor.features.gen_blocks() && !span.allows_unstable(sym::gen_blocks))
483 {
484 #[allow(rustc::untranslatable_diagnostic)]
485 feature_err(&visitor.sess, sym::coroutines, *span, "yield syntax is experimental")
488 .emit();
489 }
490 }
491 }
492 gate_all!(gen_blocks, "gen blocks are experimental");
493 gate_all!(const_trait_impl, "const trait impls are experimental");
494 gate_all!(
495 half_open_range_patterns_in_slices,
496 "half-open range patterns in slices are unstable"
497 );
498 gate_all!(inline_const_pat, "inline-const in pattern position is experimental");
499 gate_all!(associated_const_equality, "associated const equality is incomplete");
500 gate_all!(yeet_expr, "`do yeet` expression is experimental");
501 gate_all!(dyn_star, "`dyn*` trait objects are experimental");
502 gate_all!(const_closures, "const closures are experimental");
503 gate_all!(builtin_syntax, "`builtin #` syntax is unstable");
504 gate_all!(explicit_tail_calls, "`become` expression is experimental");
505 gate_all!(generic_const_items, "generic const items are experimental");
506 gate_all!(guard_patterns, "guard patterns are experimental", "consider using match arm guards");
507 gate_all!(default_field_values, "default values on fields are experimental");
508 gate_all!(fn_delegation, "functions delegation is not yet fully implemented");
509 gate_all!(postfix_match, "postfix match is experimental");
510 gate_all!(mut_ref, "mutable by-reference bindings are experimental");
511 gate_all!(global_registration, "global registration is experimental");
512 gate_all!(return_type_notation, "return type notation is experimental");
513 gate_all!(pin_ergonomics, "pinned reference syntax is experimental");
514 gate_all!(unsafe_fields, "`unsafe` fields are experimental");
515 gate_all!(unsafe_binders, "unsafe binder types are experimental");
516 gate_all!(contracts, "contracts are incomplete");
517 gate_all!(contracts_internals, "contract internal machinery is for internal use only");
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}