UNPKG

@bitloops/bl-transpiler

Version:
109 lines 3.85 kB
import antlr4 from 'antlr4'; import BitloopsLexer from './grammar/BitloopsLexer.js'; import Parser from './grammar/BitloopsParser.js'; import { isParserErrors } from './guards/index.js'; import { VerboseErrorListener } from './VerboseErrorListener.js'; export class BitloopsParser { parse(inputData) { const errors = []; const parseResult = { core: {} }; const ASTCore = this.parseCore(inputData.core); if (isParserErrors(ASTCore)) { errors.push(...ASTCore); } else { parseResult.core = ASTCore; } if (inputData.setup) { const ASTSetup = this.parseSetup(inputData.setup); if (isParserErrors(ASTSetup)) { errors.push(...ASTSetup); } else { parseResult.setup = ASTSetup; } } if (errors.length > 0) { return errors; } return parseResult; } parseCore(inputData) { /** * For each file, we need to create its tree. */ const boundedContexts = {}; const errors = []; for (const data of inputData) { const { boundedContext, module, fileId, fileContents } = data; const ASTContextOrError = BitloopsParser.getInitialAST(fileContents, fileId); if (isParserErrors(ASTContextOrError)) { errors.push(...ASTContextOrError); } else { const ASTContext = ASTContextOrError; if (boundedContexts[boundedContext] === null || boundedContexts[boundedContext] === undefined) { // first time we come across this boundedContext boundedContexts[boundedContext] = { [module]: { [fileId]: { ASTContext }, }, }; } else if (boundedContexts[boundedContext][module] === undefined) { // first time we come across this module boundedContexts[boundedContext][module] = { [fileId]: { ASTContext }, }; } else { boundedContexts[boundedContext][module][fileId] = { ASTContext }; } } } if (errors.length > 0) { return errors; } return boundedContexts; } parseSetup(setupData) { const setupContext = {}; const errors = []; for (const data of setupData) { const { fileContents, fileId } = data; const ASTContextOrError = BitloopsParser.getInitialAST(fileContents, fileId); if (isParserErrors(ASTContextOrError)) { errors.push(...ASTContextOrError); } else { const ASTContext = ASTContextOrError; setupContext[fileId] = { ASTContext }; } } if (errors.length > 0) { return errors; } return setupContext; } /** * Initial AST. * @param blCode string * @returns Parser.ProgramContext */ static getInitialAST(blCode, fileId) { const chars = new antlr4.InputStream(blCode); const lexer = new BitloopsLexer(chars); const tokens = new antlr4.CommonTokenStream(lexer); const parser = new Parser(tokens); parser.removeErrorListeners(); const errorListener = new VerboseErrorListener(fileId); parser.addErrorListener(errorListener); const tree = parser.program(); if (errorListener.hasErrors()) { return errorListener.getErrors(); } return tree; } } //# sourceMappingURL=index.js.map