lang_c/
span.rs

1//! Source text location tracking
2use std::usize::MAX;
3use std::{cmp, fmt};
4
5/// Byte offset of a node start and end positions in the input stream
6#[derive(Copy, Clone)]
7pub struct Span {
8    pub start: usize,
9    pub end: usize,
10}
11
12impl Span {
13    /// Create a new span for a specific location
14    pub fn span(start: usize, end: usize) -> Span {
15        Span {
16            start: start,
17            end: end,
18        }
19    }
20
21    /// Create a new undefined span that is equal to any other span
22    pub fn none() -> Span {
23        Span {
24            start: MAX,
25            end: MAX,
26        }
27    }
28
29    /// Test if span is undefined
30    pub fn is_none(&self) -> bool {
31        self.start == MAX && self.end == MAX
32    }
33}
34
35impl cmp::PartialEq for Span {
36    fn eq(&self, other: &Self) -> bool {
37        (self.start == other.start && self.end == other.end) || self.is_none() || other.is_none()
38    }
39}
40
41impl fmt::Debug for Span {
42    fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
43        if !self.is_none() {
44            write!(fmt, "{}…{}", self.start, self.end)
45        } else {
46            write!(fmt, "…")
47        }
48    }
49}
50
51/// Associate a span with an arbitrary type
52#[derive(Debug, PartialEq, Clone)]
53pub struct Node<T> {
54    pub node: T,
55    pub span: Span,
56}
57
58impl<T> Node<T> {
59    /// Create new node
60    pub fn new(node: T, span: Span) -> Node<T> {
61        Node {
62            node: node,
63            span: span,
64        }
65    }
66}