index.js 1.3 KB

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