parser-service.js 2.0 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, { languageOptions })
  37. };
  38. }
  39. // if we made it to here there was an error
  40. return {
  41. ok: false,
  42. errors: result.errors.map(error => ({
  43. ruleId: null,
  44. nodeType: null,
  45. fatal: true,
  46. severity: 2,
  47. message: `Parsing error: ${error.message}`,
  48. line: error.line,
  49. column: error.column
  50. }))
  51. };
  52. }
  53. }
  54. module.exports = { ParserService };