Skip to content

Commit f396387

Browse files
authored
Rollup merge of rust-lang#67820 - ecstatic-morse:const-trait, r=oli-obk
Parse the syntax described in RFC 2632 This adds support for both `impl const Trait for Ty` and `?const Trait` bound syntax from rust-lang/rfcs#2632 to the parser. For now, both modifiers end up in a newly-added `constness` field on `ast::TraitRef`, although this may change once the implementation is fleshed out. I was planning on using `delay_span_bug` when this syntax is encountered during lowering, but I can't write `should-ice` UI tests. I emit a normal error instead, which causes duplicates when the feature gate is not enabled (see the `.stderr` files for the feature gate tests). Not sure what the desired approach is; Maybe just do nothing when the syntax is encountered with the feature gate is enabled? @oli-obk I went with `const_trait_impl` and `const_trait_bound_opt_out` for the names of these features. Are these to your liking? cc rust-lang#67792 rust-lang#67794 r? @Centril
2 parents e180d36 + fd1c003 commit f396387

37 files changed

+586
-25
lines changed

src/librustc_ast_lowering/item.rs

+6
Original file line numberDiff line numberDiff line change
@@ -71,6 +71,12 @@ impl<'a, 'lowering, 'hir> Visitor<'a> for ItemLowerer<'a, 'lowering, 'hir> {
7171
self.lctx.with_parent_item_lifetime_defs(hir_id, |this| {
7272
let this = &mut ItemLowerer { lctx: this };
7373
if let ItemKind::Impl(.., ref opt_trait_ref, _, _) = item.kind {
74+
if opt_trait_ref.as_ref().map(|tr| tr.constness.is_some()).unwrap_or(false) {
75+
this.lctx
76+
.diagnostic()
77+
.span_err(item.span, "const trait impls are not yet implemented");
78+
}
79+
7480
this.with_trait_impl_ref(opt_trait_ref, |this| visit::walk_item(this, item));
7581
} else {
7682
visit::walk_item(this, item);

src/librustc_ast_lowering/lib.rs

+4
Original file line numberDiff line numberDiff line change
@@ -2579,6 +2579,10 @@ impl<'a, 'hir> LoweringContext<'a, 'hir> {
25792579
p: &PolyTraitRef,
25802580
mut itctx: ImplTraitContext<'_, 'hir>,
25812581
) -> hir::PolyTraitRef<'hir> {
2582+
if p.trait_ref.constness.is_some() {
2583+
self.diagnostic().span_err(p.span, "`?const` on trait bounds is not yet implemented");
2584+
}
2585+
25822586
let bound_generic_params = self.lower_generic_params(
25832587
&p.bound_generic_params,
25842588
&NodeMap::default(),

src/librustc_expand/build.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -110,7 +110,7 @@ impl<'a> ExtCtxt<'a> {
110110
}
111111

112112
pub fn trait_ref(&self, path: ast::Path) -> ast::TraitRef {
113-
ast::TraitRef { path, ref_id: ast::DUMMY_NODE_ID }
113+
ast::TraitRef { path, constness: None, ref_id: ast::DUMMY_NODE_ID }
114114
}
115115

116116
pub fn poly_trait_ref(&self, span: Span, path: ast::Path) -> ast::PolyTraitRef {

src/librustc_feature/active.rs

+8
Original file line numberDiff line numberDiff line change
@@ -544,6 +544,12 @@ declare_features! (
544544
/// For example, you can write `x @ Some(y)`.
545545
(active, bindings_after_at, "1.41.0", Some(65490), None),
546546

547+
/// Allows `impl const Trait for T` syntax.
548+
(active, const_trait_impl, "1.42.0", Some(67792), None),
549+
550+
/// Allows `T: ?const Trait` syntax in bounds.
551+
(active, const_trait_bound_opt_out, "1.42.0", Some(67794), None),
552+
547553
// -------------------------------------------------------------------------
548554
// feature-group-end: actual feature gates
549555
// -------------------------------------------------------------------------
@@ -559,4 +565,6 @@ pub const INCOMPLETE_FEATURES: &[Symbol] = &[
559565
sym::or_patterns,
560566
sym::let_chains,
561567
sym::raw_dylib,
568+
sym::const_trait_impl,
569+
sym::const_trait_bound_opt_out,
562570
];

src/librustc_parse/parser/item.rs

+21-4
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,7 @@ use crate::maybe_whole;
55

66
use rustc_error_codes::*;
77
use rustc_errors::{struct_span_err, Applicability, DiagnosticBuilder, PResult, StashKey};
8-
use rustc_span::source_map::{self, respan, Span};
8+
use rustc_span::source_map::{self, respan, Span, Spanned};
99
use rustc_span::symbol::{kw, sym, Symbol};
1010
use rustc_span::BytePos;
1111
use syntax::ast::{self, AttrKind, AttrStyle, AttrVec, Attribute, Ident, DUMMY_NODE_ID};
@@ -542,10 +542,11 @@ impl<'a> Parser<'a> {
542542
/// impl<'a, T> TYPE { /* impl items */ }
543543
/// impl<'a, T> TRAIT for TYPE { /* impl items */ }
544544
/// impl<'a, T> !TRAIT for TYPE { /* impl items */ }
545+
/// impl<'a, T> const TRAIT for TYPE { /* impl items */ }
545546
///
546547
/// We actually parse slightly more relaxed grammar for better error reporting and recovery.
547-
/// `impl` GENERICS `!`? TYPE `for`? (TYPE | `..`) (`where` PREDICATES)? `{` BODY `}`
548-
/// `impl` GENERICS `!`? TYPE (`where` PREDICATES)? `{` BODY `}`
548+
/// `impl` GENERICS `const`? `!`? TYPE `for`? (TYPE | `..`) (`where` PREDICATES)? `{` BODY `}`
549+
/// `impl` GENERICS `const`? `!`? TYPE (`where` PREDICATES)? `{` BODY `}`
549550
fn parse_item_impl(
550551
&mut self,
551552
unsafety: Unsafety,
@@ -558,6 +559,14 @@ impl<'a> Parser<'a> {
558559
Generics::default()
559560
};
560561

562+
let constness = if self.eat_keyword(kw::Const) {
563+
let span = self.prev_span;
564+
self.sess.gated_spans.gate(sym::const_trait_impl, span);
565+
Some(respan(span, Constness::Const))
566+
} else {
567+
None
568+
};
569+
561570
// Disambiguate `impl !Trait for Type { ... }` and `impl ! { ... }` for the never type.
562571
let polarity = if self.check(&token::Not) && self.look_ahead(1, |t| t.can_begin_type()) {
563572
self.bump(); // `!`
@@ -618,7 +627,8 @@ impl<'a> Parser<'a> {
618627
err_path(ty_first.span)
619628
}
620629
};
621-
let trait_ref = TraitRef { path, ref_id: ty_first.id };
630+
let constness = constness.map(|c| c.node);
631+
let trait_ref = TraitRef { path, constness, ref_id: ty_first.id };
622632

623633
ItemKind::Impl(
624634
unsafety,
@@ -631,6 +641,13 @@ impl<'a> Parser<'a> {
631641
)
632642
}
633643
None => {
644+
// Reject `impl const Type {}` here
645+
if let Some(Spanned { node: Constness::Const, span }) = constness {
646+
self.struct_span_err(span, "`const` cannot modify an inherent impl")
647+
.help("only a trait impl can be `const`")
648+
.emit();
649+
}
650+
634651
// impl Type
635652
ItemKind::Impl(
636653
unsafety,

src/librustc_parse/parser/ty.rs

+77-14
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,7 @@ use crate::{maybe_recover_from_interpolated_ty_qpath, maybe_whole};
66
use rustc_error_codes::*;
77
use rustc_errors::{pluralize, struct_span_err, Applicability, PResult};
88
use rustc_span::source_map::Span;
9-
use rustc_span::symbol::kw;
9+
use rustc_span::symbol::{kw, sym};
1010
use syntax::ast::{
1111
self, BareFnTy, FunctionRetTy, GenericParam, Ident, Lifetime, MutTy, Ty, TyKind,
1212
};
@@ -17,6 +17,24 @@ use syntax::ast::{Mac, Mutability};
1717
use syntax::ptr::P;
1818
use syntax::token::{self, Token};
1919

20+
/// Any `?` or `?const` modifiers that appear at the start of a bound.
21+
struct BoundModifiers {
22+
/// `?Trait`.
23+
maybe: Option<Span>,
24+
25+
/// `?const Trait`.
26+
maybe_const: Option<Span>,
27+
}
28+
29+
impl BoundModifiers {
30+
fn trait_bound_modifier(&self) -> TraitBoundModifier {
31+
match self.maybe {
32+
Some(_) => TraitBoundModifier::Maybe,
33+
None => TraitBoundModifier::None,
34+
}
35+
}
36+
}
37+
2038
/// Returns `true` if `IDENT t` can start a type -- `IDENT::a::b`, `IDENT<u8, u8>`,
2139
/// `IDENT<<u8 as Trait>::AssocTy>`.
2240
///
@@ -195,7 +213,9 @@ impl<'a> Parser<'a> {
195213
lo: Span,
196214
parse_plus: bool,
197215
) -> PResult<'a, TyKind> {
198-
let poly_trait_ref = PolyTraitRef::new(generic_params, path, lo.to(self.prev_span));
216+
assert_ne!(self.token, token::Question);
217+
218+
let poly_trait_ref = PolyTraitRef::new(generic_params, path, None, lo.to(self.prev_span));
199219
let mut bounds = vec![GenericBound::Trait(poly_trait_ref, TraitBoundModifier::None)];
200220
if parse_plus {
201221
self.eat_plus(); // `+`, or `+=` gets split and `+` is discarded
@@ -421,12 +441,15 @@ impl<'a> Parser<'a> {
421441
let has_parens = self.eat(&token::OpenDelim(token::Paren));
422442
let inner_lo = self.token.span;
423443
let is_negative = self.eat(&token::Not);
424-
let question = self.eat(&token::Question).then_some(self.prev_span);
444+
445+
let modifiers = self.parse_ty_bound_modifiers();
425446
let bound = if self.token.is_lifetime() {
426-
self.parse_generic_lt_bound(lo, inner_lo, has_parens, question)?
447+
self.error_lt_bound_with_modifiers(modifiers);
448+
self.parse_generic_lt_bound(lo, inner_lo, has_parens)?
427449
} else {
428-
self.parse_generic_ty_bound(lo, has_parens, question)?
450+
self.parse_generic_ty_bound(lo, has_parens, modifiers)?
429451
};
452+
430453
Ok(if is_negative { Err(anchor_lo.to(self.prev_span)) } else { Ok(bound) })
431454
}
432455

@@ -439,9 +462,7 @@ impl<'a> Parser<'a> {
439462
lo: Span,
440463
inner_lo: Span,
441464
has_parens: bool,
442-
question: Option<Span>,
443465
) -> PResult<'a, GenericBound> {
444-
self.error_opt_out_lifetime(question);
445466
let bound = GenericBound::Outlives(self.expect_lifetime());
446467
if has_parens {
447468
// FIXME(Centril): Consider not erroring here and accepting `('lt)` instead,
@@ -451,8 +472,17 @@ impl<'a> Parser<'a> {
451472
Ok(bound)
452473
}
453474

454-
fn error_opt_out_lifetime(&self, question: Option<Span>) {
455-
if let Some(span) = question {
475+
/// Emits an error if any trait bound modifiers were present.
476+
fn error_lt_bound_with_modifiers(&self, modifiers: BoundModifiers) {
477+
if let Some(span) = modifiers.maybe_const {
478+
self.struct_span_err(
479+
span,
480+
"`?const` may only modify trait bounds, not lifetime bounds",
481+
)
482+
.emit();
483+
}
484+
485+
if let Some(span) = modifiers.maybe {
456486
self.struct_span_err(span, "`?` may only modify trait bounds, not lifetime bounds")
457487
.emit();
458488
}
@@ -478,25 +508,58 @@ impl<'a> Parser<'a> {
478508
Ok(())
479509
}
480510

511+
/// Parses the modifiers that may precede a trait in a bound, e.g. `?Trait` or `?const Trait`.
512+
///
513+
/// If no modifiers are present, this does not consume any tokens.
514+
///
515+
/// ```
516+
/// TY_BOUND_MODIFIERS = "?" ["const" ["?"]]
517+
/// ```
518+
fn parse_ty_bound_modifiers(&mut self) -> BoundModifiers {
519+
if !self.eat(&token::Question) {
520+
return BoundModifiers { maybe: None, maybe_const: None };
521+
}
522+
523+
// `? ...`
524+
let first_question = self.prev_span;
525+
if !self.eat_keyword(kw::Const) {
526+
return BoundModifiers { maybe: Some(first_question), maybe_const: None };
527+
}
528+
529+
// `?const ...`
530+
let maybe_const = first_question.to(self.prev_span);
531+
self.sess.gated_spans.gate(sym::const_trait_bound_opt_out, maybe_const);
532+
if !self.eat(&token::Question) {
533+
return BoundModifiers { maybe: None, maybe_const: Some(maybe_const) };
534+
}
535+
536+
// `?const ? ...`
537+
let second_question = self.prev_span;
538+
BoundModifiers { maybe: Some(second_question), maybe_const: Some(maybe_const) }
539+
}
540+
481541
/// Parses a type bound according to:
482542
/// ```
483543
/// TY_BOUND = TY_BOUND_NOPAREN | (TY_BOUND_NOPAREN)
484-
/// TY_BOUND_NOPAREN = [?] [for<LT_PARAM_DEFS>] SIMPLE_PATH (e.g., `?for<'a: 'b> m::Trait<'a>`)
544+
/// TY_BOUND_NOPAREN = [TY_BOUND_MODIFIERS] [for<LT_PARAM_DEFS>] SIMPLE_PATH
485545
/// ```
546+
///
547+
/// For example, this grammar accepts `?const ?for<'a: 'b> m::Trait<'a>`.
486548
fn parse_generic_ty_bound(
487549
&mut self,
488550
lo: Span,
489551
has_parens: bool,
490-
question: Option<Span>,
552+
modifiers: BoundModifiers,
491553
) -> PResult<'a, GenericBound> {
492554
let lifetime_defs = self.parse_late_bound_lifetime_defs()?;
493555
let path = self.parse_path(PathStyle::Type)?;
494556
if has_parens {
495557
self.expect(&token::CloseDelim(token::Paren))?;
496558
}
497-
let poly_trait = PolyTraitRef::new(lifetime_defs, path, lo.to(self.prev_span));
498-
let modifier = question.map_or(TraitBoundModifier::None, |_| TraitBoundModifier::Maybe);
499-
Ok(GenericBound::Trait(poly_trait, modifier))
559+
560+
let constness = modifiers.maybe_const.map(|_| ast::Constness::NotConst);
561+
let poly_trait = PolyTraitRef::new(lifetime_defs, path, constness, lo.to(self.prev_span));
562+
Ok(GenericBound::Trait(poly_trait, modifiers.trait_bound_modifier()))
500563
}
501564

502565
/// Optionally parses `for<$generic_params>`.

0 commit comments

Comments
 (0)