antlr-ng
Version:
Next generation ANTLR Tool
328 lines (327 loc) • 15.6 kB
JavaScript
var __create = Object.create;
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __knownSymbol = (name, symbol) => (symbol = Symbol[name]) ? symbol : Symbol.for("Symbol." + name);
var __typeError = (msg) => {
throw TypeError(msg);
};
var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
var __name = (target, value) => __defProp(target, "name", { value, configurable: true });
var __decoratorStart = (base) => [, , , __create(base?.[__knownSymbol("metadata")] ?? null)];
var __decoratorStrings = ["class", "method", "getter", "setter", "accessor", "field", "value", "get", "set"];
var __expectFn = (fn) => fn !== void 0 && typeof fn !== "function" ? __typeError("Function expected") : fn;
var __decoratorContext = (kind, name, done, metadata, fns) => ({ kind: __decoratorStrings[kind], name, metadata, addInitializer: (fn) => done._ ? __typeError("Already initialized") : fns.push(__expectFn(fn || null)) });
var __decoratorMetadata = (array, target) => __defNormalProp(target, __knownSymbol("metadata"), array[3]);
var __runInitializers = (array, flags, self, value) => {
for (var i = 0, fns = array[flags >> 1], n = fns && fns.length; i < n; i++) flags & 1 ? fns[i].call(self) : value = fns[i].call(self, value);
return value;
};
var __decorateElement = (array, flags, name, decorators, target, extra) => {
var fn, it, done, ctx, access, k = flags & 7, s = !!(flags & 8), p = !!(flags & 16);
var j = k > 3 ? array.length + 1 : k ? s ? 1 : 2 : 0, key = __decoratorStrings[k + 5];
var initializers = k > 3 && (array[j - 1] = []), extraInitializers = array[j] || (array[j] = []);
var desc = k && (!p && !s && (target = target.prototype), k < 5 && (k > 3 || !p) && __getOwnPropDesc(k < 4 ? target : { get [name]() {
return __privateGet(this, extra);
}, set [name](x) {
return __privateSet(this, extra, x);
} }, name));
k ? p && k < 4 && __name(extra, (k > 2 ? "set " : k > 1 ? "get " : "") + name) : __name(target, name);
for (var i = decorators.length - 1; i >= 0; i--) {
ctx = __decoratorContext(k, name, done = {}, array[3], extraInitializers);
if (k) {
ctx.static = s, ctx.private = p, access = ctx.access = { has: p ? (x) => __privateIn(target, x) : (x) => name in x };
if (k ^ 3) access.get = p ? (x) => (k ^ 1 ? __privateGet : __privateMethod)(x, target, k ^ 4 ? extra : desc.get) : (x) => x[name];
if (k > 2) access.set = p ? (x, y) => __privateSet(x, target, y, k ^ 4 ? extra : desc.set) : (x, y) => x[name] = y;
}
it = (0, decorators[i])(k ? k < 4 ? p ? extra : desc[key] : k > 4 ? void 0 : { get: desc.get, set: desc.set } : target, ctx), done._ = 1;
if (k ^ 4 || it === void 0) __expectFn(it) && (k > 4 ? initializers.unshift(it) : k ? p ? extra = it : desc[key] = it : target = it);
else if (typeof it !== "object" || it === null) __typeError("Object expected");
else __expectFn(fn = it.get) && (desc.get = fn), __expectFn(fn = it.set) && (desc.set = fn), __expectFn(fn = it.init) && initializers.unshift(fn);
}
return k || __decoratorMetadata(array, target), desc && __defProp(target, name, desc), p ? k ^ 4 ? extra : desc : target;
};
var __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);
var __accessCheck = (obj, member, msg) => member.has(obj) || __typeError("Cannot " + msg);
var __privateIn = (member, obj) => Object(obj) !== obj ? __typeError('Cannot use the "in" operator on this value') : member.has(obj);
var __privateGet = (obj, member, getter) => (__accessCheck(obj, member, "read from private field"), getter ? getter.call(obj) : member.get(obj));
var __privateSet = (obj, member, value, setter) => (__accessCheck(obj, member, "write to private field"), setter ? setter.call(obj, value) : member.set(obj, value), value);
var __privateMethod = (obj, member, method) => (__accessCheck(obj, member, "access private method"), method);
var _postamble_dec, _exceptions_dec, _finallyAction_dec, _namedActions_dec, _altLabelCtxs_dec, _ruleCtx_dec, _args_dec, _locals_dec, _code_dec, _a, _init;
import { IntervalSet, OrderedHashSet, RecognitionException } from "antlr4ng";
import { ANTLRv4Lexer } from "../../generated/ANTLRv4Lexer.js";
import { CommonTreeNodeStream } from "../../tree/CommonTreeNodeStream.js";
import { FrequencySet } from "../../misc/FrequencySet.js";
import { ModelElement } from "../../misc/ModelElement.js";
import { IssueCode } from "../../tool/Issues.js";
import { PredAST } from "../../tool/ast/PredAST.js";
import { Action } from "./Action.js";
import { ElementFrequenciesVisitor } from "./ElementFrequenciesVisitor.js";
import { ExceptionClause } from "./ExceptionClause.js";
import { OutputModelObject } from "./OutputModelObject.js";
import { AltLabelStructDecl } from "./decl/AltLabelStructDecl.js";
import { AttributeDecl } from "./decl/AttributeDecl.js";
import { ContextRuleGetterDecl } from "./decl/ContextRuleGetterDecl.js";
import { ContextRuleListGetterDecl } from "./decl/ContextRuleListGetterDecl.js";
import { ContextRuleListIndexedGetterDecl } from "./decl/ContextRuleListIndexedGetterDecl.js";
import { ContextTokenGetterDecl } from "./decl/ContextTokenGetterDecl.js";
import { ContextTokenListGetterDecl } from "./decl/ContextTokenListGetterDecl.js";
import { ContextTokenListIndexedGetterDecl } from "./decl/ContextTokenListIndexedGetterDecl.js";
import { StructDecl } from "./decl/StructDecl.js";
const _RuleFunction = class _RuleFunction extends (_a = OutputModelObject, _code_dec = [ModelElement], _locals_dec = [ModelElement], _args_dec = [ModelElement], _ruleCtx_dec = [ModelElement], _altLabelCtxs_dec = [ModelElement], _namedActions_dec = [ModelElement], _finallyAction_dec = [ModelElement], _exceptions_dec = [ModelElement], _postamble_dec = [ModelElement], _a) {
constructor(factory, r) {
super(factory);
__publicField(this, "name");
__publicField(this, "escapedName");
__publicField(this, "modifiers");
__publicField(this, "ctxType");
__publicField(this, "ruleLabels", null);
__publicField(this, "tokenLabels");
__publicField(this, "startState");
__publicField(this, "index");
__publicField(this, "rule");
__publicField(this, "altToContext");
__publicField(this, "hasLookaheadBlock");
__publicField(this, "code", __runInitializers(_init, 8, this)), __runInitializers(_init, 11, this);
__publicField(this, "locals", __runInitializers(_init, 12, this, new OrderedHashSet())), __runInitializers(_init, 15, this);
__publicField(this, "args", __runInitializers(_init, 16, this)), __runInitializers(_init, 19, this);
__publicField(this, "ruleCtx", __runInitializers(_init, 20, this)), __runInitializers(_init, 23, this);
__publicField(this, "altLabelCtxs", __runInitializers(_init, 24, this)), __runInitializers(_init, 27, this);
__publicField(this, "namedActions", __runInitializers(_init, 28, this)), __runInitializers(_init, 31, this);
__publicField(this, "finallyAction", __runInitializers(_init, 32, this)), __runInitializers(_init, 35, this);
__publicField(this, "exceptions", __runInitializers(_init, 36, this)), __runInitializers(_init, 39, this);
__publicField(this, "postamble", __runInitializers(_init, 40, this)), __runInitializers(_init, 43, this);
this.name = r.name;
this.escapedName = factory.getGenerator().target.escapeIfNeeded(r.name);
this.rule = r;
this.modifiers = this.nodesToStrings(r.modifiers ?? []);
this.index = r.index;
this.ruleCtx = new StructDecl(factory, r);
this.altToContext = new Array(r.getOriginalNumberOfAlts() + 1);
this.addContextGetters(factory, r);
if (r.args) {
if (r.args.attributes.size > 0) {
this.args = [];
this.ruleCtx.addDecls(Array.from(r.args.attributes.values()));
for (const a of r.args.attributes.values()) {
this.args.push(new AttributeDecl(factory, a));
}
this.ruleCtx.ctorAttrs = this.args;
}
}
if (r.retvals) {
this.ruleCtx.addDecls(Array.from(r.retvals.attributes.values()));
}
if (r.locals) {
this.ruleCtx.addDecls(Array.from(r.locals.attributes.values()));
}
this.ruleLabels = r.getElementLabelNames();
this.tokenLabels = r.getTokenRefs();
this.exceptions = new Array();
for (const e of r.exceptions) {
const catchArg = e.children[0];
const catchAction = e.children[1];
this.exceptions.push(new ExceptionClause(factory, catchArg, catchAction));
}
this.startState = factory.g.atn.ruleToStartState[r.index];
}
addContextGetters(factory, r) {
const altsNoLabels = r.getUnlabeledAltASTs();
if (altsNoLabels !== null) {
const decls = this.getDeclsForAllElements(altsNoLabels);
for (const d of decls) {
this.ruleCtx.addDecl(d);
}
}
this.altLabelCtxs = /* @__PURE__ */ new Map();
const labels = r.getAltLabels();
if (labels !== null) {
for (const [label, list] of labels) {
const alts = new Array();
for (const [_, ast] of list) {
alts.push(ast);
}
const decls = this.getDeclsForAllElements(alts);
for (const [altNum] of list) {
this.altToContext[altNum] = new AltLabelStructDecl(factory, r, altNum, label);
if (!this.altLabelCtxs.has(label)) {
this.altLabelCtxs.set(label, this.altToContext[altNum]);
}
for (const d of decls) {
this.altToContext[altNum].addDecl(d);
}
}
}
}
}
fillNamedActions(factory, r) {
if (r.finallyAction) {
this.finallyAction = new Action(factory, r.finallyAction);
}
this.namedActions = /* @__PURE__ */ new Map();
for (const name of r.namedActions.keys()) {
const ast = r.namedActions.get(name);
this.namedActions.set(name, new Action(factory, ast));
}
}
/**
* For all alts, find which ref X or r needs List. Must see across alts.
* If any alt needs X or r as list, then define as list.
*/
getDeclsForAllElements(altASTs) {
const needsList = /* @__PURE__ */ new Set();
const nonOptional = /* @__PURE__ */ new Set();
const allRefs = new Array();
let firstAlt = true;
const refTypes = new IntervalSet();
refTypes.addOne(ANTLRv4Lexer.RULE_REF);
refTypes.addOne(ANTLRv4Lexer.TOKEN_REF);
refTypes.addOne(ANTLRv4Lexer.STRING_LITERAL);
for (const ast of altASTs) {
const refs = this.getRuleTokens(ast.getNodesWithType(refTypes));
allRefs.push(...refs);
const [minFreq, altFreq] = this.getElementFrequenciesForAlt(ast);
for (const t of refs) {
const refLabelName = this.getName(t);
if (refLabelName !== null) {
if (altFreq.count(refLabelName) > 1) {
needsList.add(refLabelName);
}
if (firstAlt && minFreq.count(refLabelName) !== 0) {
nonOptional.add(refLabelName);
}
}
}
for (const ref of nonOptional) {
if (minFreq.count(ref) === 0) {
nonOptional.delete(ref);
}
}
firstAlt = false;
}
const decls = /* @__PURE__ */ new Set();
for (const t of allRefs) {
const refLabelName = this.getName(t);
if (refLabelName === null) {
continue;
}
const d = this.getDeclForAltElement(
t,
refLabelName,
needsList.has(refLabelName),
!nonOptional.has(refLabelName)
);
d.forEach((decl) => {
return decls.add(decl);
});
}
return decls;
}
getDeclForAltElement(t, refLabelName, needList, optional) {
const decls = new Array();
if (t.getType() === ANTLRv4Lexer.RULE_REF) {
const ruleRef = this.factory.g.getRule(t.getText());
const ctxName = this.factory.getGenerator().target.getRuleFunctionContextStructName(ruleRef);
if (needList) {
if (this.factory.getGenerator().target.supportsOverloadedMethods()) {
decls.push(new ContextRuleListGetterDecl(this.factory, refLabelName, ctxName));
}
decls.push(new ContextRuleListIndexedGetterDecl(this.factory, refLabelName, ctxName));
} else {
decls.push(new ContextRuleGetterDecl(this.factory, refLabelName, ctxName, optional));
}
} else {
if (needList) {
if (this.factory.getGenerator().target.supportsOverloadedMethods()) {
decls.push(new ContextTokenListGetterDecl(this.factory, refLabelName));
}
decls.push(new ContextTokenListIndexedGetterDecl(this.factory, refLabelName));
} else {
decls.push(new ContextTokenGetterDecl(this.factory, refLabelName, optional));
}
}
return decls;
}
/** Add local var decl */
addLocalDecl(d) {
this.locals.add(d);
d.isLocal = true;
}
/** Add decl to struct ctx for rule or alt if labeled. */
addContextDecl(altLabel, d) {
const alt = d.getOuterMostAltCodeBlock();
if (alt && this.altLabelCtxs) {
const altCtx = this.altLabelCtxs.get(altLabel);
if (altCtx) {
altCtx.addDecl(d);
return;
}
}
this.ruleCtx.addDecl(d);
}
/** Given list of X and r refs in alt, compute how many of each there are. */
getElementFrequenciesForAlt(ast) {
const errorManager = this.factory.g.tool.errorManager;
try {
const visitor = new ElementFrequenciesVisitor(errorManager, new CommonTreeNodeStream(ast));
visitor.outerAlternative();
if (visitor.frequencies.length !== 1) {
errorManager.toolError(IssueCode.InternalError);
return [new FrequencySet(), new FrequencySet()];
}
return [visitor.minFrequencies[0], visitor.frequencies[0]];
} catch (ex) {
if (ex instanceof RecognitionException) {
errorManager.toolError(IssueCode.InternalError, ex);
return [new FrequencySet(), new FrequencySet()];
} else {
throw ex;
}
}
}
getRuleTokens(refs) {
const result = [];
for (const ref of refs) {
let r = ref;
let ignore = false;
while (r !== null) {
if (r instanceof PredAST) {
ignore = true;
break;
}
r = r.parent;
}
if (!ignore) {
result.push(ref);
}
}
return result;
}
getName(token) {
const tokenText = token.getText();
const tokenName = token.getType() !== ANTLRv4Lexer.STRING_LITERAL ? tokenText : token.g.getTokenName(tokenText);
return tokenName === null || tokenName.startsWith("T__") ? null : tokenName;
}
nodesToStrings(nodes) {
const a = new Array();
for (const t of nodes) {
a.push(t.getText());
}
return a;
}
};
_init = __decoratorStart(_a);
__decorateElement(_init, 5, "code", _code_dec, _RuleFunction);
__decorateElement(_init, 5, "locals", _locals_dec, _RuleFunction);
__decorateElement(_init, 5, "args", _args_dec, _RuleFunction);
__decorateElement(_init, 5, "ruleCtx", _ruleCtx_dec, _RuleFunction);
__decorateElement(_init, 5, "altLabelCtxs", _altLabelCtxs_dec, _RuleFunction);
__decorateElement(_init, 5, "namedActions", _namedActions_dec, _RuleFunction);
__decorateElement(_init, 5, "finallyAction", _finallyAction_dec, _RuleFunction);
__decorateElement(_init, 5, "exceptions", _exceptions_dec, _RuleFunction);
__decorateElement(_init, 5, "postamble", _postamble_dec, _RuleFunction);
__decoratorMetadata(_init, _RuleFunction);
__name(_RuleFunction, "RuleFunction");
let RuleFunction = _RuleFunction;
export {
RuleFunction
};