You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

93 lines
2.6 KiB

4 years ago
  1. var createCustomError = require('../utils/createCustomError');
  2. var generate = require('../definition-syntax/generate');
  3. function fromMatchResult(matchResult) {
  4. var tokens = matchResult.tokens;
  5. var longestMatch = matchResult.longestMatch;
  6. var node = longestMatch < tokens.length ? tokens[longestMatch].node : null;
  7. var mismatchOffset = -1;
  8. var entries = 0;
  9. var css = '';
  10. for (var i = 0; i < tokens.length; i++) {
  11. if (i === longestMatch) {
  12. mismatchOffset = css.length;
  13. }
  14. if (node !== null && tokens[i].node === node) {
  15. if (i <= longestMatch) {
  16. entries++;
  17. } else {
  18. entries = 0;
  19. }
  20. }
  21. css += tokens[i].value;
  22. }
  23. return {
  24. node: node,
  25. css: css,
  26. mismatchOffset: mismatchOffset === -1 ? css.length : mismatchOffset,
  27. last: node === null || entries > 1
  28. };
  29. }
  30. function getLocation(node, point) {
  31. var loc = node && node.loc && node.loc[point];
  32. if (loc) {
  33. return {
  34. offset: loc.offset,
  35. line: loc.line,
  36. column: loc.column
  37. };
  38. }
  39. return null;
  40. }
  41. var SyntaxReferenceError = function(type, referenceName) {
  42. var error = createCustomError(
  43. 'SyntaxReferenceError',
  44. type + (referenceName ? ' `' + referenceName + '`' : '')
  45. );
  46. error.reference = referenceName;
  47. return error;
  48. };
  49. var MatchError = function(message, syntax, node, matchResult) {
  50. var error = createCustomError('SyntaxMatchError', message);
  51. var details = fromMatchResult(matchResult);
  52. var mismatchOffset = details.mismatchOffset || 0;
  53. var badNode = details.node || node;
  54. var end = getLocation(badNode, 'end');
  55. var start = details.last ? end : getLocation(badNode, 'start');
  56. var css = details.css;
  57. error.rawMessage = message;
  58. error.syntax = syntax ? generate(syntax) : '<generic>';
  59. error.css = css;
  60. error.mismatchOffset = mismatchOffset;
  61. error.loc = {
  62. source: (badNode && badNode.loc && badNode.loc.source) || '<unknown>',
  63. start: start,
  64. end: end
  65. };
  66. error.line = start ? start.line : undefined;
  67. error.column = start ? start.column : undefined;
  68. error.offset = start ? start.offset : undefined;
  69. error.message = message + '\n' +
  70. ' syntax: ' + error.syntax + '\n' +
  71. ' value: ' + (error.css || '<empty string>') + '\n' +
  72. ' --------' + new Array(error.mismatchOffset + 1).join('-') + '^';
  73. return error;
  74. };
  75. module.exports = {
  76. SyntaxReferenceError: SyntaxReferenceError,
  77. MatchError: MatchError
  78. };