Throw error for unknown labels

This commit is contained in:
Rene Saarsoo 2020-09-22 21:34:21 +03:00
parent 45467a434f
commit d998caf91d
2 changed files with 22 additions and 15 deletions

View File

@ -46,6 +46,15 @@ Description:
`);
});
it("throws error for unknown labels", () => {
expect(() =>
parse(`
Name: Strange workout
Level: Advanced
`),
).toThrowErrorMatchingInlineSnapshot(`"Unknown label \\"Level:\\" at line 3 char 1"`);
});
it("parses basic intervals", () => {
expect(
parse(`

View File

@ -117,22 +117,14 @@ const tokenizeComment = (line: string, row: number): Token[] | undefined => {
];
};
const tokenizeRule = (line: string, row: number): Token[] => {
const commentTokens = tokenizeComment(line, row);
if (commentTokens) {
return commentTokens;
const tokenizeLabelToken = (line: string, row: number): Token[] | undefined => {
const [, label, separator, paramString] = line.match(/^(\w+)(:\s*)(.*?)\s*$/) || [];
if (!label) {
return undefined;
}
const matches = line.match(/^(\w+)(:\s*)(.*?)\s*$/);
if (!matches) {
return [{ type: "text", value: line.trim(), loc: { row, col: 0 } }];
if (!isLabelTokenValue(label)) {
throw new ParseError(`Unknown label "${label}:"`, { row, col: 0 });
}
if (!isLabelTokenValue(matches[1])) {
return [{ type: "text", value: line.trim(), loc: { row, col: 0 } }];
}
const [, label, separator, paramString] = matches;
const labelToken: LabelToken = {
type: "label",
value: label as LabelTokenValue,
@ -142,10 +134,16 @@ const tokenizeRule = (line: string, row: number): Token[] => {
row,
col: label.length + separator.length,
});
return [labelToken, ...params];
};
const tokenizeRule = (line: string, row: number): Token[] => {
return (
tokenizeLabelToken(line, row) ||
tokenizeComment(line, row) || [{ type: "text", value: line.trim(), loc: { row, col: 0 } }]
);
};
export const tokenize = (file: string): Token[] => {
const tokens: Token[] = [];