-
-
Notifications
You must be signed in to change notification settings - Fork 3
/
reader.spice
81 lines (71 loc) · 1.62 KB
/
reader.spice
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
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
// Std imports
import "std/io/filepath";
import "std/io/file";
import "std/type/error";
import "std/os/os";
// Own imports
import "../reader/code-loc";
public type Reader struct {
File file
string filename
char curChar = '\0'
CodeLoc curCodeLoc
}
public p Reader.ctor(string inputFileName) {
this.filename = inputFileName;
this.curCodeLoc = CodeLoc(1l, 0l, inputFileName);
// Open the file input stream
Result<File> result = openFile(inputFileName, MODE_READ);
if !result.isOk() {
panic(Error("Source file cannot be opened"));
}
this.file = result.unwrap();
// Read the first character
this.advance();
}
/**
* Get the previously read character
*
* @return char Last character
*/
public inline f<char> Reader.getChar() {
return this.curChar;
}
/**
* Get the code location of the previously read character
*
* @return CodeLoc Code location
*/
public inline f<CodeLoc&> Reader.getCodeLoc() {
return this.curCodeLoc;
}
/**
* Advance the reader by one character
*/
public p Reader.advance() {
assert !this.isEOF();
this.curChar = this.file.readChar();
if this.curChar == '\n' {
this.curCodeLoc.line++;
this.curCodeLoc.col = 0l;
} else {
this.curCodeLoc.col++;
}
}
/**
* Advance the reader by one character and check if this char equals the expected.
*
* @param c Expected char
*/
public inline p Reader.expect(char c) {
assert this.curChar == c;
this.advance();
}
/**
* Check if we are at the end of the input file
*
* @return At the end or not
*/
public inline f<bool> Reader.isEOF() {
return this.file.isEOF();
}