summaryrefslogtreecommitdiff
path: root/src/syntax/test.rs
blob: 639fbb61fe6c8b12bb96d9e8f7892595f30e2f39 (plain) (blame)
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
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
use std::fmt::Debug;

use super::func::FuncHeader;
use super::span::Spanned;
use super::expr::{Expr, Tuple, NamedTuple, Object};
use super::*;

/// Check whether the expected and found results are the same.
pub fn check<T>(src: &str, exp: T, found: T, cmp_spans: bool)
where T: Debug + PartialEq + SpanlessEq {
    let cmp = if cmp_spans { PartialEq::eq } else { SpanlessEq::spanless_eq };
    if !cmp(&exp, &found) {
        println!("source:   {:?}", src);
        println!("expected: {:#?}", exp);
        println!("found:    {:#?}", found);
        panic!("test failed");
    }
}

/// Create a vector of optionally spanned expressions from a list description.
///
/// # Examples
/// ```
/// // With spans
/// spanned![(0:0, 0:5, "hello"), (0:5, 0:3, "world")]
///
/// // Without spans: Implicit zero spans.
/// spanned!["hello", "world"]
/// ```
macro_rules! span_vec {
    ($(($sl:tt:$sc:tt, $el:tt:$ec:tt, $v:expr)),* $(,)?) => {
        (vec![$(span_item!(($sl:$sc, $el:$ec, $v))),*], true)
    };

    ($($v:expr),* $(,)?) => {
        (vec![$(span_item!($v)),*], false)
    };
}

macro_rules! span_item {
    (($sl:tt:$sc:tt, $el:tt:$ec:tt, $v:expr)) => ({
        use $crate::syntax::span::{Pos, Span, Spanned};
        Spanned {
            span: Span::new(
                Pos::new($sl, $sc),
                Pos::new($el, $ec)
            ),
            v: $v
        }
    });

    ($v:expr) => {
        $crate::syntax::span::Spanned::zero($v)
    };
}

function! {
    /// Most functions in the tests are parsed into the debug function for easy
    /// inspection of arguments and body.
    #[derive(Debug, Clone, PartialEq)]
    pub struct DebugFn {
        pub header: FuncHeader,
        pub body: Option<SyntaxModel>,
    }

    parse(header, body, state, f) {
        let cloned = header.clone();
        header.args.pos.items.clear();
        header.args.key.pairs.clear();
        DebugFn {
            header: cloned,
            body: body!(opt: body, state, f),
        }
    }

    layout(self, ctx, f) { vec![] }
}

/// Compares elements by only looking at values and ignoring spans.
pub trait SpanlessEq<Rhs=Self> {
    fn spanless_eq(&self, other: &Rhs) -> bool;
}

impl SpanlessEq for SyntaxModel {
    fn spanless_eq(&self, other: &SyntaxModel) -> bool {
        self.nodes.spanless_eq(&other.nodes)
    }
}

impl SpanlessEq for Node {
    fn spanless_eq(&self, other: &Node) -> bool {
        fn downcast<'a>(func: &'a (dyn Model + 'static)) -> &'a DebugFn {
            func.downcast::<DebugFn>().expect("not a debug fn")
        }

        match (self, other) {
            (Node::Model(a), Node::Model(b)) => {
                downcast(a.as_ref()).spanless_eq(downcast(b.as_ref()))
            }
            (a, b) => a == b,
        }
    }
}

impl SpanlessEq for DebugFn {
    fn spanless_eq(&self, other: &DebugFn) -> bool {
        self.header.name.v == other.header.name.v
        && self.header.args.pos.spanless_eq(&other.header.args.pos)
        && self.header.args.key.spanless_eq(&other.header.args.key)
    }
}

impl SpanlessEq for Expr {
    fn spanless_eq(&self, other: &Expr) -> bool {
        match (self, other) {
            (Expr::Tuple(a), Expr::Tuple(b)) => a.spanless_eq(b),
            (Expr::NamedTuple(a), Expr::NamedTuple(b)) => a.spanless_eq(b),
            (Expr::Object(a), Expr::Object(b)) => a.spanless_eq(b),
            (Expr::Neg(a), Expr::Neg(b)) => a.spanless_eq(&b),
            (Expr::Add(a1, a2), Expr::Add(b1, b2)) => a1.spanless_eq(&b1) && a2.spanless_eq(&b2),
            (Expr::Sub(a1, a2), Expr::Sub(b1, b2)) => a1.spanless_eq(&b1) && a2.spanless_eq(&b2),
            (Expr::Mul(a1, a2), Expr::Mul(b1, b2)) => a1.spanless_eq(&b1) && a2.spanless_eq(&b2),
            (Expr::Div(a1, a2), Expr::Div(b1, b2)) => a1.spanless_eq(&b1) && a2.spanless_eq(&b2),
            (a, b) => a == b,
        }
    }
}

impl SpanlessEq for Tuple {
    fn spanless_eq(&self, other: &Tuple) -> bool {
        self.items.len() == other.items.len()
        && self.items.iter().zip(&other.items)
            .all(|(x, y)| x.v.spanless_eq(&y.v))
    }
}

impl SpanlessEq for NamedTuple {
    fn spanless_eq(&self, other: &NamedTuple) -> bool {
        self.name.v == other.name.v
        && self.tuple.v.spanless_eq(&other.tuple.v)
    }
}

impl SpanlessEq for Object {
    fn spanless_eq(&self, other: &Object) -> bool {
        self.pairs.len() == other.pairs.len()
        && self.pairs.iter().zip(&other.pairs)
            .all(|(x, y)| x.v.key.v == y.v.key.v && x.v.value.v.spanless_eq(&y.v.value.v))
    }
}

impl<T: SpanlessEq> SpanlessEq for Vec<T> {
    fn spanless_eq(&self, other: &Vec<T>) -> bool {
        self.len() == other.len()
        && self.iter().zip(other).all(|(x, y)| x.spanless_eq(&y))
    }
}

impl<T: SpanlessEq> SpanlessEq for Spanned<T> {
    fn spanless_eq(&self, other: &Spanned<T>) -> bool {
        self.v.spanless_eq(&other.v)
    }
}

impl<T: SpanlessEq> SpanlessEq for Box<T> {
    fn spanless_eq(&self, other: &Box<T>) -> bool {
        (&**self).spanless_eq(&**other)
    }
}

macro_rules! impl_through_partial_eq {
    ($type:ty) => {
        impl SpanlessEq for $type {
            fn spanless_eq(&self, other: &$type) -> bool {
                self == other
            }
        }
    };
}

impl_through_partial_eq!(Token<'_>);

// Implement for string and decoration to be able to compare feedback.
impl_through_partial_eq!(String);
impl_through_partial_eq!(Decoration);