lezer-grammar-compiler.js 1.9 KB

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