antlr-ng
Version:
Next generation ANTLR Tool
112 lines (111 loc) • 3.36 kB
JavaScript
var __defProp = Object.defineProperty;
var __name = (target, value) => __defProp(target, "name", { value, configurable: true });
import { CommonToken, isToken } from "antlr4ng";
import { CommonTree } from "./CommonTree.js";
class CommonTreeAdaptor {
static {
__name(this, "CommonTreeAdaptor");
}
create(...args) {
if (args.length < 2) {
const [payload] = args;
return new CommonTree(payload);
}
switch (args.length) {
case 2: {
if (typeof args[1] === "string") {
const [tokenType, text] = args;
const fromToken = this.createToken(tokenType, text);
return this.create(fromToken);
} else {
const [tokenType, fromToken] = args;
const temp = this.createToken(fromToken);
temp.type = tokenType;
return this.create(temp);
}
}
case 3: {
const [tokenType, fromToken, text] = args;
if (fromToken === null) {
return this.create(tokenType, text);
}
const temp = this.createToken(fromToken);
temp.type = tokenType;
temp.text = text;
return this.create(temp);
}
default: {
throw new Error("Invalid number of arguments");
}
}
}
/**
* If oldRoot is a nil root, just copy or move the children to newRoot. If not a nil root, make oldRoot a child
* of newRoot.
* ```
* old=^(nil a b c), new=r yields ^(r a b c)
* old=^(a b c), new=r yields ^(r ^(a b c))
* ```
* If newRoot is a nil-rooted single child tree, use the single child as the new root node.
* ```
* old=^(nil a b c), new=^(nil r) yields ^(r a b c)
* old=^(a b c), new=^(nil r) yields ^(r ^(a b c))
* ```
* If oldRoot was null, it's ok, just return newRoot (even if isNil).
* ```
* old=null, new=r yields r
* old=null, new=^(nil r) yields ^(nil r)
* ```
*
* @returns newRoot. Throw an error if newRoot is not a simple node or nil root with a single child node. It must
* be a root node. If newRoot is ^(nil x) return x as newRoot.
*
* Be advised that it's ok for newRoot to point at oldRoot's children, i.e. you don't have to copy the list. We are
* constructing these nodes so we should have this control for efficiency.
*/
becomeRoot(newRoot, oldRoot) {
if (isToken(newRoot)) {
newRoot = this.create(newRoot);
}
if (oldRoot === null) {
return newRoot;
}
if (newRoot.isNil()) {
const nc = newRoot.children.length;
if (nc === 1) {
newRoot = newRoot.children[0];
} else if (nc > 1) {
throw new Error("more than one node as root (TODO: make exception hierarchy)");
}
}
newRoot.addChild(oldRoot);
return newRoot;
}
/**
* Transforms ^(nil x) to x and nil to null.
*/
rulePostProcessing(root) {
let r = root;
if (r.isNil()) {
if (r.children.length === 0) {
r = null;
} else if (r.children.length === 1) {
r = r.children[0];
r.parent = null;
r.childIndex = -1;
}
}
return r;
}
createToken(...args) {
if (args.length === 1) {
const [fromToken] = args;
return CommonToken.fromToken(fromToken);
}
const [tokenType, text] = args;
return CommonToken.fromType(tokenType, text);
}
}
export {
CommonTreeAdaptor
};