From c6f60748e25c707a2eb210b30cd3dd7d8c9a05b3 Mon Sep 17 00:00:00 2001 From: PaddiM8 Date: Tue, 9 Jun 2020 14:59:29 +0200 Subject: [PATCH] Made the `x_1` notation possible. --- .gitignore | 1 + kalk/src/lexer.rs | 12 +++++++++++- kalk_cli/src/repl.rs | 4 ++-- 3 files changed, 14 insertions(+), 3 deletions(-) diff --git a/.gitignore b/.gitignore index 03bf9d4..103cab8 100644 --- a/.gitignore +++ b/.gitignore @@ -1,2 +1,3 @@ */target kalk/Cargo.lock +kalk_cli/test diff --git a/kalk/src/lexer.rs b/kalk/src/lexer.rs index c2678f7..4e0f4ad 100644 --- a/kalk/src/lexer.rs +++ b/kalk/src/lexer.rs @@ -140,12 +140,22 @@ impl<'a> Lexer<'a> { fn next_identifier(&mut self) -> Token { let start = self.index; let mut end = start; - let letter_reg = regex::Regex::new(r"[A-z']").unwrap(); + let letter_reg = regex::Regex::new(r"[A-z'_]").unwrap(); let mut value = String::new(); while is_valid_identifier(self.peek()) { let c = *self.peek().unwrap(); + // If the current character is an underscore, expect a number next. + // This is to allow the notation like the following: x_1 + if c == '_' { + self.advance(); + let num = self.next_number_literal().value; + value.push('_'); + value.push_str(&num.trim_end()); // Trim, since the number_literal function allows whitespace, which identifiers should not contain. + break; + } + // Only allow identifiers with a special character to have *one* character. No more. // Break the loop if it isn't the first run and the current character is a special character. if end - start > 0 && !letter_reg.is_match(&c.to_string()) { diff --git a/kalk_cli/src/repl.rs b/kalk_cli/src/repl.rs index a8ff3c2..82d491d 100644 --- a/kalk_cli/src/repl.rs +++ b/kalk_cli/src/repl.rs @@ -54,9 +54,9 @@ impl Highlighter for LineHighlighter { fn highlight<'l>(&self, line: &'l str, _: usize) -> Cow<'l, str> { let mut coloured = line.to_string(); - let reg = Regex::new(r"([A-z]+|[\+-/\*\^!])").unwrap(); + let reg = Regex::new(r"(([^0-9\.,\(\)=\+-/\*\^!_]+(_\d+)?)|[\+-/\*\^!])").unwrap(); let unit = Regex::new(r"(deg|rad)").unwrap(); - let identifier = Regex::new(r"[^0-9\.,\(\)=\+-/\*\^!]+").unwrap(); + let identifier = Regex::new(r"[^0-9\.,\(\)=\+-/\*\^!_]+(_\d+)?").unwrap(); let op = Regex::new(r"[\+-/\*\^!]+").unwrap(); coloured = reg