UNPKG

antlr-ng

Version:

Next generation ANTLR Tool

79 lines (78 loc) 2.06 kB
var __defProp = Object.defineProperty; var __name = (target, value) => __defProp(target, "name", { value, configurable: true }); import { RecognitionException } from "antlr4ng"; import { CommonTreeNodeStream } from "./CommonTreeNodeStream.js"; import { TreeParser } from "./TreeParser.js"; import { TreeVisitor } from "./TreeVisitor.js"; class TreeRewriter extends TreeParser { static { __name(this, "TreeRewriter"); } originalTokenStream; constructor(errorManager, input) { super(errorManager, input); this.originalTokenStream = input.tokens; } downUp(t) { const v = new TreeVisitor(); const actions = new class { constructor($outer) { this.$outer = $outer; } pre(t2) { return this.$outer.applyOnce(t2, this.$outer.topdown); } post(t2) { return this.$outer.applyRepeatedly(t2); } }(this); t = v.visit(t, actions); return t; } /** * Methods the down-up strategy uses to do the up and down rules. To override, just define tree grammar rule * topdown and turn on filter = true. * * @returns the tree created from applying the down-up rules */ topdown = /* @__PURE__ */ __name(() => { return void 0; }, "topdown"); bottomup = /* @__PURE__ */ __name(() => { return void 0; }, "bottomup"); applyOnce = /* @__PURE__ */ __name((t, whichRule) => { try { const input = new CommonTreeNodeStream(t); input.tokens = this.originalTokenStream; this.input = input; this.backtracking = 1; const r = whichRule(); this.backtracking = 0; if (this.failed) { return t; } if (r) { return r; } return t; } catch (e) { if (!(e instanceof RecognitionException)) { throw e; } } return t; }, "applyOnce"); applyRepeatedly(t) { let treeChanged = true; while (treeChanged) { const u = this.applyOnce(t, this.bottomup); treeChanged = t !== u; t = u; } return t; } } export { TreeRewriter };