lezer-grammar-compiler.js 2.1 KB

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