lezer-grammar-compiler.js 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. const fs = require('fs')
  2. const path = require('path')
  3. const modulePath = path.resolve(
  4. __dirname,
  5. '../scripts/lezer-latex/generate.mjs'
  6. )
  7. try {
  8. fs.accessSync(modulePath, fs.constants.W_OK)
  9. const { compile, grammars } = require(modulePath).default
  10. const PLUGIN_NAME = 'lezer-grammar-compiler'
  11. class LezerGrammarCompilerPlugin {
  12. apply(compiler) {
  13. for (const grammar of grammars) {
  14. compiler.hooks.make.tap(PLUGIN_NAME, compilation => {
  15. // Add the grammar file to the file paths watched by webpack
  16. compilation.fileDependencies.add(grammar.grammarPath)
  17. })
  18. compiler.hooks.beforeCompile.tapAsync(
  19. PLUGIN_NAME,
  20. (_compilation, callback) => {
  21. // Check timestamps on grammar and parser files, and re-compile if needed.
  22. // (Note: the compiled parser file is watched by webpack, and so will trigger
  23. // a second compilation immediately after. This seems harmless.)
  24. if (
  25. !fs.existsSync(grammar.parserOutputPath) ||
  26. !fs.existsSync(grammar.termsOutputPath)
  27. ) {
  28. console.log('Parser does not exist, compiling')
  29. compile(grammar)
  30. return callback()
  31. }
  32. fs.stat(grammar.grammarPath, (err, grammarStat) => {
  33. if (err) {
  34. return callback(err)
  35. }
  36. fs.stat(grammar.parserOutputPath, (err, parserStat) => {
  37. if (err) {
  38. return callback(err)
  39. }
  40. callback()
  41. if (grammarStat.mtime > parserStat.mtime) {
  42. console.log(
  43. 'Grammar file newer than parser file, re-compiling'
  44. )
  45. compile(grammar)
  46. }
  47. })
  48. })
  49. }
  50. )
  51. }
  52. }
  53. }
  54. module.exports = { LezerGrammarCompilerPlugin }
  55. } catch {
  56. class NoOpPlugin {
  57. apply() {
  58. console.log('lezer-latex module not present, skipping compile')
  59. }
  60. }
  61. module.exports = { LezerGrammarCompilerPlugin: NoOpPlugin }
  62. }