Skip to content

Commit

Permalink
Introduce ~const
Browse files Browse the repository at this point in the history
 - [x] Removed `?const` and change uses of `?const`
 - [x] Added `~const` to the AST. It is gated behind const_trait_impl.
 - [x] Validate `~const` in ast_validation.
 - [ ] Add enum `BoundConstness` to the HIR. (With variants `NotConst` and
 `ConstIfConst` allowing future extensions)
 - [ ] Adjust trait selection and pre-existing code to use `BoundConstness`.
 - [ ] Optional steps (*for this PR, obviously*)
      - [ ] Fix #88155
      - [ ] Do something with constness bounds in chalk
  • Loading branch information
fee1-dead committed Aug 27, 2021
1 parent d5cd320 commit 8660832
Show file tree
Hide file tree
Showing 16 changed files with 178 additions and 125 deletions.
6 changes: 3 additions & 3 deletions compiler/rustc_ast/src/ast.rs
Original file line number Diff line number Diff line change
Expand Up @@ -284,7 +284,7 @@ impl ParenthesizedArgs {

pub use crate::node_id::{NodeId, CRATE_NODE_ID, DUMMY_NODE_ID};

/// A modifier on a bound, e.g., `?Sized` or `?const Trait`.
/// A modifier on a bound, e.g., `?Sized` or `~const Trait`.
///
/// Negative bounds should also be handled here.
#[derive(Copy, Clone, PartialEq, Eq, Encodable, Decodable, Debug)]
Expand All @@ -295,10 +295,10 @@ pub enum TraitBoundModifier {
/// `?Trait`
Maybe,

/// `?const Trait`
/// `~const Trait`
MaybeConst,

/// `?const ?Trait`
/// `~const ?Trait`
//
// This parses but will be rejected during AST validation.
MaybeConstMaybe,
Expand Down
2 changes: 1 addition & 1 deletion compiler/rustc_ast_lowering/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1414,7 +1414,7 @@ impl<'a, 'hir> LoweringContext<'a, 'hir> {
ref ty,
TraitBoundModifier::None | TraitBoundModifier::MaybeConst,
) => Some(this.lower_poly_trait_ref(ty, itctx.reborrow())),
// `?const ?Bound` will cause an error during AST validation
// `~const ?Bound` will cause an error during AST validation
// anyways, so treat it like `?Bound` as compilation proceeds.
GenericBound::Trait(
_,
Expand Down
152 changes: 100 additions & 52 deletions compiler/rustc_ast_passes/src/ast_validation.rs
Original file line number Diff line number Diff line change
Expand Up @@ -17,10 +17,11 @@ use rustc_errors::{error_code, pluralize, struct_span_err, Applicability};
use rustc_parse::validate_attr;
use rustc_session::lint::builtin::PATTERNS_IN_FNS_WITHOUT_BODY;
use rustc_session::lint::{BuiltinLintDiagnostics, LintBuffer};
use rustc_session::Session;
use rustc_session::{DiagnosticMessageId, Session};
use rustc_span::source_map::Spanned;
use rustc_span::symbol::{kw, sym, Ident};
use rustc_span::Span;
use std::convert::TryInto;
use std::mem;
use std::ops::DerefMut;

Expand All @@ -33,24 +34,6 @@ enum SelfSemantic {
No,
}

/// A syntactic context that disallows certain kinds of bounds (e.g., `?Trait` or `?const Trait`).
#[derive(Clone, Copy)]
enum BoundContext {
ImplTrait,
TraitBounds,
TraitObject,
}

impl BoundContext {
fn description(&self) -> &'static str {
match self {
Self::ImplTrait => "`impl Trait`",
Self::TraitBounds => "supertraits",
Self::TraitObject => "trait objects",
}
}
}

struct AstValidator<'a> {
session: &'a Session,

Expand All @@ -60,18 +43,16 @@ struct AstValidator<'a> {
/// Are we inside a trait impl?
in_trait_impl: bool,

in_const_trait_impl: bool,

has_proc_macro_decls: bool,

/// Used to ban nested `impl Trait`, e.g., `impl Into<impl Debug>`.
/// Nested `impl Trait` _is_ allowed in associated type position,
/// e.g., `impl Iterator<Item = impl Debug>`.
outer_impl_trait: Option<Span>,

/// Keeps track of the `BoundContext` as we recurse.
///
/// This is used to forbid `?const Trait` bounds in, e.g.,
/// `impl Iterator<Item = Box<dyn ?const Trait>`.
bound_context: Option<BoundContext>,
is_tilde_const_allowed: bool,

/// Used to ban `impl Trait` in path projections like `<impl Iterator>::Item`
/// or `Foo::Bar<impl Trait>`
Expand All @@ -88,10 +69,18 @@ struct AstValidator<'a> {
}

impl<'a> AstValidator<'a> {
fn with_in_trait_impl(&mut self, is_in: bool, f: impl FnOnce(&mut Self)) {
fn with_in_trait_impl(
&mut self,
is_in: bool,
constness: Option<Const>,
f: impl FnOnce(&mut Self),
) {
let old = mem::replace(&mut self.in_trait_impl, is_in);
let old_const =
mem::replace(&mut self.in_const_trait_impl, matches!(constness, Some(Const::Yes(_))));
f(self);
self.in_trait_impl = old;
self.in_const_trait_impl = old_const;
}

fn with_banned_impl_trait(&mut self, f: impl FnOnce(&mut Self)) {
Expand All @@ -100,6 +89,18 @@ impl<'a> AstValidator<'a> {
self.is_impl_trait_banned = old;
}

fn with_tilde_const_allowed(&mut self, f: impl FnOnce(&mut Self)) {
let old = mem::replace(&mut self.is_tilde_const_allowed, true);
f(self);
self.is_tilde_const_allowed = old;
}

fn with_banned_tilde_const(&mut self, f: impl FnOnce(&mut Self)) {
let old = mem::replace(&mut self.is_tilde_const_allowed, false);
f(self);
self.is_tilde_const_allowed = old;
}

fn with_let_allowed(&mut self, allowed: bool, f: impl FnOnce(&mut Self, bool)) {
let old = mem::replace(&mut self.is_let_allowed, allowed);
f(self, old);
Expand Down Expand Up @@ -130,19 +131,13 @@ impl<'a> AstValidator<'a> {
fn with_impl_trait(&mut self, outer: Option<Span>, f: impl FnOnce(&mut Self)) {
let old = mem::replace(&mut self.outer_impl_trait, outer);
if outer.is_some() {
self.with_bound_context(BoundContext::ImplTrait, |this| f(this));
self.with_banned_tilde_const(f);
} else {
f(self)
f(self);
}
self.outer_impl_trait = old;
}

fn with_bound_context(&mut self, ctx: BoundContext, f: impl FnOnce(&mut Self)) {
let old = self.bound_context.replace(ctx);
f(self);
self.bound_context = old;
}

fn visit_assoc_ty_constraint_from_generic_args(&mut self, constraint: &'a AssocTyConstraint) {
match constraint.kind {
AssocTyConstraintKind::Equality { .. } => {}
Expand All @@ -164,9 +159,7 @@ impl<'a> AstValidator<'a> {
TyKind::ImplTrait(..) => {
self.with_impl_trait(Some(t.span), |this| visit::walk_ty(this, t))
}
TyKind::TraitObject(..) => {
self.with_bound_context(BoundContext::TraitObject, |this| visit::walk_ty(this, t));
}
TyKind::TraitObject(..) => self.with_banned_tilde_const(|this| visit::walk_ty(this, t)),
TyKind::Path(ref qself, ref path) => {
// We allow these:
// - `Option<impl Trait>`
Expand Down Expand Up @@ -1083,13 +1076,13 @@ impl<'a> Visitor<'a> for AstValidator<'a> {
unsafety,
polarity,
defaultness: _,
constness: _,
generics: _,
constness,
ref generics,
of_trait: Some(ref t),
ref self_ty,
items: _,
ref items,
}) => {
self.with_in_trait_impl(true, |this| {
self.with_in_trait_impl(true, Some(constness), |this| {
this.invalid_visibility(&item.vis, None);
if let TyKind::Err = self_ty.kind {
this.err_handler()
Expand All @@ -1112,7 +1105,17 @@ impl<'a> Visitor<'a> for AstValidator<'a> {
.emit();
}

visit::walk_item(this, item);
this.visit_vis(&item.vis);
this.visit_ident(item.ident);
if let Const::Yes(_) = constness {
this.with_tilde_const_allowed(|this| this.visit_generics(generics));
} else {
this.visit_generics(generics);
}
this.visit_trait_ref(t);
this.visit_ty(self_ty);

walk_list!(this, visit_assoc_item, items, AssocCtxt::Impl);
});
return; // Avoid visiting again.
}
Expand Down Expand Up @@ -1157,13 +1160,23 @@ impl<'a> Visitor<'a> for AstValidator<'a> {
.emit();
}
}
ItemKind::Fn(box FnKind(def, _, _, ref body)) => {
ItemKind::Fn(box FnKind(def, ref sig, ref generics, ref body)) => {
self.check_defaultness(item.span, def);

if body.is_none() {
let msg = "free function without a body";
self.error_item_without_body(item.span, "function", msg, " { <body> }");
}
self.visit_vis(&item.vis);
self.visit_ident(item.ident);
if let Const::Yes(_) = sig.header.constness {
self.with_tilde_const_allowed(|this| this.visit_generics(generics));
} else {
self.visit_generics(generics);
}
let kind = FnKind::Fn(FnCtxt::Free, item.ident, sig, &item.vis, body.as_deref());
self.visit_fn(kind, item.span, item.id);
walk_list!(self, visit_attribute, &item.attrs);
}
ItemKind::ForeignMod(ForeignMod { unsafety, .. }) => {
let old_item = mem::replace(&mut self.extern_mod, Some(item));
Expand Down Expand Up @@ -1206,9 +1219,7 @@ impl<'a> Visitor<'a> for AstValidator<'a> {
self.visit_vis(&item.vis);
self.visit_ident(item.ident);
self.visit_generics(generics);
self.with_bound_context(BoundContext::TraitBounds, |this| {
walk_list!(this, visit_param_bound, bounds);
});
self.with_banned_tilde_const(|this| walk_list!(this, visit_param_bound, bounds));
walk_list!(self, visit_assoc_item, trait_items, AssocCtxt::Trait);
walk_list!(self, visit_attribute, &item.attrs);
return;
Expand Down Expand Up @@ -1281,7 +1292,7 @@ impl<'a> Visitor<'a> for AstValidator<'a> {
_ => {}
}

visit::walk_item(self, item)
visit::walk_item(self, item);
}

fn visit_foreign_item(&mut self, fi: &'a ForeignItem) {
Expand Down Expand Up @@ -1428,15 +1439,26 @@ impl<'a> Visitor<'a> for AstValidator<'a> {
fn visit_param_bound(&mut self, bound: &'a GenericBound) {
match bound {
GenericBound::Trait(_, TraitBoundModifier::MaybeConst) => {
if let Some(ctx) = self.bound_context {
let msg = format!("`?const` is not permitted in {}", ctx.description());
self.err_handler().span_err(bound.span(), &msg);
if !self.is_tilde_const_allowed {
let msg = "`~const` is not allowed here";
let id_span_msg = (
DiagnosticMessageId::StabilityId(67792.try_into().ok()),
Some(bound.span()),
msg.to_owned(),
);
let fresh = self.session.one_time_diagnostics.borrow_mut().insert(id_span_msg);
if fresh {
self.err_handler()
.struct_span_err(bound.span(), msg)
.note("only allowed on bounds on traits' associated types, const fns, const impls and its associated functions")
.emit();
}
}
}

GenericBound::Trait(_, TraitBoundModifier::MaybeConstMaybe) => {
self.err_handler()
.span_err(bound.span(), "`?const` and `?` are mutually exclusive");
.span_err(bound.span(), "`~const` and `?` are mutually exclusive");
}

_ => {}
Expand Down Expand Up @@ -1589,7 +1611,32 @@ impl<'a> Visitor<'a> for AstValidator<'a> {
self.check_item_named(item.ident, "const");
}

self.with_in_trait_impl(false, |this| visit::walk_assoc_item(this, item, ctxt));
match item.kind {
AssocItemKind::TyAlias(box TyAliasKind(_, ref generics, ref bounds, ref ty))
if ctxt == AssocCtxt::Trait =>
{
self.visit_vis(&item.vis);
self.visit_ident(item.ident);
walk_list!(self, visit_attribute, &item.attrs);
self.with_tilde_const_allowed(|this| {
this.visit_generics(generics);
walk_list!(this, visit_param_bound, bounds);
});
walk_list!(self, visit_ty, ty);
}
AssocItemKind::Fn(box FnKind(_, ref sig, ref generics, ref body))
if self.in_const_trait_impl =>
{
self.visit_vis(&item.vis);
self.visit_ident(item.ident);
self.with_tilde_const_allowed(|this| this.visit_generics(generics));
let kind =
FnKind::Fn(FnCtxt::Assoc(ctxt), item.ident, sig, &item.vis, body.as_deref());
self.visit_fn(kind, item.span, item.id);
}
_ => self
.with_in_trait_impl(false, None, |this| visit::walk_assoc_item(this, item, ctxt)),
}
}
}

Expand Down Expand Up @@ -1683,9 +1730,10 @@ pub fn check_crate(session: &Session, krate: &Crate, lints: &mut LintBuffer) ->
session,
extern_mod: None,
in_trait_impl: false,
in_const_trait_impl: false,
has_proc_macro_decls: false,
outer_impl_trait: None,
bound_context: None,
is_tilde_const_allowed: false,
is_impl_trait_banned: false,
is_assoc_ty_bound_banned: false,
is_let_allowed: false,
Expand Down
1 change: 0 additions & 1 deletion compiler/rustc_ast_passes/src/feature_gate.rs
Original file line number Diff line number Diff line change
Expand Up @@ -656,7 +656,6 @@ pub fn check_crate(krate: &ast::Crate, sess: &Session) {
gate_all!(more_qualified_paths, "usage of qualified paths in this context is experimental");
gate_all!(generators, "yield syntax is experimental");
gate_all!(raw_ref_op, "raw address of syntax is experimental");
gate_all!(const_trait_bound_opt_out, "`?const` on trait bounds is experimental");
gate_all!(const_trait_impl, "const trait impls are experimental");
gate_all!(half_open_range_patterns, "half-open range patterns are unstable");
gate_all!(inline_const, "inline-const is experimental");
Expand Down
3 changes: 0 additions & 3 deletions compiler/rustc_feature/src/active.rs
Original file line number Diff line number Diff line change
Expand Up @@ -515,9 +515,6 @@ declare_features! (
/// Allows `impl const Trait for T` syntax.
(active, const_trait_impl, "1.42.0", Some(67792), None),

/// Allows `T: ?const Trait` syntax in bounds.
(incomplete, const_trait_bound_opt_out, "1.42.0", Some(67794), None),

/// Allows the use of `no_sanitize` attribute.
(active, no_sanitize, "1.42.0", Some(39699), None),

Expand Down
3 changes: 3 additions & 0 deletions compiler/rustc_feature/src/removed.rs
Original file line number Diff line number Diff line change
Expand Up @@ -123,6 +123,9 @@ declare_features! (
/// Allows overlapping impls of marker traits.
(removed, overlapping_marker_traits, "1.42.0", Some(29864), None,
Some("removed in favor of `#![feature(marker_trait_attr)]`")),
/// Allows `T: ?const Trait` syntax in bounds.
(removed, const_trait_bound_opt_out, "1.42.0", Some(67794), None,
Some("Removed in favor of `~const` bound in #![feature(const_trait_impl)]")),
/// Allows `#[no_debug]`.
(removed, no_debug, "1.43.0", Some(29721), None, Some("removed due to lack of demand")),
/// Allows comparing raw pointers during const eval.
Expand Down
7 changes: 1 addition & 6 deletions compiler/rustc_middle/src/ty/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -457,10 +457,6 @@ pub enum PredicateKind<'tcx> {
/// Corresponds to `where Foo: Bar<A, B, C>`. `Foo` here would be
/// the `Self` type of the trait reference and `A`, `B`, and `C`
/// would be the type parameters.
///
/// A trait predicate will have `Constness::Const` if it originates
/// from a bound on a `const fn` without the `?const` opt-out (e.g.,
/// `const fn foobar<Foo: Bar>() {}`).
Trait(TraitPredicate<'tcx>),

/// `where 'a: 'b`
Expand Down Expand Up @@ -633,8 +629,7 @@ pub struct TraitPredicate<'tcx> {
pub trait_ref: TraitRef<'tcx>,

/// A trait predicate will have `Constness::Const` if it originates
/// from a bound on a `const fn` without the `?const` opt-out (e.g.,
/// `const fn foobar<Foo: Bar>() {}`).
/// from a bound marked with `~const`.
pub constness: hir::Constness,
}

Expand Down
Loading

0 comments on commit 8660832

Please sign in to comment.