Skip to content
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.

Commit 8d8135f

Browse files
committedMar 24, 2022
Auto merge of #94876 - b-naber:thir-abstract-const-changes, r=lcnr
Change Thir to lazily create constants To allow `AbstractConst`s to work with the previous thir changes we made and those we want to make, i.e. to avoid problems due to `ValTree` and `ConstValue` conversions, we instead switch to a thir representation for constants that allows us to lazily create constants. r? `@oli-obk`
2 parents d2df372 + 19041d9 commit 8d8135f

File tree

17 files changed

+346
-155
lines changed

17 files changed

+346
-155
lines changed
 

‎compiler/rustc_middle/src/query/mod.rs

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -955,6 +955,7 @@ rustc_queries! {
955955
desc { "get a &core::panic::Location referring to a span" }
956956
}
957957

958+
// FIXME get rid of this with valtrees
958959
query lit_to_const(
959960
key: LitToConstInput<'tcx>
960961
) -> Result<ty::Const<'tcx>, LitToConstError> {

‎compiler/rustc_middle/src/thir.rs

Lines changed: 25 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -369,7 +369,8 @@ pub enum ExprKind<'tcx> {
369369
},
370370
/// An inline `const` block, e.g. `const {}`.
371371
ConstBlock {
372-
value: Const<'tcx>,
372+
did: DefId,
373+
substs: SubstsRef<'tcx>,
373374
},
374375
/// An array literal constructed from one repeated element, e.g. `[1; 5]`.
375376
Repeat {
@@ -408,13 +409,25 @@ pub enum ExprKind<'tcx> {
408409
},
409410
/// A literal.
410411
Literal {
411-
literal: Const<'tcx>,
412+
lit: &'tcx hir::Lit,
413+
neg: bool,
414+
},
415+
/// For literals that don't correspond to anything in the HIR
416+
NonHirLiteral {
417+
lit: ty::ScalarInt,
418+
user_ty: Option<Canonical<'tcx, UserType<'tcx>>>,
419+
},
420+
/// Associated constants and named constants
421+
NamedConst {
422+
def_id: DefId,
423+
substs: SubstsRef<'tcx>,
412424
user_ty: Option<Canonical<'tcx, UserType<'tcx>>>,
413-
/// The `DefId` of the `const` item this literal
414-
/// was produced from, if this is not a user-written
415-
/// literal value.
416-
const_id: Option<DefId>,
417425
},
426+
ConstParam {
427+
param: ty::ParamConst,
428+
def_id: DefId,
429+
},
430+
// FIXME improve docs for `StaticRef` by distinguishing it from `NamedConst`
418431
/// A literal containing the address of a `static`.
419432
///
420433
/// This is only distinguished from `Literal` so that we can register some
@@ -439,6 +452,12 @@ pub enum ExprKind<'tcx> {
439452
},
440453
}
441454

455+
impl<'tcx> ExprKind<'tcx> {
456+
pub fn zero_sized_literal(user_ty: Option<Canonical<'tcx, UserType<'tcx>>>) -> Self {
457+
ExprKind::NonHirLiteral { lit: ty::ScalarInt::ZST, user_ty }
458+
}
459+
}
460+
442461
/// Represents the association of a field identifier and an expression.
443462
///
444463
/// This is used in struct constructors.

‎compiler/rustc_middle/src/thir/visit.rs

Lines changed: 8 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,6 @@
11
use super::{
22
Arm, Block, Expr, ExprKind, Guard, InlineAsmOperand, Pat, PatKind, Stmt, StmtKind, Thir,
33
};
4-
use rustc_middle::ty::Const;
54

65
pub trait Visitor<'a, 'tcx: 'a>: Sized {
76
fn thir(&self) -> &'a Thir<'tcx>;
@@ -25,8 +24,6 @@ pub trait Visitor<'a, 'tcx: 'a>: Sized {
2524
fn visit_pat(&mut self, pat: &Pat<'tcx>) {
2625
walk_pat(self, pat);
2726
}
28-
29-
fn visit_const(&mut self, _cnst: Const<'tcx>) {}
3027
}
3128

