-
Notifications
You must be signed in to change notification settings - Fork 12.9k
/
eval.rs
1372 lines (1283 loc) · 54.2 KB
/
eval.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright 2012-2016 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
//#![allow(non_camel_case_types)]
use rustc::middle::const_val::ConstVal::*;
use rustc::middle::const_val::ConstVal;
use self::ErrKind::*;
use self::EvalHint::*;
use rustc::hir::map as ast_map;
use rustc::hir::map::blocks::FnLikeNode;
use rustc::middle::cstore::InlinedItem;
use rustc::traits;
use rustc::hir::def::{Def, PathResolution};
use rustc::hir::def_id::DefId;
use rustc::hir::pat_util::def_to_path;
use rustc::ty::{self, Ty, TyCtxt};
use rustc::ty::util::IntTypeExt;
use rustc::ty::subst::Substs;
use rustc::traits::Reveal;
use rustc::util::common::ErrorReported;
use rustc::util::nodemap::NodeMap;
use rustc::lint;
use graphviz::IntoCow;
use syntax::ast;
use rustc::hir::{Expr, PatKind};
use rustc::hir;
use rustc::hir::intravisit::FnKind;
use syntax::ptr::P;
use syntax::codemap;
use syntax::attr::IntType;
use syntax_pos::{self, Span};
use std::borrow::Cow;
use std::cmp::Ordering;
use std::collections::hash_map::Entry::Vacant;
use rustc_const_math::*;
use rustc_errors::DiagnosticBuilder;
macro_rules! math {
($e:expr, $op:expr) => {
match $op {
Ok(val) => val,
Err(e) => signal!($e, Math(e)),
}
}
}
fn lookup_variant_by_id<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
variant_def: DefId)
-> Option<&'tcx Expr> {
fn variant_expr<'a>(variants: &'a [hir::Variant], id: ast::NodeId)
-> Option<&'a Expr> {
for variant in variants {
if variant.node.data.id() == id {
return variant.node.disr_expr.as_ref().map(|e| &**e);
}
}
None
}
if let Some(variant_node_id) = tcx.map.as_local_node_id(variant_def) {
let enum_node_id = tcx.map.get_parent(variant_node_id);
match tcx.map.find(enum_node_id) {
None => None,
Some(ast_map::NodeItem(it)) => match it.node {
hir::ItemEnum(hir::EnumDef { ref variants }, _) => {
variant_expr(variants, variant_node_id)
}
_ => None
},
Some(_) => None
}
} else {
None
}
}
/// * `def_id` is the id of the constant.
/// * `substs` is the monomorphized substitutions for the expression.
///
/// `substs` is optional and is used for associated constants.
/// This generally happens in late/trans const evaluation.
pub fn lookup_const_by_id<'a, 'tcx: 'a>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
def_id: DefId,
substs: Option<&'tcx Substs<'tcx>>)
-> Option<(&'tcx Expr, Option<ty::Ty<'tcx>>)> {
if let Some(node_id) = tcx.map.as_local_node_id(def_id) {
match tcx.map.find(node_id) {
None => None,
Some(ast_map::NodeItem(it)) => match it.node {
hir::ItemConst(ref ty, ref const_expr) => {
Some((&const_expr, tcx.ast_ty_to_prim_ty(ty)))
}
_ => None
},
Some(ast_map::NodeTraitItem(ti)) => match ti.node {
hir::ConstTraitItem(..) => {
if let Some(substs) = substs {
// If we have a trait item and the substitutions for it,
// `resolve_trait_associated_const` will select an impl
// or the default.
let trait_id = tcx.map.get_parent(node_id);
let trait_id = tcx.map.local_def_id(trait_id);
resolve_trait_associated_const(tcx, ti, trait_id, substs)
} else {
// Technically, without knowing anything about the
// expression that generates the obligation, we could
// still return the default if there is one. However,
// it's safer to return `None` than to return some value
// that may differ from what you would get from
// correctly selecting an impl.
None
}
}
_ => None
},
Some(ast_map::NodeImplItem(ii)) => match ii.node {
hir::ImplItemKind::Const(ref ty, ref expr) => {
Some((&expr, tcx.ast_ty_to_prim_ty(ty)))
}
_ => None
},
Some(_) => None
}
} else {
match tcx.extern_const_statics.borrow().get(&def_id) {
Some(&None) => return None,
Some(&Some((expr_id, ty))) => {
return Some((tcx.map.expect_expr(expr_id), ty));
}
None => {}
}
let mut used_substs = false;
let expr_ty = match tcx.sess.cstore.maybe_get_item_ast(tcx, def_id) {
Some((&InlinedItem::Item(_, ref item), _)) => match item.node {
hir::ItemConst(ref ty, ref const_expr) => {
Some((&**const_expr, tcx.ast_ty_to_prim_ty(ty)))
},
_ => None
},
Some((&InlinedItem::TraitItem(trait_id, ref ti), _)) => match ti.node {
hir::ConstTraitItem(..) => {
used_substs = true;
if let Some(substs) = substs {
// As mentioned in the comments above for in-crate
// constants, we only try to find the expression for
// a trait-associated const if the caller gives us
// the substitutions for the reference to it.
resolve_trait_associated_const(tcx, ti, trait_id, substs)
} else {
None
}
}
_ => None
},
Some((&InlinedItem::ImplItem(_, ref ii), _)) => match ii.node {
hir::ImplItemKind::Const(ref ty, ref expr) => {
Some((&**expr, tcx.ast_ty_to_prim_ty(ty)))
},
_ => None
},
_ => None
};
// If we used the substitutions, particularly to choose an impl
// of a trait-associated const, don't cache that, because the next
// lookup with the same def_id may yield a different result.
if !used_substs {
tcx.extern_const_statics
.borrow_mut()
.insert(def_id, expr_ty.map(|(e, t)| (e.id, t)));
}
expr_ty
}
}
fn inline_const_fn_from_external_crate<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
def_id: DefId)
-> Option<ast::NodeId> {
match tcx.extern_const_fns.borrow().get(&def_id) {
Some(&ast::DUMMY_NODE_ID) => return None,
Some(&fn_id) => return Some(fn_id),
None => {}
}
if !tcx.sess.cstore.is_const_fn(def_id) {
tcx.extern_const_fns.borrow_mut().insert(def_id, ast::DUMMY_NODE_ID);
return None;
}
let fn_id = match tcx.sess.cstore.maybe_get_item_ast(tcx, def_id) {
Some((&InlinedItem::Item(_, ref item), _)) => Some(item.id),
Some((&InlinedItem::ImplItem(_, ref item), _)) => Some(item.id),
_ => None
};
tcx.extern_const_fns.borrow_mut().insert(def_id,
fn_id.unwrap_or(ast::DUMMY_NODE_ID));
fn_id
}
pub fn lookup_const_fn_by_id<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, def_id: DefId)
-> Option<FnLikeNode<'tcx>>
{
let fn_id = if let Some(node_id) = tcx.map.as_local_node_id(def_id) {
node_id
} else {
if let Some(fn_id) = inline_const_fn_from_external_crate(tcx, def_id) {
fn_id
} else {
return None;
}
};
let fn_like = match FnLikeNode::from_node(tcx.map.get(fn_id)) {
Some(fn_like) => fn_like,
None => return None
};
match fn_like.kind() {
FnKind::ItemFn(_, _, _, hir::Constness::Const, ..) => {
Some(fn_like)
}
FnKind::Method(_, m, ..) => {
if m.constness == hir::Constness::Const {
Some(fn_like)
} else {
None
}
}
_ => None
}
}
pub fn const_expr_to_pat<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
expr: &Expr,
pat_id: ast::NodeId,
span: Span)
-> Result<P<hir::Pat>, DefId> {
let pat_ty = tcx.expr_ty(expr);
debug!("expr={:?} pat_ty={:?} pat_id={}", expr, pat_ty, pat_id);
match pat_ty.sty {
ty::TyFloat(_) => {
tcx.sess.add_lint(
lint::builtin::ILLEGAL_FLOATING_POINT_CONSTANT_PATTERN,
pat_id,
span,
format!("floating point constants cannot be used in patterns"));
}
ty::TyAdt(adt_def, _) if adt_def.is_union() => {
// Matching on union fields is unsafe, we can't hide it in constants
tcx.sess.span_err(span, "cannot use unions in constant patterns");
}
ty::TyAdt(adt_def, _) => {
if !tcx.has_attr(adt_def.did, "structural_match") {
tcx.sess.add_lint(
lint::builtin::ILLEGAL_STRUCT_OR_ENUM_CONSTANT_PATTERN,
pat_id,
span,
format!("to use a constant of type `{}` \
in a pattern, \
`{}` must be annotated with `#[derive(PartialEq, Eq)]`",
tcx.item_path_str(adt_def.did),
tcx.item_path_str(adt_def.did)));
}
}
_ => { }
}
let pat = match expr.node {
hir::ExprTup(ref exprs) =>
PatKind::Tuple(exprs.iter()
.map(|expr| const_expr_to_pat(tcx, &expr, pat_id, span))
.collect::<Result<_, _>>()?, None),
hir::ExprCall(ref callee, ref args) => {
let def = tcx.expect_def(callee.id);
if let Vacant(entry) = tcx.def_map.borrow_mut().entry(expr.id) {
entry.insert(PathResolution::new(def));
}
let path = match def {
Def::Struct(def_id) => def_to_path(tcx, def_id),
Def::Variant(variant_did) => def_to_path(tcx, variant_did),
Def::Fn(..) | Def::Method(..) => return Ok(P(hir::Pat {
id: expr.id,
node: PatKind::Lit(P(expr.clone())),
span: span,
})),
_ => bug!()
};
let pats = args.iter()
.map(|expr| const_expr_to_pat(tcx, &**expr, pat_id, span))
.collect::<Result<_, _>>()?;
PatKind::TupleStruct(path, pats, None)
}
hir::ExprStruct(ref path, ref fields, None) => {
let field_pats =
fields.iter()
.map(|field| Ok(codemap::Spanned {
span: syntax_pos::DUMMY_SP,
node: hir::FieldPat {
name: field.name.node,
pat: const_expr_to_pat(tcx, &field.expr, pat_id, span)?,
is_shorthand: false,
},
}))
.collect::<Result<_, _>>()?;
PatKind::Struct(path.clone(), field_pats, false)
}
hir::ExprArray(ref exprs) => {
let pats = exprs.iter()
.map(|expr| const_expr_to_pat(tcx, &expr, pat_id, span))
.collect::<Result<_, _>>()?;
PatKind::Slice(pats, None, hir::HirVec::new())
}
hir::ExprPath(_, ref path) => {
match tcx.expect_def(expr.id) {
Def::Struct(..) | Def::Variant(..) => PatKind::Path(None, path.clone()),
Def::Const(def_id) | Def::AssociatedConst(def_id) => {
let substs = Some(tcx.node_id_item_substs(expr.id).substs);
let (expr, _ty) = lookup_const_by_id(tcx, def_id, substs).unwrap();
return const_expr_to_pat(tcx, expr, pat_id, span);
},
_ => bug!(),
}
}
_ => PatKind::Lit(P(expr.clone()))
};
Ok(P(hir::Pat { id: expr.id, node: pat, span: span }))
}
pub fn report_const_eval_err<'a, 'tcx>(
tcx: TyCtxt<'a, 'tcx, 'tcx>,
err: &ConstEvalErr,
primary_span: Span,
primary_kind: &str)
-> DiagnosticBuilder<'tcx>
{
let mut err = err;
while let &ConstEvalErr { kind: ErroneousReferencedConstant(box ref i_err), .. } = err {
err = i_err;
}
let mut diag = struct_span_err!(tcx.sess, err.span, E0080, "constant evaluation error");
note_const_eval_err(tcx, err, primary_span, primary_kind, &mut diag);
diag
}
pub fn fatal_const_eval_err<'a, 'tcx>(
tcx: TyCtxt<'a, 'tcx, 'tcx>,
err: &ConstEvalErr,
primary_span: Span,
primary_kind: &str)
-> !
{
report_const_eval_err(tcx, err, primary_span, primary_kind).emit();
tcx.sess.abort_if_errors();
unreachable!()
}
pub fn note_const_eval_err<'a, 'tcx>(
_tcx: TyCtxt<'a, 'tcx, 'tcx>,
err: &ConstEvalErr,
primary_span: Span,
primary_kind: &str,
diag: &mut DiagnosticBuilder)
{
match err.description() {
ConstEvalErrDescription::Simple(message) => {
diag.span_label(err.span, &message);
}
}
if !primary_span.contains(err.span) {
diag.span_note(primary_span,
&format!("for {} here", primary_kind));
}
}
pub fn eval_const_expr<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
e: &Expr) -> ConstVal {
match eval_const_expr_partial(tcx, e, ExprTypeChecked, None) {
Ok(r) => r,
// non-const path still needs to be a fatal error, because enums are funky
Err(s) => {
report_const_eval_err(tcx, &s, e.span, "expression").emit();
match s.kind {
NonConstPath |
UnimplementedConstVal(_) => tcx.sess.abort_if_errors(),
_ => {}
}
Dummy
},
}
}
pub type FnArgMap<'a> = Option<&'a NodeMap<ConstVal>>;
#[derive(Clone)]
pub struct ConstEvalErr {
pub span: Span,
pub kind: ErrKind,
}
#[derive(Clone)]
pub enum ErrKind {
CannotCast,
CannotCastTo(&'static str),
InvalidOpForInts(hir::BinOp_),
InvalidOpForBools(hir::BinOp_),
InvalidOpForFloats(hir::BinOp_),
InvalidOpForIntUint(hir::BinOp_),
InvalidOpForUintInt(hir::BinOp_),
NegateOn(ConstVal),
NotOn(ConstVal),
CallOn(ConstVal),
MissingStructField,
NonConstPath,
UnimplementedConstVal(&'static str),
UnresolvedPath,
ExpectedConstTuple,
ExpectedConstStruct,
TupleIndexOutOfBounds,
IndexedNonVec,
IndexNegative,
IndexNotInt,
IndexOutOfBounds { len: u64, index: u64 },
RepeatCountNotNatural,
RepeatCountNotInt,
MiscBinaryOp,
MiscCatchAll,
IndexOpFeatureGated,
Math(ConstMathErr),
IntermediateUnsignedNegative,
/// Expected, Got
TypeMismatch(String, ConstInt),
BadType(ConstVal),
ErroneousReferencedConstant(Box<ConstEvalErr>),
CharCast(ConstInt),
}
impl From<ConstMathErr> for ErrKind {
fn from(err: ConstMathErr) -> ErrKind {
Math(err)
}
}
#[derive(Clone, Debug)]
pub enum ConstEvalErrDescription<'a> {
Simple(Cow<'a, str>),
}
impl<'a> ConstEvalErrDescription<'a> {
/// Return a one-line description of the error, for lints and such
pub fn into_oneline(self) -> Cow<'a, str> {
match self {
ConstEvalErrDescription::Simple(simple) => simple,
}
}
}
impl ConstEvalErr {
pub fn description(&self) -> ConstEvalErrDescription {
use self::ErrKind::*;
use self::ConstEvalErrDescription::*;
macro_rules! simple {
($msg:expr) => ({ Simple($msg.into_cow()) });
($fmt:expr, $($arg:tt)+) => ({
Simple(format!($fmt, $($arg)+).into_cow())
})
}
match self.kind {
CannotCast => simple!("can't cast this type"),
CannotCastTo(s) => simple!("can't cast this type to {}", s),
InvalidOpForInts(_) => simple!("can't do this op on integrals"),
InvalidOpForBools(_) => simple!("can't do this op on bools"),
InvalidOpForFloats(_) => simple!("can't do this op on floats"),
InvalidOpForIntUint(..) => simple!("can't do this op on an isize and usize"),
InvalidOpForUintInt(..) => simple!("can't do this op on a usize and isize"),
NegateOn(ref const_val) => simple!("negate on {}", const_val.description()),
NotOn(ref const_val) => simple!("not on {}", const_val.description()),
CallOn(ref const_val) => simple!("call on {}", const_val.description()),
MissingStructField => simple!("nonexistent struct field"),
NonConstPath => simple!("non-constant path in constant expression"),
UnimplementedConstVal(what) =>
simple!("unimplemented constant expression: {}", what),
UnresolvedPath => simple!("unresolved path in constant expression"),
ExpectedConstTuple => simple!("expected constant tuple"),
ExpectedConstStruct => simple!("expected constant struct"),
TupleIndexOutOfBounds => simple!("tuple index out of bounds"),
IndexedNonVec => simple!("indexing is only supported for arrays"),
IndexNegative => simple!("indices must be non-negative integers"),
IndexNotInt => simple!("indices must be integers"),
IndexOutOfBounds { len, index } => {
simple!("index out of bounds: the len is {} but the index is {}",
len, index)
}
RepeatCountNotNatural => simple!("repeat count must be a natural number"),
RepeatCountNotInt => simple!("repeat count must be integers"),
MiscBinaryOp => simple!("bad operands for binary"),
MiscCatchAll => simple!("unsupported constant expr"),
IndexOpFeatureGated => simple!("the index operation on const values is unstable"),
Math(ref err) => Simple(err.description().into_cow()),
IntermediateUnsignedNegative => simple!(
"during the computation of an unsigned a negative \
number was encountered. This is most likely a bug in\
the constant evaluator"),
TypeMismatch(ref expected, ref got) => {
simple!("expected {}, found {}", expected, got.description())
},
BadType(ref i) => simple!("value of wrong type: {:?}", i),
ErroneousReferencedConstant(_) => simple!("could not evaluate referenced constant"),
CharCast(ref got) => {
simple!("only `u8` can be cast as `char`, not `{}`", got.description())
},
}
}
}
pub type EvalResult = Result<ConstVal, ConstEvalErr>;
pub type CastResult = Result<ConstVal, ErrKind>;
// FIXME: Long-term, this enum should go away: trying to evaluate
// an expression which hasn't been type-checked is a recipe for
// disaster. That said, it's not clear how to fix ast_ty_to_ty
// to avoid the ordering issue.
/// Hint to determine how to evaluate constant expressions which
/// might not be type-checked.
#[derive(Copy, Clone, Debug)]
pub enum EvalHint<'tcx> {
/// We have a type-checked expression.
ExprTypeChecked,
/// We have an expression which hasn't been type-checked, but we have
/// an idea of what the type will be because of the context. For example,
/// the length of an array is always `usize`. (This is referred to as
/// a hint because it isn't guaranteed to be consistent with what
/// type-checking would compute.)
UncheckedExprHint(Ty<'tcx>),
/// We have an expression which has not yet been type-checked, and
/// and we have no clue what the type will be.
UncheckedExprNoHint,
}
impl<'tcx> EvalHint<'tcx> {
fn erase_hint(&self) -> EvalHint<'tcx> {
match *self {
ExprTypeChecked => ExprTypeChecked,
UncheckedExprHint(_) | UncheckedExprNoHint => UncheckedExprNoHint,
}
}
fn checked_or(&self, ty: Ty<'tcx>) -> EvalHint<'tcx> {
match *self {
ExprTypeChecked => ExprTypeChecked,
_ => UncheckedExprHint(ty),
}
}
}
macro_rules! signal {
($e:expr, $exn:expr) => {
return Err(ConstEvalErr { span: $e.span, kind: $exn })
}
}
/// Evaluate a constant expression in a context where the expression isn't
/// guaranteed to be evaluatable. `ty_hint` is usually ExprTypeChecked,
/// but a few places need to evaluate constants during type-checking, like
/// computing the length of an array. (See also the FIXME above EvalHint.)
pub fn eval_const_expr_partial<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
e: &Expr,
ty_hint: EvalHint<'tcx>,
fn_args: FnArgMap) -> EvalResult {
// Try to compute the type of the expression based on the EvalHint.
// (See also the definition of EvalHint, and the FIXME above EvalHint.)
let ety = match ty_hint {
ExprTypeChecked => {
// After type-checking, expr_ty is guaranteed to succeed.
Some(tcx.expr_ty(e))
}
UncheckedExprHint(ty) => {
// Use the type hint; it's not guaranteed to be right, but it's
// usually good enough.
Some(ty)
}
UncheckedExprNoHint => {
// This expression might not be type-checked, and we have no hint.
// Try to query the context for a type anyway; we might get lucky
// (for example, if the expression was imported from another crate).
tcx.expr_ty_opt(e)
}
};
let result = match e.node {
hir::ExprUnary(hir::UnNeg, ref inner) => {
// unary neg literals already got their sign during creation
if let hir::ExprLit(ref lit) = inner.node {
use syntax::ast::*;
use syntax::ast::LitIntType::*;
const I8_OVERFLOW: u64 = ::std::i8::MAX as u64 + 1;
const I16_OVERFLOW: u64 = ::std::i16::MAX as u64 + 1;
const I32_OVERFLOW: u64 = ::std::i32::MAX as u64 + 1;
const I64_OVERFLOW: u64 = ::std::i64::MAX as u64 + 1;
match (&lit.node, ety.map(|t| &t.sty)) {
(&LitKind::Int(I8_OVERFLOW, Unsuffixed), Some(&ty::TyInt(IntTy::I8))) |
(&LitKind::Int(I8_OVERFLOW, Signed(IntTy::I8)), _) => {
return Ok(Integral(I8(::std::i8::MIN)))
},
(&LitKind::Int(I16_OVERFLOW, Unsuffixed), Some(&ty::TyInt(IntTy::I16))) |
(&LitKind::Int(I16_OVERFLOW, Signed(IntTy::I16)), _) => {
return Ok(Integral(I16(::std::i16::MIN)))
},
(&LitKind::Int(I32_OVERFLOW, Unsuffixed), Some(&ty::TyInt(IntTy::I32))) |
(&LitKind::Int(I32_OVERFLOW, Signed(IntTy::I32)), _) => {
return Ok(Integral(I32(::std::i32::MIN)))
},
(&LitKind::Int(I64_OVERFLOW, Unsuffixed), Some(&ty::TyInt(IntTy::I64))) |
(&LitKind::Int(I64_OVERFLOW, Signed(IntTy::I64)), _) => {
return Ok(Integral(I64(::std::i64::MIN)))
},
(&LitKind::Int(n, Unsuffixed), Some(&ty::TyInt(IntTy::Is))) |
(&LitKind::Int(n, Signed(IntTy::Is)), _) => {
match tcx.sess.target.int_type {
IntTy::I16 => if n == I16_OVERFLOW {
return Ok(Integral(Isize(Is16(::std::i16::MIN))));
},
IntTy::I32 => if n == I32_OVERFLOW {
return Ok(Integral(Isize(Is32(::std::i32::MIN))));
},
IntTy::I64 => if n == I64_OVERFLOW {
return Ok(Integral(Isize(Is64(::std::i64::MIN))));
},
_ => bug!(),
}
},
_ => {},
}
}
match eval_const_expr_partial(tcx, &inner, ty_hint, fn_args)? {
Float(f) => Float(-f),
Integral(i) => Integral(math!(e, -i)),
const_val => signal!(e, NegateOn(const_val)),
}
}
hir::ExprUnary(hir::UnNot, ref inner) => {
match eval_const_expr_partial(tcx, &inner, ty_hint, fn_args)? {
Integral(i) => Integral(math!(e, !i)),
Bool(b) => Bool(!b),
const_val => signal!(e, NotOn(const_val)),
}
}
hir::ExprUnary(hir::UnDeref, _) => signal!(e, UnimplementedConstVal("deref operation")),
hir::ExprBinary(op, ref a, ref b) => {
let b_ty = match op.node {
hir::BiShl | hir::BiShr => ty_hint.erase_hint(),
_ => ty_hint
};
// technically, if we don't have type hints, but integral eval
// gives us a type through a type-suffix, cast or const def type
// we need to re-eval the other value of the BinOp if it was
// not inferred
match (eval_const_expr_partial(tcx, &a, ty_hint, fn_args)?,
eval_const_expr_partial(tcx, &b, b_ty, fn_args)?) {
(Float(a), Float(b)) => {
use std::cmp::Ordering::*;
match op.node {
hir::BiAdd => Float(math!(e, a + b)),
hir::BiSub => Float(math!(e, a - b)),
hir::BiMul => Float(math!(e, a * b)),
hir::BiDiv => Float(math!(e, a / b)),
hir::BiRem => Float(math!(e, a % b)),
hir::BiEq => Bool(math!(e, a.try_cmp(b)) == Equal),
hir::BiLt => Bool(math!(e, a.try_cmp(b)) == Less),
hir::BiLe => Bool(math!(e, a.try_cmp(b)) != Greater),
hir::BiNe => Bool(math!(e, a.try_cmp(b)) != Equal),
hir::BiGe => Bool(math!(e, a.try_cmp(b)) != Less),
hir::BiGt => Bool(math!(e, a.try_cmp(b)) == Greater),
_ => signal!(e, InvalidOpForFloats(op.node)),
}
}
(Integral(a), Integral(b)) => {
use std::cmp::Ordering::*;
match op.node {
hir::BiAdd => Integral(math!(e, a + b)),
hir::BiSub => Integral(math!(e, a - b)),
hir::BiMul => Integral(math!(e, a * b)),
hir::BiDiv => Integral(math!(e, a / b)),
hir::BiRem => Integral(math!(e, a % b)),
hir::BiBitAnd => Integral(math!(e, a & b)),
hir::BiBitOr => Integral(math!(e, a | b)),
hir::BiBitXor => Integral(math!(e, a ^ b)),
hir::BiShl => Integral(math!(e, a << b)),
hir::BiShr => Integral(math!(e, a >> b)),
hir::BiEq => Bool(math!(e, a.try_cmp(b)) == Equal),
hir::BiLt => Bool(math!(e, a.try_cmp(b)) == Less),
hir::BiLe => Bool(math!(e, a.try_cmp(b)) != Greater),
hir::BiNe => Bool(math!(e, a.try_cmp(b)) != Equal),
hir::BiGe => Bool(math!(e, a.try_cmp(b)) != Less),
hir::BiGt => Bool(math!(e, a.try_cmp(b)) == Greater),
_ => signal!(e, InvalidOpForInts(op.node)),
}
}
(Bool(a), Bool(b)) => {
Bool(match op.node {
hir::BiAnd => a && b,
hir::BiOr => a || b,
hir::BiBitXor => a ^ b,
hir::BiBitAnd => a & b,
hir::BiBitOr => a | b,
hir::BiEq => a == b,
hir::BiNe => a != b,
_ => signal!(e, InvalidOpForBools(op.node)),
})
}
_ => signal!(e, MiscBinaryOp),
}
}
hir::ExprCast(ref base, ref target_ty) => {
let ety = tcx.ast_ty_to_prim_ty(&target_ty).or(ety)
.unwrap_or_else(|| {
tcx.sess.span_fatal(target_ty.span,
"target type not found for const cast")
});
let base_hint = if let ExprTypeChecked = ty_hint {
ExprTypeChecked
} else {
match tcx.expr_ty_opt(&base) {
Some(t) => UncheckedExprHint(t),
None => ty_hint
}
};
let val = match eval_const_expr_partial(tcx, &base, base_hint, fn_args) {
Ok(val) => val,
Err(ConstEvalErr { kind: ErroneousReferencedConstant(
box ConstEvalErr { kind: TypeMismatch(_, val), .. }), .. }) |
Err(ConstEvalErr { kind: TypeMismatch(_, val), .. }) => {
// Something like `5i8 as usize` doesn't need a type hint for the base
// instead take the type hint from the inner value
let hint = match val.int_type() {
Some(IntType::UnsignedInt(ty)) => ty_hint.checked_or(tcx.mk_mach_uint(ty)),
Some(IntType::SignedInt(ty)) => ty_hint.checked_or(tcx.mk_mach_int(ty)),
// we had a type hint, so we can't have an unknown type
None => bug!(),
};
eval_const_expr_partial(tcx, &base, hint, fn_args)?
},
Err(e) => return Err(e),
};
match cast_const(tcx, val, ety) {
Ok(val) => val,
Err(kind) => return Err(ConstEvalErr { span: e.span, kind: kind }),
}
}
hir::ExprPath(..) => {
// This function can be used before type checking when not all paths are fully resolved.
// FIXME: There's probably a better way to make sure we don't panic here.
let resolution = tcx.expect_resolution(e.id);
if resolution.depth != 0 {
signal!(e, UnresolvedPath);
}
match resolution.base_def {
Def::Const(def_id) |
Def::AssociatedConst(def_id) => {
let substs = if let ExprTypeChecked = ty_hint {
Some(tcx.node_id_item_substs(e.id).substs)
} else {
None
};
if let Some((expr, ty)) = lookup_const_by_id(tcx, def_id, substs) {
let item_hint = match ty {
Some(ty) => ty_hint.checked_or(ty),
None => ty_hint,
};
match eval_const_expr_partial(tcx, expr, item_hint, None) {
Ok(val) => val,
Err(err) => {
debug!("bad reference: {:?}, {:?}", err.description(), err.span);
signal!(e, ErroneousReferencedConstant(box err))
},
}
} else {
signal!(e, NonConstPath);
}
},
Def::Variant(variant_def) => {
if let Some(const_expr) = lookup_variant_by_id(tcx, variant_def) {
match eval_const_expr_partial(tcx, const_expr, ty_hint, None) {
Ok(val) => val,
Err(err) => {
debug!("bad reference: {:?}, {:?}", err.description(), err.span);
signal!(e, ErroneousReferencedConstant(box err))
},
}
} else {
signal!(e, UnimplementedConstVal("enum variants"));
}
}
Def::Struct(..) => {
ConstVal::Struct(e.id)
}
Def::Local(def_id) => {
let id = tcx.map.as_local_node_id(def_id).unwrap();
debug!("Def::Local({:?}): {:?}", id, fn_args);
if let Some(val) = fn_args.and_then(|args| args.get(&id)) {
val.clone()
} else {
signal!(e, NonConstPath);
}
},
Def::Method(id) | Def::Fn(id) => Function(id),
_ => signal!(e, NonConstPath),
}
}
hir::ExprCall(ref callee, ref args) => {
let sub_ty_hint = ty_hint.erase_hint();
let callee_val = eval_const_expr_partial(tcx, callee, sub_ty_hint, fn_args)?;
let did = match callee_val {
Function(did) => did,
Struct(_) => signal!(e, UnimplementedConstVal("tuple struct constructors")),
callee => signal!(e, CallOn(callee)),
};
let (decl, result) = if let Some(fn_like) = lookup_const_fn_by_id(tcx, did) {
(fn_like.decl(), &fn_like.body().expr)
} else {
signal!(e, NonConstPath)
};
let result = result.as_ref().expect("const fn has no result expression");
assert_eq!(decl.inputs.len(), args.len());
let mut call_args = NodeMap();
for (arg, arg_expr) in decl.inputs.iter().zip(args.iter()) {
let arg_hint = ty_hint.erase_hint();
let arg_val = eval_const_expr_partial(
tcx,
arg_expr,
arg_hint,
fn_args
)?;
debug!("const call arg: {:?}", arg);
let old = call_args.insert(arg.pat.id, arg_val);
assert!(old.is_none());
}
debug!("const call({:?})", call_args);
eval_const_expr_partial(tcx, &result, ty_hint, Some(&call_args))?
},
hir::ExprLit(ref lit) => match lit_to_const(&lit.node, tcx, ety) {
Ok(val) => val,
Err(err) => signal!(e, err),
},
hir::ExprBlock(ref block) => {
match block.expr {
Some(ref expr) => eval_const_expr_partial(tcx, &expr, ty_hint, fn_args)?,
None => signal!(e, UnimplementedConstVal("empty block")),
}
}
hir::ExprType(ref e, _) => eval_const_expr_partial(tcx, &e, ty_hint, fn_args)?,
hir::ExprTup(_) => Tuple(e.id),
hir::ExprStruct(..) => Struct(e.id),
hir::ExprIndex(ref arr, ref idx) => {
if !tcx.sess.features.borrow().const_indexing {
signal!(e, IndexOpFeatureGated);
}
let arr_hint = ty_hint.erase_hint();
let arr = eval_const_expr_partial(tcx, arr, arr_hint, fn_args)?;
let idx_hint = ty_hint.checked_or(tcx.types.usize);
let idx = match eval_const_expr_partial(tcx, idx, idx_hint, fn_args)? {
Integral(Usize(i)) => i.as_u64(tcx.sess.target.uint_type),
Integral(_) => bug!(),
_ => signal!(idx, IndexNotInt),
};
assert_eq!(idx as usize as u64, idx);
match arr {
Array(_, n) if idx >= n => {
signal!(e, IndexOutOfBounds { len: n, index: idx })
}
Array(v, n) => if let hir::ExprArray(ref v) = tcx.map.expect_expr(v).node {
assert_eq!(n as usize as u64, n);
eval_const_expr_partial(tcx, &v[idx as usize], ty_hint, fn_args)?
} else {
bug!()
},
Repeat(_, n) if idx >= n => {
signal!(e, IndexOutOfBounds { len: n, index: idx })
}
Repeat(elem, _) => eval_const_expr_partial(
tcx,
&tcx.map.expect_expr(elem),
ty_hint,
fn_args,
)?,
ByteStr(ref data) if idx >= data.len() as u64 => {
signal!(e, IndexOutOfBounds { len: data.len() as u64, index: idx })
}
ByteStr(data) => {
Integral(U8(data[idx as usize]))
},
_ => signal!(e, IndexedNonVec),
}
}
hir::ExprArray(ref v) => Array(e.id, v.len() as u64),
hir::ExprRepeat(_, ref n) => {
let len_hint = ty_hint.checked_or(tcx.types.usize);
Repeat(
e.id,
match eval_const_expr_partial(tcx, &n, len_hint, fn_args)? {
Integral(Usize(i)) => i.as_u64(tcx.sess.target.uint_type),
Integral(_) => signal!(e, RepeatCountNotNatural),
_ => signal!(e, RepeatCountNotInt),
},
)
},
hir::ExprTupField(ref base, index) => {
let base_hint = ty_hint.erase_hint();
let c = eval_const_expr_partial(tcx, base, base_hint, fn_args)?;
if let Tuple(tup_id) = c {
if let hir::ExprTup(ref fields) = tcx.map.expect_expr(tup_id).node {
if index.node < fields.len() {
eval_const_expr_partial(tcx, &fields[index.node], ty_hint, fn_args)?
} else {
signal!(e, TupleIndexOutOfBounds);
}
} else {
bug!()
}
} else {
signal!(base, ExpectedConstTuple);
}
}
hir::ExprField(ref base, field_name) => {
let base_hint = ty_hint.erase_hint();
// Get the base expression if it is a struct and it is constant
let c = eval_const_expr_partial(tcx, base, base_hint, fn_args)?;
if let Struct(struct_id) = c {
if let hir::ExprStruct(_, ref fields, _) = tcx.map.expect_expr(struct_id).node {
// Check that the given field exists and evaluate it
// if the idents are compared run-pass/issue-19244 fails
if let Some(f) = fields.iter().find(|f| f.name.node
== field_name.node) {
eval_const_expr_partial(tcx, &f.expr, ty_hint, fn_args)?
} else {
signal!(e, MissingStructField);
}
} else {
bug!()
}
} else {
signal!(base, ExpectedConstStruct);
}
}
hir::ExprAddrOf(..) => signal!(e, UnimplementedConstVal("address operator")),
_ => signal!(e, MiscCatchAll)
};
match (ety.map(|t| &t.sty), result) {
(Some(ref ty_hint), Integral(i)) => match infer(i, tcx, ty_hint) {
Ok(inferred) => Ok(Integral(inferred)),
Err(err) => signal!(e, err),
},
(_, result) => Ok(result),
}
}
fn infer<'a, 'tcx>(i: ConstInt,
tcx: TyCtxt<'a, 'tcx, 'tcx>,
ty_hint: &ty::TypeVariants<'tcx>)
-> Result<ConstInt, ErrKind> {
use syntax::ast::*;
match (ty_hint, i) {
(&ty::TyInt(IntTy::I8), result @ I8(_)) => Ok(result),
(&ty::TyInt(IntTy::I16), result @ I16(_)) => Ok(result),
(&ty::TyInt(IntTy::I32), result @ I32(_)) => Ok(result),