run.mjs 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. import { readFileSync } from 'fs'
  2. import { logTree } from '../../frontend/js/features/source-editor/lezer-latex/print-tree.mjs'
  3. import { parser } from '../../frontend/js/features/source-editor/lezer-latex/latex.mjs'
  4. // Runs the lezer-latex parser on a supplied file, and prints the resulting
  5. // parse tree to stdout
  6. //
  7. // show parse tree: lezer-latex-run.js test/frontend/shared/lezer-latex/examples/amsmath.tex
  8. // show error summary: lezer-latex-run.js coverage test/frontend/shared/lezer-latex/examples/amsmath.tex
  9. let files = process.argv.slice(2)
  10. if (!files.length) {
  11. files = ['test/unit/src/LezerLatex/examples/demo.tex']
  12. }
  13. let coverage = false
  14. if (files[0] === 'coverage') {
  15. // count errors
  16. coverage = true
  17. files.shift()
  18. }
  19. function reportErrorCounts(output) {
  20. if (coverage) process.stdout.write(output)
  21. }
  22. function parseFile(filename) {
  23. const text = readFileSync(filename).toString()
  24. const t0 = process.hrtime()
  25. const tree = parser.parse(text)
  26. const dt = process.hrtime(t0)
  27. const timeTaken = dt[0] + dt[1] * 1e-9
  28. let errorCount = 0
  29. let nodeCount = 0
  30. tree.iterate({
  31. enter: syntaxNodeRef => {
  32. nodeCount++
  33. if (syntaxNodeRef.type.isError) {
  34. errorCount++
  35. }
  36. },
  37. })
  38. if (!coverage) logTree(tree, text)
  39. return { nodeCount, errorCount, timeTaken, bytes: text.length }
  40. }
  41. let totalErrors = 0
  42. let totalTime = 0
  43. let totalBytes = 0
  44. for (const file of files) {
  45. const { nodeCount, errorCount, timeTaken, bytes } = parseFile(file)
  46. const errorRate = Math.round((100 * errorCount) / nodeCount)
  47. totalErrors += errorCount
  48. totalTime += timeTaken
  49. totalBytes += bytes
  50. reportErrorCounts(
  51. `${errorCount} errors`.padStart(12) +
  52. `${nodeCount} nodes`.padStart(12) +
  53. `(${errorRate}%)`.padStart(6) +
  54. `${(1000 * timeTaken).toFixed(1)} ms`.padStart(8) +
  55. `${(bytes / 1024).toFixed(1)} KB`.padStart(8) +
  56. ` ${file}\n`
  57. )
  58. }
  59. const timeInMilliseconds = 1000 * totalTime
  60. const hundredKBs = totalBytes / (100 * 1024)
  61. reportErrorCounts(
  62. `\ntotal errors ${totalErrors}, performance ${(
  63. timeInMilliseconds / hundredKBs
  64. ).toFixed(1)} ms/100KB \n`
  65. )
  66. if (totalErrors > 0) {
  67. process.exit(1) // return non-zero exit status for tests
  68. }