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