-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlexer.js
83 lines (70 loc) · 1.45 KB
/
lexer.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
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
"use strict";
function Lexer(txt) {
this.txt = txt;
this.idx = 0;
this.idy = 0;
this.val = 0;
this.load(); // initialize
}
Lexer.prototype.load = function() {
if (this.idx < this.txt.length) {
this.val = this.txt.charCodeAt(this.idx);
} else {
this.val = 0;
}
};
Lexer.prototype.read = function() {
this.idx = this.idx + 1;
};
Lexer.prototype.discard = function() {
this.idy = this.idx;
};
Lexer.prototype.length = function() {
return this.idx - this.idy;
};
Lexer.prototype.yield = function() {
var tok = this.txt.substr(this.idy, this.length());
this.discard();
return tok;
};
Lexer.prototype.accept = function(val) {
if (this.val === val) {
this.read();
this.load();
return true;
}
return false;
};
Lexer.prototype.expect = function(val) {
if (!this.accept(val)) {
throw new Error("expected " + String.fromCharCode(val));
}
};
Lexer.prototype.acceptBetween = function(a, b) {
var val = this.val;
if (a <= val && val <= b) {
this.read();
this.load();
return true;
}
return false;
};
Lexer.prototype.acceptWhiteSpace = function() {
var val = this.val;
if (val === 9 || val === 10 || val === 13 || val === 32) {
this.read();
this.load();
return true;
}
return false;
};
Lexer.prototype.not = function(val) {
if (this.val !== 0 && this.val !== val) {
this.read();
this.load();
return true;
}
return false;
};
Lexer.default = Lexer;
module.exports = Lexer;