-
Notifications
You must be signed in to change notification settings - Fork 0
The Parser Generator
The Parser Generator is responsible for generating the C++ code for your parser based on the grammar specifications. It also manages important things like detecting and correcting for left recursive rules via memoization. Generally you won't have to interact with the parser generator, as it is abstracted behind a function which takes you grammar as input and returns a string containing the C++ code for the parser.
namespace Parsergen {
std::string generate_parser(std::string grammar);
}
The introspection process is responsible for identifying left recursive rules and rules that might be able to match successfully without consuming any input. It is used by the parser generator to give warnings and apply left recursion correction correctly.
A program for loading a grammar file and saving the parser to a C++ file.
#include "parsergen/parser_generator.hpp"
#include <iostream>
#include <fstream>
#include <sstream>
using namespace Parsergen;
int main(){
std::ifstream file;
file.open("examples/calc/calc.gram");
if (file.is_open()){
std::stringstream strStream;
strStream << file.rdbuf(); //read the file
std::string pgram = strStream.str(); //str holds the content of the file
auto result = generate_parser(pgram);
std::ofstream f("examples/calc/calc.hpp");
f << result;
f.close();
std::cout << "Generation complete.\n";
}
else {
std::cout << "Unable to open file" << std::endl;
return 1;
}
return 0;
}
This can also be done using the command-line tool parsergen-cpp
as follows:
parsegen-cpp examples/calc/calc.gram -o examples/calc/calc.hpp