Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
Download
80529 views
1
var aparse = require('acorn').parse;
2
function parse (src) { return aparse(src, { ecmaVersion: 6 }) }
3
4
module.exports = function (src, file) {
5
if (typeof src !== 'string') src = String(src);
6
7
try {
8
eval('throw "STOP"; (function () { ' + src + '})()');
9
return;
10
}
11
catch (err) {
12
if (err === 'STOP') return undefined;
13
if (err.constructor.name !== 'SyntaxError') throw err;
14
return errorInfo(src, file);
15
}
16
};
17
18
function errorInfo (src, file) {
19
try { parse(src) }
20
catch (err) {
21
return new ParseError(err, src, file);
22
}
23
return undefined;
24
}
25
26
function ParseError (err, src, file) {
27
SyntaxError.call(this);
28
29
this.message = err.message.replace(/\s+\(\d+:\d+\)$/, '');
30
31
this.line = err.loc.line;
32
this.column = err.loc.column + 1;
33
34
this.annotated = '\n'
35
+ (file || '(anonymous file)')
36
+ ':' + this.line
37
+ '\n'
38
+ src.split('\n')[this.line - 1]
39
+ '\n'
40
+ Array(this.column).join(' ') + '^'
41
+ '\n'
42
+ 'ParseError: ' + this.message
43
;
44
}
45
46
ParseError.prototype = Object.create(SyntaxError.prototype);
47
48
ParseError.prototype.toString = function () {
49
return this.annotated;
50
};
51
52
ParseError.prototype.inspect = function () {
53
return this.annotated;
54
};
55
56