SyntaxError.js 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. var createCustomError = require('../utils/createCustomError');
  2. var MAX_LINE_LENGTH = 100;
  3. var OFFSET_CORRECTION = 60;
  4. var TAB_REPLACEMENT = ' ';
  5. function sourceFragment(error, extraLines) {
  6. function processLines(start, end) {
  7. return lines.slice(start, end).map(function(line, idx) {
  8. var num = String(start + idx + 1);
  9. while (num.length < maxNumLength) {
  10. num = ' ' + num;
  11. }
  12. return num + ' |' + line;
  13. }).join('\n');
  14. }
  15. var lines = error.source.split(/\r\n?|\n|\f/);
  16. var line = error.line;
  17. var column = error.column;
  18. var startLine = Math.max(1, line - extraLines) - 1;
  19. var endLine = Math.min(line + extraLines, lines.length + 1);
  20. var maxNumLength = Math.max(4, String(endLine).length) + 1;
  21. var cutLeft = 0;
  22. // column correction according to replaced tab before column
  23. column += (TAB_REPLACEMENT.length - 1) * (lines[line - 1].substr(0, column - 1).match(/\t/g) || []).length;
  24. if (column > MAX_LINE_LENGTH) {
  25. cutLeft = column - OFFSET_CORRECTION + 3;
  26. column = OFFSET_CORRECTION - 2;
  27. }
  28. for (var i = startLine; i <= endLine; i++) {
  29. if (i >= 0 && i < lines.length) {
  30. lines[i] = lines[i].replace(/\t/g, TAB_REPLACEMENT);
  31. lines[i] =
  32. (cutLeft > 0 && lines[i].length > cutLeft ? '\u2026' : '') +
  33. lines[i].substr(cutLeft, MAX_LINE_LENGTH - 2) +
  34. (lines[i].length > cutLeft + MAX_LINE_LENGTH - 1 ? '\u2026' : '');
  35. }
  36. }
  37. return [
  38. processLines(startLine, line),
  39. new Array(column + maxNumLength + 2).join('-') + '^',
  40. processLines(line, endLine)
  41. ].filter(Boolean).join('\n');
  42. }
  43. var SyntaxError = function(message, source, offset, line, column) {
  44. var error = createCustomError('SyntaxError', message);
  45. error.source = source;
  46. error.offset = offset;
  47. error.line = line;
  48. error.column = column;
  49. error.sourceFragment = function(extraLines) {
  50. return sourceFragment(error, isNaN(extraLines) ? 0 : extraLines);
  51. };
  52. Object.defineProperty(error, 'formattedMessage', {
  53. get: function() {
  54. return (
  55. 'Parse error: ' + error.message + '\n' +
  56. sourceFragment(error, 2)
  57. );
  58. }
  59. });
  60. // for backward capability
  61. error.parseError = {
  62. offset: offset,
  63. line: line,
  64. column: column
  65. };
  66. return error;
  67. };
  68. module.exports = SyntaxError;