Debian Codegraph @

frontend/src/codemirror/bql-stream-parser.ts

raw
1 import type { StreamParser, StringStream } from "@codemirror/language";
2
3 // Import the autogenerated (by a script in the 'contrib' directory) lists
4 import grammar from "./bql-grammar";
5
6 const keywords = new Set(grammar.keywords);
7 const columns = new Set(grammar.columns);
8 const functions = new Set(grammar.functions);
9
10 // This should match the grammar defined in Beancount (`query/query_parser.py`).
11 const string = /^("[^"]*"|'[^']*')/;
12 const date = /^(?:#(?:"[^"]*"|'[^']*')|\d\d\d\d-\d\d-\d\d)/;
13 const decimal = /^[-+]?([0-9]+\.[0-9]*|[0-9]*\.[0-9]+)/;
14 const integer = /^[-+]?[0-9]+/;
15
16 // Check for matches - convert the response of StringStream.match into a boolean explicitly
17 const m = (s: StringStream, p: RegExp) => {
18 const match = s.match(p);
19 return match != null && match !== false;
20 };
21
22 export const bqlStreamParser: StreamParser<unknown> = {
23 token(stream) {
24 if (stream.eatSpace() || stream.eol()) {
25 return null;
26 }
27 if (m(stream, string)) {
28 return "string";
29 }
30 if (m(stream, date) || m(stream, decimal) || m(stream, integer)) {
31 return "number";
32 }
33 if (m(stream, /\w+/)) {
34 const word = stream.current().toLowerCase();
35 if (keywords.has(word)) {
36 return "keyword";
37 }
38 if (columns.has(word)) {
39 return "typeName";
40 }
41 if (functions.has(word) && stream.peek() === "(") {
42 return "macroName";
43 }
44 return "name";
45 }
46 // Skip one character since no known token matched.
47 const char = stream.next();
48 if (char === "*") {
49 return "typeName";
50 }
51 return null;
52 },
53 };