cedar_policy_core/parser/
node.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 std::fmt::{self, Debug, Display};
18
19use educe::Educe;
20use miette::Diagnostic;
21
22use super::err::{ToASTError, ToASTErrorKind};
23use super::Loc;
24
25/// Metadata for our syntax trees
26#[derive(Educe, Debug, Clone)]
27#[educe(PartialEq, Eq, Hash, Ord, PartialOrd)]
28pub struct Node<T> {
29    /// Main data represented
30    pub node: T,
31
32    /// Source location
33    #[educe(PartialEq(ignore))]
34    #[educe(PartialOrd(ignore))]
35    #[educe(Hash(ignore))]
36    pub loc: Option<Loc>,
37}
38
39impl<T> Node<T> {
40    /// Create a new Node with the given source location
41    pub fn with_source_loc(node: T, loc: Loc) -> Self {
42        Node {
43            node,
44            loc: Some(loc),
45        }
46    }
47
48    /// Create a new Node with an optional source location
49    pub fn with_maybe_source_loc(node: T, loc: Option<Loc>) -> Self {
50        Node { node, loc }
51    }
52
53    /// Create a new Node with no source location
54    pub fn new(node: T) -> Self {
55        Node { node, loc: None }
56    }
57
58    /// Transform the inner value while retaining the attached source info.
59    pub fn map<R>(self, f: impl FnOnce(T) -> R) -> Node<R> {
60        Node {
61            node: f(self.node),
62            loc: self.loc,
63        }
64    }
65
66    /// Converts from `&Node<T>` to `Node<&T>`.
67    pub fn as_ref(&self) -> Node<&T> {
68        Node {
69            node: &self.node,
70            loc: self.loc.clone(),
71        }
72    }
73
74    /// Converts from `&mut Node<T>` to `Node<&mut T>`.
75    pub fn as_mut(&mut self) -> Node<&mut T> {
76        Node {
77            node: &mut self.node,
78            loc: self.loc.clone(),
79        }
80    }
81
82    /// Consume the `Node`, yielding the node and attached source info.
83    pub fn into_inner(self) -> (T, Option<Loc>) {
84        (self.node, self.loc)
85    }
86
87    /// Utility to construct a `ToAstError` with the source location taken from this node.
88    pub fn to_ast_err(&self, error_kind: impl Into<ToASTErrorKind>) -> ToASTError {
89        ToASTError::new(error_kind.into(), self.loc.clone())
90    }
91
92    /// Get the source location of this `Node`
93    pub fn loc(&self) -> Option<&Loc> {
94        self.loc.as_ref()
95    }
96}
97
98impl<T: Clone> Node<&T> {
99    /// Converts a `Node<&T>` to a `Node<T>` by cloning the inner value.
100    pub fn cloned(self) -> Node<T> {
101        self.map(|value| value.clone())
102    }
103}
104
105impl<T: Copy> Node<&T> {
106    /// Converts a `Node<&T>` to a `Node<T>` by copying the inner value.
107    pub fn copied(self) -> Node<T> {
108        self.map(|value| *value)
109    }
110}
111
112impl<T: Display> Display for Node<T> {
113    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
114        Display::fmt(&self.node, f)
115    }
116}
117
118impl<T: std::error::Error> std::error::Error for Node<T> {
119    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
120        self.node.source()
121    }
122
123    #[allow(deprecated)]
124    fn description(&self) -> &str {
125        self.node.description()
126    }
127
128    fn cause(&self) -> Option<&dyn std::error::Error> {
129        #[allow(deprecated)]
130        self.node.cause()
131    }
132}
133
134// impl Diagnostic by taking `labels()` and `source_code()` from .loc and everything else from .node
135impl<T: Diagnostic> Diagnostic for Node<T> {
136    impl_diagnostic_from_source_loc_opt_field!(loc);
137
138    fn code<'a>(&'a self) -> Option<Box<dyn Display + 'a>> {
139        self.node.code()
140    }
141
142    fn severity(&self) -> Option<miette::Severity> {
143        self.node.severity()
144    }
145
146    fn help<'a>(&'a self) -> Option<Box<dyn Display + 'a>> {
147        self.node.help()
148    }
149
150    fn url<'a>(&'a self) -> Option<Box<dyn Display + 'a>> {
151        self.node.url()
152    }
153
154    fn related<'a>(&'a self) -> Option<Box<dyn Iterator<Item = &'a dyn Diagnostic> + 'a>> {
155        self.node.related()
156    }
157
158    fn diagnostic_source(&self) -> Option<&dyn Diagnostic> {
159        self.node.diagnostic_source()
160    }
161}
162
163/// Convenience methods on `Node<Option<T>>`
164impl<T> Node<Option<T>> {
165    /// Get the inner data as `&T`, if it exists
166    pub fn as_inner(&self) -> Option<&T> {
167        self.node.as_ref()
168    }
169
170    /// `None` if the node is empty, otherwise a node without the `Option`
171    pub fn collapse(&self) -> Option<Node<&T>> {
172        self.node.as_ref().map(|node| Node {
173            node,
174            loc: self.loc.clone(),
175        })
176    }
177
178    /// Apply the function `f` to the main data and source info. Returns `None`
179    /// if no main data or if `f` returns `None`.
180    pub fn apply<F, R>(&self, f: F) -> Option<R>
181    where
182        F: FnOnce(&T, Option<&Loc>) -> Option<R>,
183    {
184        f(self.node.as_ref()?, self.loc.as_ref())
185    }
186
187    /// Apply the function `f` to the main data and `Loc`, consuming them.
188    /// Returns `None` if no main data or if `f` returns `None`.
189    pub fn into_apply<F, R>(self, f: F) -> Option<R>
190    where
191        F: FnOnce(T, Option<Loc>) -> Option<R>,
192    {
193        f(self.node?, self.loc)
194    }
195
196    /// Get node data if present or return the error `EmptyNodeInvariantViolation`
197    pub fn try_as_inner(&self) -> Result<&T, ToASTError> {
198        self.node
199            .as_ref()
200            .ok_or_else(|| self.to_ast_err(ToASTErrorKind::EmptyNodeInvariantViolation))
201    }
202
203    /// Get node data if present or return the error `EmptyNodeInvariantViolation`
204    pub fn try_into_inner(self) -> Result<T, ToASTError> {
205        self.node
206            .ok_or_else(|| ToASTError::new(ToASTErrorKind::EmptyNodeInvariantViolation, self.loc))
207    }
208}