ombre: Track token locations in scanner

67621d998d108592d1ac8ac0fd99d479c0bd2151
Alexis Sellier committed ago 1 parent 02ba6be8
ombre/src/lang.rs +4 -4
7 7
//! 2. Parser: transforms the tokens into an abstract syntax tree (AST) made of expressions
8 8
//! 3. Evaluator: Evaluates the program represented by the AST
9 9
//!
10 10
//! Each phase is an iterator which feeds into the next.
11 11
pub mod dynamic;
12 +
pub mod error;
12 13
pub mod evaluator;
13 14
pub mod parser;
14 15
pub mod scanner;
15 16
16 -
use std::error;
17 -
18 17
pub use dynamic::{Dynamic, IsDynamic};
19 -
pub use evaluator::{Env, Error, Evaluator, Expr, Result, Symbol};
18 +
pub use error::Error;
19 +
pub use evaluator::{Env, Evaluator, Expr, Result, Symbol};
20 20
pub use parser::Parser;
21 21
pub use scanner::Scanner;
22 22
23 23
/// File extension for language files.
24 24
pub const FILE_EXTENSION: &str = "om";
27 27
pub fn parse(input: &str) -> impl Iterator<Item = parser::Result<Expr>> + '_ {
28 28
    Parser::new(Scanner::new(input))
29 29
}
30 30
31 31
/// Evaluate expressions returned by a parser. Returns the result and modified environment.
32 -
pub fn evaluate<E: error::Error + 'static>(
32 +
pub fn evaluate<E: error::ErrorWithLocation + 'static>(
33 33
    exprs: impl Iterator<Item = Result<Expr, E>>,
34 34
    env: &mut evaluator::Env<'_>,
35 35
) -> evaluator::Result<Expr> {
36 36
    Evaluator::new(exprs).eval(env)
37 37
}
ombre/src/lang/error.rs added +232 -0
1 +
//! Error-related types.
2 +
use std::fmt;
3 +
use std::ops::Range;
4 +
use std::path::Path;
5 +
use std::rc::Rc;
6 +
7 +
use super::evaluator::{Expr, Symbol};
8 +
9 +
/// Evaluation error.
10 +
#[derive(Debug)]
11 +
pub enum Error {
12 +
    /// Error coming from parsing stage.
13 +
    Parser(Box<dyn ErrorWithLocation>),
14 +
    /// Undefined symbol.
15 +
    UndefinedSymbol(Symbol),
16 +
    /// Module not found when importing.
17 +
    ModuleNotFound(Symbol),
18 +
    /// Expected value of a certain type.
19 +
    ExpectedValue(&'static str),
20 +
    /// Expected value for named argument.
21 +
    ExpectedNamedValue(Rc<str>),
22 +
    /// Unexpected value.
23 +
    UnexpectedValue(Expr),
24 +
    /// Unexpected named argument.
25 +
    UnexpectedNamedArgument(Symbol),
26 +
    /// Wrong number of arguments supplied.
27 +
    WrongArgumentCount {
28 +
        /// Expected count.
29 +
        expected: usize,
30 +
        /// Actual count.
31 +
        actual: usize,
32 +
    },
33 +
    /// Invalid function argument.
34 +
    InvalidArgument,
35 +
    /// Error raised by user.
36 +
    User(Expr),
37 +
}
38 +
39 +
impl ErrorWithLocation for Error {
40 +
    fn location(&self) -> Option<CodeLocation> {
41 +
        match self {
42 +
            Self::Parser(e) => e.location(),
43 +
            _ => None,
44 +
        }
45 +
    }
46 +
}
47 +
48 +
impl fmt::Display for Error {
49 +
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
50 +
        match self {
51 +
            Error::Parser(e) => write!(f, "{e}"),
52 +
            Error::UndefinedSymbol(s) => write!(f, "undefined symbol: {s}"),
53 +
            Error::ModuleNotFound(s) => write!(f, "module not found: {s}"),
54 +
            Error::ExpectedValue(s) => write!(f, "expected value: {s}"),
55 +
            Error::ExpectedNamedValue(s) => write!(f, "expected named value: {s}"),
56 +
            Error::UnexpectedValue(e) => write!(f, "unexpected value: {e:?}"),
57 +
            Error::UnexpectedNamedArgument(s) => write!(f, "unexpected named argument: {s}"),
58 +
            Error::WrongArgumentCount { expected, actual } => {
59 +
                write!(f, "expected {expected} argument(s), got {actual}")
60 +
            }
61 +
            Error::InvalidArgument => write!(f, "invalid argument"),
62 +
            Error::User(e) => write!(f, "user error: {e:?}"),
63 +
        }
64 +
    }
65 +
}
66 +
67 +
impl std::error::Error for Error {}
68 +
69 +
/// Code location.
70 +
#[derive(Eq, PartialEq, Clone, Debug)]
71 +
pub struct CodeLocation {
72 +
    /// Line, 1-indexed.
73 +
    pub line: usize,
74 +
    /// Column, 1-indexed.
75 +
    pub column: usize,
76 +
    /// Byte range.
77 +
    pub range: Range<usize>,
78 +
}
79 +
80 +
/// An error that has an optional code location.
81 +
pub trait ErrorWithLocation: std::error::Error {
82 +
    /// Get the code location, if any.
83 +
    fn location(&self) -> Option<CodeLocation>;
84 +
}
85 +
86 +
/// Explains an error, relating it to an input source code string.
87 +
pub struct ErrorExplainer<'a, E> {
88 +
    /// The source code.
89 +
    pub input: &'a str,
90 +
    /// The source code path.
91 +
    pub path: &'a Path,
92 +
    /// The error.
93 +
    pub error: &'a E,
94 +
    /// Whether or not to use color.
95 +
    #[allow(dead_code)]
96 +
    pub color: bool,
97 +
}
98 +
99 +
impl<'a, E> ErrorExplainer<'a, E> {
100 +
    /// Create a new error explainer.
101 +
    pub fn new(error: &'a E, input: &'a str, path: &'a Path) -> Self {
102 +
        Self {
103 +
            input,
104 +
            error,
105 +
            path,
106 +
            color: false,
107 +
        }
108 +
    }
109 +
110 +
    fn line_at(&self, position: usize) -> &str {
111 +
        let start = self.input[..position].rfind('\n').map_or(0, |i| i + 1);
112 +
        let end = self.input[position..]
113 +
            .find('\n')
114 +
            .map_or(self.input.len(), |i| position + i);
115 +
116 +
        &self.input[start..end]
117 +
    }
118 +
}
119 +
120 +
impl<E: ErrorWithLocation + std::error::Error> fmt::Display for ErrorExplainer<'_, E> {
121 +
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
122 +
        let msg = self.error.to_string();
