-
Notifications
You must be signed in to change notification settings - Fork 8
/
Copy pathlex.js
70 lines (55 loc) · 1.59 KB
/
lex.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
/*
This file is part of llang.
llang is MIT licensed. Feel free to use it, contribute or spread the word. Created with love by Petr Nevyhoštěný (Twitter).
*/
module.exports.lex = lex;
function lex(input) {
var pointer = 0;
var tokens = [];
var c;
var operator = '';
while (next()) {
if (isSpecial(c)) {
operator += c;
if (operatorExists(operator)) {
push('operator', operator);
operator = '';
}
}
else {
if (operator.length) unrecognizedToken(operator, pointer - operator.length - 1);
if (isWhiteSpace(c)) continue;
else if (isVariable(c)) push('variable', c.toUpperCase());
else if (isExpressionBoundary(c)) push('boundary', c);
else unrecognizedToken(c, pointer - 2);
}
}
return tokens;
function next() {
return (c = input[pointer++]);
}
function push(type, value) {
tokens.push({
type : type,
value : value
});
}
function isWhiteSpace(c) {
return /\s/.test(c);
}
function isVariable(c) {
return /[A-Za-z]/.test(c);
}
function isSpecial(c) {
return /[<>\-|&!]/.test(c);
}
function isExpressionBoundary(c) {
return /[\(\)]/.test(c);
}
function operatorExists(op) {
return ['!', '|', '&', '->', '<->'].indexOf(op) !== -1;
}
function unrecognizedToken(token, position) {
throw new Error('Unrecognized token "' + token + '" on position ' + position + '!');
}
}