UNPKG

antlr-ng

Version:

Next generation ANTLR Tool

86 lines (85 loc) 2.37 kB
var __defProp = Object.defineProperty; var __name = (target, value) => __defProp(target, "name", { value, configurable: true }); import { CommonToken, Token } from "antlr4ng"; import { Constants } from "../Constants.js"; import { CommonTree } from "./CommonTree.js"; class TreeIterator { static { __name(this, "TreeIterator"); } /** Navigation nodes to return during walk and at end. */ static up = new CommonTree(CommonToken.fromType(Constants.Up, "UP")); static down = new CommonTree(CommonToken.fromType(Constants.Down, "DOWN")); static eof = new CommonTree(CommonToken.fromType(Token.EOF, "EOF")); root; tree; firstTime = true; /** If we emit UP/DOWN nodes, we need to spit out multiple nodes per next() call. */ nodes = []; constructor(tree) { this.tree = tree; this.root = tree; } reset() { this.firstTime = true; this.tree = this.root; this.nodes.length = 0; } hasNext() { if (this.firstTime) { return this.root !== void 0; } if (this.nodes.length > 0) { return true; } if (this.tree === void 0) { return false; } if (this.tree.children.length > 0) { return true; } return this.tree.parent !== null; } nextTree() { if (this.firstTime) { this.firstTime = false; if (this.tree?.children.length === 0) { this.nodes.push(TreeIterator.eof); return this.tree; } return this.tree; } if (this.nodes.length > 0) { return this.nodes.shift(); } if (this.tree === void 0) { return TreeIterator.eof; } if (this.tree.children.length > 0) { this.tree = this.tree.children[0]; this.nodes.push(this.tree); return TreeIterator.down; } let parent = this.tree.parent; while (parent !== null && this.tree.childIndex + 1 >= parent.children.length) { this.nodes.push(TreeIterator.up); this.tree = parent; parent = this.tree.parent; } if (parent === null) { this.tree = void 0; this.nodes.push(TreeIterator.eof); return this.nodes.shift(); } const nextSiblingIndex = this.tree.childIndex + 1; this.tree = parent.children[nextSiblingIndex]; this.nodes.push(this.tree); return this.nodes.shift(); } remove() { throw new Error("Remove is unsupported"); } } export { TreeIterator };