123 +
        let Some(CodeLocation {
124 +
            line,
125 +
            column,
126 +
            range,
127 +
        }) = self.error.location()
128 +
        else {
129 +
            writeln!(f, "error: {msg}")?;
130 +
            return Ok(());
131 +
        };
132 +
        let length = range.end - range.start;
133 +
        let line_no = line.to_string();
134 +
        let line_str = self.line_at(range.start);
135 +
        let underline = format!(
136 +
            "{:>width$}",
137 +
            "^".repeat(length),
138 +
            width = column + length - 1,
139 +
        );
140 +
141 +
        writeln!(f, "error: {msg}")?;
142 +
        writeln!(f, "   --> {}:{line}:{column}", self.path.display())?;
143 +
        writeln!(f, "   {} |", " ".repeat(line_no.len()))?;
144 +
        writeln!(f, "{line_no:>width$} | {line_str}", width = 4)?;
145 +
        writeln!(f, "   {} | {}", " ".repeat(line_no.len()), underline)?;
146 +
147 +
        Ok(())
148 +
    }
149 +
}
150 +
151 +
#[cfg(test)]
152 +
mod tests {
153 +
    use super::*;
154 +
    use crate::lang::scanner::{Token, TokenWithLocation};
155 +
    use crate::lang::{parser, scanner};
156 +
157 +
    #[test]
158 +
    fn test_explainer_line_at() {
159 +
        let explainer = ErrorExplainer {
160 +
            input: "First line.\nSecond line.\nThird line.",
161 +
            error: &Error::InvalidArgument,
162 +
            path: Path::new("fnord/test.txt"),
163 +
            color: false,
164 +
        };
165 +
        assert_eq!(explainer.line_at(0), "First line.");
166 +
        assert_eq!(explainer.line_at(3), "First line.");
167 +
        assert_eq!(explainer.line_at(15), "Second line.");
168 +
        assert_eq!(explainer.line_at(25), "Third line.");
169 +
        assert_eq!(explainer.line_at(36), "Third line.");
170 +
171 +
        let explainer = ErrorExplainer {
172 +
            input: "Only line.",
173 +
            error: &Error::InvalidArgument,
174 +
            path: Path::new("fnord/test.txt"),
175 +
            color: false,
176 +
        };
177 +
        assert_eq!(explainer.line_at(3), "Only line.");
178 +
    }
179 +
180 +
    #[test]
181 +
    fn test_explainer_unexpected_token() {
182 +
        let explainer = ErrorExplainer {
183 +
            input: "First line.\nSecond line.\nThird line.",
184 +
            error: &Error::Parser(Box::new(parser::Error::UnexpectedToken(
185 +
                TokenWithLocation {
186 +
                    value: Token::Symbol("line".into()),
187 +
                    line: 2,
188 +
                    column: 8,
189 +
                    range: 19..23,
190 +
                },
191 +
            ))),
192 +
            path: Path::new("fnord/test.txt"),
193 +
            color: false,
194 +
        };
195 +
        assert_eq!(
196 +
            explainer.to_string(),
197 +
            "\
198 +
    error: unexpected token `line` at line 2, column 8
199 +
   --> fnord/test.txt:2:8
200 +
     |
201 +
   2 | Second line.
202 +
     |        ^^^^\n"
203 +
        );
204 +
    }
205 +
206 +
    #[test]
207 +
    fn test_explainer_end_of_input() {
208 +
        let explainer = ErrorExplainer {
209 +
            input: "This is the input.\n",
210 +
            error: &Error::Parser(Box::new(parser::Error::Scanner(
211 +
                scanner::Error::EndOfInput {
212 +
                    location: CodeLocation {
213 +
                        line: 1,
214 +
                        column: 19,
215 +
                        range: 18..19,
216 +
                    },
217 +
                },
218 +
            ))),
219 +
            path: Path::new("fnord/test.txt"),
220 +
            color: false,
221 +
        };
222 +
        assert_eq!(
223 +
            explainer.to_string(),
224 +
            "\
225 +
    error: unexpected end of input
226 +
   --> fnord/test.txt:1:19
227 +
     |
228 +
   1 | This is the input.
229 +
     |                   ^\n"
230 +
        );
231 +
    }
232 +
}
ombre/src/lang/evaluator.rs +2 -52
10 10
11 11
use crate::gfx::Rgba;
12 12
use crate::lang::dynamic::{Dynamic, IsDynamic};
13 13
use crate::math::{Vector2D, Vector3D, Vector4D};
14 14
15 +
use super::error::{Error, ErrorWithLocation};
15 16
use super::{Parser, Scanner, FILE_EXTENSION};
16 17
17 18
/// Result type for all functions.
18 19
pub type Result<T, E = Error> = result::Result<T, E>;
19 20
20 -
/// Evaluation error.
21 -
#[derive(Debug)]
22 -
pub enum Error {
23 -
    /// Error coming from parsing stage.
24 -
    Parser(Box<dyn std::error::Error>),
25 -
    /// Undefined symbol.
26 -
    UndefinedSymbol(Symbol),
27 -
    /// Module not found when importing.
28 -
    ModuleNotFound(Symbol),
29 -
    /// Expected value of a certain type.
30 -
    ExpectedValue(&'static str),
31 -
    /// Expected value for named argument.
32 -
    ExpectedNamedValue(Rc<str>),
33 -
    /// Unexpected value.
34 -
    UnexpectedValue(Expr),
35 -
    /// Unexpected named argument.
36 -
    UnexpectedNamedArgument(Symbol),
37 -
    /// Wrong number of arguments supplied.
38 -
    WrongArgumentCount {
39 -
        /// Expected count.
40 -
        expected: usize,
41 -
        /// Actual count.
42 -
        actual: usize,
43 -
    },
44 -
    /// Invalid function argument.
45 -
    InvalidArgument,
46 -
    /// Error raised by user.
47 -
    User(Expr),
48 -
}
49 -
50 -
impl fmt::Display for Error {
51 -
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
52 -
        match self {
53 -
            Error::Parser(e) => write!(f, "parser: {e}"),
54 -
            Error::UndefinedSymbol(s) => write!(f, "undefined symbol: {s}"),
55 -
            Error::ModuleNotFound(s) => write!(f, "module not found: {s}"),
56 -
            Error::ExpectedValue(s) => write!(f, "expected value: {s}"),
57 -
            Error::ExpectedNamedValue(s) => write!(f, "expected named value: {s}"),
58 -
            Error::UnexpectedValue(e) => write!(f, "unexpected value: {e:?}"),
59 -
            Error::UnexpectedNamedArgument(s) => write!(f, "unexpected named argument: {s}"),
60 -
            Error::WrongArgumentCount { expected, actual } => {
61 -
                write!(f, "expected {expected} argument(s), got {actual}")
62 -
            }
63 -
            Error::InvalidArgument => write!(f, "invalid argument"),
64 -
            Error::User(e) => write!(f, "user error: {e:?}"),
65 -
        }
66 -
    }
67 -
}
68 -
69 -
impl std::error::Error for Error {}
70 -
71 21
/// A symbol is an immutable string.
72 22
#[derive(Debug, Clone, Eq, PartialOrd, Ord)]
73 23
pub struct Symbol(Rc<str>);
74 24
75 25
impl Hash for Symbol {
1208 1158
}
1209 1159
1210 1160
impl<T, E> Evaluator<T, E>
1211 1161
where
1212 1162
    T: Iterator<Item = Result<Expr, E>>,
