specker 0.3.5

Testing utility that simplifies file matching against bunch of templates.
Documentation
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
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
// Copyright 2017 Nerijus Arlauskas
//
// Licensed under the Apache License, Version 2.0, <LICENSE-APACHE or
// http://apache.org/licenses/LICENSE-2.0> or the MIT license <LICENSE-MIT or
// http://opensource.org/licenses/MIT>, at your option. This file may not be
// copied, modified, or distributed except according to those terms.

use std::error::Error;
use std::fmt;
use std::result;
use std::str;
use tokens::TokenValue;

/// Spec lexer error.
#[derive(Debug, Clone, Eq, PartialEq)]
pub enum LexError {
    ExpectedSequenceFoundNewline { expected: Vec<u8> },
    ExpectedNewline,
    Utf8(str::Utf8Error),
}

impl ::std::error::Error for LexError {
    fn description(&self) -> &str {
        match *self {
            LexError::ExpectedSequenceFoundNewline { .. } => "expected sequence, found newline",
            LexError::ExpectedNewline => "expected newline",
            LexError::Utf8(ref e) => e.description(),
        }
    }
}

impl fmt::Display for LexError {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        match *self {
            LexError::ExpectedSequenceFoundNewline { ref expected } => write!(
                f,
                "Expected \"{}\", found new line",
                String::from_utf8_lossy(expected)
            ),
            LexError::ExpectedNewline => "Expected new line".fmt(f),
            LexError::Utf8(e) => e.fmt(f),
        }
    }
}

impl LexError {
    pub fn at(self, lo: FilePosition, hi: FilePosition) -> At<LexError> {
        At {
            lo: lo,
            hi: hi,
            desc: self,
        }
    }
}

impl From<str::Utf8Error> for LexError {
    fn from(other: str::Utf8Error) -> Self {
        LexError::Utf8(other)
    }
}

/// Spec parser error.
#[derive(Debug, Clone, Eq, PartialEq)]
pub enum ParseError {
    Lex(LexError),
    ExpectedKeyFoundValue,
    UnexpectedEndOfTokens,
    ExpectedDifferentToken {
        expected: Vec<TokenValue>,
        found: TokenValue,
    },
}

impl ::std::error::Error for ParseError {
    fn description(&self) -> &str {
        match *self {
            ParseError::Lex(ref e) => e.description(),
            ParseError::ExpectedKeyFoundValue => "expected key, found value",
            ParseError::UnexpectedEndOfTokens => "unexpected end of tokens",
            ParseError::ExpectedDifferentToken { .. } => "expected different token",
        }
    }
}

impl From<At<LexError>> for At<ParseError> {
    fn from(At { lo, hi, desc }: At<LexError>) -> Self {
        ParseError::Lex(desc).at(lo, hi)
    }
}

impl fmt::Display for ParseError {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        match *self {
            ParseError::Lex(ref e) => e.fmt(f),
            ParseError::ExpectedKeyFoundValue => "Expected key, found value".fmt(f),
            ParseError::UnexpectedEndOfTokens => "Unexpected end of file".fmt(f),
            ParseError::ExpectedDifferentToken {
                ref expected,
                ref found,
            } => write!(
                f,
                "Expected {}, buf found {}",
                expected
                    .iter()
                    .map(|t| format!("{}", t))
                    .collect::<Vec<_>>()
                    .join(" or "),
                found
            ),
        }
    }
}

impl ParseError {
    pub fn at(self, lo: FilePosition, hi: FilePosition) -> At<ParseError> {
        At {
            lo: lo,
            hi: hi,
            desc: self,
        }
    }
}

/// Error returned for failed template write.
#[derive(Debug)]
pub enum TemplateWriteError {
    TemplateIsNotValidUtf8(::std::string::FromUtf8Error),
    CanNotWriteMatchAnySymbols,
    MissingParam(String),
    Io(::std::io::Error),
}

