Haxe
The Haxe target can compile to JavaScript, HashLink, and other Haxe backends. This project primarily validates JavaScript and HashLink.
Minimal working example
Create the following two files in an empty directory. Parser.hx is generated by pegtool.
identifier.peg
{
class ParserCustomData {
public function new() {}
}
}
Start = value:<Identifier> !. { return value; }
Identifier = [\pL_] [\pL\p{Nd}_]*Main.hx
class Main {
static function main() {
var parser = new Parser("input.txt", "name_世界", []);
var value:String = cast parser.parse(null);
#if js
js.Lib.global.console.log(value);
#else
Sys.println(value);
#end
}
}Generate and compile to JavaScript:
pegtool -t hx -optimize-parser -o Parser.hx identifier.peg
haxe -cp . -main Main -js main.js -D analyzer-optimize
node main.jsThe same two files can be compiled to HashLink:
haxe -cp . -main Main -hl main.hl -D analyzer-optimize
hl main.hlBoth commands print:
name_世界Parser and custom data
new Parser(filename, input, options) creates a parser, and parse(null) uses the default grammar in the generated file. To select another entry point, set parser.entrypoint before calling parse. For custom data, set the public parser.cur.data field or provide a project wrapper in the generated module.
-optimize-parser and memoization
The two are mutually exclusive in Haxe:
-optimize-parserremoves debug, statistics, memo fields, and cache branches. It is intended for fixed, near-linear production grammars.- When a backtracking-heavy grammar needs memoization, omit
-optimize-parserand setparser.memoize = truebefore parsing.
var parser = new Parser("input.txt", source, []);
parser.memoize = true;
var value = parser.parse(null);In a HashLink workload with repeated failing scans, named-rule memoization was 2.53x-2.61x faster than the no-memo version. It was about 1%-1.4% slower on a linear workload, and roughly 24% slower in an exploratory workload that cached a simple failing rule. It is therefore not a default switch.
Unicode tables
By default, Parser.hx embeds the Unicode tables actually used by the grammar. This has no third-party dependency and fixes the character set to the generator version. When parser source size matters more, use the external library:
haxelib install hxUnicode
pegtool -t hx -haxe-use-hxunicode -o Parser.hx identifier.peg
haxe -cp . -main Main -js main.js -lib hxUnicode -D analyzer-optimize-haxe-use-hxunicode is a size and dependency choice, not a validated performance option. The external library can also use a different Unicode version than the generator.
Do not make -optimize-ref-expr-by-index a default option. Inserting or reordering rules then rewrites many numeric references. Enable it only when generated output is not reviewed and a real benchmark confirms the benefit.