-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathindex.ts
187 lines (155 loc) · 5.57 KB
/
index.ts
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
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
import * as stream from 'stream';
import * as util from 'util';
import * as makeError from 'make-error';
import { StringDecoder } from 'string_decoder';
export type Action = (match: string, pos: number) => Promise<void>;
export interface Rule {
re: string;
action: Action;
}
export type Rules = Rule[];
export class RuleError extends makeError.BaseError {
constructor(private msg_: string,
readonly ruleIndex: string,
readonly char: number) { super(); }
readonly name: string = "RuleError";
public get message(): string {
return this.name + ": rule " + this.ruleIndex + ", position " + this.char + ": " + this.msg_;
}
}
function checkRules(rules: Rules) {
for (const i in rules) {
const r = rules[i]
const re = new RegExp(r.re); //Does this ever throw?
if ((typeof r.action) !== 'function') {
throw new Error("Action is not a function for rule " + i + "(" + r.re + ")");
}
// No capturing parentheses in re
const m = /[^\\]\([^?][^:]/.exec(r.re); // /[^\\]\([^?][^:]/.exec(r.re);
if (m) {
throw new RuleError("capturing parentheses forbidden: " + m[0], i, m.index);
}
}
}
export class LexError extends makeError.BaseError {
constructor(public readonly msg: string,
public readonly start: number,
public readonly end?: number,
public readonly text?: string) {
super(LexError.makeMessage(msg, start, end, text));
}
private static makeMessage(msg: string, start: number, end?: number, text?: string) {
let ret = msg + ": ";
let dets: { start: number, end?: number, text?: string } = { start: start };
if (end) {
dets.end = end;
}
if (text) {
dets.text = text;
}
return ret + JSON.stringify(dets);
}
}
export interface LexOptions {
aggregateUntil?: number;
encoding?: string;
}
export interface Lexer {
lex(ins: stream.Readable, options?: LexOptions): Promise<void>
regexString(): string; //Regex being used to lex
}
async function processChunk(exp: RegExp, rules: Rules, offset: number, s: string): Promise<number> {
let m = null;
do {
let oldIndex = exp.lastIndex;
m = exp.exec(s);
if (!m) {
return oldIndex;
}
if (m.index != oldIndex) {
throw new LexError("No rule matched",
oldIndex + offset,
m.index + offset,
s.slice(oldIndex, m.index));
}
//We have a match, find out which rule matched
for (let i = 0; i < rules.length; i++) {
if (m[i + 1] !== undefined) {
await rules[i].action(m[i + 1], m.index + offset);
break;
}
}
} while (m && exp.lastIndex != s.length);
return exp.lastIndex;
}
function dataStream(ins: stream.Readable, f: (data: Buffer) => Promise<void>) {
const ret = new Promise((resolve, reject) => {
ins.on('data', (chunk: Buffer) => {
(async () => {
ins.pause(); //This blocks data and end events
try {
await f(chunk);
} catch (e) {
reject(e);
}
ins.resume();
})();
});
ins.on('end', () => resolve());
});
return ret;
}
class LexerImpl implements Lexer {
private expStr_: string;
constructor(private rules_: Rules) {
//FIXME(manishv) deep copy rules here so that user cannot change them and screw up the lexer
this.expStr_ = rules_.map((r) => '(' + r.re + ')').join('|');
}
//aggregateUntil is characters not bytes, relevant for multi-byte UTF-8
async lex(ins: stream.Readable, optionsIn?: LexOptions): Promise<void> {
const options: LexOptions = Object.assign({}, {
aggregateUntil: 1024,
encoding: 'utf-8'
}, optionsIn);
//Create a new state (e.g., string decoder, RegExp) so this function is re-entrant
const exp = new RegExp(this.expStr_, "g");
const rules = this.rules_;
const decode = new StringDecoder(options.encoding);
let buf = "";
let offset = 0;
await dataStream(ins, async (chunk: Buffer) => {
const newChars = decode.write(chunk);
if ((chunk.length > 0) && (newChars.length == 0)) {
return;
}
buf += newChars;
//We must wait until the full aggregateUntil limit
//to ensure the largest possible token matches.
if(buf.length < options.aggregateUntil) {
return;
}
exp.lastIndex = 0; //parse from start of buf
let consumed = await processChunk(exp, rules, offset, buf);
buf = buf.slice(consumed);
offset += consumed;
if (buf.length >= options.aggregateUntil) {
throw new LexError("No rule matched", offset, offset + buf.length, buf);
}
});
if(buf.length > 0) {
//Process any trailing chunk < aggregateUntil size
let consumed = await processChunk(exp, rules, offset, buf);
buf = buf.slice(consumed);
offset += consumed;
}
if (buf.length === 0) {
return;
}
throw new LexError("No rule matched at end of data", offset, offset + buf.length, buf);
}
regexString() { return this.expStr_; }
}
export function create(rules: Rules): Lexer {
checkRules(rules);
return new LexerImpl(rules);
}