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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
/*
 * 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.
 */

//! This module contains the parser for the Cedar language.

/// Concrete Syntax Tree def used as parser first pass
pub mod cst;
/// Step two: convert CST to package AST
mod cst_to_ast;
/// error handling utilities
pub mod err;
/// implementations for formatting, like `Display`
mod fmt;
/// Source location struct
mod loc;
pub use loc::Loc;
/// Metadata wrapper for CST Nodes
mod node;
pub use node::Node;
/// Step one: Convert text to CST
pub mod text_to_cst;
/// Utility functions to unescape string literals
pub mod unescape;

use smol_str::SmolStr;
use std::collections::HashMap;

use crate::ast;
use crate::ast::RestrictedExprParseError;
use crate::est;

/// simple main function for parsing policies
/// generates numbered ids
pub fn parse_policyset(text: &str) -> Result<ast::PolicySet, err::ParseErrors> {
    let mut errs = err::ParseErrors::new();
    let cst = text_to_cst::parse_policies(text)?;
    let Some(ast) = cst.to_policyset(&mut errs) else {
        return Err(errs);
    };
    if errs.is_empty() {
        Ok(ast)
    } else {
        Err(errs)
    }
}

/// Like `parse_policyset()`, but also returns the (lossless) original text of
/// each individual policy.
/// INVARIANT: The `PolicyId` of every `Policy` and `Template` returned by the
/// `policies()` and `templates()` methods on the returned `Policy` _must_
/// appear as a key in the returned map.
pub fn parse_policyset_and_also_return_policy_text(
    text: &str,
) -> Result<(HashMap<ast::PolicyID, &str>, ast::PolicySet), err::ParseErrors> {
    let mut errs = err::ParseErrors::new();
    let cst = text_to_cst::parse_policies(text)?;
    let Some(pset) = cst.to_policyset(&mut errs) else {
        return Err(errs);
    };
    if errs.is_empty() {
        // PANIC SAFETY Shouldn't be `none` since `parse_policies()` and `to_policyset()` didn't return `Err`
        #[allow(clippy::expect_used)]
        // PANIC SAFETY Indexing is safe because of how the `SourceSpan` is constructed
        #[allow(clippy::indexing_slicing)]
        // The `PolicyID` keys for `texts` are generated by
        // `cst.with_generated_policyids()`. This is the same method used to
        // generate the ids for policies and templates in `cst.to_policyset()`,
        // so every static policy and template in the policy set will have its
        // `PolicyId` present as a key in this map.
        let texts = cst
            .with_generated_policyids()
            .expect("shouldn't be None since parse_policies() and to_policyset() didn't return Err")
            .map(|(id, policy)| (id, &text[policy.loc.start()..policy.loc.end()]))
            .collect::<HashMap<ast::PolicyID, &str>>();
        Ok((texts, pset))
    } else {
        Err(errs)
    }
}

/// Like `parse_policyset()`, but also returns the (lossless) ESTs -- that is,
/// the ESTs of the original policies without any of the lossy transforms
/// involved in converting to AST.
pub fn parse_policyset_to_ests_and_pset(
    text: &str,
) -> Result<(HashMap<ast::PolicyID, est::Policy>, ast::PolicySet), err::ParseErrors> {
    let mut errs = err::ParseErrors::new();
    let cst = text_to_cst::parse_policies(text)?;
    let Some(pset) = cst.to_policyset(&mut errs) else {
        return Err(errs);
    };
    if errs.is_empty() {
        // PANIC SAFETY Shouldn't be `None` since `parse_policies()` and `to_policyset()` didn't return `Err`
        #[allow(clippy::expect_used)]
        let ests = cst
            .with_generated_policyids()
            .expect("missing policy set node")
            .map(|(id, policy)| {
                let p = policy.node.as_ref().expect("missing policy node").clone();
                Ok((id, p.try_into()?))
            })
            .collect::<Result<HashMap<ast::PolicyID, est::Policy>, err::ParseErrors>>()?;
        Ok((ests, pset))
    } else {
        Err(errs)
    }
}

/// Simple main function for parsing a policy template.
/// If `id` is Some, then the resulting template will have that `id`.
/// If the `id` is None, the parser will use "policy0".
pub fn parse_policy_template(
    id: Option<String>,
    text: &str,
) -> Result<ast::Template, err::ParseErrors> {
    let mut errs = err::ParseErrors::new();
    let id = match id {
        Some(id) => ast::PolicyID::from_string(id),
        None => ast::PolicyID::from_string("policy0"),
    };
    let cst = text_to_cst::parse_policy(text)?;
    let Some(ast) = cst.to_policy_template(id, &mut errs) else {
        return Err(errs);
    };
    if errs.is_empty() {
        Ok(ast)
    } else {
        Err(errs)
    }
}