impl PartialEq for TemplateWriteError {
    fn eq(&self, other: &TemplateWriteError) -> bool {
        match (self, other) {
            (
                &TemplateWriteError::CanNotWriteMatchAnySymbols,
                &TemplateWriteError::CanNotWriteMatchAnySymbols,
            ) => true,
            (
                &TemplateWriteError::MissingParam(ref a),
                &TemplateWriteError::MissingParam(ref b),
            ) => a.eq(b),
            (&TemplateWriteError::Io(ref a), &TemplateWriteError::Io(ref b)) => {
                a.description() == b.description()
            }
            (_, _) => false,
        }
    }
}

impl Eq for TemplateWriteError {}

impl ::std::error::Error for TemplateWriteError {
    fn description(&self) -> &str {
        match *self {
            TemplateWriteError::TemplateIsNotValidUtf8(_) => {
                "can not write template to utf8 string"
            }
            TemplateWriteError::CanNotWriteMatchAnySymbols => {
                "can not write template symbol to match any lines"
            }
            TemplateWriteError::MissingParam(_) => "missing template param",
            TemplateWriteError::Io(ref e) => e.description(),
        }
    }
}

impl fmt::Display for TemplateWriteError {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        match *self {
            TemplateWriteError::TemplateIsNotValidUtf8(ref e) => {
                write!(f, "Can not write template to utf8 string: {:?}", e)
            }
            TemplateWriteError::CanNotWriteMatchAnySymbols => {
                "Can not write template symbol to match any lines".fmt(f)
            }
            TemplateWriteError::MissingParam(ref p) => write!(f, "Missing template param {:?}", p),
            TemplateWriteError::Io(ref e) => e.fmt(f),
        }
    }
}

impl From<::std::io::Error> for TemplateWriteError {
    fn from(other: ::std::io::Error) -> Self {
        TemplateWriteError::Io(other)
    }
}

/// Error returned for failed template match.
#[derive(Debug)]
pub enum TemplateMatchError {
    ExpectedEof,
    ExpectedEol,
    ExpectedText { expected: String, found: String },
    ExpectedTextFoundEof(String),
    MissingParam(String),
    Io(::std::io::Error),
}

impl TemplateMatchError {
    pub fn at(self, lo: FilePosition, hi: FilePosition) -> At<TemplateMatchError> {
        At {
            lo: lo,
            hi: hi,
            desc: self,
        }
    }
}

impl PartialEq for TemplateMatchError {
    fn eq(&self, other: &TemplateMatchError) -> bool {
        match (self, other) {
            (&TemplateMatchError::ExpectedEof, &TemplateMatchError::ExpectedEof) => true,
            (&TemplateMatchError::ExpectedEol, &TemplateMatchError::ExpectedEol) => true,
            (
                &TemplateMatchError::ExpectedText {
                    expected: ref expected_a,
                    found: ref found_a,
                },
                &TemplateMatchError::ExpectedText {
                    expected: ref expected_b,
                    found: ref found_b,
                },
            ) => expected_a.eq(expected_b) && found_a.eq(found_b),
            (
                &TemplateMatchError::ExpectedTextFoundEof(ref a),
                &TemplateMatchError::ExpectedTextFoundEof(ref b),
            ) => a.eq(b),
            (
                &TemplateMatchError::MissingParam(ref a),
                &TemplateMatchError::MissingParam(ref b),
            ) => a.eq(b),
            (&TemplateMatchError::Io(ref a), &TemplateMatchError::Io(ref b)) => {
                a.description() == b.description()
            }
            (_, _) => false,
        }
    }
}

impl Eq for TemplateMatchError {}

impl ::std::error::Error for TemplateMatchError {
    fn description(&self) -> &str {
        match *self {
            TemplateMatchError::ExpectedEof => "expected end of file",
            TemplateMatchError::ExpectedEol => "expected end of line",
            TemplateMatchError::ExpectedText { .. } => "expected text not found",
            TemplateMatchError::ExpectedTextFoundEof(_) => "expected text, found end of file",
            TemplateMatchError::MissingParam(_) => "missing template param",
            TemplateMatchError::Io(ref e) => e.description(),
        }
    }
}

