UNPKG

esther-medina-quintero-parser-nearley

Version:
48 lines (41 loc) 1.55 kB
#!/usr/bin/env node /** * @description A parser for egg lang files * @author Esther M. Quintero <alu0101434780@ull.edu.es> * @since 12/03/2024 */ 'use strict'; const fs = require('fs'); const nearley = require("nearley"); const grammar = require("./src/grammar.js"); /** * A function that parses a egg file * @param {string} origin The name of the origin file * @throws Will throw if there are errors in the program or if the files * can't be opened */ const parseFromFile = (origin) => { try { // Read the file contents const code = fs.readFileSync(origin, { encoding: 'utf8' }); // Initialize Nearley parser with the grammar const parser = new nearley.Parser(nearley.Grammar.fromCompiled(grammar)); // Parse the code parser.feed(code); console.log(JSON.stringify(parser.results[0], null, 2)); // Check if the parsing was successful if (parser.results.length === 0) { throw new Error('No parse results. The file may be empty or not match the grammar.'); } else if (parser.results.length > 1) { throw new Error('Ambiguous results. The grammar may allow multiple parses.'); } /// Show the whole AST console.log(JSON.stringify(parser.results[0], null, 2)); // Return the AST from the first (and should be only) parse result return parser.results[0]; } catch (error) { // Rethrow the error with additional context if needed throw new Error(`\nFailed to parse file "${origin}": ${error.message}`); } }; module.exports = { parseFromFile };