1213 -
    E: std::error::Error + 'static,
1163 +
    E: ErrorWithLocation + 'static,
1214 1164
{
1215 1165
    /// Create a new evaluator.
1216 1166
    pub fn new(exprs: T) -> Self {
1217 1167
        Self {
1218 1168
            modules: ModuleRegistry::default(),
ombre/src/lang/parser.rs +38 -14
5 5
use std::iter::Peekable;
6 6
use std::ops::Deref;
7 7
use std::rc::Rc;
8 8
use std::result;
9 9
10 +
use crate::lang::error::{CodeLocation, ErrorWithLocation};
10 11
use crate::lang::evaluator::{Expr, Key, Symbol, Tuple};
11 12
use crate::lang::scanner;
12 -
use crate::lang::scanner::Token;
13 +
use crate::lang::scanner::{Token, TokenWithLocation};
13 14
14 15
/// Result type for all functions.
15 16
pub type Result<T> = result::Result<T, Error>;
16 17
17 18
/// Parse error.
18 19
#[derive(Debug, Clone, PartialEq)]
19 20
pub enum Error {
20 21
    /// Scanning error.
21 22
    Scanner(scanner::Error),
22 23
    /// An unexpected token was encountered.
23 -
    UnexpectedToken(Token<'static>),
24 +
    UnexpectedToken(TokenWithLocation<'static>),
24 25
    /// An unexpected end of input was reached.
25 26
    EndOfInput,
26 27
    /// Invalid dictionary key.
27 28
    InvalidDictKey(Expr),
28 29
    /// Incomplete dictionary key/value pair.
30 31
}
31 32
32 33
impl fmt::Display for Error {
33 34
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
34 35
        match self {
35 -
            Error::Scanner(e) => write!(f, "scanner: {e}"),
36 -
            Error::UnexpectedToken(token) => write!(f, "unexpected token: {token:?}"),
36 +
            Error::Scanner(e) => write!(f, "{e}"),
37 +
            Error::UnexpectedToken(token) => write!(
38 +
                f,
39 +
                "unexpected token {} at line {}, column {}",
40 +
                token.value, token.line, token.column
41 +
            ),
37 42
            Error::EndOfInput => write!(f, "unexpected end of input"),
38 43
            Error::InvalidDictKey(e) => write!(f, "invalid dictionary key {e}"),
39 44
            Error::IncompleteDictPair(k) => write!(f, "missing value for dictionary key {k}"),
40 45
        }
41 46
    }
42 47
}
43 48
44 49
impl std::error::Error for Error {}
45 50
51 +
impl ErrorWithLocation for Error {
52 +
    fn location(&self) -> Option<CodeLocation> {
53 +
        match self {
54 +
            Self::Scanner(e) => e.location(),
55 +
            Self::UnexpectedToken(t) => Some(CodeLocation {
56 +
                line: t.line,
57 +
                column: t.column,
58 +
                range: t.range.clone(),
59 +
            }),
60 +
            Self::EndOfInput => None,
61 +
            Self::InvalidDictKey(_) => None,
62 +
            Self::IncompleteDictPair(_) => None,
63 +
        }
64 +
    }
65 +
}
66 +
46 67
/// Parse a stream of tokens into a syntax tree.
47 68
#[derive(Debug)]
48 69
pub struct Parser<'a, T>
49 70
where
50 -
    T: Iterator<Item = scanner::Result<Token<'a>>>,
71 +
    T: Iterator<Item = scanner::Result<TokenWithLocation<'a>>>,
51 72
{
52 73
    tokens: Peekable<T>,
53 74
}
54 75
55 76
impl<'a, T> Parser<'a, T>
56 77
where
57 -
    T: Iterator<Item = scanner::Result<Token<'a>>>,
78 +
    T: Iterator<Item = scanner::Result<TokenWithLocation<'a>>>,
58 79
{
59 80
    /// Create a new parser from a token stream.
60 81
    pub fn new(tokens: T) -> Self {
61 82
        Parser {
62 83
            tokens: tokens.peekable(),
66 87
    /// Parse all the input into a vector of expressions.
67 88
    pub fn parse(self) -> Result<Vec<Expr>> {
68 89
        self.collect()
69 90
    }
70 91
71 -
    fn peek(&mut self) -> Result<Token<'a>> {
92 +
    fn peek(&mut self) -> Result<TokenWithLocation<'a>> {
72 93
        self.tokens
73 94
            .peek()
74 95
            .cloned()
75 96
            .ok_or(Error::EndOfInput)?
76 97
            .map_err(Error::Scanner)
77 98
    }
78 99
79 100
    fn parse_expr(&mut self) -> Result<Expr> {
80 101
        let token = self.peek()?;
81 -
        let expr = match token {
102 +
        let expr = match token.value {
82 103
            Token::LParen => self.parse_tuple().map(Expr::tuple)?,
83 104
            Token::RParen => return Err(Error::UnexpectedToken(token.owned())),
84 105
            Token::LBrace => self.parse_dict()?,
85 106
            Token::RBrace => return Err(Error::UnexpectedToken(token.owned())),
86 107
            Token::LBracket => self.parse_tuple_lit().map(|es| {
172 193
        Ok(Expr::Quoted(expr.into()))
173 194
    }
174 195
175 196
    fn parse_ref(&mut self) -> Result<Expr> {
176 197
        self.next_if(|t| t == &Token::Ref)?;
177 -
178 -
        let e = match self.peek()? {
198 +
        let next = self.peek()?;
199 +
        let e = match &next.value {
179 200
            Token::LParen => self.parse_tuple(),
180 201
            Token::LBracket => self.parse_tuple_lit(),
181 -
            t => return Err(Error::UnexpectedToken(t.owned())),
202 +
            _ => return Err(Error::UnexpectedToken(next.owned())),
182 203
        }?;
183 204
        Ok(Expr::Vector(Rc::new(RefCell::new(e))))
184 205
    }
185 206
186 -
    fn next_if(&mut self, condition: impl FnOnce(&Token<'_>) -> bool) -> Result<Token<'a>> {
207 +
    fn next_if(
208 +
        &mut self,
209 +
        condition: impl FnOnce(&Token<'_>) -> bool,
210 +
    ) -> Result<TokenWithLocation<'a>> {
187 211
        let tok = self.tokens.next().ok_or(Error::EndOfInput)?.map_err(Error::Scanner)?;
188 212
189 -
        if condition(&tok) {
213 +
        if condition(&tok.value) {
190 214
            return Ok(tok);
191 215
        }
192 216
        Err(Error::UnexpectedToken(tok.owned()))
193 217
    }
194 218
206 230
    }
207 231
}
208 232
209 233
impl<'a, T> Iterator for Parser<'a, T>
210 234
where
211 -
    T: Iterator<Item = scanner::Result<Token<'a>>>,
235 +
    T: Iterator<Item = scanner::Result<TokenWithLocation<'a>>>,
212 236
{
213 237
    type Item = Result<Expr>;
214 238
215 239
    fn next(&mut self) -> Option<Self::Item> {
216 240
        if self.tokens.peek().is_some() {
ombre/src/lang/scanner.rs +269 -58
1 1
//! Token scanner or "lexer".
2 2
use std::borrow::Cow;
3 3
use std::fmt;
4 4
use std::iter::Peekable;
5 +
use std::ops::Range;
5 6
use std::result;
6 7
use std::str::CharIndices;
7 8
9 +
use lang::error::{CodeLocation, ErrorWithLocation};
10 +
8 11
use crate::gfx::color::Rgba8;
9 12
use crate::*;
10 13
11 14
/// Result type for all functions.
12 15
pub type Result<T> = result::Result<T, Error>;
20 23
        ch: char,
21 24
        /// Its index in the input string.
22 25
        ix: usize,
23 26
    },
24 27
    /// The end of the input was reached unexpectedly.
25 -
    EndOfInput,
28 +
    EndOfInput {
29 +
        /// Location of error.
30 +
        location: CodeLocation,
31 +
    },
26 32
    /// Error parsing a float.
27 33
    ParseFloat(std::num::ParseFloatError),
28 34
    /// Error parsing an integer.
29 35
    ParseInteger(std::num::ParseIntError),
30 36
    /// Error parsing a color.
35 41
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
36 42
        match self {
37 43
            Error::UnexpectedChar { ch, ix } => {
38 44
                write!(f, "unexpected character '{ch}' at index {ix}")
39 45
            }
40 -
            Error::EndOfInput => write!(f, "unexpected end of input"),
46 +
            Error::EndOfInput { .. } => write!(f, "unexpected end of input"),
41 47
            Error::ParseFloat(e) => write!(f, "parsing float: {e}"),
42 48
            Error::ParseInteger(e) => write!(f, "parsing integer: {e}"),
43 49
            Error::ParseColor(e) => write!(f, "parsing color: {e}"),
44 50
        }
45 51
    }
46 52
}
47 53
48 54
impl std::error::Error for Error {}
49 55
56 +
impl ErrorWithLocation for Error {
57 +
    fn location(&self) -> Option<CodeLocation> {
58 +
        match self {
59 +
            Self::EndOfInput { location } => Some(location.clone()),
60 +
            _ => None,
61 +
        }
62 +
    }
63 +
}
64 +
65 +
/// A [`Token`] with line and column number.
66 +
#[derive(Debug, Clone, PartialEq)]
67 +
pub struct TokenWithLocation<'a> {
68 +
    /// The token.
69 +
    pub value: Token<'a>,
70 +
    /// The line number, indexed from `1`.
71 +
    pub line: usize,
72 +
    /// The column number, indexed from `1`.
73 +
    pub column: usize,
74 +
    /// Index into the input buffer where this token starts and ends.
75 +
    pub range: Range<usize>,
76 +
}
77 +
78 +
impl<'a> std::ops::Deref for TokenWithLocation<'a> {
79 +
    type Target = Token<'a>;
80 +
81 +
    fn deref(&self) -> &Self::Target {
82 +
        &self.value
83 +
    }
84 +
}
85 +
86 +
impl TokenWithLocation<'_> {
87 +
    /// Make this token with location static.
88 +
    pub fn owned(self) -> TokenWithLocation<'static> {
89 +
        TokenWithLocation {
90 +
            value: self.value.owned(),
91 +
            line: self.line,
92 +
            column: self.column,
93 +
            range: self.range,
94 +
        }
95 +
    }
96 +
}
97 +
50 98
/// A token representing some piece of source code.
51 99
#[derive(Debug, Clone, PartialEq)]
52 100
pub enum Token<'a> {
53 101
    /// Eg. `{`
54 102
    LBrace,
105 153
            Color(c) => Color(c),
106 154
        }
107 155
    }
108 156
}
109 157
158 +
impl fmt::Display for Token<'_> {
159 +
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
160 +
        match self {
161 +
            Token::LBrace => write!(f, "`{{`"),
162 +
            Token::RBrace => write!(f, "`}}`"),
163 +
            Token::LParen => write!(f, "`(`"),
164 +
            Token::RParen => write!(f, "`)`"),
165 +
            Token::LBracket => write!(f, "`[`"),
166 +
            Token::RBracket => write!(f, "`]`"),
167 +
            Token::Quote => write!(f, "`'`"),
168 +
            Token::Ref => write!(f, "`@`"),
169 +
            Token::Symbol(s) => write!(f, "`{s}`"),
170 +
            Token::Atom(s) => write!(f, ":{s}"),
171 +
            Token::Char(c) => write!(f, "``{c}``"),
172 +
            Token::Str(s) => write!(f, "\"{s}\""),
173 +
            Token::Float(n) => write!(f, "{n}"),
174 +
            Token::Integer(n) => write!(f, "{n}"),
175 +
            Token::Color(c) => write!(f, "#{:02x}{:02x}{:02x}", c.r, c.g, c.b),
176 +
        }
177 +
    }
178 +
}
179 +
110 180
/// Generates a stream of [`Token`] values given an input string.
111 181
#[derive(Debug, Clone)]
112 182
pub struct Scanner<'a> {
113 183
    chars: Peekable<CharIndices<'a>>,
114 184
    input: &'a str,
185 +
    line: usize,
186 +
    column: usize,
187 +
    index: usize,
115 188
}
116 189
117 190
impl<'a> Scanner<'a> {
118 191
    /// Create a new scanner for the given input.
119 192
    pub fn new(input: &'a str) -> Self {
120 193
        Self {
121 194
            chars: input.char_indices().peekable(),
122 195
            input,
196 +
            line: 1,
197 +
            column: 1,
198 +
            index: 0,
123 199
        }
124 200
    }
125 201
}
126 202
127 203
impl<'a> Scanner<'a> {
128 -
    fn scan_color(&mut self) -> Result<Token<'a>> {
204 +
    fn location(&self) -> CodeLocation {
205 +
        CodeLocation {
206 +
            line: self.line,
207 +
            column: self.column,
208 +
            range: self.index..self.index + 1,
209 +
        }
210 +
    }
211 +
212 +
    fn scan_color(&mut self) -> Result<TokenWithLocation<'a>> {
213 +
        let (line, column) = (self.line, self.column);
129 214
        let (start, _) = self.skip_char('#')?;
130 215
        let digits = self.skip_while(|c| c.is_ascii_hexdigit());
131 216
132 217
        if digits.is_empty() {
133 -
            return Err(Error::EndOfInput);
218 +
            return Err(Error::EndOfInput {
219 +
                location: self.location(),
220 +
            });
134 221
        }
135 -
        self.input[start..=start + digits.len()]
222 +
        let token = self.input[start..=start + digits.len()]
136 223
            .parse()
137 224
            .map(Token::Color)
138 -
            .map_err(Error::ParseColor)
225 +
            .map_err(Error::ParseColor)?;
226 +
227 +
        Ok(TokenWithLocation {
228 +
            value: token,
229 +
            line,
230 +
            column,
231 +
            range: start..start + digits.len() + 1,
232 +
        })
139 233
    }
140 234
141 -
    fn scan_atom(&mut self) -> Result<Token<'a>> {
142 -
        let (_, _) = self.skip_char(':')?;
235 +
    fn scan_atom(&mut self) -> Result<TokenWithLocation<'a>> {
236 +
        let (line, column) = (self.line, self.column);
237 +
        let (start, _) = self.skip_char(':')?;
143 238
        let sym = self.scan_ident()?;
144 239
145 -
        Ok(Token::Atom(sym.into()))
240 +
        Ok(TokenWithLocation {
241 +
            value: Token::Atom(sym.into()),
242 +
            line,
243 +
            column,
244 +
            range: start..start + sym.len() + 1,
245 +
        })
146 246
    }
147 247
148 -
    fn scan_symbol(&mut self) -> Result<Token<'a>> {
248 +
    fn scan_symbol(&mut self) -> Result<TokenWithLocation<'a>> {
249 +
        let (start, line, column) = (self.index, self.line, self.column);
149 250
        let sym = self.scan_ident()?;
150 251
151 -
        Ok(Token::Symbol(sym.into()))
252 +
        Ok(TokenWithLocation {
253 +
            value: Token::Symbol(sym.into()),
254 +
            line,
255 +
            column,
256 +
            range: start..start + sym.len(),
257 +
        })
152 258
    }
153 259
154 260
    fn scan_ident(&mut self) -> Result<&'a str> {
155 261
        let valid = "!@#$%^&*/-+=<>?~_";
156 262
        let ident = self.skip_while(|c| c.is_ascii_alphanumeric() || valid.contains(c));
160 266
        } else {
161 267
            Ok(ident)
162 268
        }
163 269
    }
