lezer-grammar-compiler.js 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  1. const {
  2. compile,
  3. options,
  4. } = require('../modules/source-editor/scripts/lezer-latex/generate')
  5. const fs = require('fs')
  6. const PLUGIN_NAME = 'lezer-grammar-compiler'
  7. class LezerGrammarCompilerPlugin {
  8. apply(compiler) {
  9. compiler.hooks.make.tap(PLUGIN_NAME, compilation => {
  10. // Add the grammar file to the file paths watched by webpack
  11. compilation.fileDependencies.add(options.grammarPath)
  12. })
  13. compiler.hooks.beforeCompile.tapAsync(
  14. PLUGIN_NAME,
  15. (_compilation, callback) => {
  16. // Check timestamps on grammar and parser files, and re-compile if needed.
  17. // (Note: the compiled parser file is watched by webpack, and so will trigger
  18. // a second compilation immediately after. This seems harmless.)
  19. if (
  20. !fs.existsSync(options.parserOutputPath) ||
  21. !fs.existsSync(options.termsOutputPath)
  22. ) {
  23. console.log('Parser does not exist, compiling')
  24. compile()
  25. return callback()
  26. }
  27. fs.stat(options.grammarPath, (err, grammarStat) => {
  28. if (err) {
  29. return callback(err)
  30. }
  31. fs.stat(options.parserOutputPath, (err, parserStat) => {
  32. if (err) {
  33. return callback(err)
  34. }
  35. callback()
  36. if (grammarStat.mtime > parserStat.mtime) {
  37. console.log('Grammar file newer than parser file, re-compiling')
  38. compile()
  39. }
  40. })
  41. })
  42. }
  43. )
  44. }
  45. }
  46. module.exports = { LezerGrammarCompilerPlugin }