-
Notifications
You must be signed in to change notification settings - Fork 1
/
core.js
73 lines (66 loc) · 1.76 KB
/
core.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
var findMatchingRule = function(rules, text){
var i;
for(i=0; i<rules.length; i++)
if(rules[i].regex.test(text))
return rules[i];
return undefined;
};
var findMaxIndexAndRule = function(rules, text){
var i, rule, last_matching_rule;
for(i=0; i<text.length; i++){
rule = findMatchingRule(rules, text.substring(0, i + 1));
if(rule)
last_matching_rule = rule;
else if(last_matching_rule)
return {max_index: i, rule: last_matching_rule};
}
return last_matching_rule ? {max_index: text.length, rule: last_matching_rule} : undefined;
};
module.exports = function(onToken_orig){
var buffer = "";
var rules = [];
var line = 1;
var col = 1;
var onToken = function(src, type){
onToken_orig({
type: type,
src: src,
line: line,
col: col
});
var lines = src.split("\n");
line += lines.length - 1;
col = (lines.length > 1 ? 1 : col) + lines[lines.length - 1].length;
};
return {
addRule: function(regex, type){
rules.push({regex: regex, type: type});
},
onText: function(text){
var str = buffer + text;
var m = findMaxIndexAndRule(rules, str);
while(m && m.max_index !== str.length){
onToken(str.substring(0, m.max_index), m.rule.type);
//now find the next token
str = str.substring(m.max_index);
m = findMaxIndexAndRule(rules, str);
}
buffer = str;
},
end: function(){
if(buffer.length === 0)
return;
var rule = findMatchingRule(rules, buffer);
if(!rule){
var err = new Error("unable to tokenize");
err.tokenizer2 = {
buffer: buffer,
line: line,
col: col
};
throw err;
}
onToken(buffer, rule.type);
}
};
};