-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlib.rs
More file actions
81 lines (71 loc) · 2 KB
/
lib.rs
File metadata and controls
81 lines (71 loc) · 2 KB
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
#[cfg(feature = "ast")]
pub mod ast;
pub mod lex;
#[cfg(feature = "transpiler")]
pub mod transpile;
use std::fmt;
pub use lex::Lexer;
/// Source code span
/// Useful to track the position of a text fragment in the source code, for error reporting.
///
/// ```
/// use cppshift::SourceSpan;
///
/// let src = "test";
/// let src_span = SourceSpan::new(src, 1, 2);
/// assert_eq!("es", src_span.src());
/// assert_eq!((1..3), core::ops::Range::<usize>::from(src_span));
/// ```
#[derive(Clone, Copy, PartialEq)]
pub struct SourceSpan<'de> {
src: &'de str,
offset: usize,
len: usize,
}
impl<'de> SourceSpan<'de> {
/// Create a new Span from an offset and a length
pub fn new(src: &'de str, offset: usize, len: usize) -> SourceSpan<'de> {
SourceSpan { src, offset, len }
}
/// Getter of the source code value
pub fn src(&self) -> &'de str {
&self.src[core::ops::Range::from(*self)]
}
/// Returns the full backing source string (not just this span's slice).
pub fn full_source(&self) -> &'de str {
self.src
}
}
impl<'de> fmt::Debug for SourceSpan<'de> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("SourceSpan")
.field("src", &self.src())
.field("offset", &self.offset)
.field("len", &self.len)
.finish()
}
}
impl<'de> From<SourceSpan<'de>> for miette::SourceSpan {
fn from(span: SourceSpan<'de>) -> Self {
miette::SourceSpan::new(span.offset.into(), span.len)
}
}
impl<'de> From<SourceSpan<'de>> for core::ops::Range<usize> {
fn from(span: SourceSpan<'de>) -> Self {
core::ops::Range {
start: span.offset,
end: span.offset + span.len,
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn source_span() {
let src = "test";
let src_span = SourceSpan::new(src, 1, 2);
assert_eq!("es", src_span.src());
assert_eq!((1..3), core::ops::Range::<usize>::from(src_span));
}
}