forked from nickdesaulniers/node-tokenizer
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtokenizer.js
More file actions
64 lines (57 loc) · 1.32 KB
/
tokenizer.js
File metadata and controls
64 lines (57 loc) · 1.32 KB
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
var tokens = [];
var source = '';
var regexQueue = [];
var debugFlag = false;
function logSrc () {
console.log(source);
}
function logTok () {
console.log('Tokens: ' + tokens);
}
exports.__defineSetter__('debug', function (value) {
if (typeof value === 'boolean') debugFlag = value;
});
exports.rule = function (tokenType, re) {
regexQueue.push(function () {
var ret = false;
var result = re.exec(source);
if (result) {
var value = result[0]
if (debugFlag) console.log(tokenType + ' token: ' + value);
var token = {
value,
tokenType
}
tokens.push(token);
source = source.substring(value.length);
ret = true;
}
return ret;
});
}
exports.tokenize = function (src) {
tokens = [];
source = '';
source = src;
if (debugFlag) {
console.log('-- Starting tokenizer --');
logSrc();
console.log('-- --');
}
while (source) {
var foundToken = regexQueue.some(function (element, index, array) {
return element();
});
if (!foundToken) {
console.error('Did not find any tokens on this pass:');
logSrc();
process.exit(1);
}
}
if (debugFlag) {
console.log('-- Tokenizing complete --');
console.log(tokens);
console.log('-- --');
}
return tokens;
}