3229
pub fn walk_expr<'a, 'tcx: 'a, V: Visitor<'a, 'tcx>>(visitor: &mut V, expr: &Expr<'tcx>) {
@@ -93,10 +90,9 @@ pub fn walk_expr<'a, 'tcx: 'a, V: Visitor<'a, 'tcx>>(visitor: &mut V, expr: &Exp
9390
visitor.visit_expr(&visitor.thir()[value])
9491
}
9592
}
96-
ConstBlock { value } => visitor.visit_const(value),
97-
Repeat { value, count } => {
93+
ConstBlock { did: _, substs: _ } => {}
94+
Repeat { value, count: _ } => {
9895
visitor.visit_expr(&visitor.thir()[value]);
99-
visitor.visit_const(count);
10096
}
10197
Array { ref fields } | Tuple { ref fields } => {
10298
for &field in &**fields {
@@ -122,7 +118,10 @@ pub fn walk_expr<'a, 'tcx: 'a, V: Visitor<'a, 'tcx>>(visitor: &mut V, expr: &Exp
122118
visitor.visit_expr(&visitor.thir()[source])
123119
}
124120
Closure { closure_id: _, substs: _, upvars: _, movability: _, fake_reads: _ } => {}
125-
Literal { literal, user_ty: _, const_id: _ } => visitor.visit_const(literal),
121+
Literal { lit: _, neg: _ } => {}
122+
NonHirLiteral { lit: _, user_ty: _ } => {}
123+
NamedConst { def_id: _, substs: _, user_ty: _ } => {}
124+
ConstParam { param: _, def_id: _ } => {}
126125
StaticRef { alloc_id: _, ty: _, def_id: _ } => {}
127126
InlineAsm { ref operands, template: _, options: _, line_spans: _ } => {
128127
for op in &**operands {
@@ -209,11 +208,8 @@ pub fn walk_pat<'a, 'tcx: 'a, V: Visitor<'a, 'tcx>>(visitor: &mut V, pat: &Pat<'
209208
visitor.visit_pat(&subpattern.pattern);
210209
}
211210
}
212-
Constant { value } => visitor.visit_const(*value),
213-
Range(range) => {
214-
visitor.visit_const(range.lo);
215-
visitor.visit_const(range.hi);
216-
}
211+
Constant { value: _ } => {}
212+
Range(_) => {}
217213
Slice { prefix, slice, suffix } | Array { prefix, slice, suffix } => {
218214
for subpattern in prefix {
219215
visitor.visit_pat(&subpattern);
Lines changed: 108 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -1,43 +1,141 @@
11
//! See docs in build/expr/mod.rs
22
33
use crate::build::Builder;
4-
use rustc_middle::mir::interpret::{ConstValue, Scalar};
4+
use crate::thir::constant::parse_float;
5+
use rustc_ast::ast;
6+
use rustc_hir::def_id::DefId;
7+
use rustc_middle::mir::interpret::{
8+
Allocation, ConstValue, LitToConstError, LitToConstInput, Scalar,
9+
};
510
use rustc_middle::mir::*;
611
use rustc_middle::thir::*;
7-
use rustc_middle::ty::CanonicalUserTypeAnnotation;
12+
use rustc_middle::ty::subst::SubstsRef;
13+
use rustc_middle::ty::{self, CanonicalUserTypeAnnotation, Ty, TyCtxt};
14+
use rustc_target::abi::Size;
815

916
impl<'a, 'tcx> Builder<'a, 'tcx> {
1017
/// Compile `expr`, yielding a compile-time constant. Assumes that
1118
/// `expr` is a valid compile-time constant!
1219
crate fn as_constant(&mut self, expr: &Expr<'tcx>) -> Constant<'tcx> {
20+
let create_uneval_from_def_id =
21+
|tcx: TyCtxt<'tcx>, def_id: DefId, ty: Ty<'tcx>, substs: SubstsRef<'tcx>| {
22+
let uneval = ty::Unevaluated::new(ty::WithOptConstParam::unknown(def_id), substs);
23+
tcx.mk_const(ty::ConstS { val: ty::ConstKind::Unevaluated(uneval), ty })
24+
};
25+
1326
let this = self;
27+
let tcx = this.tcx;
1428
let Expr { ty, temp_lifetime: _, span, ref kind } = *expr;
1529
match *kind {
1630
ExprKind::Scope { region_scope: _, lint_level: _, value } => {
1731
this.as_constant(&this.thir[value])
1832
}
19-
ExprKind::Literal { literal, user_ty, const_id: _ } => {
33+
ExprKind::Literal { lit, neg } => {
34+
let literal =
35+
match lit_to_constant(tcx, LitToConstInput { lit: &lit.node, ty, neg }) {
36+
Ok(c) => c,
37+
Err(LitToConstError::Reported) => ConstantKind::Ty(tcx.const_error(ty)),
38+
Err(LitToConstError::TypeError) => {
39+
bug!("encountered type error in `lit_to_constant")
40+
}
41+
};
42+
43+
Constant { span, user_ty: None, literal: literal.into() }
44+
}
45+
ExprKind::NonHirLiteral { lit, user_ty } => {
2046
let user_ty = user_ty.map(|user_ty| {
2147
this.canonical_user_type_annotations.push(CanonicalUserTypeAnnotation {
2248
span,
2349
user_ty,
2450
inferred_ty: ty,
2551
})
2652
});
27-
assert_eq!(literal.ty(), ty);
28-
Constant { span, user_ty, literal: literal.into() }
53+
54+
let literal = ConstantKind::Val(ConstValue::Scalar(Scalar::Int(lit)), ty);
55+
56+
Constant { span, user_ty: user_ty, literal }
57+
}
58+
ExprKind::NamedConst { def_id, substs, user_ty } => {
59+
let user_ty = user_ty.map(|user_ty| {
60+
this.canonical_user_type_annotations.push(CanonicalUserTypeAnnotation {
61+
span,
62+
user_ty,
63+
inferred_ty: ty,
64+
})
65+
});
66+
let literal = ConstantKind::Ty(create_uneval_from_def_id(tcx, def_id, ty, substs));
67+
68+
Constant { user_ty, span, literal }
69+
}
70+
ExprKind::ConstParam { param, def_id: _ } => {
71+
let const_param =
72+
tcx.mk_const(ty::ConstS { val: ty::ConstKind::Param(param), ty: expr.ty });
73+
let literal = ConstantKind::Ty(const_param);
74+
75+
Constant { user_ty: None, span, literal }
76+
}
77+
ExprKind::ConstBlock { did: def_id, substs } => {
78+
let literal = ConstantKind::Ty(create_uneval_from_def_id(tcx, def_id, ty, substs));
79+
80+
Constant { user_ty: None, span, literal }
2981
}
3082
ExprKind::StaticRef { alloc_id, ty, .. } => {
31-
let const_val =
32-
ConstValue::Scalar(Scalar::from_pointer(alloc_id.into(), &this.tcx));
83+
let const_val = ConstValue::Scalar(Scalar::from_pointer(alloc_id.into(), &tcx));
3384
let literal = ConstantKind::Val(const_val, ty);
3485

3586
Constant { span, user_ty: None, literal }
3687
}
37-
ExprKind::ConstBlock { value } => {
38-
Constant { span: span, user_ty: None, literal: value.into() }
39-
}
4088
_ => span_bug!(span, "expression is not a valid constant {:?}", kind),
4189
}
4290
}
4391
}
92+
93+
crate fn lit_to_constant<'tcx>(
94+
tcx: TyCtxt<'tcx>,
95+
lit_input: LitToConstInput<'tcx>,
96+
) -> Result<ConstantKind<'tcx>, LitToConstError> {
97+
let LitToConstInput { lit, ty, neg } = lit_input;
98+
let trunc = |n| {
99+
let param_ty = ty::ParamEnv::reveal_all().and(ty);
100+
let width = tcx.layout_of(param_ty).map_err(|_| LitToConstError::Reported)?.size;
101+
trace!("trunc {} with size {} and shift {}", n, width.bits(), 128 - width.bits());
102+
let result = width.truncate(n);
103+
trace!("trunc result: {}", result);
104+
Ok(ConstValue::Scalar(Scalar::from_uint(result, width)))
105+
};
106+
107+
let value = match (lit, &ty.kind()) {
108+
(ast::LitKind::Str(s, _), ty::Ref(_, inner_ty, _)) if inner_ty.is_str() => {
109+
let s = s.as_str();
110+
let allocation = Allocation::from_bytes_byte_aligned_immutable(s.as_bytes());
111+
let allocation = tcx.intern_const_alloc(allocation);
112+
ConstValue::Slice { data: allocation, start: 0, end: s.len() }
113+
}
114+
(ast::LitKind::ByteStr(data), ty::Ref(_, inner_ty, _))
115+
if matches!(inner_ty.kind(), ty::Slice(_)) =>
116+
{
117+
let allocation = Allocation::from_bytes_byte_aligned_immutable(data as &[u8]);
118+
let allocation = tcx.intern_const_alloc(allocation);
119+
ConstValue::Slice { data: allocation, start: 0, end: data.len() }
120+
}
121+
(ast::LitKind::ByteStr(data), ty::Ref(_, inner_ty, _)) if inner_ty.is_array() => {
122+
let id = tcx.allocate_bytes(data);
123+
ConstValue::Scalar(Scalar::from_pointer(id.into(), &tcx))
124+
}
125+
(ast::LitKind::Byte(n), ty::Uint(ty::UintTy::U8)) => {
126+
ConstValue::Scalar(Scalar::from_uint(*n, Size::from_bytes(1)))
127+
}
128+
(ast::LitKind::Int(n, _), ty::Uint(_)) | (ast::LitKind::Int(n, _), ty::Int(_)) => {
129+
trunc(if neg { (*n as i128).overflowing_neg().0 as u128 } else { *n })?
130+
}
131+
(ast::LitKind::Float(n, _), ty::Float(fty)) => {
132+
parse_float(*n, *fty, neg).ok_or(LitToConstError::Reported)?
133+
}
134+
(ast::LitKind::Bool(b), ty::Bool) => ConstValue::Scalar(Scalar::from_bool(*b)),
135+
(ast::LitKind::Char(c), ty::Char) => ConstValue::Scalar(Scalar::from_char(*c)),
136+
(ast::LitKind::Err(_), _) => return Err(LitToConstError::Reported),
137+
_ => return Err(LitToConstError::TypeError),
138+
};
139+
140+
Ok(ConstantKind::Val(value, ty))
141+
}

‎compiler/rustc_mir_build/src/build/expr/as_place.rs

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -566,6 +566,9 @@ impl<'a, 'tcx> Builder<'a, 'tcx> {
566566
| ExprKind::Continue { .. }
567567
| ExprKind::Return { .. }
568568
| ExprKind::Literal { .. }
569+
| ExprKind::NamedConst { .. }
570+
| ExprKind::NonHirLiteral { .. }
571+
| ExprKind::ConstParam { .. }
569572
| ExprKind::ConstBlock { .. }
570573
| ExprKind::StaticRef { .. }
571574
| ExprKind::InlineAsm { .. }

‎compiler/rustc_mir_build/src/build/expr/as_rvalue.rs

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -327,6 +327,9 @@ impl<'a, 'tcx> Builder<'a, 'tcx> {
327327
}
328328
ExprKind::Yield { .. }
329329
| ExprKind::Literal { .. }
330+
| ExprKind::NamedConst { .. }
331+
| ExprKind::NonHirLiteral { .. }
332+
| ExprKind::ConstParam { .. }
330333
| ExprKind::ConstBlock { .. }
331334
| ExprKind::StaticRef { .. }
332335
| ExprKind::Block { .. }

‎compiler/rustc_mir_build/src/build/expr/as_temp.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -70,7 +70,7 @@ impl<'a, 'tcx> Builder<'a, 'tcx> {
7070
local_decl.local_info =
7171
Some(Box::new(LocalInfo::StaticRef { def_id, is_thread_local: true }));
7272
}
73-
ExprKind::Literal { const_id: Some(def_id), .. } => {
73+
ExprKind::NamedConst { def_id, .. } | ExprKind::ConstParam { def_id, .. } => {
7474
local_decl.local_info = Some(Box::new(LocalInfo::ConstRef { def_id }));
7575
}
7676
_ => {}

‎compiler/rustc_mir_build/src/build/expr/category.rs

Lines changed: 6 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -69,9 +69,12 @@ impl Category {
6969
| ExprKind::AssignOp { .. }
7070
| ExprKind::ThreadLocalRef(_) => Some(Category::Rvalue(RvalueFunc::AsRvalue)),
7171

72-
ExprKind::ConstBlock { .. } | ExprKind::Literal { .. } | ExprKind::StaticRef { .. } => {
73-
Some(Category::Constant)
74-
}
72+
ExprKind::ConstBlock { .. }
73+
| ExprKind::Literal { .. }
74+
| ExprKind::NonHirLiteral { .. }
75+
| ExprKind::ConstParam { .. }
76+
| ExprKind::StaticRef { .. }
77+
| ExprKind::NamedConst { .. } => Some(Category::Constant),
7578

7679
ExprKind::Loop { .. }
7780
| ExprKind::Block { .. }

‎compiler/rustc_mir_build/src/build/expr/into.rs

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -533,6 +533,9 @@ impl<'a, 'tcx> Builder<'a, 'tcx> {
533533
| ExprKind::Closure { .. }
534534
| ExprKind::ConstBlock { .. }
535535
| ExprKind::Literal { .. }
536+
| ExprKind::NamedConst { .. }
537+
| ExprKind::NonHirLiteral { .. }
538+
| ExprKind::ConstParam { .. }
536539
| ExprKind::ThreadLocalRef(_)
537540
| ExprKind::StaticRef { .. } => {
538541
debug_assert!(match Category::of(&expr.kind).unwrap() {

‎compiler/rustc_mir_build/src/build/expr/mod.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -60,7 +60,7 @@
6060
//! basically the point where the "by value" operations are bridged
6161
//! over to the "by reference" mode (`as_place`).
6262
63-
mod as_constant;
63+
crate mod as_constant;
6464
mod as_operand;
6565
pub mod as_place;
6666
mod as_rvalue;

‎compiler/rustc_mir_build/src/check_unsafety.rs

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -303,6 +303,9 @@ impl<'a, 'tcx> Visitor<'a, 'tcx> for UnsafetyVisitor<'a, 'tcx> {
303303
| ExprKind::Block { .. }
304304
| ExprKind::Borrow { .. }
305305
| ExprKind::Literal { .. }
306+
| ExprKind::NamedConst { .. }
307+
| ExprKind::NonHirLiteral { .. }
308+
| ExprKind::ConstParam { .. }
306309
| ExprKind::ConstBlock { .. }
307310
| ExprKind::Deref { .. }
308311
| ExprKind::Index { .. }

‎compiler/rustc_mir_build/src/thir/constant.rs

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@ use rustc_middle::ty::{self, ParamEnv, TyCtxt};
77
use rustc_span::symbol::Symbol;
88
use rustc_target::abi::Size;
99

10+
// FIXME Once valtrees are available, get rid of this function and the query
1011
crate fn lit_to_const<'tcx>(
1112
tcx: TyCtxt<'tcx>,
1213
lit_input: LitToConstInput<'tcx>,
@@ -57,7 +58,12 @@ crate fn lit_to_const<'tcx>(
5758
Ok(ty::Const::from_value(tcx, lit, ty))
5859
}
5960

60-
fn parse_float<'tcx>(num: Symbol, fty: ty::FloatTy, neg: bool) -> Option<ConstValue<'tcx>> {
61+
// FIXME move this to rustc_mir_build::build
62+
pub(crate) fn parse_float<'tcx>(
63+
num: Symbol,
64+
fty: ty::FloatTy,
65+
neg: bool,
66+
) -> Option<ConstValue<'tcx>> {
6167
let num = num.as_str();
6268
use rustc_apfloat::ieee::{Double, Single};
6369
let scalar = match fty {

‎compiler/rustc_mir_build/src/thir/cx/expr.rs

Lines changed: 50 additions & 86 deletions
Original file line numberDiff line numberDiff line change
@@ -14,7 +14,9 @@ use rustc_middle::ty::adjustment::{
1414
Adjust, Adjustment, AutoBorrow, AutoBorrowMutability, PointerCast,
1515
};
1616
use rustc_middle::ty::subst::{InternalSubsts, SubstsRef};
17-
use rustc_middle::ty::{self, AdtKind, Ty, UpvarSubsts, UserType};
17+
use rustc_middle::ty::{
18+
self, AdtKind, InlineConstSubsts, InlineConstSubstsParts, ScalarInt, Ty, UpvarSubsts, UserType,
19+
};
1820
use rustc_span::def_id::DefId;
1921
use rustc_span::Span;
2022
use rustc_target::abi::VariantIdx;
@@ -290,11 +292,7 @@ impl<'tcx> Cx<'tcx> {
290292
}
291293
}
292294

293-
hir::ExprKind::Lit(ref lit) => ExprKind::Literal {
294-
literal: self.const_eval_literal(&lit.node, expr_ty, lit.span, false),
295-
user_ty: None,
296-
const_id: None,
297-
},
295+
hir::ExprKind::Lit(ref lit) => ExprKind::Literal { lit, neg: false },
298296

299297
hir::ExprKind::Binary(op, ref lhs, ref rhs) => {
300298
if self.typeck_results().is_method_call(expr) {
@@ -359,11 +357,7 @@ impl<'tcx> Cx<'tcx> {
359357
let arg = self.mirror_expr(arg);
360358
self.overloaded_operator(expr, Box::new([arg]))
361359
} else if let hir::ExprKind::Lit(ref lit) = arg.kind {
362-
ExprKind::Literal {
363-
literal: self.const_eval_literal(&lit.node, expr_ty, lit.span, true),
364-
user_ty: None,
365-
const_id: None,
366-
}
360+
ExprKind::Literal { lit, neg: true }
367361
} else {
368362
ExprKind::Unary { op: UnOp::Neg, arg: self.mirror_expr(arg) }
369363
}
@@ -524,11 +518,7 @@ impl<'tcx> Cx<'tcx> {
524518
ty,
525519
temp_lifetime,
526520
span: expr.span,
527-
kind: ExprKind::Literal {
528-
literal: ty::Const::zero_sized(self.tcx, ty),
529-
user_ty,
530-
const_id: None,
531-
},
521+
kind: ExprKind::zero_sized_literal(user_ty),
532522
}),
533523
}
534524
}
@@ -550,11 +540,7 @@ impl<'tcx> Cx<'tcx> {
550540
ty,
551541
temp_lifetime,
552542
span: expr.span,
553-
kind: ExprKind::Literal {
554-
literal: ty::Const::zero_sized(self.tcx, ty),
555-
user_ty: None,
556-
const_id: None,
557-
},
543+
kind: ExprKind::zero_sized_literal(None),
558544
}),
559545
}
560546
}
@@ -568,13 +554,21 @@ impl<'tcx> Cx<'tcx> {
568554
},
569555

570556
hir::ExprKind::ConstBlock(ref anon_const) => {
571-
let anon_const_def_id = self.tcx.hir().local_def_id(anon_const.hir_id);
572-
573-
// FIXME Do we want to use `from_inline_const` once valtrees
574-
// are introduced? This would create `ValTree`s that will never be used...
575-
let value = ty::Const::from_inline_const(self.tcx, anon_const_def_id);
576-
577-
ExprKind::ConstBlock { value }
557+
let tcx = self.tcx;
558+
let local_def_id = tcx.hir().local_def_id(anon_const.hir_id);
559+
let anon_const_def_id = local_def_id.to_def_id();
560+
561+
// Need to include the parent substs
562+
let hir_id = tcx.hir().local_def_id_to_hir_id(local_def_id);
563+
let ty = tcx.typeck(local_def_id).node_type(hir_id);
564+
let typeck_root_def_id = tcx.typeck_root_def_id(anon_const_def_id);
565+
let parent_substs =
566+
tcx.erase_regions(InternalSubsts::identity_for_item(tcx, typeck_root_def_id));
567+
let substs =
568+
InlineConstSubsts::new(tcx, InlineConstSubstsParts { parent_substs, ty })
569+
.substs;
570+
571+
ExprKind::ConstBlock { did: anon_const_def_id, substs }
578572
}
579573
// Now comes the rote stuff:
580574
hir::ExprKind::Repeat(ref v, _) => {
@@ -692,32 +686,36 @@ impl<'tcx> Cx<'tcx> {
692686
};
693687

694688
let source = if let Some((did, offset, var_ty)) = var {
695-
let mk_const = |literal| Expr {
689+
let param_env_ty = self.param_env.and(var_ty);
690+
let size = self
691+
.tcx
692+
.layout_of(param_env_ty)
693+
.unwrap_or_else(|e| {
694+
panic!("could not compute layout for {:?}: {:?}", param_env_ty, e)
695+
})
696+
.size;
697+
let lit = ScalarInt::try_from_uint(offset as u128, size).unwrap();
698+
let kind = ExprKind::NonHirLiteral { lit, user_ty: None };
699+
let offset = self.thir.exprs.push(Expr {
696700
temp_lifetime,
697701
ty: var_ty,
698702
span: expr.span,
699-
kind: ExprKind::Literal { literal, user_ty: None, const_id: None },
700-
};
701-
let offset = self.thir.exprs.push(mk_const(ty::Const::from_bits(
702-
self.tcx,
703-
offset as u128,
704-
self.param_env.and(var_ty),
705-
)));
703+
kind,
704+
});
706705
match did {
707706
Some(did) => {
708707
// in case we are offsetting from a computed discriminant
709708
// and not the beginning of discriminants (which is always `0`)
710709
let substs = InternalSubsts::identity_for_item(self.tcx(), did);
711-
let lhs = ty::ConstS {
712-
val: ty::ConstKind::Unevaluated(ty::Unevaluated::new(
713-
ty::WithOptConstParam::unknown(did),
714-
substs,
715-
)),
710+
let kind =
711+
ExprKind::NamedConst { def_id: did, substs, user_ty: None };
712+
let lhs = self.thir.exprs.push(Expr {
713+
temp_lifetime,
716714
ty: var_ty,
717-
};
718-
let lhs = self.thir.exprs.push(mk_const(self.tcx().mk_const(lhs)));
719-
let bin =
720-
ExprKind::Binary { op: BinOp::Add, lhs: lhs, rhs: offset };
715+
span: expr.span,
716+
kind,
717+
});
718+
let bin = ExprKind::Binary { op: BinOp::Add, lhs, rhs: offset };
721719
self.thir.exprs.push(Expr {
722720
temp_lifetime,
723721
ty: var_ty,
@@ -832,16 +830,7 @@ impl<'tcx> Cx<'tcx> {
832830
}
833831
};
834832
let ty = self.tcx().mk_fn_def(def_id, substs);
835-
Expr {
836-
temp_lifetime,
837-
ty,
838-
span,
839-
kind: ExprKind::Literal {
840-
literal: ty::Const::zero_sized(self.tcx(), ty),
841-
user_ty,
842-
const_id: None,
843-
},
844-
}
833+
Expr { temp_lifetime, ty, span, kind: ExprKind::zero_sized_literal(user_ty) }
845834
}
846835

847836
fn convert_arm(&mut self, arm: &'tcx hir::Arm<'tcx>) -> ArmId {
@@ -868,17 +857,9 @@ impl<'tcx> Cx<'tcx> {
868857
Res::Def(DefKind::Fn, _)
869858
| Res::Def(DefKind::AssocFn, _)
870859
| Res::Def(DefKind::Ctor(_, CtorKind::Fn), _)
871-
| Res::SelfCtor(..) => {
860+
| Res::SelfCtor(_) => {
872861
let user_ty = self.user_substs_applied_to_res(expr.hir_id, res);
873-
debug!("convert_path_expr: user_ty={:?}", user_ty);
874-
ExprKind::Literal {
875-
literal: ty::Const::zero_sized(
876-
self.tcx,
877-
self.typeck_results().node_type(expr.hir_id),
878-
),
879-
user_ty,
880-
const_id: None,
881-
}
862+
ExprKind::zero_sized_literal(user_ty)
882863
}
883864

884865
Res::Def(DefKind::ConstParam, def_id) => {
@@ -888,31 +869,14 @@ impl<'tcx> Cx<'tcx> {
888869
let generics = self.tcx.generics_of(item_def_id);
889870
let index = generics.param_def_id_to_index[&def_id];
890871
let name = self.tcx.hir().name(hir_id);
891-
let val = ty::ConstKind::Param(ty::ParamConst::new(index, name));
892-
ExprKind::Literal {
893-
literal: self.tcx.mk_const(ty::ConstS {
894-
val,
895-
ty: self.typeck_results().node_type(expr.hir_id),
896-
}),
897-
user_ty: None,
898-
const_id: Some(def_id),
899-
}
872+
let param = ty::ParamConst::new(index, name);
873+
874+
ExprKind::ConstParam { param, def_id }
900875
}
901876

902877
Res::Def(DefKind::Const, def_id) | Res::Def(DefKind::AssocConst, def_id) => {
903878
let user_ty = self.user_substs_applied_to_res(expr.hir_id, res);
904-
debug!("convert_path_expr: (const) user_ty={:?}", user_ty);
905-
ExprKind::Literal {
906-
literal: self.tcx.mk_const(ty::ConstS {
907-
val: ty::ConstKind::Unevaluated(ty::Unevaluated::new(
908-
ty::WithOptConstParam::unknown(def_id),
909-
substs,
910-
)),
911-
ty: self.typeck_results().node_type(expr.hir_id),
912-
}),
913-
user_ty,
914-
const_id: Some(def_id),
915-
}
879+
ExprKind::NamedConst { def_id, substs, user_ty: user_ty }
916880
}
917881

918882
Res::Def(DefKind::Ctor(_, CtorKind::Const), def_id) => {

‎compiler/rustc_mir_build/src/thir/cx/mod.rs

Lines changed: 1 addition & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -5,17 +5,15 @@
55
use crate::thir::pattern::pat_from_hir;
66
use crate::thir::util::UserAnnotatedTyHelpers;
77

8-
use rustc_ast as ast;
98
use rustc_data_structures::steal::Steal;
109
use rustc_errors::ErrorGuaranteed;
1110
use rustc_hir as hir;
1211
use rustc_hir::def_id::{DefId, LocalDefId};
1312
use rustc_hir::HirId;
1413
use rustc_hir::Node;
1514
use rustc_middle::middle::region;
16-
use rustc_middle::mir::interpret::{LitToConstError, LitToConstInput};
1715
use rustc_middle::thir::*;
18-
use rustc_middle::ty::{self, Ty, TyCtxt};
16+
use rustc_middle::ty::{self, TyCtxt};
1917
use rustc_span::Span;
2018

2119
crate fn thir_body<'tcx>(
@@ -77,25 +75,6 @@ impl<'tcx> Cx<'tcx> {
7775
}
7876
}
7977

80-
crate fn const_eval_literal(
81-
&mut self,
82-
lit: &'tcx ast::LitKind,
83-
ty: Ty<'tcx>,
84-
sp: Span,
85-
neg: bool,
86-
) -> ty::Const<'tcx> {
87-
trace!("const_eval_literal: {:#?}, {:?}, {:?}, {:?}", lit, ty, sp, neg);
88-
89-
match self.tcx.at(sp).lit_to_const(LitToConstInput { lit, ty, neg }) {
90-
Ok(c) => c,
91-
Err(LitToConstError::Reported) => {
92-
// create a dummy value and continue compiling
93-
self.tcx.const_error(ty)
94-
}
95-
Err(LitToConstError::TypeError) => bug!("const_eval_literal: had type error"),
96-
}
97-
}
98-
9978
crate fn pattern_from_hir(&mut self, p: &hir::Pat<'_>) -> Pat<'tcx> {
10079
let p = match self.tcx.hir().get(p.hir_id) {
10180
Node::Pat(p) | Node::Binding(p) => p,

‎compiler/rustc_trait_selection/src/traits/const_evaluatable.rs

Lines changed: 84 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -14,7 +14,9 @@ use rustc_hir::def::DefKind;
1414
use rustc_index::vec::IndexVec;
1515
use rustc_infer::infer::InferCtxt;
1616
use rustc_middle::mir;
17-
use rustc_middle::mir::interpret::ErrorHandled;
17+
use rustc_middle::mir::interpret::{
18+
ConstValue, ErrorHandled, LitToConstError, LitToConstInput, Scalar,
19+
};
1820
use rustc_middle::thir;
1921
use rustc_middle::thir::abstract_const::{self, Node, NodeId, NotConstEvaluatable};
2022
use rustc_middle::ty::subst::{Subst, SubstsRef};
@@ -28,13 +30,13 @@ use std::iter;
2830
use std::ops::ControlFlow;
2931

3032
/// Check if a given constant can be evaluated.
33+
#[instrument(skip(infcx), level = "debug")]
3134
pub fn is_const_evaluatable<'cx, 'tcx>(
3235
infcx: &InferCtxt<'cx, 'tcx>,
3336
uv: ty::Unevaluated<'tcx, ()>,
3437
param_env: ty::ParamEnv<'tcx>,
3538
span: Span,
3639
) -> Result<(), NotConstEvaluatable> {
37-
debug!("is_const_evaluatable({:?})", uv);
3840
let tcx = infcx.tcx;
3941

4042
if tcx.features().generic_const_exprs {
@@ -304,6 +306,7 @@ impl<'a, 'tcx> AbstractConstBuilder<'a, 'tcx> {
304306
Err(reported)
305307
}
306308

309+
#[instrument(skip(tcx, body, body_id), level = "debug")]
307310
fn new(
308311
tcx: TyCtxt<'tcx>,
309312
(body, body_id): (&'a thir::Thir<'tcx>, thir::ExprId),
@@ -315,29 +318,61 @@ impl<'a, 'tcx> AbstractConstBuilder<'a, 'tcx> {
315318
thir: &'a thir::Thir<'tcx>,
316319
}
317320

321+
use crate::rustc_middle::thir::visit::Visitor;
318322
use thir::visit;
319-
impl<'a, 'tcx: 'a> visit::Visitor<'a, 'tcx> for IsThirPolymorphic<'a, 'tcx> {
323+
324+
impl<'a, 'tcx> IsThirPolymorphic<'a, 'tcx> {
325+
fn expr_is_poly(&mut self, expr: &thir::Expr<'tcx>) -> bool {
326+
if expr.ty.has_param_types_or_consts() {
327+
return true;
328+
}
329+
330+
match expr.kind {
331+
thir::ExprKind::NamedConst { substs, .. } => substs.has_param_types_or_consts(),
332+
thir::ExprKind::ConstParam { .. } => true,
333+
thir::ExprKind::Repeat { value, count } => {
334+
self.visit_expr(&self.thir()[value]);
335+
count.has_param_types_or_consts()
336+
}
337+
_ => false,
338+
}
339+
}
340+
341+
fn pat_is_poly(&mut self, pat: &thir::Pat<'tcx>) -> bool {
342+
if pat.ty.has_param_types_or_consts() {
343+
return true;
344+
}
345+
346+
match pat.kind.as_ref() {
347+
thir::PatKind::Constant { value } => value.has_param_types_or_consts(),
348+
thir::PatKind::Range(thir::PatRange { lo, hi, .. }) => {
349+
lo.has_param_types_or_consts() || hi.has_param_types_or_consts()
350+
}
351+
_ => false,
352+
}
353+
}
354+
}
355+
356+
impl<'a, 'tcx> visit::Visitor<'a, 'tcx> for IsThirPolymorphic<'a, 'tcx> {
320357
fn thir(&self) -> &'a thir::Thir<'tcx> {
321358
&self.thir
322359
}
323360

361+
#[instrument(skip(self), level = "debug")]
324362
fn visit_expr(&mut self, expr: &thir::Expr<'tcx>) {
325-
self.is_poly |= expr.ty.has_param_types_or_consts();
363+
self.is_poly |= self.expr_is_poly(expr);
326364
if !self.is_poly {
327365
visit::walk_expr(self, expr)
328366
}
329367
}
330368

369+
#[instrument(skip(self), level = "debug")]
331370
fn visit_pat(&mut self, pat: &thir::Pat<'tcx>) {
332-
self.is_poly |= pat.ty.has_param_types_or_consts();
371+
self.is_poly |= self.pat_is_poly(pat);
333372
if !self.is_poly {
334373
visit::walk_pat(self, pat);
335374
}
336375
}
337-
338-
fn visit_const(&mut self, ct: ty::Const<'tcx>) {
339-
self.is_poly |= ct.has_param_types_or_consts();
340-
}
341376
}
342377

343378
let mut is_poly_vis = IsThirPolymorphic { is_poly: false, thir: body };
@@ -393,16 +428,49 @@ impl<'a, 'tcx> AbstractConstBuilder<'a, 'tcx> {
393428
fn recurse_build(&mut self, node: thir::ExprId) -> Result<NodeId, ErrorGuaranteed> {
394429
use thir::ExprKind;
395430
let node = &self.body.exprs[node];
396-
debug!("recurse_build: node={:?}", node);
397431
Ok(match &node.kind {
398432
// I dont know if handling of these 3 is correct
399433
&ExprKind::Scope { value, .. } => self.recurse_build(value)?,
400434
&ExprKind::PlaceTypeAscription { source, .. }
401435
| &ExprKind::ValueTypeAscription { source, .. } => self.recurse_build(source)?,
436+
&ExprKind::Literal { lit, neg} => {
437+
let sp = node.span;
438+
let constant =
439+
match self.tcx.at(sp).lit_to_const(LitToConstInput { lit: &lit.node, ty: node.ty, neg }) {
440+
Ok(c) => c,
441+
Err(LitToConstError::Reported) => {
442+
self.tcx.const_error(node.ty)
443+
}
444+
Err(LitToConstError::TypeError) => {
445+
bug!("encountered type error in lit_to_const")
446+
}
447+
};
448+
449+
self.nodes.push(Node::Leaf(constant))
450+
}
451+
&ExprKind::NonHirLiteral { lit , user_ty: _} => {
452+
// FIXME Construct a Valtree from this ScalarInt when introducing Valtrees
453+
let const_value = ConstValue::Scalar(Scalar::Int(lit));
454+
self.nodes.push(Node::Leaf(ty::Const::from_value(self.tcx, const_value, node.ty)))
455+
}
456+
&ExprKind::NamedConst { def_id, substs, user_ty: _ } => {
457+
let uneval = ty::Unevaluated::new(ty::WithOptConstParam::unknown(def_id), substs);
458+
459+
let constant = self.tcx.mk_const(ty::ConstS {
460+
val: ty::ConstKind::Unevaluated(uneval),
461+
ty: node.ty,
462+
});
402463

403-
// subtle: associated consts are literals this arm handles
404-
// `<T as Trait>::ASSOC` as well as `12`
405-
&ExprKind::Literal { literal, .. } => self.nodes.push(Node::Leaf(literal)),
464+
self.nodes.push(Node::Leaf(constant))
465+
}
466+
467+
ExprKind::ConstParam {param, ..} => {
468+
let const_param = self.tcx.mk_const(ty::ConstS {
469+
val: ty::ConstKind::Param(*param),
470+
ty: node.ty,
471+
});
472+
self.nodes.push(Node::Leaf(const_param))
473+
}
406474

407475
ExprKind::Call { fun, args, .. } => {
408476
let fun = self.recurse_build(*fun)?;
@@ -585,6 +653,7 @@ pub(super) fn try_unify_abstract_consts<'tcx>(
585653
// on `ErrorGuaranteed`.
586654
}
587655

656+
#[instrument(skip(tcx, f), level = "debug")]
588657
pub fn walk_abstract_const<'tcx, R, F>(
589658
tcx: TyCtxt<'tcx>,
590659
ct: AbstractConst<'tcx>,
@@ -593,13 +662,15 @@ pub fn walk_abstract_const<'tcx, R, F>(
593662
where
594663
F: FnMut(AbstractConst<'tcx>) -> ControlFlow<R>,
595664
{
665+
#[instrument(skip(tcx, f), level = "debug")]
596666
fn recurse<'tcx, R>(
597667
tcx: TyCtxt<'tcx>,
598668
ct: AbstractConst<'tcx>,
599669
f: &mut dyn FnMut(AbstractConst<'tcx>) -> ControlFlow<R>,
600670
) -> ControlFlow<R> {
601671
f(ct)?;
602672
let root = ct.root(tcx);
673+
debug!(?root);
603674
match root {
604675
Node::Leaf(_) => ControlFlow::CONTINUE,
605676
Node::Binop(_, l, r) => {
Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
// build-pass
2+
3+
#![feature(adt_const_params)]
4+
#![allow(incomplete_features)]
5+
6+
#[derive(PartialEq, Eq)]
7+
struct Yikes;
8+
9+
impl Yikes {
10+
fn mut_self(&mut self) {}
11+
}
12+
13+
fn foo<const YIKES: Yikes>() {
14+
YIKES.mut_self()
15+
//~^ WARNING taking a mutable reference
16+
}
17+
18+
fn main() {
19+
foo::<{ Yikes }>()
20+
}
Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
warning: taking a mutable reference to a `const` item
2+
--> $DIR/thir-constparam-temp.rs:14:5
3+
|
4+
LL | YIKES.mut_self()
5+
| ^^^^^^^^^^^^^^^^
6+
|
7+
= note: `#[warn(const_item_mutation)]` on by default
8+
= note: each usage of a `const` item creates a new temporary
9+
= note: the mutable reference will refer to this temporary, not the original `const` item
10+
note: mutable reference created due to call to this method
11+
--> $DIR/thir-constparam-temp.rs:10:5
12+
|
13+
LL | fn mut_self(&mut self) {}
14+
| ^^^^^^^^^^^^^^^^^^^^^^
15+
note: `const` item defined here
16+
--> $DIR/thir-constparam-temp.rs:13:14
17+
|
18+
LL | fn foo<const YIKES: Yikes>() {
19+
| ^^^^^
20+
21+
warning: 1 warning emitted
22+

0 commit comments

Comments
 (0)
Please sign in to comment.