/// Like `parse_policy_template()`, but also returns the (lossless) EST -- that
/// is, the EST of the original template without any of the lossy transforms
/// involved in converting to AST.
pub fn parse_policy_template_to_est_and_ast(
    id: Option<String>,
    text: &str,
) -> Result<(est::Policy, ast::Template), err::ParseErrors> {
    let mut errs = err::ParseErrors::new();
    let id = match id {
        Some(id) => ast::PolicyID::from_string(id),
        None => ast::PolicyID::from_string("policy0"),
    };
    let cst = text_to_cst::parse_policy(text)?;
    let (Some(ast), Some(cst_node)) = (cst.to_policy_template(id, &mut errs), cst.node) else {
        return Err(errs);
    };
    if errs.is_empty() {
        let est = cst_node.try_into()?;
        Ok((est, ast))
    } else {
        Err(errs)
    }
}

/// simple main function for parsing a policy.
/// If `id` is Some, then the resulting policy will have that `id`.
/// If the `id` is None, the parser will use "policy0".
pub fn parse_policy(id: Option<String>, text: &str) -> Result<ast::StaticPolicy, err::ParseErrors> {
    let mut errs = err::ParseErrors::new();
    let id = match id {
        Some(id) => ast::PolicyID::from_string(id),
        None => ast::PolicyID::from_string("policy0"),
    };
    let cst = text_to_cst::parse_policy(text)?;
    let Some(ast) = cst.to_policy(id, &mut errs) else {
        return Err(errs);
    };
    if errs.is_empty() {
        Ok(ast)
    } else {
        Err(errs)
    }
}

/// Like `parse_policy()`, but also returns the (lossless) EST -- that is, the
/// EST of the original policy without any of the lossy transforms involved in
/// converting to AST.
pub fn parse_policy_to_est_and_ast(
    id: Option<String>,
    text: &str,
) -> Result<(est::Policy, ast::StaticPolicy), err::ParseErrors> {
    let mut errs = err::ParseErrors::new();
    let id = match id {
        Some(id) => ast::PolicyID::from_string(id),
        None => ast::PolicyID::from_string("policy0"),
    };
    let cst = text_to_cst::parse_policy(text)?;
    let (Some(ast), Some(cst_node)) = (cst.to_policy(id, &mut errs), cst.node) else {
        return Err(errs);
    };
    if errs.is_empty() {
        let est = cst_node.try_into()?;
        Ok((est, ast))
    } else {
        Err(errs)
    }
}

/// Parse a policy or template (either one works) to its EST representation
pub fn parse_policy_or_template_to_est(text: &str) -> Result<est::Policy, err::ParseErrors> {
    let cst = text_to_cst::parse_policy(text)?;
    // PANIC SAFETY Shouldn't be `none` since `parse_policy()` didn't return `Err`
    #[allow(clippy::expect_used)]
    let cst_node = cst.node.expect("missing policy or template node");
    cst_node.try_into()
}

/// parse an Expr
///
/// Private to this crate. Users outside Core should use `Expr`'s `FromStr` impl
/// or its constructors
pub(crate) fn parse_expr(ptext: &str) -> Result<ast::Expr, err::ParseErrors> {
    let mut errs = err::ParseErrors::new();
    let cst = text_to_cst::parse_expr(ptext)?;
    let Some(ast) = cst.to_expr(&mut errs) else {
        return Err(errs);
    };
    if errs.is_empty() {
        Ok(ast)
    } else {
        Err(errs)
    }
}

/// parse a RestrictedExpr
///
/// Private to this crate. Users outside Core should use `RestrictedExpr`'s
/// `FromStr` impl or its constructors
pub(crate) fn parse_restrictedexpr(
    ptext: &str,
) -> Result<ast::RestrictedExpr, RestrictedExprParseError> {
    let expr = parse_expr(ptext)?;
    Ok(ast::RestrictedExpr::new(expr)?)
}

/// parse an EntityUID
///
/// Private to this crate. Users outside Core should use `EntityUID`'s `FromStr`
/// impl or its constructors
pub(crate) fn parse_euid(euid: &str) -> Result<ast::EntityUID, err::ParseErrors> {
    let mut errs = err::ParseErrors::new();
    let cst = text_to_cst::parse_ref(euid)?;
    let Some(ast) = cst.to_ref(&mut errs) else {
        return Err(errs);
    };
    if errs.is_empty() {
        Ok(ast)
    } else {
        Err(errs)
    }
}

/// parse a Name
///
/// Private to this crate. Users outside Core should use `Name`'s `FromStr` impl
/// or its constructors
pub(crate) fn parse_name(name: &str) -> Result<ast::Name, err::ParseErrors> {
    let mut errs = err::ParseErrors::new();
    let cst = text_to_cst::parse_name(name)?;
    let Some(ast) = cst.to_name(&mut errs) else {
        return Err(errs);
    };
    if errs.is_empty() {
        Ok(ast)
    } else {
        Err(errs)
    }
}