164 270
165 -
    fn scan_number(&mut self, negative: bool) -> Result<Token<'a>> {
271 +
    fn scan_number(&mut self, negative: bool) -> Result<TokenWithLocation<'a>> {
272 +
        let (line, column) = (self.line, self.column);
166 273
        let (start, _) = self.skip_if(|c| c.is_ascii_digit())?;
167 274
        let mut floating = false;
168 275
169 276
        while let Some((_, ch)) = self.peek() {
170 277
            if ch.is_ascii_digit() {
174 281
                self.skip_next()?;
175 282
            } else {
176 283
                break;
177 284
            }
178 285
        }
179 -
        let string = &self.input[start..self.index()];
180 -
181 -
        if floating {
182 -
            string
183 -
                .parse::<f64>()
184 -
                .map(|n| if negative { -n } else { n })
185 -
                .map(Token::Float)
186 -
                .map_err(Error::ParseFloat)
286 +
        let (column, range) = if negative {
287 +
            (column - 1, start - 1..self.index())
187 288
        } else {
188 -
            string
189 -
                .parse::<i64>()
190 -
                .map(|n| if negative { -n } else { n })
191 -
                .map(Token::Integer)
192 -
                .map_err(Error::ParseInteger)
193 -
        }
289 +
            (column, start..self.index())
290 +
        };
