lang_c/
span.rs

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
//! Source text location tracking
use std::usize::MAX;
use std::{cmp, fmt};

/// Byte offset of a node start and end positions in the input stream
#[derive(Copy, Clone)]
pub struct Span {
    pub start: usize,
    pub end: usize,
}

impl Span {
    /// Create a new span for a specific location
    pub fn span(start: usize, end: usize) -> Span {
        Span {
            start: start,
            end: end,
        }
    }

    /// Create a new undefined span that is equal to any other span
    pub fn none() -> Span {
        Span {
            start: MAX,
            end: MAX,
        }
    }

    /// Test if span is undefined
    pub fn is_none(&self) -> bool {
        self.start == MAX && self.end == MAX
    }
}

impl cmp::PartialEq for Span {
    fn eq(&self, other: &Self) -> bool {
        (self.start == other.start && self.end == other.end) || self.is_none() || other.is_none()
    }
}

impl fmt::Debug for Span {
    fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
        if !self.is_none() {
            write!(fmt, "{}…{}", self.start, self.end)
        } else {
            write!(fmt, "…")
        }
    }
}

/// Associate a span with an arbitrary type
#[derive(Debug, PartialEq, Clone)]
pub struct Node<T> {
    pub node: T,
    pub span: Span,
}

impl<T> Node<T> {
    /// Create new node
    pub fn new(node: T, span: Span) -> Node<T> {
        Node {
            node: node,
            span: span,
        }
    }
}