BlueGit

ict rusty-teams

Files

rusty-teams / crates / app / src / render / syntax.rs

syntax.rs

syntax.rs 8.4 KiB Download Raw
1use std::ops::Range;
2
3#[derive(Debug, Clone, Copy, PartialEq, Eq)]
4pub enum Token {
5 Keyword,
6 String,
7 Number,
8 Comment,
9}
10
11struct Grammar {
12 line_comments: &'static [&'static str],
13 block_comment: Option<(&'static str, &'static str)>,
14 keywords: &'static [&'static str],
15 char_quotes: bool,
16}
17
18const C_LIKE_KEYWORDS: &[&str] = &[
19 "abstract",
20 "as",
21 "async",
22 "await",
23 "break",
24 "case",
25 "catch",
26 "class",
27 "const",
28 "continue",
29 "default",
30 "do",
31 "else",
32 "enum",
33 "export",
34 "extends",
35 "false",
36 "final",
37 "finally",
38 "fn",
39 "for",
40 "from",
41 "func",
42 "function",
43 "go",
44 "if",
45 "impl",
46 "import",
47 "in",
48 "interface",
49 "let",
50 "loop",
51 "match",
52 "mod",
53 "mut",
54 "namespace",
55 "new",
56 "null",
57 "override",
58 "package",
59 "private",
60 "protected",
61 "pub",
62 "public",
63 "readonly",
64 "return",
65 "self",
66 "static",
67 "struct",
68 "super",
69 "switch",
70 "this",
71 "throw",
72 "trait",
73 "true",
74 "try",
75 "type",
76 "typeof",
77 "use",
78 "using",
79 "var",
80 "void",
81 "where",
82 "while",
83 "yield",
84];
85const PYTHON_KEYWORDS: &[&str] = &[
86 "and", "as", "async", "await", "break", "class", "continue", "def", "del", "elif", "else",
87 "except", "False", "finally", "for", "from", "if", "import", "in", "is", "lambda", "None",
88 "not", "or", "pass", "raise", "return", "True", "try", "while", "with", "yield",
89];
90const SHELL_KEYWORDS: &[&str] = &[
91 "case", "do", "done", "elif", "else", "esac", "export", "fi", "for", "function", "if", "in",
92 "local", "return", "then", "while",
93];
94const SQL_KEYWORDS: &[&str] = &[
95 "and", "as", "by", "create", "delete", "from", "group", "insert", "into", "join", "left",
96 "not", "null", "on", "or", "order", "select", "set", "table", "update", "values", "where",
97];
98
99const C_LIKE: Grammar = Grammar {
100 line_comments: &["//"],
101 block_comment: Some(("/*", "*/")),
102 keywords: C_LIKE_KEYWORDS,
103 char_quotes: false,
104};
105const CHAR_LIKE: Grammar = Grammar {
106 char_quotes: true,
107 ..C_LIKE
108};
109const HASH: Grammar = Grammar {
110 line_comments: &["#"],
111 block_comment: None,
112 keywords: PYTHON_KEYWORDS,
113 char_quotes: false,
114};
115const SHELL: Grammar = Grammar {
116 line_comments: &["#"],
117 block_comment: None,
118 keywords: SHELL_KEYWORDS,
119 char_quotes: false,
120};
121const SQL: Grammar = Grammar {
122 line_comments: &["--"],
123 block_comment: Some(("/*", "*/")),
124 keywords: SQL_KEYWORDS,
125 char_quotes: false,
126};
127const MARKUP: Grammar = Grammar {
128 line_comments: &[],
129 block_comment: Some(("<!--", "-->")),
130 keywords: &[],
131 char_quotes: false,
132};
133
134fn grammar_for(language: &str) -> Option<&'static Grammar> {
135 match language.to_ascii_lowercase().as_str() {
136 "rust" | "rs" | "c" | "cpp" | "c++" | "csharp" | "cs" | "c#" | "java" | "go" | "kotlin"
137 | "scala" => Some(&CHAR_LIKE),
138 "javascript" | "js" | "jsx" | "typescript" | "ts" | "tsx" | "swift" | "php" | "json"
139 | "css" | "scss" | "less" | "dart" => Some(&C_LIKE),
140 "python" | "py" | "ruby" | "rb" | "yaml" | "yml" | "toml" | "r" | "perl" | "dockerfile"
141 | "makefile" => Some(&HASH),
142 "bash" | "sh" | "shell" | "zsh" | "powershell" | "ps1" => Some(&SHELL),
143 "sql" | "tsql" | "plsql" | "lua" => Some(&SQL),
144 "html" | "xml" | "svg" | "markdown" | "md" => Some(&MARKUP),
145 _ => None,
146 }
147}
148
149pub fn highlight(code: &str, language: &str) -> Option<Vec<(Range<usize>, Token)>> {
150 let grammar = grammar_for(language)?;
151 let sql = grammar.keywords == SQL_KEYWORDS;
152 let mut tokens = Vec::new();
153 let mut index = 0;
154 while index < code.len() {
155 let rest = &code[index..];
156 if let Some((open, close)) = grammar.block_comment
157 && rest.starts_with(open)
158 {
159 let end = rest[open.len()..].find(close).map_or(code.len(), |offset| {
160 index + open.len() + offset + close.len()
161 });
162 tokens.push((index..end, Token::Comment));
163 index = end;
164 continue;
165 }
166 if grammar
167 .line_comments
168 .iter()
169 .any(|marker| rest.starts_with(marker))
170 {
171 let end = rest.find('\n').map_or(code.len(), |offset| index + offset);
172 tokens.push((index..end, Token::Comment));
173 index = end;
174 continue;
175 }
176 let character = rest.chars().next().unwrap_or_default();
177 if character == '\'' && grammar.char_quotes && !is_char_literal(rest) {
178 index += 1;
179 continue;
180 }
181 if matches!(character, '"' | '\'' | '`') {
182 let end = string_end(code, index, character);
183 tokens.push((index..end, Token::String));
184 index = end;
185 continue;
186 }
187 if character.is_ascii_digit() {
188 let length = rest
189 .find(|next: char| !(next.is_ascii_alphanumeric() || next == '.' || next == '_'))
190 .unwrap_or(rest.len());
191 tokens.push((index..index + length, Token::Number));
192 index += length;
193 continue;
194 }
195 if character.is_alphabetic() || character == '_' {
196 let length = rest
197 .find(|next: char| !(next.is_alphanumeric() || next == '_'))
198 .unwrap_or(rest.len());
199 let word = &rest[..length];
200 let is_keyword = if sql {
201 grammar
202 .keywords
203 .iter()
204 .any(|keyword| keyword.eq_ignore_ascii_case(word))
205 } else {
206 grammar.keywords.contains(&word)
207 };
208 if is_keyword {
209 tokens.push((index..index + length, Token::Keyword));
210 }
211 index += length;
212 continue;
213 }
214 index += character.len_utf8();
215 }
216 Some(tokens)
217}
218
219fn is_char_literal(rest: &str) -> bool {
220 let mut characters = rest.chars().skip(1);
221 match characters.next() {
222 Some('\\') => characters.take(9).any(|character| character == '\''),
223 Some('\n') | None => false,
224 Some(_) => characters.next() == Some('\''),
225 }
226}
227
228fn string_end(code: &str, start: usize, quote: char) -> usize {
229 let mut escaped = false;
230 for (offset, character) in code[start + quote.len_utf8()..].char_indices() {
231 if character == '\n' && quote != '`' {
232 return start + quote.len_utf8() + offset;
233 }
234 if escaped {
235 escaped = false;
236 } else if character == '\\' {
237 escaped = true;
238 } else if character == quote {
239 return start + quote.len_utf8() + offset + character.len_utf8();
240 }
241 }
242 code.len()
243}
244
245#[cfg(test)]
246mod tests {
247 use super::*;
248
249 fn kinds<'a>(code: &'a str, language: &str) -> Vec<(&'a str, Token)> {
250 highlight(code, language)
251 .unwrap()
252 .into_iter()
253 .map(|(range, token)| (&code[range], token))
254 .collect()
255 }
256
257 #[test]
258 fn rust_keywords_strings_and_comments() {
259 assert_eq!(
260 kinds("// x\nfn a() { \"b\" }", "rust"),
261 vec![
262 ("// x", Token::Comment),
263 ("fn", Token::Keyword),
264 ("\"b\"", Token::String),
265 ]
266 );
267 }
268
269 #[test]
270 fn escaped_quote_stays_in_string() {
271 assert_eq!(kinds(r#""a\"b" 1"#, "js")[0].0, r#""a\"b""#);
272 }
273
274 #[test]
275 fn unterminated_string_stops_at_line_end() {
276 assert_eq!(
277 kinds("x = 'abc\nreturn", "python"),
278 vec![("'abc", Token::String), ("return", Token::Keyword)]
279 );
280 }
281
282 #[test]
283 fn rust_lifetime_is_not_a_string() {
284 assert_eq!(
285 kinds("fn a<'b>(x: &'b str) -> char { 'c' }", "rust"),
286 vec![("fn", Token::Keyword), ("'c'", Token::String),]
287 );
288 assert_eq!(kinds(r"'\n'", "rust"), vec![(r"'\n'", Token::String)]);
289 }
290
291 #[test]
292 fn sql_keywords_ignore_case() {
293 assert_eq!(kinds("SELECT 1", "sql")[0], ("SELECT", Token::Keyword));
294 }
295
296 #[test]
297 fn unknown_language_has_no_highlight() {
298 assert!(highlight("x", "brainfuck").is_none());
299 }
300
301 #[test]
302 fn identifier_with_digits_is_not_a_number() {
303 assert!(kinds("let x1 = 2;", "rust").contains(&("2", Token::Number)));
304 assert!(
305 !kinds("let x1 = 2;", "rust")
306 .iter()
307 .any(|(text, _)| *text == "1")
308 );
309 }
310}