lezer-grammar-compiler.js 1.9 KB

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