parser-service.js 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. /**
  2. * @fileoverview ESLint Parser
  3. * @author Nicholas C. Zakas
  4. */
  5. /* eslint class-methods-use-this: off -- Anticipate future constructor arguments. */
  6. "use strict";
  7. //-----------------------------------------------------------------------------
  8. // Types
  9. //-----------------------------------------------------------------------------
  10. /** @typedef {import("../linter/vfile.js").VFile} VFile */
  11. /** @typedef {import("@eslint/core").Language} Language */
  12. /** @typedef {import("@eslint/core").LanguageOptions} LanguageOptions */
  13. //-----------------------------------------------------------------------------
  14. // Exports
  15. //-----------------------------------------------------------------------------
  16. /**
  17. * The parser for ESLint.
  18. */
  19. class ParserService {
  20. /**
  21. * Parses the given file synchronously.
  22. * @param {VFile} file The file to parse.
  23. * @param {{language:Language,languageOptions:LanguageOptions}} config The configuration to use.
  24. * @returns {Object} An object with the parsed source code or errors.
  25. * @throws {Error} If the parser returns a promise.
  26. */
  27. parseSync(file, config) {
  28. const { language, languageOptions } = config;
  29. const result = language.parse(file, { languageOptions });
  30. if (typeof result.then === "function") {
  31. throw new Error("Unsupported: Language parser returned a promise.");
  32. }
  33. if (result.ok) {
  34. return {
  35. ok: true,
  36. sourceCode: language.createSourceCode(file, result, {
  37. languageOptions,
  38. }),
  39. };
  40. }
  41. // if we made it to here there was an error
  42. return {
  43. ok: false,
  44. errors: result.errors.map(error => ({
  45. ruleId: null,
  46. nodeType: null,
  47. fatal: true,
  48. severity: 2,
  49. message: `Parsing error: ${error.message}`,
  50. line: error.line,
  51. column: error.column,
  52. })),
  53. };
  54. }
  55. }
  56. module.exports = { ParserService };