291 +
        let string = &self.input[range.clone()];
292 +
        let token = if floating {
293 +
            string.parse::<f64>().map(Token::Float).map_err(Error::ParseFloat)
294 +
        } else {
295 +
            string.parse::<i64>().map(Token::Integer).map_err(Error::ParseInteger)
296 +
        }?;
297 +
298 +
        Ok(TokenWithLocation {
299 +
            value: token,
300 +
            line,
301 +
            column,
302 +
            range,
303 +
        })
194 304
    }
195 305
196 -
    fn scan_char(&mut self) -> Result<Token<'a>> {
197 -
        self.skip_char('`')?;
306 +
    fn scan_char(&mut self) -> Result<TokenWithLocation<'a>> {
307 +
        let (line, column) = (self.line, self.column);
308 +
        let (ix, _) = self.skip_char('`')?;
198 309
        let (_, ch) = self.skip_next()?;
199 310
200 311
        let ch = if ch == '\\' {
201 312
            let (_, escaped) = self.skip_next()?;
202 313
            escaped
203 314
        } else {
204 315
            ch
205 316
        };
206 317
        self.skip_char('`')?;
207 318
208 -
        Ok(Token::Char(ch))
319 +
        Ok(TokenWithLocation {
320 +
            value: Token::Char(ch),
321 +
            line,
322 +
            column,
323 +
            range: ix..self.index,
324 +
        })
