cedar_policy_core/parser/loc.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 serde::{Deserialize, Serialize};
18use std::sync::Arc;
19
20/// Represents a source location: index/range, and a reference to the source
21/// code which that index/range indexes into
22#[derive(Debug, Clone, PartialEq, Eq, Hash, Deserialize, Serialize, PartialOrd, Ord)]
23pub struct Loc {
24 /// `SourceSpan` indicating a specific source code location or range
25 pub span: miette::SourceSpan,
26
27 /// Original source code (which the above source span indexes into)
28 pub src: Arc<str>,
29}
30
31impl Loc {
32 /// Create a new `Loc`
33 pub fn new(span: impl Into<miette::SourceSpan>, src: Arc<str>) -> Self {
34 Self {
35 span: span.into(),
36 src,
37 }
38 }
39
40 /// Create a new `Loc` with the same source code but a different span
41 pub fn span(&self, span: impl Into<miette::SourceSpan>) -> Self {
42 Self {
43 span: span.into(),
44 src: Arc::clone(&self.src),
45 }
46 }
47
48 /// Get the index representing the start of the source span
49 pub fn start(&self) -> usize {
50 self.span.offset()
51 }
52
53 /// Get the index representing the end of the source span
54 pub fn end(&self) -> usize {
55 self.span.offset() + self.span.len()
56 }
57
58 /// Get the actual source snippet indicated, or `None` if the `Loc` isn't
59 /// internally consistent (its `SourceSpan` isn't a valid index into its
60 /// `src`)
61 pub fn snippet(&self) -> Option<&str> {
62 self.src.get(self.start()..self.end())
63 }
64}