-
Notifications
You must be signed in to change notification settings - Fork 70
/
Copy pathinputstream.js
52 lines (42 loc) · 1.26 KB
/
inputstream.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
const constants = require("./constants.js");
const fs = require("fs");
class InputStream {
constructor (fileName) {
this.code = this.readProgramFile(fileName);
this.line = 1;
this.column = 0;
this.position = 0;
this.fileName = fileName;
}
readProgramFile (fileName) {
try {
return fs.readFileSync(process.cwd() + "/" + fileName, "utf8");
} catch (e) {
throw new Error(`Could not read file: ${fileName}`);
}
}
// return the next value and also discard it from the stream
next () {
const character = this.code.charAt(this.position++);
if (character === constants.SYM.NEW_LINE) {
this.column = 0; this.line++;
} else {
this.column++;
}
return character;
}
// return the next value without discarding it from the stream
peek () {
return this.code.charAt(this.position);
}
throwError (msg) {
throw new Error(`There's an error at line ${this.line} near column ${this.column} in file ${this.fileName} :\n ${msg}`);
}
isEndOfFile () {
return this.peek() === "";
}
isNotEndOfFile () {
return this.peek() !== "";
}
}
module.exports = InputStream;