209 325
    }
210 326
211 -
    fn scan_str(&mut self) -> Result<Token<'a>> {
327 +
    fn scan_str(&mut self) -> Result<TokenWithLocation<'a>> {
328 +
        let (line, column) = (self.line, self.column);
212 329
        let (start, _) = self.skip_char('"')?;
213 330
        loop {
214 331
            let (ix, ch) = self.skip_next()?;
215 332
216 333
            match ch {
217 334
                '"' => {
218 -
                    return Ok(Token::Str(self.input[start + 1..ix].into()));
335 +
                    return Ok(TokenWithLocation {
336 +
                        value: Token::Str(self.input[start + 1..ix].into()),
337 +
                        line,
338 +
                        column,
339 +
                        range: start..ix + 1,
340 +
                    });
219 341
                }
220 342
                '\\' => {
221 343
                    self.skip_next()?;
222 344
                }
223 345
                _ => {}
228 350
    fn skip_char(&mut self, ch: char) -> Result<(usize, char)> {
229 351
        self.skip_if(|c| c == ch)
230 352
    }
231 353
232 354
    fn skip_if(&mut self, condition: impl FnOnce(char) -> bool) -> Result<(usize, char)> {
233 -
        let (i, c) = self.peek().ok_or(Error::EndOfInput)?;
355 +
        let (i, c) = self.peek().ok_or(Error::EndOfInput {
356 +
            location: self.location(),
357 +
        })?;
234 358
235 359
        if condition(c) {
236 -
            self.chars.next();
360 +
            self.skip_next()?;
237 361
            Ok((i, c))
238 362
        } else {
239 363
            Err(self.error())
240 364
        }
241 365
    }
244 368
        let Some((start, _)) = self.peek() else {
245 369
            return "";
246 370
        };
247 371
        while let Some((ix, c)) = self.peek() {
248 372
            if condition(c) {
249 -
                self.chars.next();
373 +
                self.skip_next().ok();
250 374
            } else {
251 375
                return &self.input[start..ix];
252 376
            }
253 377
        }
254 378
        &self.input[start..]
255 379
    }
256 380
257 381
    fn skip_next(&mut self) -> Result<(usize, char)> {
258 -
        self.chars.next().ok_or(Error::EndOfInput)
382 +
        let (ix, ch) = self.chars.next().ok_or(Error::EndOfInput {
383 +
            location: self.location(),
384 +
        })?;
385 +
        if ch == '\n' {
386 +
            self.line += 1;
387 +
            self.column = 1;
388 +
        } else {
389 +
            self.column += 1;
390 +
        }
391 +
        self.index += 1;
392 +
393 +
        Ok((ix, ch))
259 394
    }
260 395
261 396
    fn index(&mut self) -> usize {
262 397
        if let Some((ix, _)) = self.chars.peek() {
263 398
            *ix
268 403
269 404
    fn peek(&mut self) -> Option<(usize, char)> {
270 405
        self.chars.peek().cloned()
271 406
    }
272 407
408 +
    fn emit(&mut self, value: Token<'a>) -> Result<TokenWithLocation<'a>> {
409 +
        let token = TokenWithLocation {
410 +
            value,
411 +
            line: self.line,
412 +
            column: self.column,
413 +
            range: self.index..self.index + 1,
414 +
        };
415 +
        self.skip_next()?;
416 +
417 +
        Ok(token)
418 +
    }
419 +
273 420
    fn error(&mut self) -> Error {
274 421
        if let Some((index, input)) = self.peek() {
275 422
            Error::UnexpectedChar {
276 423
                ch: input,
277 424
                ix: index,
278 425
            }
279 426
        } else {
280 -
            Error::EndOfInput
427 +
            Error::EndOfInput {
428 +
                location: self.location(),
429 +
            }
281 430
        }
282 431
    }
283 432
}
284 433
285 434
impl<'a> Iterator for Scanner<'a> {
286 -
    type Item = Result<Token<'a>>;
435 +
    type Item = Result<TokenWithLocation<'a>>;
287 436
288 -
    fn next(&mut self) -> Option<Result<Token<'a>>> {
437 +
    fn next(&mut self) -> Option<Result<TokenWithLocation<'a>>> {
289 438
        while let Some((ix, c)) = self.peek() {
439 +
            let (line, column) = (self.line, self.column);
290 440
            match c {
291 441
                '(' => {
292 -
                    self.chars.next();
293 -
                    return Some(Ok(Token::LParen));
442 +
                    return Some(self.emit(Token::LParen));
294 443
                }
295 444
                ')' => {
296 -
                    self.chars.next();
297 -
                    return Some(Ok(Token::RParen));
445 +
                    return Some(self.emit(Token::RParen));
298 446
                }
299 447
                '{' => {
300 -
                    self.chars.next();
301 -
                    return Some(Ok(Token::LBrace));
448 +
                    return Some(self.emit(Token::LBrace));
302 449
                }
303 450
                '}' => {
304 -
                    self.chars.next();
305 -
                    return Some(Ok(Token::RBrace));
451 +
                    return Some(self.emit(Token::RBrace));
306 452
                }
307 453
                '[' => {
308 -
                    self.chars.next();
309 -
                    return Some(Ok(Token::LBracket));
454 +
                    return Some(self.emit(Token::LBracket));
310 455
                }
311 456
                ']' => {
312 -
                    self.chars.next();
313 -
                    return Some(Ok(Token::RBracket));
457 +
                    return Some(self.emit(Token::RBracket));
314 458
                }
315 459
                ';' => {
316 460
                    // Comment.
317 461
                    self.skip_while(|c| c != '\n');
318 462
                }
327 471
                }
328 472
                ':' => {
329 473
                    return Some(self.scan_atom());
330 474
                }
331 475
                '\'' => {
332 -
                    self.chars.next();
333 -
                    return Some(Ok(Token::Quote));
476 +
                    return Some(self.emit(Token::Quote));
334 477
                }
335 478
                '@' => {
336 -
                    self.chars.next();
337 -
                    return Some(Ok(Token::Ref));
479 +
                    return Some(self.emit(Token::Ref));
338 480
                }
339 481
                '-' => {
340 -
                    self.chars.next();
482 +
                    self.skip_next().ok();
341 483
                    match self.peek() {
342 484
                        Some((_, c)) if c.is_ascii_digit() => return Some(self.scan_number(true)),
343 485
                        _ => {
344 486
                            let symbol = match self.scan_ident() {
345 487
                                Ok(ident) => &self.input[ix..=ix + ident.len()],
346 488
                                Err(_) => "-",
347 489
                            };
348 -
                            return Some(Ok(Token::Symbol(Cow::Borrowed(symbol))));
490 +
                            return Some(Ok(TokenWithLocation {
491 +
                                value: Token::Symbol(Cow::Borrowed(symbol)),
492 +
                                line,
493 +
                                column,
494 +
                                range: ix..ix + symbol.len(),
495 +
                            }));
349 496
                        }
350 497
                    }
351 498
                }
352 499
                c if c.is_ascii_whitespace() => {
353 -
                    self.chars.next();
500 +
                    self.skip_next().ok();
354 501
                }
355 502
                c if c.is_ascii_digit() => {
356 503
                    return Some(self.scan_number(false));
357 504
                }
358 505
                _ => {
371 518
    use super::Token;
372 519
373 520
    #[track_caller]
374 521
    fn ok(input: &str, expected: &[Token<'_>]) {
375 522
        let mut scanner = super::Scanner::new(input);
376 -
        let tokens = scanner.by_ref().collect::<Result<Vec<_>, _>>().unwrap();
523 +
        let tokens = scanner
524 +
            .by_ref()
525 +
            .map(|t| t.map(|t| t.value))
526 +
            .collect::<Result<Vec<_>, _>>()
527 +
            .unwrap();
377 528
        let next = scanner.peek();
378 529
379 530
        assert_eq!(tokens.as_slice(), expected, "Next character {next:?}");
380 531
        assert!(scanner.peek().is_none(), "Unexpected character {next:?}");
381 532
    }
382 533
534 +
    #[track_caller]
535 +
    fn location(
536 +
        input: &str,
537 +
        expected: Token<'_>,
538 +
        line: usize,
539 +
        column: usize,
540 +
        range: std::ops::Range<usize>,
541 +
    ) {
542 +
        let mut scanner = super::Scanner::new(input);
543 +
        let tokens = scanner.by_ref().collect::<Result<Vec<_>, _>>().unwrap();
544 +
        let token = tokens.first().unwrap();
545 +
        let next = scanner.peek();
546 +
547 +
        assert_eq!(
548 +
            token.value, expected,
549 +
            "expected token {expected:?}, got {:?}",
550 +
            token.value
551 +
        );
552 +
        assert_eq!(token.line, line, "expected line {line}, got {}", token.line);
553 +
        assert_eq!(
554 +
            token.column, column,
555 +
            "expected column {column}, got {}",
556 +
            token.column
557 +
        );
558 +
        assert_eq!(
559 +
            token.range, range,
560 +
            "expected range {range:?}, got {:?}",
561 +
            token.range
562 +
        );
563 +
        assert!(scanner.peek().is_none(), "Unexpected character {next:?}");
564 +
    }
565 +
383 566
    #[track_caller]
384 567
    fn err(input: &str) {
385 568
        let mut scanner = super::Scanner::new(input);
386 569
        scanner.by_ref().collect::<Result<Vec<_>, _>>().unwrap_err();
387 570
    }
554 737
        );
555 738
        err("#");
556 739
        err("#ff00");
557 740
        err("#ff00113399");
558 741
    }
742 +
743 +
    #[test]
744 +
    fn test_location() {
745 +
        location(
746 +
            "-symbol-ok",
747 +
            Token::Symbol("-symbol-ok".into()),
748 +
            1,
749 +
            1,
750 +
            0..10,
751 +
        );
752 +
        location(" :atom ", Token::Atom("atom".into()), 1, 2, 1..6);
753 +
        location(" - ", Token::Symbol("-".into()), 1, 2, 1..2);
754 +
        location(" -42 ", Token::Integer(-42), 1, 2, 1..4);
755 +
        location(" 42 ", Token::Integer(42), 1, 2, 1..3);
756 +
        location(" `z` ", Token::Char('z'), 1, 2, 1..4);
757 +
        location(" \"fnord\" ", Token::Str("fnord".into()), 1, 2, 1..8);
758 +
        location(" ( ", Token::LParen, 1, 2, 1..2);
759 +
        location(" @ ", Token::Ref, 1, 2, 1..2);
760 +
        location(
761 +
            " #ff0011",
762 +
            Token::Color(Rgba8::new(0xff, 0x00, 0x11, 0xff)),
763 +
            1,
764 +
            2,
765 +
            1..8,
766 +
        );
767 +
        location("\nfnord", Token::Symbol("fnord".into()), 2, 1, 1..6);
768 +
        location("\n\n888", Token::Integer(888), 3, 1, 2..5);
769 +
    }
559 770
}
ombre/tests/basic.om added +130 -0
1 +
;; Test let
2 +
(assert (eq? (let [a 1 b 2 c 3] (+ a b c)) 6) "let")
3 +
4 +
;; Basic tests for core functionality
5 +
(assert (eq? (+ 1 2 3) 6))
6 +
(assert (eq? (- 10 5) 5))
7 +
(assert (eq? (* 2 3 4) 24))
8 +
(assert (eq? (/ 10 2) 5))
9 +
10 +
;; Test tuple operations
11 +
(assert (eq? (first [1 2 3]) 1))
12 +
(assert (eq? (first []) nil))
13 +
(assert (eq? (last [1 2 3]) 3))
14 +
(assert (eq? (last []) nil))
15 +
(assert (eq? (nth [1 2 3] 0) 1))
16 +
(assert (eq? (nth [1 2 3] 1) 2))
17 +
(assert (eq? (nth [1 2 3] 2) 3))
18 +
(assert (eq? (nth [1 2 3] 4) nil))
19 +
(assert (empty? []))
20 +
(assert (not (empty? [1])))
21 +
(assert (contains? 2 [1 2 3]))
22 +
(assert (not (contains? 2 [1 3])))
23 +
(assert (eq? (length []) 0))
24 +
(assert (eq? (length [1 2 3]) 3))
25 +
26 +
;; Test vector operations
27 +
(do
28 +
  (def v @[1 2 3])
29 +
  (assert (eq? (length v) 3))
30 +
  (assert (eq? v @[1 2 3]))
31 +
  (push v 4 5 6)
32 +
  (assert (eq? (length v) 6))
33 +
  (assert (eq? v @[1 2 3 4 5 6]))
34 +
  (push v 7)
35 +
  (assert (eq? v @[1 2 3 4 5 6 7]))
36 +
  (assert (eq? (pop v) 7))
37 +
  (assert (eq? v @[1 2 3 4 5 6]))
38 +
  (assert (eq? (pop v) 6))
39 +
  (assert (eq? (pop @[]) nil)))
40 +
41 +
;; Test boolean operations
42 +
(assert true)
43 +
(assert (not false))
44 +
(assert (and true true))
45 +
(assert (not (and true false)))
46 +
(assert (or false true))
47 +
(assert (not (or false false)))
48 +
49 +
;; Test comparisons
50 +
(assert (> 5 3))
51 +
(assert (not (> 3 5)))
52 +
(assert (< 3 5))
53 +
(assert (not (< 5 3)))
54 +
(assert (>= 5 5))
55 +
(assert (>= 5 3))
56 +
(assert (<= 3 3))
57 +
(assert (<= 3 5))
58 +
59 +
;; Test equality
60 +
(assert (eq? 42 42))
61 +
(assert (not (eq? 42 43)))
62 +
(assert (eq? [] () (tuple)))
63 +
(assert (eq? '[] '()))
64 +
(assert (eq? {:x 1} {:x 1}))
65 +
(assert (not (eq? {:x 1} {:x 2})))
66 +
67 +
;; Test string operations
68 +
(assert (eq? (length "hello") 5))
69 +
(assert (contains? "lo" "hello"))
70 +
(assert (empty? ""))
71 +
(assert (not (empty? "hello")))
72 +
(assert (not (contains? "ol" "hello")))
73 +
74 +
;; Test math
75 +
(assert (eq? 10 (+ 1 2 3 4)) "addition")
76 +
(assert (eq? -8 (- 1 2 3 4)) "subtraction")
77 +
(assert (eq? 24 (* 1 2 3 4)) "multiplication")
78 +
(assert (eq? 0.125 (/ 1.0 2.0 4.0)) "division")
79 +
80 +
;; Test comparisons
81 +
(assert (< 1 2 3 4 5 6) "less than integers")
82 +
(assert (< 1.0 2.0 3.0 4.0 5.0 6.0) "less than reals")
83 +
(assert (> 6 5 4 3 2 1) "greater than integers")
84 +
(assert (> 6.0 5.0 4.0 3.0 2.0 1.0) "greater than reals")
85 +
(assert (<= 1 2 3 3 4 5 6) "less than or equal to integers")
86 +
(assert (<= 1.0 2.0 3.0 3.0 4.0 5.0 6.0) "less than or equal to reals")
87 +
(assert (>= 6 5 4 4 3 2 1) "greater than or equal to integers")
88 +
(assert (>= 6.0 5.0 4.0 4.0 3.0 2.0 1.0) "greater than or equal to reals")
89 +
(assert (>= 5 5.0 4) "greater than or equal (mixed types)")
90 +
(assert (> 5) "greater than nothing")
91 +
(assert (< 5) "lesser than nothing")
92 +
93 +
;; Test remainder operations
94 +
(assert (= 7 (% 20 13)) "rem 1")
95 +
(assert (= -7 (% -20 13)) "rem 2")
96 +
(assert (= 7 (% 20 -13)) "rem 3")
97 +
(assert (= -7 (% -20 -13)) "rem 4")
98 +
; (assert (nan? (% 20 0)) "rem 5")
99 +
100 +
(assert (= 7 (mod 20 13)) "mod 1")
101 +
(assert (= 6 (mod -20 13)) "mod 2")
102 +
(assert (= -6 (mod 20 -13)) "mod 3")
103 +
(assert (= -7 (mod -20 -13)) "mod 4")
104 +
(assert (= 20 (mod 20 0)) "mod 5")
105 +
106 +
(assert (= 7.0 (mod 20.0 13.0)) "float mod 1")
107 +
(assert (= 6.0 (mod -20.0 13.0)) "float mod 2")
108 +
(assert (= -6.0 (mod 20.0 -13.0)) "float mod 3")
109 +
(assert (= -7.0 (mod -20.0 -13.0)) "float mod 4")
110 +
(assert (= 20.0 (mod 20.0 0.0)) "float mod 5")
111 +
112 +
;; Test !=
113 +
(assert (!= 1 1 0) "!= 1 1 0")
114 +
(assert (!= 0 1 1) "!= 0 1 1")
115 +
(assert (not (!= 1 1 1)) "!= 1 1 1")
116 +
117 +
;; Range
118 +
(assert (eq? (range 10) [0 1 2 3 4 5 6 7 8 9]) "(range 10)")
119 +
(assert (eq? (range 5 10) [5 6 7 8 9]) "(range 5 10)")
120 +
(assert (eq? (range 10 5) []) "(range 10 5)")
121 +
(assert (eq? (range 5 5) []) "(range 5 5)")
122 +
(assert (eq? (range 0 16 4) [0 4 8 12]) "(range 0 16 4)")
123 +
(assert (eq? (range 0 17 4) [0 4 8 12 16]) "(range 0 17 4)")
124 +
(assert (eq? (range 16 0 -4) [16 12 8 4]) "(range 16 0 -4)")
125 +
(assert (eq? (range 17 0 -4) [17 13 9 5 1]) "(range 17 0 -4)")
126 +
(assert (eq? (length (range 10)) 10) "(range 10)")
127 +
(assert (eq? (length (range -10)) 0) "(range -10)")
128 +
(assert (eq? (length (range 1 10)) 9) "(range 1 10)")
129 +
130 +
; vim: filetype=lisp
ombre/tests/golden.rs added +23 -0
1 +
#![allow(clippy::unwrap_used)]
2 +
use std::fs;
3 +
4 +
use ombre::lang::error::ErrorExplainer;
5 +
use ombre::lang::*;
6 +
7 +
/// Helper function to run a golden test file.
8 +
fn run<P: AsRef<std::path::Path>>(path: P) {
9 +
    let path = path.as_ref();
10 +
    let content = fs::read_to_string(path).unwrap();
11 +
    let tokens = Scanner::new(&content);
12 +
    let parser = Parser::new(tokens);
13 +
14 +
    match Evaluator::new(parser).eval(&mut Env::default()) {
15 +
        Ok(_) => (),
16 +
        Err(e) => panic!("{}", ErrorExplainer::new(&e, &content, path)),
17 +
    }
18 +
}
19 +
20 +
#[test]
21 +
fn golden_basic() {
22 +
    run("tests/basic.om");
23 +
}