forked from roerohan/8086.js
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathparser.js
64 lines (57 loc) · 1.61 KB
/
parser.js
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
57
58
59
60
61
62
63
64
/**
* Grammar:
*
* S: ins_2 op_1 op_2
* S: ins_2_1 op_1 [op_2]
* S: ins_1 op_1
* S: ins_1_0 [op_1]
* S: ins_0
*
* ins_2 -> 2 address instruction
* ins_2_1 -> 2 address or 1 address instruction
* ins_1 -> 1 address instruction
* ins_1_0 -> 1 address or 0 address instruction
* ins_0 -> 0 address instruction
*/
import {
SyntaxError,
Instruction,
} from 'emulator/parser/models/index.js';
export default class Parser {
constructor(tokens) {
this.rawInstructions = Parser.getInstructionsFromTokens(tokens);
this.instructions = [];
}
static getInstructionsFromTokens(tokens) {
const instructions = [];
let instruction = [];
tokens.forEach((token) => {
if (token.name === 'NEWLINE') {
if (instruction.length) {
instructions.push(instruction);
}
instruction = [];
} else if (token.name !== 'COMMENT') {
instruction.push(token);
}
});
return instructions;
}
parse() {
this.rawInstructions.forEach((instruction) => {
if (instruction.length > 4) {
throw new SyntaxError();
}
if (instruction.length > 2
&& instruction[2].name !== 'SEPARATOR') {
throw new SyntaxError();
}
this.instructions.push(new Instruction({
mnemonic: instruction[0],
op1: instruction[1] || null,
op2: instruction[3] || null,
}));
});
return this.instructions;
}
}