Press n or j to go to the next uncovered block, b, p or k for the previous block.
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 | 1x 1x 1x 1x 19x 19x 19x 19x 12x 12x 12x 12x 12x 7x 1x | #!/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
Iif (parser.results.length === 0) {
throw new Error('No parse results. The file may be empty or not match the grammar.');
} else Iif (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 }; |