antlr | ext to lang | | Search

The generateAntlr function is an asynchronous function that performs a series of tasks including globbing grammar files, compiling and transpiling them using different commands and tools, and handling potential errors. The function is exported as a module, allowing it to be imported and used in other parts of the application.

Run example

npm run import -- "generate antlr parsers"

generate antlr parsers

var path = require('path')
var importer = require('../Core')
var {glob} = importer.import("glob files")
var execCmd = importer.import("spawn child process")
var {chext} = importer.import("changing file name")

async function generateAntlr() {
    var files = glob('**/*.g4', path.join(__dirname, '../Resources/Parsers/'))

    /*
    for(var i = 0; i < files.length; i++) {
        try {
            await execCmd(`npx antlr4ts -visitor "${files[i]}"`)
        } catch (e) {
        }
        
        if(fs.existsSync(chext(files[i], '') + 'Parser.js')
           || fs.existsSync(chext(files[i], '.js'))) {
            continue
        }
        try {
            await execCmd(`java -Xmx500M -cp "/Users/briancullinan/Downloads/antlr-4.8-complete.jar:$CLASSPATH" org.antlr.v4.Tool -Dlanguage=JavaScript -visitor "${path.dirname(files[i])}"/*.g4`)
        } catch (e) {
        }
    }
    */
    
    var typescripts = glob('**/*.ts', path.join(__dirname, '../Resources/Parsers/'))
        .map(f => path.dirname(f))
        .filter((f, i, arr) => arr.indexOf(f) === i)
    
    for(var i = 0; i < typescripts.length; i++) {
        try {
            await execCmd(`npx babel --extensions .ts,.tsx "${typescripts[i]}" --out-dir "${typescripts[i]}"`)
        } catch (e) {
        }
    }
    
}

module.exports = generateAntlr

What the code could have been:

const path = require('path');
const { glob, asyncify } = require('glob');
const { spawn } = require('child_process');

class AntlrGenerator {
  constructor(importer) {
    this.execCmd = importer.import('spawn child process');
    this.chext = importer.import('changing file name');
  }

  async generateAntlr() {
    const antlrFiles = await this.getAntlrFiles();
    const typescriptDirs = await this.getTypescriptDirs(antlrFiles);

    await this.transpileTypescript(typescriptDirs);
  }

  async getAntlrFiles() {
    try {
      return (await glob('**/*.g4', path.join(__dirname, '../Resources/Parsers/'))).map(f => f);
    } catch (error) {
      // TODO: Handle glob error
      console.error(error);
      return [];
    }
  }

  async getTypescriptDirs(antlrFiles) {
    try {
      return (await this.getUniqueDirectories(antlrFiles)).map(f => path.dirname(f));
    } catch (error) {
      // TODO: Handle glob error
      console.error(error);
      return [];
    }
  }

  async getUniqueDirectories(files) {
    try {
      return [...new Set(files.map(f => path.dirname(f)))];
    } catch (error) {
      console.error(error);
      return [];
    }
  }

  async transpileTypescript(typescriptDirs) {
    for (const dir of typescriptDirs) {
      try {
        await this.execCmd(`npx babel --extensions.ts,.tsx "${dir}" --out-dir "${dir}"`);
      } catch (error) {
        // TODO: Handle babel error
        console.error(error);
      }
    }
  }
}

module.exports = (importer) => new AntlrGenerator(importer).generateAntlr();

Code Breakdown

Requirements and Dependencies

The code requires the following dependencies:

generateAntlr Function

The generateAntlr function is an asynchronous function that performs the following tasks:

  1. Globbing Grammar Files: It uses the glob module to find all files with a .g4 extension in the ../Resources/Parsers/ directory.
  2. Compiling Grammar Files: It attempts to compile the grammar files using the npx antlr4ts command. If the compilation fails, it ignores the error.
  3. Checking for Existing Parser Files: It checks if a parser file (*.js) exists for each compiled grammar file. If a parser file exists, it skips the file.
  4. Compiling Grammar Files using Java: It attempts to compile the grammar files using the java command. If the compilation fails, it ignores the error.
  5. Transpiling TypeScript Files: It uses the glob module to find all files with a .ts extension in the ../Resources/Parsers/ directory.
  6. Transpiling TypeScript Files using Babel: It transpiles the TypeScript files using the npx babel command.

Exports

The generateAntlr function is exported as a module using module.exports. This allows the function to be imported and used in other parts of the application.