-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathparser.ts
More file actions
56 lines (46 loc) · 1.41 KB
/
parser.ts
File metadata and controls
56 lines (46 loc) · 1.41 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
import type { Lexer } from "./lexer";
import { TokenType, type Token } from "./tokens";
export class Parser {
private tokens: Token[] = [];
private pos: number = 0;
constructor(private lexer: Lexer) {
this.tokenizeAll();
}
private tokenizeAll(): void {
let token: Token | null;
do {
token = this.lexer.nextToken();
this.tokens.push(token);
} while (token.type !== TokenType.EOF);
}
private nextToken(): Token {
if (this.pos < this.tokens.length) {
return this.tokens[this.pos++] ?? { type: TokenType.EOF, value: "" }; //TODO: Will change this to a type error in the future
}
return { type: TokenType.EOF, value: "" };
}
parseAndExecute() {
const messageParts: string[] = [];
let token = this.nextToken();
// I Collect all Word tokens as message parts until a String token is found
while (token.type === TokenType.Word) {
messageParts.push(token.value);
token = this.nextToken();
if (token.type === TokenType.String) {
break;
}
}
if (token.type !== TokenType.String) {
throw new Error("Expected string token");
}
const command = token.value;
if (this.nextToken().type !== TokenType.EOF) {
throw new Error('Extra input after command');
}
if (command === 'print') {
console.log(messageParts.join(' '));
} else {
throw new Error(`Unknown command: ${command}`);
}
}
}