[IMP] compiler: improve error message for tokenization errors

This commit is contained in:
Samuel Degueldre
2022-03-08 09:37:09 +01:00
committed by Géry Debongnie
parent e4fdd32f22
commit 14d2328c88
2 changed files with 24 additions and 18 deletions
+12 -6
View File
@@ -199,15 +199,18 @@ const TOKENIZERS = [
export function tokenize(expr: string): Token[] { export function tokenize(expr: string): Token[] {
const result: Token[] = []; const result: Token[] = [];
let token: boolean | Token = true; let token: boolean | Token = true;
let error: any;
let current = expr;
try {
while (token) { while (token) {
expr = expr.trim(); current = current.trim();
if (expr) { if (current) {
for (let tokenizer of TOKENIZERS) { for (let tokenizer of TOKENIZERS) {
token = tokenizer(expr); token = tokenizer(current);
if (token) { if (token) {
result.push(token); result.push(token);
expr = expr.slice(token.size || token.value.length); current = current.slice(token.size || token.value.length);
break; break;
} }
} }
@@ -215,8 +218,11 @@ export function tokenize(expr: string): Token[] {
token = false; token = false;
} }
} }
if (expr.length) { } catch (e) {
throw new Error(`Tokenizer error: could not tokenize "${expr}"`); error = e; // Silence all errors and throw a generic error below
}
if (current.length || error) {
throw new Error(`Tokenizer error: could not tokenize \`${expr}\``);
} }
return result; return result;
} }
+5 -5
View File
@@ -65,14 +65,14 @@ describe("tokenizer", () => {
}); });
test("strings", () => { test("strings", () => {
expect(() => tokenize("'")).toThrow("Invalid expression"); expect(() => tokenize("'")).toThrow("Tokenizer error: could not tokenize `'`");
expect(() => tokenize("'\\")).toThrow("Invalid expression"); expect(() => tokenize("'\\")).toThrow("Tokenizer error: could not tokenize `'\\`");
expect(() => tokenize("'\\'")).toThrow("Invalid expression"); expect(() => tokenize("'\\'")).toThrow("Tokenizer error: could not tokenize `'\\'`");
expect(tokenize("'hello ged'")).toEqual([{ type: "VALUE", value: "'hello ged'" }]); expect(tokenize("'hello ged'")).toEqual([{ type: "VALUE", value: "'hello ged'" }]);
expect(tokenize("'hello \\'ged\\''")).toEqual([{ type: "VALUE", value: "'hello \\'ged\\''" }]); expect(tokenize("'hello \\'ged\\''")).toEqual([{ type: "VALUE", value: "'hello \\'ged\\''" }]);
expect(() => tokenize('"')).toThrow("Invalid expression"); expect(() => tokenize('"')).toThrow('Tokenizer error: could not tokenize `"`');
expect(() => tokenize('"\\"')).toThrow("Invalid expression"); expect(() => tokenize('"\\"')).toThrow('Tokenizer error: could not tokenize `"\\"`');
expect(tokenize('"hello ged"')).toEqual([{ type: "VALUE", value: '"hello ged"' }]); expect(tokenize('"hello ged"')).toEqual([{ type: "VALUE", value: '"hello ged"' }]);
expect(tokenize('"hello ged"}')).toEqual([ expect(tokenize('"hello ged"}')).toEqual([
{ type: "VALUE", value: '"hello ged"' }, { type: "VALUE", value: '"hello ged"' },