univac
Version:
Generate AST of lots of common programming languages using antlr4. JavaScript API and CLI tool.
77 lines • 2.89 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
var misc_utils_of_mine_generic_1 = require("misc-utils-of-mine-generic");
function printNodeText(text, maxLength, escape) {
if (maxLength === void 0) { maxLength = 160; }
if (escape === void 0) { escape = true; }
var s = text.substring(0, Math.min(text.length, maxLength));
return escape ? s.replace(/"/gm, '\\"').replace(/[\n]+/gm, '\\n') : s;
}
exports.printNodeText = printNodeText;
function visitDescendants(_a) {
var n = _a.node, v = _a.visitor, _b = _a.childrenFirst, childrenFirst = _b === void 0 ? true : _b, parent = _a.parent, _c = _a.level, level = _c === void 0 ? 0 : _c;
if (!n) {
return false;
}
if (!childrenFirst && v(n, parent, level)) {
return true;
}
if (!n.children.some(function (c) { return visitDescendants({ node: c, visitor: v, childrenFirst: childrenFirst, parent: n, level: level + 1 }); })) {
return childrenFirst && v(n, parent, level);
}
else {
return true;
}
}
exports.visitDescendants = visitDescendants;
/**
* Adds parents to given node and descendants. If parents are detected, it does nothing. Useful in cases where the ast was generated without parents to add them programmatically after.
*/
function addParents(n) {
n.children.forEach(function (c) {
c.parent = n;
addParents(c);
});
}
exports.addParents = addParents;
/**
* Gets the minimal node containing given position
*/
function getNodeAtPosition(node, position) {
function includes(n, p) {
return n && (n.start.line <= p.line) &&
(n.stop.line >= p.line);
}
var found;
function find(n, p) {
if (includes(n, p)) {
if (!n.children.length) {
found = n;
return n;
}
var cc = n.children.find(function (c) { return !!find(c, p); });
if (!cc) {
found = n;
return n;
}
return found || cc || n;
}
}
return find(node, position);
}
exports.getNodeAtPosition = getNodeAtPosition;
function printNode(_a) {
var node = _a.node, _b = _a.level, level = _b === void 0 ? 0 : _b;
return (("\n<" + node.type + (node.text ? " text=\"" + printNodeText(node.text) + "\"" : '') + ">\n" + (node.children.length ?
"" + misc_utils_of_mine_generic_1.indent(level + 1) + (node.children.map(function (c) { return printNode({ node: c, level: level + 1 }); }).join('') + '\n') : '') + misc_utils_of_mine_generic_1.indent(level) + "</" + node.type + ">\n ").trim())
.replace(/\>\</gm, '\> \<');
}
exports.printNode = printNode;
function getNodeId(n) {
if (!n.__id) {
n.__id = misc_utils_of_mine_generic_1.unique('node');
}
return n.__id;
}
exports.getNodeId = getNodeId;
//# sourceMappingURL=node.js.map