index.js
1.34 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
var aparse = require('acorn-node').parse;
function parse (src, opts) {
if (!opts) opts = {}
return aparse(src, opts);
}
module.exports = function (src, file,opts) {
if (typeof src !== 'string') src = String(src);
try {
eval('throw "STOP"; (function () { ' + src + '\n})()');
return;
}
catch (err) {
if (err === 'STOP') return undefined;
if (err.constructor.name !== 'SyntaxError') return err;
return errorInfo(src, file, opts);
}
};
function errorInfo (src, file, opts) {
try { parse(src,opts) }
catch (err) {
return new ParseError(err, src, file);
}
return undefined;
}
function ParseError (err, src, file) {
SyntaxError.call(this);
this.message = err.message.replace(/\s+\(\d+:\d+\)$/, '');
this.line = err.loc.line;
this.column = err.loc.column + 1;
this.annotated = '\n'
+ (file || '(anonymous file)')
+ ':' + this.line
+ '\n'
+ src.split('\n')[this.line - 1]
+ '\n'
+ Array(this.column).join(' ') + '^'
+ '\n'
+ 'ParseError: ' + this.message
;
}
ParseError.prototype = Object.create(SyntaxError.prototype);
ParseError.prototype.toString = function () {
return this.annotated;
};
ParseError.prototype.inspect = function () {
return this.annotated;
};