Project - MetaCompiler
This is a C++ library for creating front-ends of compilers. The project is similar to yacc, except for it's a run-time library rather than a static code generator. Meta Compiler is made up of MetaLexer, which is responsible for lexical analysis, and MetaParser, which is an LR(1) parser. MetaLexer takes a configuration string including the regular expression for each type of tokens as input, and outputs a token stream. MetaParser takes the token stream along with a configuration string indicating the BNF grammar rules as input, and helps generating the syntax tree by building an LR(1) parse table. Since the configuration strings for MetaLexer and MetaParser can be specified at runtime, MetaCompiler would be capable dealing with wider range of languages.
I also implemented a wrapper for GxScript(a scripting language designed myself), which makes writing parsers suprisingly easy. Below is an expression evaluator written in GxScript.
Example: constructing an expression evalutator using MetaCompiler in GxScript
var parser = CreateMetaParser();
var lexProfile =
"#WhiteSpace = {\\s+}\n" &
"Number = {\\d+(.\\d*)?}\n" &
"OpAddSub = {\\+|-}\n" &
"OpMulDiv = {\\*|/}\n" &
"LParent = {\\(}\n" &
"RParent = {\\)}\n";
parser.SetLexer(lexProfile);
parser.AddRule("#left 1 OpAddSub");
parser.AddRule("#left 2 OpMulDiv");
parser.AddRule("*Exp -> Expr",
function (n)
{
writeln("The result is " & n);
});
parser.AddRule("Expr -> Expr OpAddSub Expr",
function (n1, op, n2)
{
if (op == "+")
return n1 + n2;
else
return n1 - n2;
});
parser.AddRule("Expr -> Expr OpMulDiv Expr",
f3 = function (n1, op, n2)
{
if (op == "*")
return n1 * n2;
else
return n1 / n2;
});
parser.AddRule("Expr -> OpAddSub Expr {priority 4 #right}",
function (op, n1)
{
if (op == "+")
return n1;
else
return -n1;
});
parser.AddRule("Expr -> LParent Expr RParent", function (p, n, p){return n;});
parser.AddRule("Expr -> Number", function (n){return n;} );
parser.Init();
write("Parser ready. Input an expression: ");
var src = read();
parser.Parse(src);
Program Output:
You can visit my Codeplex page for the C++ source of this library.
Alternatively, go to GxScript project page to download the Win32 binary package of GxScript, which enables you to test with the script above.