lexer.rs 8.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284
  1. /* This file is part of DarkFi (https://dark.fi)
  2. *
  3. * Copyright (C) 2020-2024 Dyne.org foundation
  4. *
  5. * This program is free software: you can redistribute it and/or modify
  6. * it under the terms of the GNU Affero General Public License as
  7. * published by the Free Software Foundation, either version 3 of the
  8. * License, or (at your option) any later version.
  9. *
  10. * This program is distributed in the hope that it will be useful,
  11. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  12. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  13. * GNU Affero General Public License for more details.
  14. *
  15. * You should have received a copy of the GNU Affero General Public License
  16. * along with this program. If not, see <https://www.gnu.org/licenses/>.
  17. */
  18. use std::{io::Result, str::Chars};
  19. use super::error::ErrorEmitter;
  20. const SPECIAL_CHARS: [char; 9] = ['{', '}', '(', ')', '[', ']', ',', ';', '='];
  21. fn is_letter(ch: char) -> bool {
  22. ch.is_ascii_lowercase() || ch.is_ascii_uppercase() || ch == '_'
  23. }
  24. fn is_digit(ch: char) -> bool {
  25. ch.is_ascii_digit()
  26. }
  27. #[derive(Copy, Clone, PartialEq, Eq, Debug)]
  28. pub enum TokenType {
  29. Symbol,
  30. String,
  31. Number,
  32. LeftBrace,
  33. RightBrace,
  34. LeftParen,
  35. RightParen,
  36. LeftBracket,
  37. RightBracket,
  38. Comma,
  39. Semicolon,
  40. Assign,
  41. }
  42. #[derive(Clone, Debug)]
  43. pub struct Token {
  44. pub token: String,
  45. pub token_type: TokenType,
  46. pub line: usize,
  47. pub column: usize,
  48. }
  49. impl Token {
  50. fn new(token: &str, token_type: TokenType, line: usize, column: usize) -> Self {
  51. Self { token: token.to_string(), token_type, line, column }
  52. }
  53. }
  54. pub struct Lexer<'a> {
  55. source: Chars<'a>,
  56. error: ErrorEmitter,
  57. }
  58. impl<'a> Lexer<'a> {
  59. pub fn new(filename: &str, source: Chars<'a>) -> Self {
  60. // For nice error reporting, we'll load everything into a string
  61. // vector so we have references to lines.
  62. let lines: Vec<String> = source.as_str().lines().map(|x| x.to_string()).collect();
  63. let error = ErrorEmitter::new("Lexer", filename, lines);
  64. Self { source, error }
  65. }
  66. pub fn lex(&self) -> Result<Vec<Token>> {
  67. let mut tokens = vec![];
  68. let mut lineno = 1;
  69. let mut column = 0;
  70. // We use this as a buffer to store a single token, which is then
  71. // reset after a token is pushed to the returning vec.
  72. let mut buf = String::new();
  73. // We use these to keep state when iterating.
  74. let mut in_comment = false;
  75. let mut in_string = false;
  76. let mut in_number = false;
  77. let mut in_symbol = false;
  78. macro_rules! new_symbol {
  79. () => {
  80. tokens.push(Token::new(&buf, TokenType::Symbol, lineno, column - buf.len()));
  81. in_symbol = false;
  82. buf = String::new();
  83. };
  84. }
  85. macro_rules! new_string {
  86. () => {
  87. tokens.push(Token::new(&buf, TokenType::String, lineno, column - buf.len()));
  88. in_string = false;
  89. buf = String::new();
  90. };
  91. }
  92. macro_rules! new_number {
  93. () => {
  94. tokens.push(Token::new(&buf, TokenType::Number, lineno, column - buf.len()));
  95. in_number = false;
  96. buf = String::new();
  97. };
  98. }
  99. #[allow(clippy::explicit_counter_loop)]
  100. for c in self.source.clone() {
  101. column += 1;
  102. if c == '\n' {
  103. if in_symbol {
  104. new_symbol!();
  105. }
  106. if in_string {
  107. return Err(self.error.abort("Strings can't contain newlines", lineno, column))
  108. }
  109. if in_number {
  110. return Err(self.error.abort("Numbers can't contain newlines", lineno, column))
  111. }
  112. in_comment = false;
  113. lineno += 1;
  114. column = 0;
  115. continue
  116. }
  117. if c == '#' || in_comment {
  118. if in_symbol {
  119. new_symbol!();
  120. }
  121. if in_number {
  122. new_number!();
  123. }
  124. if in_string {
  125. buf.push(c);
  126. continue
  127. }
  128. in_comment = true;
  129. continue
  130. }
  131. if c.is_whitespace() {
  132. if in_symbol {
  133. new_symbol!();
  134. }
  135. if in_number {
  136. new_number!();
  137. }
  138. if in_string {
  139. // For now we forbid whitespace in strings.
  140. return Err(self.error.abort(
  141. "Strings/Namespaces can't contain whitespace",
  142. lineno,
  143. column,
  144. ))
  145. }
  146. continue
  147. }
  148. // Main cases, in_comment is already checked above.
  149. if !in_number && !in_symbol && !in_string && is_digit(c) {
  150. in_number = true;
  151. buf.push(c);
  152. continue
  153. }
  154. if in_number && !is_digit(c) {
  155. new_number!();
  156. }
  157. if in_number && is_digit(c) {
  158. buf.push(c);
  159. continue
  160. }
  161. if !in_number && !in_symbol && !in_string && is_letter(c) {
  162. in_symbol = true;
  163. buf.push(c);
  164. continue
  165. }
  166. if !in_number && !in_symbol && !in_string && c == '"' {
  167. // " I need to fix my Rust vis lexer
  168. in_string = true;
  169. continue
  170. }
  171. if (in_symbol || in_string) && (is_letter(c) || is_digit(c)) {
  172. buf.push(c);
  173. continue
  174. }
  175. if in_string && c == '"' {
  176. // " I need to fix my vis lexer
  177. if buf.is_empty() {
  178. return Err(self.error.abort("String cannot be empty", lineno, column))
  179. }
  180. new_string!();
  181. continue
  182. }
  183. if SPECIAL_CHARS.contains(&c) {
  184. if in_symbol {
  185. new_symbol!();
  186. }
  187. if in_number {
  188. new_number!();
  189. }
  190. if in_string {
  191. // TODO: Perhaps forbid these chars inside strings.
  192. }
  193. match c {
  194. '{' => {
  195. tokens.push(Token::new("{", TokenType::LeftBrace, lineno, column));
  196. continue
  197. }
  198. '}' => {
  199. tokens.push(Token::new("}", TokenType::RightBrace, lineno, column));
  200. continue
  201. }
  202. '(' => {
  203. tokens.push(Token::new("(", TokenType::LeftParen, lineno, column));
  204. continue
  205. }
  206. ')' => {
  207. tokens.push(Token::new(")", TokenType::RightParen, lineno, column));
  208. continue
  209. }
  210. '[' => {
  211. tokens.push(Token::new("[", TokenType::LeftBracket, lineno, column));
  212. continue
  213. }
  214. ']' => {
  215. tokens.push(Token::new("]", TokenType::RightBracket, lineno, column));
  216. continue
  217. }
  218. ',' => {
  219. tokens.push(Token::new(",", TokenType::Comma, lineno, column));
  220. continue
  221. }
  222. ';' => {
  223. tokens.push(Token::new(";", TokenType::Semicolon, lineno, column));
  224. continue
  225. }
  226. '=' => {
  227. tokens.push(Token::new("=", TokenType::Assign, lineno, column));
  228. continue
  229. }
  230. _ => {
  231. return Err(self.error.abort(
  232. &format!("Invalid token `{}`", c),
  233. lineno,
  234. column - 1,
  235. ))
  236. }
  237. }
  238. }
  239. return Err(self.error.abort(&format!("Invalid token `{}`", c), lineno, column - 1))
  240. }
  241. Ok(tokens)
  242. }
  243. }