Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.
function createSourceTree(
antlrNode: antlr.ParserRuleContext | TerminalNode,
fullCode: string,
codePosition: { charIndex: number } = {
charIndex: 0
}
): Node[] {
if (antlrNode instanceof antlr.ParserRuleContext) {
let tree = new Tree(antlrNode.constructor.name);
if (antlrNode.start.startIndex > codePosition.charIndex) {
tree.children.push(
new Space(
fullCode.substring(codePosition.charIndex, antlrNode.start.startIndex)
)
);
codePosition.charIndex = antlrNode.start.startIndex;
}
for (let i = 0; i < antlrNode.childCount; i++) {
let child = antlrNode.getChild(i);
if (
child instanceof antlr.ParserRuleContext ||
child instanceof TerminalNode
) {
tree.children.push(...createSourceTree(child, fullCode, codePosition));
}
): Node[] {
if (antlrNode instanceof antlr.ParserRuleContext) {
let tree = new Tree(antlrNode.constructor.name);
if (antlrNode.start.startIndex > codePosition.charIndex) {
tree.children.push(
new Space(
fullCode.substring(codePosition.charIndex, antlrNode.start.startIndex)
)
);
codePosition.charIndex = antlrNode.start.startIndex;
}
for (let i = 0; i < antlrNode.childCount; i++) {
let child = antlrNode.getChild(i);
if (
child instanceof antlr.ParserRuleContext ||
child instanceof TerminalNode
) {
tree.children.push(...createSourceTree(child, fullCode, codePosition));
} else {
throw new Error("Unexpected child: " + child);
}
}
if (antlrNode.stop!.stopIndex > codePosition.charIndex) {
tree.children.push(
new Space(
fullCode.substring(
codePosition.charIndex,
antlrNode.stop!.stopIndex + 1
)
)
);