Disallow reserved identifiers in variable names

main
Alex Bethel 2022-08-10 14:20:13 -05:00
parent dcab42d0b3
commit a88a037495
1 changed files with 26 additions and 1 deletions

View File

@ -5,7 +5,7 @@ use std::{error::Error, fmt::Display};
use chumsky::{
prelude::{choice, end, just, none_of, one_of, Simple},
recursive::recursive,
text::{ident, int, keyword, whitespace},
text::{int, keyword, whitespace},
Parser,
};
@ -213,6 +213,21 @@ impl Default for ParserMeta {
}
}
/// The list of reserved words that cannot be used as identifiers in AlexScript.
#[rustfmt::skip] // keep this on separate lines for sorting
pub const RESERVED: &'static [&'static str] = &[
"_",
"class",
"data",
"def",
"fn",
"in",
"instance",
"let",
"match",
"type",
];
/// Parser for AlexScript code.
pub fn parser<'a>(m: &'a ParserMeta) -> impl Parser<char, SyntaxTree, Error = Simple<char>> + 'a {
whitespace_cmt().ignore_then(
@ -766,6 +781,16 @@ fn pad<T>(
p.then_ignore(whitespace_cmt())
}
fn ident() -> impl Parser<char, String, Error = Simple<char>> + Clone {
chumsky::text::ident().try_map(|i: String, span| {
if RESERVED.contains(&(&i as &str)) {
Err(Simple::custom(span, format!("reserved identifer \"{i}\"")))
} else {
Ok(i)
}
})
}
#[cfg(test)]
mod tests {
use super::*;