reqlang-expr 0.5.0

A tiny (bytecode compiled, stack VM interpreted) expression language for reqlang's templating engine.
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
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
//! Errors

use std::ops::Range;

use lalrpop_util::ParseError;
use thiserror::Error;

use crate::lexer::Token;

pub type ExprResult<T> = std::result::Result<T, Vec<(ExprError, Range<usize>)>>;

#[derive(Debug, Error, PartialEq)]
pub enum ExprError {
    #[error("There was an error lexing expression: {0}")]
    LexError(#[from] LexicalError),
    #[error("There was an error in the expression syntax: {0}")]
    SyntaxError(#[from] SyntaxError),
    #[error("There was a compliation error with the expression: {0}")]
    CompileError(#[from] CompileError),
    #[error("There was a runtime error with the expression: {0}")]
    RuntimeError(#[from] RuntimeError),
}

impl diagnostics::AsDiagnostic for ExprError {
    fn as_diagnostic(&self, source: &str, span: &Range<usize>) -> diagnostics::ExprDiagnostic {
        match self {
            ExprError::LexError(e) => e.as_diagnostic(source, span),
            ExprError::CompileError(e) => e.as_diagnostic(source, span),
            ExprError::SyntaxError(e) => e.as_diagnostic(source, span),
            ExprError::RuntimeError(e) => e.as_diagnostic(source, span),
        }
    }
}

#[derive(Default, Debug, Clone, PartialEq, Error)]
pub enum LexicalError {
    #[default]
    #[error("Invalid token")]
    InvalidToken,
}

impl diagnostics::AsDiagnostic for LexicalError {
    fn as_diagnostic(&self, source: &str, span: &Range<usize>) -> diagnostics::ExprDiagnostic {
        match self {
            LexicalError::InvalidToken => diagnostics::ExprDiagnostic {
                code: "".to_string(),
                range: diagnostics::get_range(source, span),
                severity: Some(diagnostics::DiagnosisSeverity::ERROR),
                message: format!("{self}"),
            },
        }
    }
}

#[derive(Debug, Clone, Error, PartialEq)]
pub enum SyntaxError {
    #[error("extraneous input: {token:?}")]
    ExtraToken { token: String },
    #[error("invalid input")]
    InvalidToken,
    #[error("unexpected input: {token:?}")]
    UnexpectedInput { token: String },
    #[error("unexpected end of file; expected: {expected:?}")]
    UnrecognizedEOF { expected: Vec<String> },
    #[error("unexpected {token:?}; expected: {expected:?}")]
    UnrecognizedToken {
        token: String,
        expected: Vec<String>,
    },
    #[error("unterminated string")]
    UnterminatedString,
}

impl SyntaxError {
    pub fn from_parser_error(
        err: ParseError<usize, Token, (ExprError, Range<usize>)>,
        source: &str,
    ) -> (ExprError, Range<usize>) {
        match err {
            ParseError::InvalidToken { location } => {
                (SyntaxError::InvalidToken.into(), location..location)
            }
            ParseError::UnrecognizedEof { location, expected } => (
                SyntaxError::UnrecognizedEOF { expected }.into(),
                location..location,
            ),
            ParseError::UnrecognizedToken {
                token: (start, _, end),
                expected,
            } => (
                SyntaxError::UnrecognizedToken {
                    token: source[start..end].to_string(),
                    expected,
                }
                .into(),
                start..end,
            ),
            ParseError::ExtraToken {
                token: (start, _, end),
            } => (
                SyntaxError::ExtraToken {
                    token: source[start..end].to_string(),
                }
                .into(),
                start..end,
            ),
            ParseError::User { error } => error,
        }
    }
}

impl diagnostics::AsDiagnostic for SyntaxError {
    fn as_diagnostic(&self, source: &str, span: &Range<usize>) -> diagnostics::ExprDiagnostic {
        match self {
            SyntaxError::ExtraToken { token: _ } => diagnostics::ExprDiagnostic {
                code: "".to_string(),
                range: diagnostics::get_range(source, span),
                severity: Some(diagnostics::DiagnosisSeverity::ERROR),
                message: format!("{self}"),
            },
            SyntaxError::InvalidToken => diagnostics::ExprDiagnostic {
                code: "".to_string(),
                range: diagnostics::get_range(source, span),
                severity: Some(diagnostics::DiagnosisSeverity::ERROR),
                message: format!("{self}"),
            },
            SyntaxError::UnexpectedInput { token: _ } => diagnostics::ExprDiagnostic {
                code: "".to_string(),
                range: diagnostics::get_range(source, span),
                severity: Some(diagnostics::DiagnosisSeverity::ERROR),
                message: format!("{self}"),
            },
            SyntaxError::UnrecognizedEOF { expected: _ } => diagnostics::ExprDiagnostic {
                code: "".to_string(),
                range: diagnostics::get_range(source, span),
                severity: Some(diagnostics::DiagnosisSeverity::ERROR),
                message: format!("{self}"),
            },
            SyntaxError::UnrecognizedToken {
                token: _,
                expected: _,
            } => diagnostics::ExprDiagnostic {
                code: "".to_string(),
                range: diagnostics::get_range(source, span),
                severity: Some(diagnostics::DiagnosisSeverity::ERROR),
                message: format!("{self}"),
            },
            SyntaxError::UnterminatedString => diagnostics::ExprDiagnostic {
                code: "".to_string(),
                range: diagnostics::get_range(source, span),
                severity: Some(diagnostics::DiagnosisSeverity::ERROR),
                message: format!("{self}"),
            },
        }
    }
}

#[derive(Debug, Clone, PartialEq, Error)]
pub enum CompileError {
    #[error("undefined: {0}")]
    Undefined(String),
    #[error("expects {expected} arguments but received {actual}")]
    WrongNumberOfArgs { expected: usize, actual: usize },
    #[error("call expression without a callee")]
    NoCallee,
}

impl diagnostics::AsDiagnostic for CompileError {
    fn as_diagnostic(&self, source: &str, span: &Range<usize>) -> diagnostics::ExprDiagnostic {
        match self {
            CompileError::Undefined(_) => diagnostics::ExprDiagnostic {
                code: "".to_string(),
                range: diagnostics::get_range(source, span),
                severity: Some(diagnostics::DiagnosisSeverity::ERROR),
                message: format!("{self}"),
            },
            CompileError::WrongNumberOfArgs {
                expected: _,
                actual: _,
            } => diagnostics::ExprDiagnostic {
                code: "".to_string(),
                range: diagnostics::get_range(source, span),
                severity: Some(diagnostics::DiagnosisSeverity::ERROR),
                message: format!("{self}"),
            },
            CompileError::NoCallee => diagnostics::ExprDiagnostic {
                code: "".to_string(),
                range: diagnostics::get_range(source, span),
                severity: Some(diagnostics::DiagnosisSeverity::ERROR),
                message: format!("{self}"),
            },
        }
    }
}

#[derive(Debug, Clone, PartialEq, Error)]
pub enum RuntimeError {
    #[error("attempting to pop from an empty stack")]
    EmptyStack,
}

impl diagnostics::AsDiagnostic for RuntimeError {
    fn as_diagnostic(&self, source: &str, span: &Range<usize>) -> diagnostics::ExprDiagnostic {
        match self {
            RuntimeError::EmptyStack => diagnostics::ExprDiagnostic {
                code: "".to_string(),
                range: diagnostics::get_range(source, span),
                severity: Some(diagnostics::DiagnosisSeverity::ERROR),
                message: format!("{self}"),
            },
        }
    }
}

pub mod diagnostics {
    use std::ops::Range;

    use codespan_reporting::diagnostic::{Diagnostic, Label, Severity};
    use line_col::LineColLookup;

    use crate::errors::ExprError;

    pub fn get_diagnostics(
        errs: &[(ExprError, Range<usize>)],
        source: &str,
    ) -> Vec<Diagnostic<()>> {
        errs.iter()
            .map(|(err, span)| {
                let a = err.as_diagnostic(source, span);
                let b = a.to_diagnostic(span).with_message(a.message.clone());

                b
            })
            .collect()
    }

    pub trait AsDiagnostic {
        fn as_diagnostic(&self, source: &str, span: &Range<usize>) -> ExprDiagnostic;
    }

    #[derive(Debug, Eq, PartialEq, Clone, Default)]
    pub struct ExprDiagnostic {
        pub code: String,

        pub range: ExprDiagnosticRange,

        pub severity: Option<DiagnosisSeverity>,

        pub message: String,
    }

    impl ExprDiagnostic {
        pub fn to_diagnostic(
            &self,
            span: &Range<usize>,
        ) -> codespan_reporting::diagnostic::Diagnostic<()> {
            codespan_reporting::diagnostic::Diagnostic {
                severity: DiagnosisSeverity::ERROR.to_severity(),
                code: Some(self.code.clone()),
                message: self.message.clone(),
                labels: vec![Label::primary((), span.clone())],
                notes: vec![],
            }
        }
    }

    #[derive(Debug, Eq, PartialEq, Ord, PartialOrd, Clone, Copy)]
    pub struct DiagnosisSeverity(i32);
    #[allow(dead_code)]
    impl DiagnosisSeverity {
        pub const ERROR: DiagnosisSeverity = DiagnosisSeverity(1);
        pub const WARNING: DiagnosisSeverity = DiagnosisSeverity(2);
        pub const INFORMATION: DiagnosisSeverity = DiagnosisSeverity(3);
        pub const HINT: DiagnosisSeverity = DiagnosisSeverity(4);
    }

    impl DiagnosisSeverity {
        fn to_severity(&self) -> Severity {
            match *self {
                DiagnosisSeverity::HINT => Severity::Help,
                DiagnosisSeverity::INFORMATION => Severity::Note,
                DiagnosisSeverity::WARNING => Severity::Warning,
                DiagnosisSeverity::ERROR => Severity::Error,
                _ => panic!("Invalid diagnosis severity: {}", self.0),
            }
        }
    }

    #[derive(Debug, Eq, PartialEq, Ord, PartialOrd, Copy, Clone, Default)]
    pub struct ExprDiagnosticPosition {
        pub line: u32,
        pub character: u32,
    }

    impl ExprDiagnosticPosition {
        pub fn new(line: u32, character: u32) -> ExprDiagnosticPosition {
            ExprDiagnosticPosition { line, character }
        }
    }

    #[derive(Debug, Eq, PartialEq, Copy, Clone, Default)]
    pub struct ExprDiagnosticRange {
        /// The range's start position (inclusive)
        pub start: ExprDiagnosticPosition,
        /// The range's end position (exclusive)
        pub end: ExprDiagnosticPosition,
    }

    impl ExprDiagnosticRange {
        pub fn new(
            start: ExprDiagnosticPosition,
            end: ExprDiagnosticPosition,
        ) -> ExprDiagnosticRange {
            ExprDiagnosticRange { start, end }
        }
    }

    pub fn get_range(source: &str, span: &Range<usize>) -> ExprDiagnosticRange {
        ExprDiagnosticRange::new(
            get_position(source, span.start),
            get_position(source, span.end),
        )
    }

    pub fn get_position(source: &str, idx: usize) -> ExprDiagnosticPosition {
        let (line, character) = index_to_position(source, idx);

        ExprDiagnosticPosition::new(line as u32, character as u32)
    }

    /// Map index to position (line, column)
    ///
    /// Line and column are zero based
    pub fn index_to_position(source: &str, index: usize) -> (usize, usize) {
        let lookup = LineColLookup::new(source);

        let (line, char) = lookup.get(index);

        (line - 1, char - 1)
    }

    /// Map position (line, column) to index
    ///
    /// Line and column are zero based
    pub fn position_to_index(source: &str, position: (usize, usize)) -> usize {
        let (line, character) = position;
        let lines = source.split('\n');
        let lines_before = lines.take(line);
        let line_chars_before = lines_before.fold(0usize, |acc, e| acc + e.len() + 1);
        let chars = character;

        line_chars_before + chars
    }

    #[cfg(test)]
    mod index_position_fn_tests {
        use super::*;

        #[test]
        fn it_should_convert_index_to_position() {
            let source = "let a = 123;\nlet b = 456;";

            let index = 17usize;
            let expected_position = (1, 4);

            let index_to_position = index_to_position(source, index);
            let actual_position = index_to_position;

            assert_eq!(expected_position, actual_position);
        }

        #[test]
        fn it_should_convert_position_to_index() {
            let source = "let a = 123;\nlet b = 456;";
            let position = (1, 4);
            let expected_index = 17usize;
            let actual_index = position_to_index(source, position);

            assert_eq!(expected_index, actual_index);
        }

        #[test]
        fn it_should_convert_position_to_index_and_back() {
            let source = "let a = 123;\nlet b = 456;";
            let position = (1, 4);
            let actual_index = position_to_index(source, position);

            assert_eq!(position, index_to_position(source, actual_index));
        }

        #[test]
        fn it_should_convert_position_to_index_and_back_b() {
            let source = "let a = 123;\n{\n    let b = 456;\n}";
            let position = (2, 12);
            let actual_index = position_to_index(source, position);

            assert_eq!(position, index_to_position(source, actual_index));
        }

        #[test]
        fn it_should_convert_position_to_index_b() {
            let source = "let a = 123;\n{\n    let b = 456;\n}";
            let position = (2, 12);
            let actual_index = position_to_index(source, position);

            assert_eq!(27, actual_index);
        }

        #[test]
        fn it_should_convert_position_to_index_c() {
            let source = "let a = 123;\nlet b = 456;\nlet c = 789;";
            let position = (2, 8);
            let actual_index = position_to_index(source, position);

            assert_eq!(34, actual_index);
        }

        #[test]
        fn it_should_convert_position_to_index_d() {
            let source = "let a = 123;\nlet b = 456;\nlet c = 789;\nlet d = 000;";
            let position = (3, 8);
            let actual_index = position_to_index(source, position);

            assert_eq!(47, actual_index);
        }

        #[test]
        fn it_should_convert_position_to_index_e() {
            let source = "let a = 123;\nlet b = 456;\nlet c = 789;\nlet d = 000;\nlet e = 999;";
            let position = (4, 8);
            let actual_index = position_to_index(source, position);

            assert_eq!(60, actual_index);
        }

        #[test]
        fn it_should_convert_position_to_index_f() {
            let source = "let a = 123;\nlet b = 456;\nlet c = 789;\nlet d = 000;\nlet e = 999;\n";
            let position = (4, 8);
            let actual_index = position_to_index(source, position);

            assert_eq!(60, actual_index);
        }
    }

    #[cfg(test)]
    mod error_to_diagnostics_tests {
        use crate::errors::{CompileError, LexicalError};

        use super::*;
        use std::ops::Range;

        fn dummy_source() -> &'static str {
            "fn test_function(x: i32) -> i32 { x + 1 }"
        }

        fn dummy_range() -> Range<usize> {
            Range { start: 0, end: 5 }
        }

        #[test]
        fn it_converts_lexerror_to_diagnostic() {
            let source = dummy_source();
            let range = dummy_range();
            let error = ExprError::LexError(LexicalError::InvalidToken);
            let diagnostics = get_diagnostics(&[(error, range.clone())], source);

            assert_eq!(diagnostics.len(), 1);
            let diagnostic = &diagnostics[0];
            assert_eq!(diagnostic.code, Some("".to_string()));
            assert_eq!(diagnostic.message, "Invalid token".to_string());
            assert_eq!(diagnostic.severity, Severity::Error);
            assert_eq!(diagnostic.labels.len(), 1);
            assert_eq!(diagnostic.labels[0], Label::primary((), range));
        }

        #[test]
        fn it_converts_compileerror_undefined_to_diagnostic() {
            let source = dummy_source();
            let range = dummy_range();
            let error = ExprError::CompileError(CompileError::Undefined("var".to_string()));
            let diagnostics = get_diagnostics(&[(error, range.clone())], source);

            assert_eq!(diagnostics.len(), 1);
            let diagnostic = &diagnostics[0];
            assert_eq!(diagnostic.code, Some("".to_string()));
            assert_eq!(diagnostic.message, "undefined: var".to_string());
            assert_eq!(diagnostic.severity, Severity::Error);
            assert_eq!(diagnostic.labels.len(), 1);
            assert_eq!(diagnostic.labels[0], Label::primary((), range));
        }

        #[test]
        fn it_converts_compileerror_wrong_number_of_args_to_diagnostic() {
            let source = dummy_source();
            let range = dummy_range();
            let error = ExprError::CompileError(CompileError::WrongNumberOfArgs {
                expected: 2,
                actual: 3,
            });
            let diagnostics = get_diagnostics(&[(error, range.clone())], source);

            assert_eq!(diagnostics.len(), 1);
            let diagnostic = &diagnostics[0];
            assert_eq!(diagnostic.code, Some("".to_string()));
            assert_eq!(
                diagnostic.message,
                "expects 2 arguments but received 3".to_string()
            );
            assert_eq!(diagnostic.severity, Severity::Error);
            assert_eq!(diagnostic.labels.len(), 1);
            assert_eq!(diagnostic.labels[0], Label::primary((), range));
        }
    }
}