Parsing and executing
With our language greet
defined and inspected, we can now parse and execute a program. Parsing requires a Parser
, which can easily be constructed from a process's command line arguments. Note that execution returns a Promise
and has to be awaited.
try {
const parseResult = greet.parse(Parser.fromArgv());
console.log(await parseResult.execute());
} catch (error) {
if (error instanceof Error) console.log(`${error.name}: ${error.message}`);
}
We can now run the program from a terminal (after compiling it with typescript).
$ node cli.js hi
Hi mysterious person!
$ node cli.js hello world
Hello world! It is a great day today!
$ node cli.js
Error: Parser finished but expected type <t.greeting>.
$ node cli.js hello
Error: Parser finished but expected type <p.string>.
$ node cli.js hi world
Error: Unexpected token "world" at index 1.