error.js
2.59 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
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
var createCustomError = require('../utils/createCustomError');
var generate = require('../definition-syntax/generate');
function fromMatchResult(matchResult) {
var tokens = matchResult.tokens;
var longestMatch = matchResult.longestMatch;
var node = longestMatch < tokens.length ? tokens[longestMatch].node : null;
var mismatchOffset = -1;
var entries = 0;
var css = '';
for (var i = 0; i < tokens.length; i++) {
if (i === longestMatch) {
mismatchOffset = css.length;
}
if (node !== null && tokens[i].node === node) {
if (i <= longestMatch) {
entries++;
} else {
entries = 0;
}
}
css += tokens[i].value;
}
return {
node: node,
css: css,
mismatchOffset: mismatchOffset === -1 ? css.length : mismatchOffset,
last: node === null || entries > 1
};
}
function getLocation(node, point) {
var loc = node && node.loc && node.loc[point];
if (loc) {
return {
offset: loc.offset,
line: loc.line,
column: loc.column
};
}
return null;
}
var SyntaxReferenceError = function(type, referenceName) {
var error = createCustomError(
'SyntaxReferenceError',
type + (referenceName ? ' `' + referenceName + '`' : '')
);
error.reference = referenceName;
return error;
};
var MatchError = function(message, syntax, node, matchResult) {
var error = createCustomError('SyntaxMatchError', message);
var details = fromMatchResult(matchResult);
var mismatchOffset = details.mismatchOffset || 0;
var badNode = details.node || node;
var end = getLocation(badNode, 'end');
var start = details.last ? end : getLocation(badNode, 'start');
var css = details.css;
error.rawMessage = message;
error.syntax = syntax ? generate(syntax) : '<generic>';
error.css = css;
error.mismatchOffset = mismatchOffset;
error.loc = {
source: (badNode && badNode.loc && badNode.loc.source) || '<unknown>',
start: start,
end: end
};
error.line = start ? start.line : undefined;
error.column = start ? start.column : undefined;
error.offset = start ? start.offset : undefined;
error.message = message + '\n' +
' syntax: ' + error.syntax + '\n' +
' value: ' + (error.css || '<empty string>') + '\n' +
' --------' + new Array(error.mismatchOffset + 1).join('-') + '^';
return error;
};
module.exports = {
SyntaxReferenceError: SyntaxReferenceError,
MatchError: MatchError
};