-
Notifications
You must be signed in to change notification settings - Fork 90
/
Copy pathtypecheck.rs
2546 lines (2446 loc) · 118 KB
/
typecheck.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 2022-2023 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
//! Implements typechecking for Cedar policies. Typechecking is done using
//! the `Typechecker` struct by calling the `typecheck_policy` method given a
//! policy.
mod test_expr;
mod test_extensions;
mod test_namespace;
mod test_optional_attributes;
mod test_partial;
mod test_policy;
mod test_strict;
mod test_type_annotation;
mod test_unspecified_entity;
mod test_utils;
use std::{
borrow::Cow,
collections::{HashMap, HashSet},
iter::zip,
};
use crate::{
extension_schema::{ExtensionFunctionType, ExtensionSchema},
extensions::all_available_extension_schemas,
fuzzy_match::fuzzy_search,
schema::{is_action_entity_type, ValidatorSchema},
types::{
AttributeType, Effect, EffectSet, EntityRecordKind, OpenTag, Primitive, RequestEnv, Type,
},
AttributeAccess, UnexpectedTypeHelp, ValidationMode,
};
use super::type_error::TypeError;
use cedar_policy_core::ast::{
BinaryOp, EntityType, EntityUID, Expr, ExprBuilder, ExprKind, Literal, Name,
PrincipalOrResourceConstraint, SlotId, Template, UnaryOp, Var,
};
use itertools::Itertools;
const REQUIRED_STACK_SPACE: usize = 1024 * 100;
/// TypecheckAnswer holds the result of typechecking an expression.
#[derive(Debug, Eq, PartialEq)]
pub(crate) enum TypecheckAnswer<'a> {
/// Typechecking succeeded, and we know the type and a possibly empty effect
/// set for the expression. The effect set is the set of
/// (expression, attribute) pairs that are known as safe to access under the
/// assumption that the expression evaluates to true.
TypecheckSuccess {
expr_type: Expr<Option<Type>>,
expr_effect: EffectSet<'a>,
},
/// Typechecking failed. We might still be able to know the type of the
/// overall expression, but not always. For instance, an `&&` expression
/// will always have type `boolean`, so we populate `expr_recovery_type`
/// with `Some(boolean)` even when there is a type error in the expression.
TypecheckFail {
expr_recovery_type: Expr<Option<Type>>,
},
/// RecursionLimit Reached
RecursionLimit,
}
impl<'a> TypecheckAnswer<'a> {
/// Construct a successful TypecheckAnswer with a type but with an empty
/// effect set.
pub fn success(expr_type: Expr<Option<Type>>) -> Self {
Self::TypecheckSuccess {
expr_type,
expr_effect: EffectSet::new(),
}
}
/// Construct a successful TypecheckAnswer with a type and an effect.
pub fn success_with_effect(expr_type: Expr<Option<Type>>, expr_effect: EffectSet<'a>) -> Self {
Self::TypecheckSuccess {
expr_type,
expr_effect,
}
}
/// Construct a failing TypecheckAnswer with a type.
pub fn fail(expr_type: Expr<Option<Type>>) -> Self {
Self::TypecheckFail {
expr_recovery_type: expr_type,
}
}
/// Check if this TypecheckAnswer contains a particular type. It
/// contains a type if the type annotated AST contains `Some`
/// of the argument type at its root.
pub fn contains_type(&self, ty: &Type) -> bool {
match self {
TypecheckAnswer::TypecheckSuccess { expr_type, .. } => Some(expr_type),
TypecheckAnswer::TypecheckFail { expr_recovery_type } => Some(expr_recovery_type),
TypecheckAnswer::RecursionLimit => None,
}
.and_then(|e| e.data().as_ref())
== Some(ty)
}
pub fn into_typed_expr(self) -> Option<Expr<Option<Type>>> {
match self {
TypecheckAnswer::TypecheckSuccess { expr_type, .. } => Some(expr_type),
TypecheckAnswer::TypecheckFail { expr_recovery_type } => Some(expr_recovery_type),
TypecheckAnswer::RecursionLimit => None,
}
}
/// Return true if this represents successful typechecking.
pub fn typechecked(&self) -> bool {
match self {
TypecheckAnswer::TypecheckSuccess { .. } => true,
TypecheckAnswer::TypecheckFail { .. } => false,
TypecheckAnswer::RecursionLimit => false,
}
}
/// Transform the effect of this TypecheckAnswer without modifying the
/// success or type.
pub fn map_effect<F>(self, f: F) -> Self
where
F: FnOnce(EffectSet<'a>) -> EffectSet<'a>,
{
match self {
TypecheckAnswer::TypecheckSuccess {
expr_type,
expr_effect,
} => TypecheckAnswer::TypecheckSuccess {
expr_type,
expr_effect: f(expr_effect),
},
TypecheckAnswer::TypecheckFail { .. } => self,
TypecheckAnswer::RecursionLimit => self,
}
}
/// Convert this TypecheckAnswer into an equivalent answer for an expression
/// that has failed to typecheck. If this is already TypecheckFail, then no
/// change is required, otherwise, a TypecheckFail is constructed containing
/// `Some` of the `expr_type`.
pub fn into_fail(self) -> Self {
match self {
TypecheckAnswer::TypecheckSuccess { expr_type, .. } => TypecheckAnswer::fail(expr_type),
TypecheckAnswer::TypecheckFail { .. } => self,
TypecheckAnswer::RecursionLimit => self,
}
}
/// Sequence another typechecking operation after this answer. The result of
/// the operation will be adjusted to be a TypecheckFail if this is a
/// TypecheckFail, otherwise it will be returned unaltered.
pub fn then_typecheck<F>(self, f: F) -> Self
where
F: FnOnce(Expr<Option<Type>>, EffectSet<'a>) -> TypecheckAnswer<'a>,
{
match self {
TypecheckAnswer::TypecheckSuccess {
expr_type,
expr_effect,
} => f(expr_type, expr_effect),
TypecheckAnswer::TypecheckFail { expr_recovery_type } => {
f(expr_recovery_type, EffectSet::new()).into_fail()
}
TypecheckAnswer::RecursionLimit => self,
}
}
/// Sequence another typechecking operation after all of the typechecking
/// answers in the argument. The result of the operation is adjusted in the
/// same manner as in `then_typecheck`, but accounts for the all the
/// TypecheckAnswers.
pub fn sequence_all_then_typecheck<F>(
answers: impl IntoIterator<Item = TypecheckAnswer<'a>>,
f: F,
) -> TypecheckAnswer<'a>
where
F: FnOnce(Vec<(Expr<Option<Type>>, EffectSet<'a>)>) -> TypecheckAnswer<'a>,
{
let mut unwrapped = Vec::new();
let mut any_failed = false;
let mut recusion_limit_reached = false;
for ans in answers {
any_failed |= !ans.typechecked();
unwrapped.push(match ans {
TypecheckAnswer::TypecheckSuccess {
expr_type,
expr_effect,
} => (expr_type, expr_effect),
TypecheckAnswer::TypecheckFail { expr_recovery_type } => {
(expr_recovery_type, EffectSet::new())
}
TypecheckAnswer::RecursionLimit => {
recusion_limit_reached = true;
break;
}
});
}
let ans = f(unwrapped);
if recusion_limit_reached {
TypecheckAnswer::RecursionLimit
} else if any_failed {
ans.into_fail()
} else {
ans
}
}
}
/// Basic result for typechecking
#[derive(Debug)]
pub enum PolicyCheck {
/// Policy will evaluate to a bool
Success(Expr<Option<Type>>),
/// Policy will always evaluate to false, and may have errors
Irrelevant(Vec<TypeError>),
/// Policy will have errors
Fail(Vec<TypeError>),
}
/// This structure implements typechecking for Cedar policies through the
/// entry point `typecheck_policy`.
#[derive(Debug)]
pub struct Typechecker<'a> {
schema: &'a ValidatorSchema,
extensions: HashMap<Name, ExtensionSchema>,
mode: ValidationMode,
}
impl<'a> Typechecker<'a> {
/// Construct a new typechecker.
pub fn new(schema: &'a ValidatorSchema, mode: ValidationMode) -> Typechecker<'a> {
// Set the extensions using `all_available_extension_schemas`.
let extensions = all_available_extension_schemas()
.into_iter()
.map(|ext| (ext.name().clone(), ext))
.collect();
Self {
schema,
extensions,
mode,
}
}
/// The main entry point for typechecking policies. This method takes a
/// policy and a mutable `Vec` used to output type errors. Typechecking
/// ensures that the policy expression has type boolean. If typechecking
/// succeeds, then the method will return true, and no items will be
/// added to the output list. Otherwise, the function returns false and the
/// output list is populated with any errors encountered while typechecking.
pub fn typecheck_policy(&self, t: &Template, type_errors: &mut HashSet<TypeError>) -> bool {
let typecheck_answers = self.typecheck_by_request_env(t);
// consolidate the results from each query environment
let (all_false, all_succ) = typecheck_answers.into_iter().fold(
(true, true),
|(all_false, all_succ), (_, check)| match check {
PolicyCheck::Success(_) => (false, all_succ),
PolicyCheck::Irrelevant(err) => {
let no_err = err.is_empty();
type_errors.extend(err);
(all_false, all_succ && no_err)
}
PolicyCheck::Fail(err) => {
type_errors.extend(err);
(false, false)
}
},
);
// If every policy typechecked with type false, then the policy cannot
// possibly apply to any request.
if all_false {
type_errors.insert(TypeError::impossible_policy(t.condition()));
false
} else {
all_succ
}
}
/// Secondary entry point for typechecking requests. This method takes a policy and
/// typechecks it under every schema-defined request environment. The result contains
/// these environments and the individual typechecking response for each, in no
/// particular order.
pub fn typecheck_by_request_env<'b>(
&'b self,
t: &'b Template,
) -> Vec<(RequestEnv, PolicyCheck)> {
self.apply_typecheck_fn_by_request_env(t, |request, expr| {
let mut type_errors = Vec::new();
let empty_prior_eff = EffectSet::new();
let ty = self.expect_type(
request,
&empty_prior_eff,
expr,
Type::primitive_boolean(),
&mut type_errors,
|_| None,
);
let is_false = ty.contains_type(&Type::singleton_boolean(false));
match (is_false, ty.typechecked(), ty.into_typed_expr()) {
(false, true, None) => PolicyCheck::Fail(type_errors),
(false, true, Some(e)) => PolicyCheck::Success(e),
(false, false, _) => PolicyCheck::Fail(type_errors),
(true, _, _) => PolicyCheck::Irrelevant(type_errors),
}
})
}
/// Utility abstracting the common logic for strict and regular typechecking
/// by request environment.
fn apply_typecheck_fn_by_request_env<'b, F, C>(
&'b self,
t: &'b Template,
typecheck_fn: F,
) -> Vec<(RequestEnv, C)>
where
F: Fn(&RequestEnv, &Expr) -> C,
{
let mut result_checks = Vec::new();
// Validate each (principal, resource) pair with the substituted policy
// for the corresponding action. Implemented as for loop to make it
// explicit that `expect_type` will be called for every element of
// request_env without short circuiting.
let policy_condition = &t.condition();
for requeste in self
.unlinked_request_envs()
.flat_map(|env| self.link_request_env(env, t))
{
let check = typecheck_fn(&requeste, policy_condition);
result_checks.push((requeste, check))
}
result_checks
}
/// Additional entry point for typechecking requests. This method takes a slice
/// over policies and typechecks each under every schema-defined request environment.
///
/// The result contains these environments in no particular order, but each list of
/// policy checks will always match the original order.
pub fn multi_typecheck_by_request_env(
&self,
policy_templates: &[&Template],
) -> Vec<(RequestEnv, Vec<PolicyCheck>)> {
let mut env_checks = Vec::new();
for request in self.unlinked_request_envs() {
let mut policy_checks = Vec::new();
for t in policy_templates.iter() {
let condition_expr = t.condition();
for linked_env in self.link_request_env(request.clone(), t) {
let mut type_errors = Vec::new();
let empty_prior_eff = EffectSet::new();
let ty = self.expect_type(
&linked_env,
&empty_prior_eff,
&condition_expr,
Type::primitive_boolean(),
&mut type_errors,
|_| None,
);
let is_false = ty.contains_type(&Type::singleton_boolean(false));
match (is_false, ty.typechecked(), ty.into_typed_expr()) {
(false, true, None) => policy_checks.push(PolicyCheck::Fail(type_errors)),
(false, true, Some(e)) => policy_checks.push(PolicyCheck::Success(e)),
(false, false, _) => policy_checks.push(PolicyCheck::Fail(type_errors)),
(true, _, _) => policy_checks.push(PolicyCheck::Irrelevant(type_errors)),
}
}
}
env_checks.push((request, policy_checks));
}
env_checks
}
fn unlinked_request_envs(&self) -> impl Iterator<Item = RequestEnv> + '_ {
// Gather all of the actions declared in the schema.
let all_actions = self
.schema
.known_action_ids()
.filter_map(|a| self.schema.get_action_id(a));
// For every action compute the cross product of the principal and
// resource applies_to sets.
all_actions
.flat_map(|action| {
action
.applies_to
.applicable_principal_types()
.flat_map(|principal| {
action
.applies_to
.applicable_resource_types()
.map(|resource| RequestEnv::DeclaredAction {
principal,
action: &action.name,
resource,
context: &action.context,
principal_slot: None,
resource_slot: None,
})
})
})
.chain(if self.mode.is_partial() {
// A partial schema might not list all actions, and may not
// include all principal and resource types for the listed ones.
// So we typecheck with a fully unknown request to handle these
// missing cases.
Some(RequestEnv::UndeclaredAction)
} else {
None
})
}
/// Given a request environment and a template, return new environments
/// formed by instantiating template slots with possible entity types.
fn link_request_env<'b>(
&'b self,
env: RequestEnv<'b>,
t: &'b Template,
) -> Box<dyn Iterator<Item = RequestEnv> + 'b> {
match env {
RequestEnv::UndeclaredAction => Box::new(std::iter::once(RequestEnv::UndeclaredAction)),
RequestEnv::DeclaredAction {
principal,
action,
resource,
context,
..
} => Box::new(
self.possible_slot_instantiations(
t,
SlotId::principal(),
principal,
t.principal_constraint().as_inner(),
)
.flat_map(move |p_slot| {
self.possible_slot_instantiations(
t,
SlotId::resource(),
resource,
t.resource_constraint().as_inner(),
)
.map(move |r_slot| RequestEnv::DeclaredAction {
principal,
action,
resource,
context,
principal_slot: p_slot.clone(),
resource_slot: r_slot.clone(),
})
}),
),
}
}
/// Get the entity types which could instantiate the slot given in this
/// template based on the policy scope constraints. We use this function to
/// avoid typechecking with slot bindings that will always be false based
/// only on the scope constraints.
fn possible_slot_instantiations(
&self,
t: &Template,
slot_id: SlotId,
var: &'a EntityType,
constraint: &PrincipalOrResourceConstraint,
) -> Box<dyn Iterator<Item = Option<EntityType>> + 'a> {
if t.slots().contains(&slot_id) {
let all_entity_types = self.schema.entity_types();
match constraint {
// The condition is `var = ?slot`, so the policy can only apply
// if the slot has the same entity type as `var`.
PrincipalOrResourceConstraint::Eq(_) => {
Box::new(std::iter::once(Some(var.clone())))
}
// The condition is `var in ?slot` or `var is type in ?slot`, so
// the policy can only apply if the var is some descendant of
// the slot. We ignore the `is type` portion because this
// constrains the `var` and not the slot.
PrincipalOrResourceConstraint::IsIn(_, _)
| PrincipalOrResourceConstraint::In(_) => Box::new(
all_entity_types
.filter(|(_, ety)| ety.has_descendant_entity_type(var))
.map(|(name, _)| Some(EntityType::Specified(name.clone())))
.chain(std::iter::once(Some(var.clone()))),
),
// The template uses the slot, but without a scope constraint.
// This can't happen for the moment because slots may only
// appear in scope constraints, but if we ever see this, then the
// only correct way to proceed is by returning all entity types
// as possible instantiations.
PrincipalOrResourceConstraint::Is(_) | PrincipalOrResourceConstraint::Any => {
Box::new(
all_entity_types.map(|(name, _)| Some(EntityType::Specified(name.clone()))),
)
}
}
} else {
// If the template does not contain this slot, then we don't need to
// consider its instantiations..
Box::new(std::iter::once(None))
}
}
/// This method handles the majority of the work. Given an expression,
/// the type for the request, and the a prior effect context for the
/// expression, return the result of typechecking the expression, and add
/// any errors encountered into the type_errors list. The result of
/// typechecking contains the type of the expression, any current effect of
/// the expression, and a flag indicating whether the expression
/// successfully typechecked.
fn typecheck<'b>(
&self,
request_env: &RequestEnv,
prior_eff: &EffectSet<'b>,
e: &'b Expr,
type_errors: &mut Vec<TypeError>,
) -> TypecheckAnswer<'b> {
#[cfg(not(target_arch = "wasm32"))]
if stacker::remaining_stack().unwrap_or(0) < REQUIRED_STACK_SPACE {
return TypecheckAnswer::RecursionLimit;
}
match e.expr_kind() {
// Principal, resource, and context have types defined by
// the request type.
ExprKind::Var(Var::Principal) => TypecheckAnswer::success(
ExprBuilder::with_data(Some(request_env.principal_type()))
.with_same_source_loc(e)
.var(Var::Principal),
),
// While the EntityUID for Action is held in the request context,
// entity types do not consider the id of the entity (only the
// entity type), so the type of Action is only the entity type name
// taken from the euid.
ExprKind::Var(Var::Action) => {
match request_env.action_type(self.schema) {
Some(ty) => TypecheckAnswer::success(
ExprBuilder::with_data(Some(ty))
.with_same_source_loc(e)
.var(Var::Action),
),
// `None` if the action entity is not defined in the schema.
// This will only show up if we're typechecking with a
// request environment that was not constructed from the
// schema cross product, which will not happen through our
// public entry points, but it can occur if calling
// `typecheck` directly which happens in our tests.
None => TypecheckAnswer::fail(
ExprBuilder::new().with_same_source_loc(e).var(Var::Action),
),
}
}
ExprKind::Var(Var::Resource) => TypecheckAnswer::success(
ExprBuilder::with_data(Some(request_env.resource_type()))
.with_same_source_loc(e)
.var(Var::Resource),
),
ExprKind::Var(Var::Context) => TypecheckAnswer::success(
ExprBuilder::with_data(Some(request_env.context_type()))
.with_same_source_loc(e)
.var(Var::Context),
),
ExprKind::Unknown(u) => {
TypecheckAnswer::fail(ExprBuilder::with_data(None).unknown(u.clone()))
}
// Template Slots, always has to be an entity.
ExprKind::Slot(slotid) => TypecheckAnswer::success(
ExprBuilder::with_data(Some(if slotid.is_principal() {
request_env
.principal_slot()
.clone()
.map(Type::possibly_unspecified_entity_reference)
.unwrap_or(Type::any_entity_reference())
} else if slotid.is_resource() {
request_env
.resource_slot()
.clone()
.map(Type::possibly_unspecified_entity_reference)
.unwrap_or(Type::any_entity_reference())
} else {
Type::any_entity_reference()
}))
.with_same_source_loc(e)
.slot(*slotid),
),
// Literal booleans get singleton type according to their value.
ExprKind::Lit(Literal::Bool(val)) => TypecheckAnswer::success(
ExprBuilder::with_data(Some(Type::singleton_boolean(*val)))
.with_same_source_loc(e)
.val(*val),
),
// Other literal primitive values have the type of that primitive value.
ExprKind::Lit(Literal::Long(val)) => TypecheckAnswer::success(
ExprBuilder::with_data(Some(Type::primitive_long()))
.with_same_source_loc(e)
.val(*val),
),
ExprKind::Lit(Literal::String(val)) => TypecheckAnswer::success(
ExprBuilder::with_data(Some(Type::primitive_string()))
.with_same_source_loc(e)
.val(val.clone()),
),
// Literal entity reference have a type based on the entity type
// that can be looked up in the schema.
ExprKind::Lit(Literal::EntityUID(euid)) => {
// Unknown entity types/actions ids and unspecified entities will be
// detected by a different part of the validator, so a TypeError is
// not generated here. We still return `TypecheckFail` so that
// typechecking is not considered successful.
match Type::euid_literal((**euid).clone(), self.schema) {
// The entity type is undeclared, but that's OK for a
// partial schema. The attributes record will be empty if we
// try to access it later, so all attributes will have the
// bottom type.
None if self.mode.is_partial() => TypecheckAnswer::success(
ExprBuilder::with_data(Some(Type::possibly_unspecified_entity_reference(
euid.entity_type().clone(),
)))
.with_same_source_loc(e)
.val(euid.clone()),
),
Some(ty) => TypecheckAnswer::success(
ExprBuilder::with_data(Some(ty))
.with_same_source_loc(e)
.val(euid.clone()),
),
None => TypecheckAnswer::fail(
ExprBuilder::new().with_same_source_loc(e).val(euid.clone()),
),
}
}
ExprKind::If {
test_expr,
then_expr,
else_expr,
} => {
// The guard expression must be boolean.
let ans_test = self.expect_type(
request_env,
prior_eff,
test_expr,
Type::primitive_boolean(),
type_errors,
|_| None,
);
ans_test.then_typecheck(|typ_test, eff_test| {
// If the guard has type `true` or `false`, we short circuit,
// looking at only the relevant branch.
if typ_test.data() == &Some(Type::singleton_boolean(true)) {
// The `then` branch needs to be typechecked using the
// prior effect of the `if` and any new effect generated
// by `test`. This enables an attribute access
// `principal.foo` after a condition `principal has foo`.
let ans_then = self.typecheck(
request_env,
&prior_eff.union(&eff_test),
then_expr,
type_errors,
);
ans_then.then_typecheck(|typ_then, eff_then| {
TypecheckAnswer::success_with_effect(
typ_then,
// The output effect of the whole `if` expression also
// needs to contain the effect of the condition.
eff_then.union(&eff_test),
)
})
} else if typ_test.data() == &Some(Type::singleton_boolean(false)) {
// The `else` branch cannot use the `test` effect since
// we know in the `else` branch that the condition
// evaluated to `false`. It still can use the original
// prior effect.
let ans_else =
self.typecheck(request_env, prior_eff, else_expr, type_errors);
ans_else.then_typecheck(|typ_else, eff_else| {
TypecheckAnswer::success_with_effect(typ_else, eff_else)
})
} else {
// When we don't short circuit, the `then` and `else`
// branches are individually typechecked with the same
// prior effects are in their individual cases.
let ans_then = self
.typecheck(
request_env,
&prior_eff.union(&eff_test),
then_expr,
type_errors,
)
.map_effect(|ef| ef.union(&eff_test));
let ans_else =
self.typecheck(request_env, prior_eff, else_expr, type_errors);
// The type of the if expression is then the least
// upper bound of the types of the then and else
// branches. If either of these fails to typecheck, the
// other is still be typechecked to detect errors that
// may exist in that branch. This failure, in addition
// to any failure that may have occurred in the test
// expression, will propagate to final TypecheckAnswer.
ans_then.then_typecheck(|typ_then, eff_then| {
ans_else.then_typecheck(|typ_else, eff_else| {
let lub_ty = self.least_upper_bound_or_error(
e,
vec![typ_then.data().clone(), typ_else.data().clone()],
type_errors,
);
let has_lub = lub_ty.is_some();
let annot_expr = ExprBuilder::with_data(lub_ty)
.with_same_source_loc(e)
.ite(typ_test, typ_then, typ_else);
if has_lub {
// Effect is not handled in the LUB computation,
// so we need to compute the effect here. When
// the `||` evaluates to `true`, we know that
// one operand evaluated to true, but we don't
// know which. This is handled by returning an
// effect set that is the intersection of the
// operand effect sets.
TypecheckAnswer::success_with_effect(
annot_expr,
eff_else.intersect(&eff_then),
)
} else {
TypecheckAnswer::fail(annot_expr)
}
})
})
}
})
}
ExprKind::And { left, right } => {
let ans_left = self.expect_type(
request_env,
prior_eff,
left,
Type::primitive_boolean(),
type_errors,
|_| None,
);
ans_left.then_typecheck(|typ_left, eff_left| {
match typ_left.data() {
// First argument is false, so short circuit the `&&` to
// false _without_ typechecking the second argument.
// Since the type of the `&&` is `false`, it is known to
// always evaluate to `false` at run time. The `&&`
// expression typechecks with an empty effect rather
// than the effect of the lhs.
// The right operand is not typechecked, so it is not
// included in the type annotated AST.
Some(Type::False) => TypecheckAnswer::success(typ_left),
_ => {
// Similar to the `then` branch of an `if`
// expression, the rhs of an `&&` is typechecked
// using an updated prior effect that includes
// effect learned from the lhs to enable
// typechecking expressions like
// `principal has foo && principal.foo`. This is
// valid because `&&` short circuits at run time, so
// the right will only be evaluated after the left
// evaluated to `true`.
let ans_right = self.expect_type(
request_env,
&prior_eff.union(&eff_left),
right,
Type::primitive_boolean(),
type_errors,
|_| None,
);
ans_right.then_typecheck(|typ_right, eff_right| {
match (typ_left.data(), typ_right.data()) {
// The second argument is false, so the `&&`
// is false. The effect is empty for the
// same reason as when the first argument
// was false.
(Some(_), Some(Type::False)) => TypecheckAnswer::success(
ExprBuilder::with_data(Some(Type::False))
.with_same_source_loc(e)
.and(typ_left, typ_right),
),
// When either argument is true, the result type is
// the type of the other argument. Here, and
// in the remaining successful cases, the
// effect of the `&&` is the union of the
// lhs and rhs because both operands must be
// true for the whole `&&` to be true.
(Some(_), Some(Type::True)) => {
TypecheckAnswer::success_with_effect(
ExprBuilder::with_data(typ_left.data().clone())
.with_same_source_loc(e)
.and(typ_left, typ_right),
eff_left.union(&eff_right),
)
}
(Some(Type::True), Some(_)) => {
TypecheckAnswer::success_with_effect(
ExprBuilder::with_data(typ_right.data().clone())
.with_same_source_loc(e)
.and(typ_left, typ_right),
eff_right.union(&eff_right),
)
}
// Neither argument was true or false, so we only
// know the result type is boolean.
(Some(_), Some(_)) => TypecheckAnswer::success_with_effect(
ExprBuilder::with_data(Some(Type::primitive_boolean()))
.with_same_source_loc(e)
.and(typ_left, typ_right),
eff_left.union(&eff_right),
),
// One or both of the left and the right failed to
// typecheck, so the `&&` expression also fails.
_ => TypecheckAnswer::fail(
ExprBuilder::with_data(Some(Type::primitive_boolean()))
.with_same_source_loc(e)
.and(typ_left, typ_right),
),
}
})
}
}
})
}
// `||` follows the same pattern as `&&`, but with short circuiting
// effect propagation adjusted as necessary.
ExprKind::Or { left, right } => {
let ans_left = self.expect_type(
request_env,
prior_eff,
left,
Type::primitive_boolean(),
type_errors,
|_| None,
);
ans_left.then_typecheck(|ty_expr_left, eff_left| match ty_expr_left.data() {
// Contrary to `&&` where short circuiting did not permit
// any effect, an effect can be maintained when short
// circuiting `||`. We know the left operand is `true`, so
// its effect is maintained. The right operand is not
// evaluated, so its effect does not need to be considered.
// The right operand is not typechecked, so it is not
// included in the type annotated AST.
Some(Type::True) => TypecheckAnswer::success(ty_expr_left),
_ => {
// The right operand of an `||` cannot be typechecked
// using the effect learned from the left because the
// left could have evaluated to either `true` or `false`
// when the left is evaluated.
let ans_right = self.expect_type(
request_env,
prior_eff,
right,
Type::primitive_boolean(),
type_errors,
|_| None,
);
ans_right.then_typecheck(|ty_expr_right, eff_right| {
match (ty_expr_left.data(), ty_expr_right.data()) {
// Now the right operand is always `true`, so we can
// use its effect as the result effect. The left
// operand might have been `true` of `false`, but it
// does not affect the value of the `||` if the
// right is always `true`.
(Some(_), Some(Type::True)) => {
TypecheckAnswer::success_with_effect(
ExprBuilder::with_data(Some(Type::True))
.with_same_source_loc(e)
.or(ty_expr_left, ty_expr_right),
eff_right,
)
}
// If the right or left operand is always `false`,
// then the only way the `||` expression can be
// `true` is if the other operand is `true`. This
// lets us pass the effect of the other operand
// through to the effect of the `||`.
(Some(typ_left), Some(Type::False)) => {
TypecheckAnswer::success_with_effect(
ExprBuilder::with_data(Some(typ_left.clone()))
.with_same_source_loc(e)
.or(ty_expr_left, ty_expr_right),
eff_left,
)
}
(Some(Type::False), Some(typ_right)) => {
TypecheckAnswer::success_with_effect(
ExprBuilder::with_data(Some(typ_right.clone()))
.with_same_source_loc(e)
.or(ty_expr_left, ty_expr_right),
eff_right,
)
}
// When neither has a constant value, the `||`
// evaluates to true if one or both is `true`. This
// means we can only keep effects in the
// intersection of their effect sets.
(Some(_), Some(_)) => TypecheckAnswer::success_with_effect(
ExprBuilder::with_data(Some(Type::primitive_boolean()))
.with_same_source_loc(e)
.or(ty_expr_left, ty_expr_right),
eff_right.intersect(&eff_left),
),
_ => TypecheckAnswer::fail(
ExprBuilder::with_data(Some(Type::primitive_boolean()))
.with_same_source_loc(e)
.or(ty_expr_left, ty_expr_right),
),
}
})
}
})
}
ExprKind::UnaryApp { .. } => {
// INVARIANT: typecheck_unary requires a `UnaryApp`, we've just ensured this
self.typecheck_unary(request_env, prior_eff, e, type_errors)
}
ExprKind::BinaryApp { .. } => {
// INVARIANT: typecheck_binary requires a `BinaryApp`, we've just ensured this
self.typecheck_binary(request_env, prior_eff, e, type_errors)
}
ExprKind::MulByConst { .. } => {
// INVARIANT: typecheck_mul requires a `MulByConst`, we've just ensured this
self.typecheck_mul(request_env, prior_eff, e, type_errors)
}
ExprKind::ExtensionFunctionApp { .. } => {
// INVARIANT: typecheck_extension requires a `ExtensionFunctionApp`, we've just ensured this
self.typecheck_extension(request_env, prior_eff, e, type_errors)
}
ExprKind::GetAttr { expr, attr } => {
// Accessing an attribute requires either an entity or a record
// that has the attribute.
let actual = self.expect_one_of_types(
request_env,
prior_eff,
expr,
&[Type::any_entity_reference(), Type::any_record()],
type_errors,
|_| None,
);
actual.then_typecheck(|typ_expr_actual, _| match typ_expr_actual.data() {
Some(typ_actual) => {
let all_attrs = typ_actual.all_attributes(self.schema);
let attr_ty = Type::lookup_attribute_type(self.schema, typ_actual, attr);
let annot_expr = ExprBuilder::with_data(
attr_ty.clone().map(|attr_ty| attr_ty.attr_type),
)
.with_same_source_loc(e)
.get_attr(typ_expr_actual.clone(), attr.clone());
match attr_ty {
Some(ty) => {
// A safe access to an attribute requires either
// that the attribute is required (always
// present), or that the attribute is in the
// prior effect set (the current expression is
// guarded by a condition that will only
// evaluate to `true` when the attribute is
// present).
if ty.is_required || prior_eff.contains(&Effect::new(expr, attr)) {
TypecheckAnswer::success(annot_expr)
} else {
type_errors.push(TypeError::unsafe_optional_attribute_access(
e.clone(),
AttributeAccess::from_expr(request_env, &annot_expr),
));
TypecheckAnswer::fail(annot_expr)
}
}