impl fmt::Display for TemplateMatchError {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        match *self {
            TemplateMatchError::ExpectedEof => "Expected end of file".fmt(f),
            TemplateMatchError::ExpectedEol => "Expected end of line".fmt(f),
            TemplateMatchError::ExpectedText {
                ref expected,
                ref found,
            } => write!(f, "Expected {:?}, found {:?}", expected, found),
            TemplateMatchError::ExpectedTextFoundEof(ref p) => {
                write!(f, "Expected {:?}, found end of file", p)
            }
            TemplateMatchError::MissingParam(ref p) => write!(f, "Missing template param {:?}", p),
            TemplateMatchError::Io(ref e) => e.fmt(f),
        }
    }
}

impl From<::std::io::Error> for TemplateMatchError {
    fn from(other: ::std::io::Error) -> Self {
        TemplateMatchError::Io(other)
    }
}

pub type LexResult<T> = result::Result<T, At<LexError>>;
pub type ParseResult<T> = result::Result<T, At<ParseError>>;

#[derive(Debug, Clone)]
pub struct At<T>
where
    T: fmt::Debug,
{
    /// The low position at which this error is pointing at.
    pub lo: FilePosition,
    /// One byte beyond the last character at which this error is pointing at.
    pub hi: FilePosition,
    /// An inner error.
    pub desc: T,
}

impl<T: fmt::Debug> At<T> {
    pub fn assert_matches(
        &self,
        other_err: &T,
        lo: (usize, usize),
        hi: (usize, usize),
    ) -> result::Result<(), String>
    where
        T: PartialEq,
    {
        if !self.desc.eq(other_err) {
            return Err(format!("{:?} does not match {:?}", self.desc, other_err));
        }

        if self.lo.line != lo.0 {
            return Err(format!(
                "expected error start line at {}, found {}",
                lo.0, self.lo.line
            ));
        }

        if self.hi.line != hi.0 {
            return Err(format!(
                "expected error end line at {}, found {}",
                hi.0, self.hi.line
            ));
        }

        if self.lo.col != lo.1 {
            return Err(format!(
                "expected error start col at {}, found {}",
                lo.1, self.lo.col
            ));
        }

        if self.hi.col != hi.1 {
            return Err(format!(
                "expected error end col at {}, found {}",
                hi.1, self.hi.col
            ));
        }

        Ok(())
    }
}

impl<T: fmt::Debug> ::std::error::Error for At<T>
where
    T: ::std::error::Error,
{
    fn description(&self) -> &str {
        self.desc.description()
    }
}

impl<T: fmt::Debug> PartialEq for At<T>
where
    T: Eq + PartialEq,
{
    fn eq(&self, other: &At<T>) -> bool {
        self.desc == other.desc
    }
}

impl<T: fmt::Debug> fmt::Display for At<T>
where
    T: fmt::Display,
{
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        if self.lo == self.hi {
            write!(f, "{} at {}", self.desc, self.lo)
        } else {
            write!(f, "{} at {} - {}", self.desc, self.lo, self.hi)
        }
    }
}

#[derive(Debug, Copy, Clone, Eq, PartialEq)]
pub struct FilePosition {
    /// 0-based line of this position.
    pub line: usize,
    /// 0-based col of this position.
    pub col: usize,
    /// The byte position at which this position is pointing at.
    pub byte: usize,
}

impl FilePosition {
    pub fn new() -> FilePosition {
        FilePosition {
            line: 0,
            col: 0,
            byte: 0,
        }
    }

    pub fn advance(&mut self, bytes: usize) {
        self.byte += bytes;
        self.col += bytes;
    }

    pub fn advanced(&self, bytes: usize) -> FilePosition {
        let mut other = self.clone();
        other.advance(bytes);
        other
    }

    pub fn next_line(&mut self, bytes: usize) {
        if bytes > 0 {
            self.byte += bytes;
            self.col = 0;
            self.line += 1;
        }
    }
}

impl fmt::Display for FilePosition {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "line {}, col {}", self.line, self.col)
    }
}