-
Notifications
You must be signed in to change notification settings - Fork 5
/
check.js
108 lines (98 loc) · 3.04 KB
/
check.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
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
var util = require("zed/util");
/**
* inputs: text
*/
module.exports = function(info) {
var text = info.inputs.text;
var brackets = info.brackets;
var skip = info.skip || [];
var error;
var stack = [];
for (var i = 0; i < text.length; i++) {
skipper();
var ch = text[i];
if (isOpenBracket(ch)) {
stack.push(ch);
} else if (isCloseBracket(ch)) {
var closingBracket = getCloseBracket(stack[stack.length - 1]);
if (ch !== closingBracket) {
error = util.indexToPos(text, i);
error.endColumn = error.column + 1;
error.type = "error";
if(closingBracket) {
error.text = "Invalid closing bracket, expected: " + closingBracket;
} else {
error.text = "Closing bracket unexpected";
}
return [error];
} else {
stack.pop();
}
}
}
if(stack.length !== 0) {
error = util.indexToPos(text, i);
error.endColumn = error.column + 1;
error.type = "error";
error.text = "Still expecting: " + stack.map(getCloseBracket).join(", ");
return [error];
}
return [];
function skipper() {
skip.forEach(function(s) {
var start = s[0];
var end = s[1];
for(var j = 0; j < start.length; j++) {
if(text[i + j] !== start[j]) {
return;
}
}
// Still here? Good! Let's get skippin'
i += start.length;
// Now let's find the end
for(j = []; Math.max.apply(null, j) < end.length && i < text.length; increment(j), i++) {
//if (j.length > 0) console.log("Looking at", text[i], j, end);
var k = 0;
//Check that all current positions are valid
while (k < j.length) {
if(text[i] !== end[j[k]]) {
// remove invalid ones
j.splice(k, 1);
} else {
k++;
}
}
// Add a new iterator
if (text[i] === end[0]) j.push(0);
}
});
}
function increment(j) {
for (var k = 0; k < j.length; k++) {
j[k] = j[k] + 1;
}
}
function isOpenBracket(ch) {
for (var i = 0; i < brackets.length; i++) {
if (ch === brackets[i][0]) {
return true;
}
}
return false;
}
function isCloseBracket(ch) {
for (var i = 0; i < brackets.length; i++) {
if (ch === brackets[i][1]) {
return true;
}
}
return false;
}
function getCloseBracket(ch) {
for (var i = 0; i < brackets.length; i++) {
if (ch === brackets[i][0]) {
return brackets[i][1];
}
}
}
};