cedar_policy_core/ast/
literal.rs

1/*
2 * Copyright Cedar Contributors
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 *      https://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17use crate::ast::{EntityUID, Integer, StaticallyTyped, Type};
18use crate::parser;
19use smol_str::SmolStr;
20use std::sync::Arc;
21
22/// First-class values which may appear as literals in `Expr::Lit`.
23///
24/// Note that the auto-derived `PartialEq` and `Eq` are total equality -- using
25/// == to compare `Literal`s of different types results in `false`, not a type
26/// error.
27///
28/// `Literal` does not include set or record types. Although Cedar has syntax
29/// for set literals (e.g., [2, -7, 8]), these can include arbitrary
30/// expressions (e.g., [2+3, principal.foo]), so they have to become
31/// `Expr::Set`, not `Expr::Lit`.
32///
33/// Cloning is O(1).
34#[derive(Hash, Debug, PartialEq, Eq, Clone, PartialOrd, Ord)]
35pub enum Literal {
36    /// Boolean value
37    Bool(bool),
38    /// Signed integer value
39    Long(Integer),
40    /// String value
41    String(SmolStr),
42    /// Entity, represented by its UID. To get the actual `Entity`, you have to
43    /// look up this UID in a Store or Slice.
44    EntityUID(Arc<EntityUID>),
45}
46
47impl StaticallyTyped for Literal {
48    fn type_of(&self) -> Type {
49        match self {
50            Self::Bool(_) => Type::Bool,
51            Self::Long(_) => Type::Long,
52            Self::String(_) => Type::String,
53            Self::EntityUID(uid) => uid.type_of(),
54        }
55    }
56}
57
58impl std::fmt::Display for Literal {
59    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
60        match self {
61            Self::Bool(b) => write!(f, "{b}"),
62            Self::Long(i) => write!(f, "{i}"),
63            // print string literals after the `escape_debug` transformation
64            // note that it adds backslashes for more characters than we may want,
65            // e.g., a single quote is printed as `\'`.
66            Self::String(s) => write!(f, "\"{}\"", s.escape_debug()),
67            Self::EntityUID(uid) => write!(f, "{uid}"),
68        }
69    }
70}
71
72impl std::str::FromStr for Literal {
73    type Err = parser::err::LiteralParseError;
74
75    fn from_str(s: &str) -> Result<Literal, Self::Err> {
76        parser::parse_literal(s)
77    }
78}
79
80/// Create a Literal directly from a bool
81impl From<bool> for Literal {
82    fn from(b: bool) -> Self {
83        Self::Bool(b)
84    }
85}
86
87/// Create a Literal directly from an Integer
88impl From<Integer> for Literal {
89    fn from(i: Integer) -> Self {
90        Self::Long(i)
91    }
92}
93
94/// Create a Literal directly from a String
95impl From<String> for Literal {
96    fn from(s: String) -> Self {
97        Self::String(SmolStr::new(s))
98    }
99}
100
101/// Create a Literal directly from an &str
102impl From<&str> for Literal {
103    fn from(s: &str) -> Self {
104        Self::String(SmolStr::new(s))
105    }
106}
107
108impl From<SmolStr> for Literal {
109    fn from(s: SmolStr) -> Self {
110        Self::String(s)
111    }
112}
113
114/// Create a Literal directly from an EntityUID
115impl From<EntityUID> for Literal {
116    fn from(e: EntityUID) -> Self {
117        Self::EntityUID(Arc::new(e))
118    }
119}
120
121impl From<Arc<EntityUID>> for Literal {
122    fn from(ptr: Arc<EntityUID>) -> Self {
123        Self::EntityUID(ptr)
124    }
125}
126
127impl Literal {
128    /// Check if this literal is an entity reference
129    ///
130    /// This is used for policy scopes, where some syntax is
131    /// required to be an entity reference.
132    pub fn is_ref(&self) -> bool {
133        matches!(self, Self::EntityUID(..))
134    }
135}