cedar_policy_core/parser/
loc.rs1use serde::{Deserialize, Serialize};
18use std::sync::Arc;
19
20#[derive(Debug, Clone, PartialEq, Eq, Hash, Deserialize, Serialize, PartialOrd, Ord)]
23pub struct Loc {
24 pub span: miette::SourceSpan,
26
27 pub src: Arc<str>,
29}
30
31impl Loc {
32 pub fn new(span: impl Into<miette::SourceSpan>, src: Arc<str>) -> Self {
34 Self {
35 span: span.into(),
36 src,
37 }
38 }
39
40 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 pub fn start(&self) -> usize {
50 self.span.offset()
51 }
52
53 pub fn end(&self) -> usize {
55 self.span.offset() + self.span.len()
56 }
57
58 pub fn snippet(&self) -> Option<&str> {
62 self.src.get(self.start()..self.end())
63 }
64}
65
66impl From<Loc> for miette::SourceSpan {
67 fn from(loc: Loc) -> Self {
68 loc.span
69 }
70}
71
72impl From<&Loc> for miette::SourceSpan {
73 fn from(loc: &Loc) -> Self {
74 loc.span
75 }
76}
77
78impl miette::SourceCode for Loc {
79 fn read_span<'a>(
80 &'a self,
81 span: &miette::SourceSpan,
82 context_lines_before: usize,
83 context_lines_after: usize,
84 ) -> Result<Box<dyn miette::SpanContents<'a> + 'a>, miette::MietteError> {
85 self.src
86 .read_span(span, context_lines_before, context_lines_after)
87 }
88}
89
90impl miette::SourceCode for &Loc {
91 fn read_span<'a>(
92 &'a self,
93 span: &miette::SourceSpan,
94 context_lines_before: usize,
95 context_lines_after: usize,
96 ) -> Result<Box<dyn miette::SpanContents<'a> + 'a>, miette::MietteError> {
97 self.src
98 .read_span(span, context_lines_before, context_lines_after)
99 }
100}