/// parse a string into an ast::Literal (does not support expressions)
///
/// Private to this crate. Users outside Core should use `Literal`'s `FromStr` impl
/// or its constructors
pub(crate) fn parse_literal(val: &str) -> Result<ast::Literal, err::ParseErrors> {
    let mut errs = err::ParseErrors::new();
    let cst = text_to_cst::parse_primary(val)?;
    let Some(ast) = cst.to_expr(&mut errs) else {
        return Err(errs);
    };
    if errs.is_empty() {
        match ast.into_expr_kind() {
            ast::ExprKind::Lit(v) => Ok(v),
            _ => Err(
                err::ParseError::ParseLiteral(err::ParseLiteralError::ParseLiteral(
                    val.to_string(),
                ))
                .into(),
            ),
        }
    } else {
        Err(errs)
    }
}

/// parse a string into an internal Cedar string
///
/// This performs unescaping and validation, returning
/// a String suitable for an attr, eid, or literal.
///
/// Quote handling is as if the input is surrounded by
/// double quotes ("{val}").
///
/// It does not return a string suitable for a pattern. Use the
/// full expression parser for those.
pub fn parse_internal_string(val: &str) -> Result<SmolStr, err::ParseErrors> {
    let mut errs = err::ParseErrors::new();
    // we need to add quotes for this to be a valid string literal
    let cst = text_to_cst::parse_primary(&format!(r#""{val}""#))?;
    let Some(ast) = cst.to_string_literal(&mut errs) else {
        return Err(errs);
    };
    if errs.is_empty() {
        Ok(ast)
    } else {
        Err(errs)
    }
}

/// parse an identifier
///
/// Private to this crate. Users outside Core should use `Id`'s `FromStr` impl
/// or its constructors
pub(crate) fn parse_ident(id: &str) -> Result<ast::Id, err::ParseErrors> {
    let mut errs = err::ParseErrors::new();
    let cst = text_to_cst::parse_ident(id)?;
    let Some(ast) = cst.to_valid_ident(&mut errs) else {
        return Err(errs);
    };
    if errs.is_empty() {
        Ok(ast)
    } else {
        Err(errs)
    }
}

/// parse an `AnyId`
///
/// Private to this crate. Users outside Core should use `AnyId`'s `FromStr` impl
/// or its constructors
pub(crate) fn parse_anyid(id: &str) -> Result<ast::AnyId, err::ParseErrors> {
    let mut errs = err::ParseErrors::new();
    let cst = text_to_cst::parse_ident(id)?;
    let Some(ast) = cst.to_any_ident(&mut errs) else {
        return Err(errs);
    };
    if errs.is_empty() {
        Ok(ast)
    } else {
        Err(errs)
    }
}

/// Utilities used in tests in this file (and maybe other files in this crate)
#[cfg(test)]
pub(crate) mod test_utils {
    use super::err::ParseErrors;
    use crate::test_utils::*;

    /// Expect that the given `ParseErrors` contains at least one error with the given `ExpectedErrorMessage`.
    ///
    /// `src` is the original input text, just for better assertion-failure messages
    #[track_caller] // report the caller's location as the location of the panic, not the location in this function
    pub fn expect_some_error_matches(
        src: &str,
        errs: &ParseErrors,
        msg: &ExpectedErrorMessage<'_>,
    ) {
        assert!(
            !errs.is_empty(),
            "for the following input:\n{src}\nexpected an error, but the `ParseErrors` was empty"
        );
        assert!(
            errs.iter().any(|e| msg.matches(e)),
            "for the following input:\n{src}\nexpected some error to match the following:\n{msg}\nbut actual errors were:\n{:?}", // the Debug representation of `miette::Report` is the pretty one, for some reason
            miette::Report::new(errs.clone()),
        );
    }

    /// Expect that the given `ParseErrors` contains exactly one error, and that it matches the given `ExpectedErrorMessage`.
    ///
    /// `src` is the original input text, just for better assertion-failure messages
    #[track_caller] // report the caller's location as the location of the panic, not the location in this function
    pub fn expect_exactly_one_error(src: &str, errs: &ParseErrors, msg: &ExpectedErrorMessage<'_>) {
        match errs.len() {
            0 => panic!("for the following input:\n{src}\nexpected an error, but the `ParseErrors` was empty"),
            1 => {
                let err = errs.iter().next().expect("already checked that len was 1");
                assert!(
                    msg.matches(err),
                    "for the following input:\n{src}\nexpected the error to match the following:\n{msg}\nbut actual error was:\n{:?}", // the Debug representation of `miette::Report` is the pretty one, for some reason
                    miette::Report::new(err.clone()),
                )
            }
            n => panic!(
                "for the following input:\n{src}\nexpected only one error, but got {n}. Expected to match the following:\n{msg}\nbut actual errors were:\n{:?}", // the Debug representation of `miette::Report` is the pretty one, for some reason
                miette::Report::new(errs.clone()),
            )
        }
    }
}

// PANIC SAFETY: Unit Test Code
#[allow(clippy::panic)]
#[cfg(test)]
mod test {
    use super::*;
    use crate::ast::{test_generators::*, Template};
    use cool_asserts::assert_matches;
    use std::collections::HashSet;

    #[test]
    fn test_template_parsing() {
        for template in all_templates().map(Template::from) {
            let id = template.id();
            let src = format!("{template}");
            let parsed = parse_policy_template(Some(id.to_string()), &src).unwrap();
            assert_eq!(
                parsed.slots().collect::<HashSet<_>>(),
                template.slots().collect::<HashSet<_>>()
            );
            assert_eq!(parsed.id(), template.id());
            assert_eq!(parsed.effect(), template.effect());
            assert_eq!(
                parsed.principal_constraint(),
                template.principal_constraint()
            );
            assert_eq!(parsed.action_constraint(), template.action_constraint());
            assert_eq!(parsed.resource_constraint(), template.resource_constraint());
            assert!(
                parsed
                    .non_head_constraints()
                    .eq_shape(template.non_head_constraints()),
                "{:?} and {:?} should have the same shape.",
                parsed.non_head_constraints(),
                template.non_head_constraints()
            );
        }
    }

    #[test]
    fn test_error_out() {
        assert_matches!(parse_policyset(
            r#"
            permit(principal:p,action:a,resource:r)
            when{w or if c but not z} // expr error
            unless{u if c else d or f} // expr error
            advice{"doit"};

            permit(principality in Group::"jane_friends", // policy error
            action in [PhotoOp::"view", PhotoOp::"comment"],
            resource in Album::"jane_trips");

            forbid(principal, action, resource)
            when   { "private" in resource.tags }
            unless { resource in principal.account };
        "#,
        ), Err(e) => assert!(e.len() >= 3, "expected at least 3 errors, but actual errors were:\n{:?}", miette::Report::new(e)) );
    }
}

#[cfg(test)]
mod eval_tests {
    use super::err::{ParseErrors, ToASTErrorKind};
    use super::*;
    use crate::evaluator as eval;
    use crate::extensions::Extensions;
    use crate::parser::err::ParseError;

    use std::sync::Arc;

    #[test]
    fn entity_literals1() {
        let src = r#"Test::{ test : "Test" }"#;
        let ParseErrors(errs) = parse_euid(src).err().unwrap();
        assert_eq!(errs.len(), 1);
        let expected = ToASTErrorKind::UnsupportedEntityLiterals;
        assert!(errs
            .iter()
            .any(|e| matches!(e, ParseError::ToAST(e) if e.kind() == &expected)));
    }

    #[test]
    fn entity_literals2() {
        let src = r#"permit(principal == Test::{ test : "Test" }, action, resource);"#;
        let ParseErrors(errs) = parse_policy(None, src).err().unwrap();
        assert_eq!(errs.len(), 1);
        let expected = ToASTErrorKind::UnsupportedEntityLiterals;
        assert!(errs
            .iter()
            .any(|e| matches!(e, ParseError::ToAST(e) if e.kind() == &expected)));
    }

    #[test]
    fn interpret_exprs() {
        let request = eval::test::basic_request();
        let entities = eval::test::basic_entities();
        let exts = Extensions::none();
        let evaluator = eval::Evaluator::new(request, &entities, &exts);
        // The below tests check not only that we get the expected `Value`, but
        // that it has the expected source location.
        // We have to check that separately because the `PartialEq` and `Eq`
        // impls for `Value` do not compare source locations.
        // This is somewhat a test of the evaluator, not just the parser; but
        // the actual evaluator unit tests do not use the parser and thus do
        // not have source locations attached to their input expressions, so
        // this file is where we effectively perform evaluator tests related to
        // propagating source locations from expressions to values.

        // bools
        let src = "false";
        let expr = parse_expr(src).unwrap();
        let val = evaluator.interpret_inline_policy(&expr).unwrap();
        assert_eq!(val, ast::Value::from(false));
        assert_eq!(val.source_loc(), Some(&Loc::new(0..5, Arc::from(src))));

        let src = "true && true";
        let expr = parse_expr(src).unwrap();
        let val = evaluator.interpret_inline_policy(&expr).unwrap();
        assert_eq!(val, ast::Value::from(true));
        assert_eq!(val.source_loc(), Some(&Loc::new(0..12, Arc::from(src))));

        let src = "!true || false && !true";
        let expr = parse_expr(src).unwrap();
        let val = evaluator.interpret_inline_policy(&expr).unwrap();
        assert_eq!(val, ast::Value::from(false));
        assert_eq!(val.source_loc(), Some(&Loc::new(0..23, Arc::from(src))));

        let src = "!!!!true";
        let expr = parse_expr(src).unwrap();
        let val = evaluator.interpret_inline_policy(&expr).unwrap();
        assert_eq!(val, ast::Value::from(true));
        assert_eq!(val.source_loc(), Some(&Loc::new(0..8, Arc::from(src))));

        let src = r#"
        if false || true != 4 then
            600
        else
            -200
        "#;
        let expr = parse_expr(src).unwrap();
        let val = evaluator.interpret_inline_policy(&expr).unwrap();
        assert_eq!(val, ast::Value::from(600));
        assert_eq!(val.source_loc(), Some(&Loc::new(9..81, Arc::from(src))));
    }

    #[test]
    fn interpret_membership() {
        let request = eval::test::basic_request();
        let entities = eval::test::rich_entities();
        let exts = Extensions::none();
        let evaluator = eval::Evaluator::new(request, &entities, &exts);
        // The below tests check not only that we get the expected `Value`, but
        // that it has the expected source location.
        // See note on this in the above test.

        let src = r#"

        test_entity_type::"child" in
            test_entity_type::"unrelated"

        "#;
        let expr = parse_expr(src).unwrap();
        let val = evaluator.interpret_inline_policy(&expr).unwrap();
        assert_eq!(val, ast::Value::from(false));
        assert_eq!(val.source_loc(), Some(&Loc::new(10..80, Arc::from(src))));
        // because "10..80" is hard to read, we also assert that the correct portion of `src` is indicated
        assert_eq!(
            val.source_loc().unwrap().snippet(),
            Some(
                r#"test_entity_type::"child" in
            test_entity_type::"unrelated""#
            )
        );

        let src = r#"

        test_entity_type::"child" in
            test_entity_type::"child"

        "#;
        let expr = parse_expr(src).unwrap();
        let val = evaluator.interpret_inline_policy(&expr).unwrap();
        assert_eq!(val, ast::Value::from(true));
        assert_eq!(val.source_loc(), Some(&Loc::new(10..76, Arc::from(src))));
        assert_eq!(
            val.source_loc().unwrap().snippet(),
            Some(
                r#"test_entity_type::"child" in
            test_entity_type::"child""#
            )
        );

        let src = r#"

        other_type::"other_child" in
            test_entity_type::"parent"

        "#;
        let expr = parse_expr(src).unwrap();
        let val = evaluator.interpret_inline_policy(&expr).unwrap();
        assert_eq!(val, ast::Value::from(true));
        assert_eq!(val.source_loc(), Some(&Loc::new(10..77, Arc::from(src))));
        assert_eq!(
            val.source_loc().unwrap().snippet(),
            Some(
                r#"other_type::"other_child" in
            test_entity_type::"parent""#
            )
        );

        let src = r#"

        test_entity_type::"child" in
            test_entity_type::"grandparent"

        "#;
        let expr = parse_expr(src).unwrap();
        let val = evaluator.interpret_inline_policy(&expr).unwrap();
        assert_eq!(val, ast::Value::from(true));
        assert_eq!(val.source_loc(), Some(&Loc::new(10..82, Arc::from(src))));
        assert_eq!(
            val.source_loc().unwrap().snippet(),
            Some(
                r#"test_entity_type::"child" in
            test_entity_type::"grandparent""#
            )
        );
    }

    #[test]
    fn interpret_relation() {
        let request = eval::test::basic_request();
        let entities = eval::test::basic_entities();
        let exts = Extensions::none();
        let evaluator = eval::Evaluator::new(request, &entities, &exts);
        // The below tests check not only that we get the expected `Value`, but
        // that it has the expected source location.
        // See note on this in the above test.

        let src = r#"

            3 < 2 || 2 > 3

        "#;
        let expr = parse_expr(src).unwrap();
        let val = evaluator.interpret_inline_policy(&expr).unwrap();
        assert_eq!(val, ast::Value::from(false));
        assert_eq!(val.source_loc(), Some(&Loc::new(14..28, Arc::from(src))));
        // because "14..28" is hard to read, we also assert that the correct portion of `src` is indicated
        assert_eq!(val.source_loc().unwrap().snippet(), Some("3 < 2 || 2 > 3"));

        let src = r#"

            7 <= 7 && 4 != 5

        "#;
        let expr = parse_expr(src).unwrap();
        let val = evaluator.interpret_inline_policy(&expr).unwrap();
        assert_eq!(val, ast::Value::from(true));
        assert_eq!(val.source_loc(), Some(&Loc::new(14..30, Arc::from(src))));
        assert_eq!(
            val.source_loc().unwrap().snippet(),
            Some("7 <= 7 && 4 != 5")
        );
    }
}

#[cfg(test)]
mod parse_tests {
    use super::test_utils::*;
    use super::*;
    use crate::test_utils::*;
    use cool_asserts::assert_matches;
    use miette::Diagnostic;

    #[test]
    fn parse_exists() {
        let result = parse_policyset(
            r#"
            permit(principal, action, resource)
            when{ true };
        "#,
        );
        assert!(!result.expect("parse error").is_empty());
    }

    #[test]
    fn test_parse_policyset() {
        use crate::ast::PolicyID;
        let multiple_policies = r#"
            permit(principal, action, resource)
            when { principal == resource.owner };

            forbid(principal, action == Action::"modify", resource) // a comment
            when { resource . highSecurity }; // intentionally not conforming to our formatter
        "#;
        let pset = parse_policyset(multiple_policies).expect("Should parse");
        assert_eq!(pset.policies().count(), 2);
        assert_eq!(pset.static_policies().count(), 2);
        let (texts, pset) =
            parse_policyset_and_also_return_policy_text(multiple_policies).expect("Should parse");
        assert_eq!(pset.policies().count(), 2);
        assert_eq!(pset.static_policies().count(), 2);
        assert_eq!(texts.len(), 2);
        assert_eq!(
            texts.get(&PolicyID::from_string("policy0")),
            Some(
                &r#"permit(principal, action, resource)
            when { principal == resource.owner };"#
            )
        );
        assert_eq!(
            texts.get(&PolicyID::from_string("policy1")),
            Some(
                &r#"forbid(principal, action == Action::"modify", resource) // a comment
            when { resource . highSecurity };"#
            )
        );
    }

    #[test]
    fn test_parse_string() {
        // test idempotence
        assert_eq!(
            ast::Eid::new(parse_internal_string(r"a\nblock\nid").expect("should parse"))
                .to_string(),
            r"a\nblock\nid",
        );
        parse_internal_string(r#"oh, no, a '! "#).expect("single quote should be fine");
        parse_internal_string(r#"oh, no, a "! "#).expect_err("double quote not allowed");
        parse_internal_string(r#"oh, no, a \"! and a \'! "#).expect("escaped quotes should parse");
    }

    #[test]
    fn good_cst_bad_ast() {
        let src = r#"
            permit(principal, action, resource) when { principal.name.like == "3" };
            "#;
        let p = parse_policyset_to_ests_and_pset(src);
        assert_matches!(p, Err(e) => expect_err(src, &e, &ExpectedErrorMessage::error("this identifier is reserved and cannot be used: `like`")));
    }

    #[test]
    fn no_slots_in_condition() {
        let src = r#"
            permit(principal, action, resource) when {
                resource == ?resource
            };
            "#;
        let slot_in_when_clause = ExpectedErrorMessage::error_and_help(
            "found template slot ?resource in a `when` clause",
            "slots are currently unsupported in `when` clauses",
        );
        let unexpected_template = ExpectedErrorMessage::error_and_help(
            "expected a static policy, got a template containing the slot ?resource",
            "try removing the template slot(s) from this policy",
        );
        assert_matches!(parse_policy(None, src), Err(e) => {
            expect_some_error_matches(src, &e, &slot_in_when_clause);
            expect_some_error_matches(src, &e, &unexpected_template);
        });
        assert_matches!(parse_policy_template(None, src), Err(e) => {
            expect_some_error_matches(src, &e, &slot_in_when_clause);
        });
        assert_matches!(parse_policy_to_est_and_ast(None, src), Err(e) => {
            expect_some_error_matches(src, &e, &slot_in_when_clause);
            expect_some_error_matches(src, &e, &unexpected_template);
        });
        assert_matches!(parse_policy_template_to_est_and_ast(None, src), Err(e) => {
            expect_some_error_matches(src, &e, &slot_in_when_clause);
        });
        assert_matches!(parse_policyset(src), Err(e) => {
            expect_some_error_matches(src, &e, &slot_in_when_clause);
        });
        assert_matches!(parse_policyset_to_ests_and_pset(src), Err(e) => {
            expect_some_error_matches(src, &e, &slot_in_when_clause);
        });

        let src = r#"
            permit(principal, action, resource) when {
                resource == ?principal
            };
            "#;
        let slot_in_when_clause = ExpectedErrorMessage::error_and_help(
            "found template slot ?principal in a `when` clause",
            "slots are currently unsupported in `when` clauses",
        );
        let unexpected_template = ExpectedErrorMessage::error_and_help(
            "expected a static policy, got a template containing the slot ?principal",
            "try removing the template slot(s) from this policy",
        );
        assert_matches!(parse_policy(None, src), Err(e) => {
            expect_some_error_matches(src, &e, &slot_in_when_clause);
            expect_some_error_matches(src, &e, &unexpected_template);
        });
        assert_matches!(parse_policy_template(None, src), Err(e) => {
            expect_some_error_matches(src, &e, &slot_in_when_clause);
        });
        assert_matches!(parse_policy_to_est_and_ast(None, src), Err(e) => {
            expect_some_error_matches(src, &e, &slot_in_when_clause);
            expect_some_error_matches(src, &e, &unexpected_template);
        });
        assert_matches!(parse_policy_template_to_est_and_ast(None, src), Err(e) => {
            expect_some_error_matches(src, &e, &slot_in_when_clause);
        });
        assert_matches!(parse_policyset(src), Err(e) => {
            expect_some_error_matches(src, &e, &slot_in_when_clause);
        });
        assert_matches!(parse_policyset_to_ests_and_pset(src), Err(e) => {
            expect_some_error_matches(src, &e, &slot_in_when_clause);
        });

        let src = r#"
            permit(principal, action, resource) when {
                resource == ?blah
            };
            "#;
        let error = ExpectedErrorMessage::error_and_help(
            "`?blah` is not a valid template slot",
            "a template slot may only be `?principal` or `?resource`",
        );
        assert_matches!(parse_policy(None, src), Err(e) => {
            expect_some_error_matches(src, &e, &error);
        });
        assert_matches!(parse_policy_template(None, src), Err(e) => {
            expect_some_error_matches(src, &e, &error);
        });
        assert_matches!(parse_policy_to_est_and_ast(None, src), Err(e) => {
            expect_some_error_matches(src, &e, &error);
        });
        assert_matches!(parse_policy_template_to_est_and_ast(None, src), Err(e) => {
            expect_some_error_matches(src, &e, &error);
        });
        assert_matches!(parse_policyset(src), Err(e) => {
            expect_some_error_matches(src, &e, &error);
        });
        assert_matches!(parse_policyset_to_ests_and_pset(src), Err(e) => {
            expect_some_error_matches(src, &e, &error);
        });

        let src = r#"
            permit(principal, action, resource) unless {
                resource == ?resource
            };
            "#;
        let slot_in_unless_clause = ExpectedErrorMessage::error_and_help(
            "found template slot ?resource in a `unless` clause",
            "slots are currently unsupported in `unless` clauses",
        );
        let unexpected_template = ExpectedErrorMessage::error_and_help(
            "expected a static policy, got a template containing the slot ?resource",
            "try removing the template slot(s) from this policy",
        );
        assert_matches!(parse_policy(None, src), Err(e) => {
            expect_some_error_matches(src, &e, &slot_in_unless_clause);
            expect_some_error_matches(src, &e, &unexpected_template);
        });
        assert_matches!(parse_policy_template(None, src), Err(e) => {
            expect_some_error_matches(src, &e, &slot_in_unless_clause);
        });
        assert_matches!(parse_policy_to_est_and_ast(None, src), Err(e) => {
            expect_some_error_matches(src, &e, &slot_in_unless_clause);
            expect_some_error_matches(src, &e, &unexpected_template);
        });
        assert_matches!(parse_policy_template_to_est_and_ast(None, src), Err(e) => {
            expect_some_error_matches(src, &e, &slot_in_unless_clause);
        });
        assert_matches!(parse_policyset(src), Err(e) => {
            expect_some_error_matches(src, &e, &slot_in_unless_clause);
        });
        assert_matches!(parse_policyset_to_ests_and_pset(src), Err(e) => {
            expect_some_error_matches(src, &e, &slot_in_unless_clause);
        });

        let src = r#"
            permit(principal, action, resource) unless {
                resource == ?principal
            };
            "#;
        let slot_in_unless_clause = ExpectedErrorMessage::error_and_help(
            "found template slot ?principal in a `unless` clause",
            "slots are currently unsupported in `unless` clauses",
        );
        let unexpected_template = ExpectedErrorMessage::error_and_help(
            "expected a static policy, got a template containing the slot ?principal",
            "try removing the template slot(s) from this policy",
        );
        assert_matches!(parse_policy(None, src), Err(e) => {
            expect_some_error_matches(src, &e, &slot_in_unless_clause);
            expect_some_error_matches(src, &e, &unexpected_template);
        });
        assert_matches!(parse_policy_template(None, src), Err(e) => {
            expect_some_error_matches(src, &e, &slot_in_unless_clause);
        });
        assert_matches!(parse_policy_to_est_and_ast(None, src), Err(e) => {
            expect_some_error_matches(src, &e, &slot_in_unless_clause);
            expect_some_error_matches(src, &e, &unexpected_template);
        });
        assert_matches!(parse_policy_template_to_est_and_ast(None, src), Err(e) => {
            expect_some_error_matches(src, &e, &slot_in_unless_clause);
        });
        assert_matches!(parse_policyset(src), Err(e) => {
            expect_some_error_matches(src, &e, &slot_in_unless_clause);
        });
        assert_matches!(parse_policyset_to_ests_and_pset(src), Err(e) => {
            expect_some_error_matches(src, &e, &slot_in_unless_clause);
        });

        let src = r#"
            permit(principal, action, resource) unless {
                resource == ?blah
            };
            "#;
        let error = ExpectedErrorMessage::error_and_help(
            "`?blah` is not a valid template slot",
            "a template slot may only be `?principal` or `?resource`",
        );
        assert_matches!(parse_policy(None, src), Err(e) => {
            expect_some_error_matches(src, &e, &error);
        });
        assert_matches!(parse_policy_template(None, src), Err(e) => {
            expect_some_error_matches(src, &e, &error);
        });
        assert_matches!(parse_policy_to_est_and_ast(None, src), Err(e) => {
            expect_some_error_matches(src, &e, &error);
        });
        assert_matches!(parse_policy_template_to_est_and_ast(None, src), Err(e) => {
            expect_some_error_matches(src, &e, &error);
        });
        assert_matches!(parse_policyset(src), Err(e) => {
            expect_some_error_matches(src, &e, &error);
        });
        assert_matches!(parse_policyset_to_ests_and_pset(src), Err(e) => {
            expect_some_error_matches(src, &e, &error);
        });

        let src = r#"
            permit(principal, action, resource) unless {
                resource == ?resource
            } when {
                resource == ?resource
            };
            "#;
        let slot_in_when_clause = ExpectedErrorMessage::error_and_help(
            "found template slot ?resource in a `when` clause",
            "slots are currently unsupported in `when` clauses",
        );
        let slot_in_unless_clause = ExpectedErrorMessage::error_and_help(
            "found template slot ?resource in a `unless` clause",
            "slots are currently unsupported in `unless` clauses",
        );
        let unexpected_template = ExpectedErrorMessage::error_and_help(
            "expected a static policy, got a template containing the slot ?resource",
            "try removing the template slot(s) from this policy",
        );
        assert_matches!(parse_policy(None, src), Err(e) => {
            expect_some_error_matches(src, &e, &slot_in_when_clause);
            expect_some_error_matches(src, &e, &slot_in_unless_clause);
            expect_some_error_matches(src, &e, &unexpected_template);
        });
        assert_matches!(parse_policy_template(None, src), Err(e) => {
            expect_some_error_matches(src, &e, &slot_in_when_clause);
            expect_some_error_matches(src, &e, &slot_in_unless_clause);
        });
        assert_matches!(parse_policy_to_est_and_ast(None, src), Err(e) => {
            expect_some_error_matches(src, &e, &slot_in_when_clause);
            expect_some_error_matches(src, &e, &slot_in_unless_clause);
            expect_some_error_matches(src, &e, &unexpected_template);
        });
        assert_matches!(parse_policy_template_to_est_and_ast(None, src), Err(e) => {
            expect_some_error_matches(src, &e, &slot_in_when_clause);
            expect_some_error_matches(src, &e, &slot_in_unless_clause);
        });
        assert_matches!(parse_policyset(src), Err(e) => {
            expect_some_error_matches(src, &e, &slot_in_when_clause);
            expect_some_error_matches(src, &e, &slot_in_unless_clause);
        });
        assert_matches!(parse_policyset_to_ests_and_pset(src), Err(e) => {
            expect_some_error_matches(src, &e, &slot_in_when_clause);
            expect_some_error_matches(src, &e, &slot_in_unless_clause);
        });
    }

    #[test]
    fn record_literals() {
        // unquoted keys
        let src = r#"permit(principal, action, resource) when { context.foo == { foo: 2, bar: "baz" } };"#;
        assert_matches!(parse_policy(None, src), Ok(_));
        // quoted keys
        let src = r#"permit(principal, action, resource) when { context.foo == { "foo": 2, "hi mom it's 🦀": "baz" } };"#;
        assert_matches!(parse_policy(None, src), Ok(_));
        // duplicate key
        let src = r#"permit(principal, action, resource) when { context.foo == { "spam": -341, foo: 2, "🦀": true, foo: "baz" } };"#;
        assert_matches!(parse_policy(None, src), Err(e) => {
            expect_exactly_one_error(src, &e, &ExpectedErrorMessage::error("duplicate key `foo` in record literal"));
        });
    }

    #[test]
    fn annotation_errors() {
        let src = r#"
            @foo("1")
            @foo("2")
            permit(principal, action, resource);
        "#;
        assert_matches!(parse_policy(None, src), Err(e) => {
            expect_exactly_one_error(src, &e, &ExpectedErrorMessage::error("duplicate annotation: @foo"));
            let expected_span = 35..44;
            assert_eq!(&src[expected_span.clone()], r#"@foo("2")"#);
            itertools::assert_equal(e.labels().expect("should have labels"), [miette::LabeledSpan::underline(expected_span)]);
        });

        let src = r#"
            @foo("1")
            @foo("1")
            permit(principal, action, resource);
        "#;
        assert_matches!(parse_policy(None, src), Err(e) => {
            expect_exactly_one_error(src, &e, &ExpectedErrorMessage::error("duplicate annotation: @foo"));
            let expected_span = 35..44;
            assert_eq!(&src[expected_span.clone()], r#"@foo("1")"#);
            itertools::assert_equal(e.labels().expect("should have labels"), [miette::LabeledSpan::underline(expected_span)]);
        });

        let src = r#"
            @foo("1")
            @bar("yellow")
            @foo("abc")
            @hello("goodbye")
            @bar("123")
            @foo("def")
            permit(principal, action, resource);
        "#;
        assert_matches!(parse_policy(None, src), Err(e) => {
            assert_eq!(e.len(), 3); // two errors for @foo and one for @bar
            expect_some_error_matches(src, &e, &ExpectedErrorMessage::error("duplicate annotation: @foo"));
            expect_some_error_matches(src, &e, &ExpectedErrorMessage::error("duplicate annotation: @bar"));
            for ((err, expected_span), expected_snippet) in e.iter().zip([62..73, 116..127, 140..151]).zip([r#"@foo("abc")"#, r#"@bar("123")"#, r#"@foo("def")"#]) {
                assert_eq!(&src[expected_span.clone()], expected_snippet);
                itertools::assert_equal(err.labels().expect("should have labels"), [miette::LabeledSpan::underline(expected_span)]);
            }
        })
    }
}