mermaid
Version:
Markdown-ish syntax for generating flowcharts, mindmaps, sequence diagrams, class diagrams, gantt charts, git graphs and more.
32,843 lines • 1.34 MB
JavaScript
import {
__name
} from "./chunk-PTVI3W5X.mjs";
// ../parser/dist/chunks/mermaid-parser.core/chunk-FOHPRMQF.mjs
var __create = Object.create;
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __getProtoOf = Object.getPrototypeOf;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __name2 = /* @__PURE__ */ __name((target, value) => __defProp(target, "name", { value, configurable: true }), "__name");
var __esm = /* @__PURE__ */ __name((fn, res) => /* @__PURE__ */ __name(function __init() {
return fn && (res = (0, fn[__getOwnPropNames(fn)[0]])(fn = 0)), res;
}, "__init"), "__esm");
var __commonJS = /* @__PURE__ */ __name((cb, mod) => /* @__PURE__ */ __name(function __require() {
return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports;
}, "__require"), "__commonJS");
var __export = /* @__PURE__ */ __name((target, all) => {
for (var name in all)
__defProp(target, name, { get: all[name], enumerable: true });
}, "__export");
var __copyProps = /* @__PURE__ */ __name((to, from, except, desc) => {
if (from && typeof from === "object" || typeof from === "function") {
for (let key of __getOwnPropNames(from))
if (!__hasOwnProp.call(to, key) && key !== except)
__defProp(to, key, { get: /* @__PURE__ */ __name(() => from[key], "get"), enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
}
return to;
}, "__copyProps");
var __reExport = /* @__PURE__ */ __name((target, mod, secondTarget) => (__copyProps(target, mod, "default"), secondTarget && __copyProps(secondTarget, mod, "default")), "__reExport");
var __toESM = /* @__PURE__ */ __name((mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
// If the importer is in node compatibility mode or this is not an ESM
// file that has been converted to a CommonJS file using a Babel-
// compatible transform (i.e. "__esModule" has not been set), then set
// "default" to the CommonJS "module.exports" for node compatibility.
isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
mod
)), "__toESM");
var __toCommonJS = /* @__PURE__ */ __name((mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod), "__toCommonJS");
var main_exports = {};
__export(main_exports, {
AnnotatedTextEdit: /* @__PURE__ */ __name(() => AnnotatedTextEdit, "AnnotatedTextEdit"),
ChangeAnnotation: /* @__PURE__ */ __name(() => ChangeAnnotation, "ChangeAnnotation"),
ChangeAnnotationIdentifier: /* @__PURE__ */ __name(() => ChangeAnnotationIdentifier, "ChangeAnnotationIdentifier"),
CodeAction: /* @__PURE__ */ __name(() => CodeAction, "CodeAction"),
CodeActionContext: /* @__PURE__ */ __name(() => CodeActionContext, "CodeActionContext"),
CodeActionKind: /* @__PURE__ */ __name(() => CodeActionKind, "CodeActionKind"),
CodeActionTriggerKind: /* @__PURE__ */ __name(() => CodeActionTriggerKind, "CodeActionTriggerKind"),
CodeDescription: /* @__PURE__ */ __name(() => CodeDescription, "CodeDescription"),
CodeLens: /* @__PURE__ */ __name(() => CodeLens, "CodeLens"),
Color: /* @__PURE__ */ __name(() => Color, "Color"),
ColorInformation: /* @__PURE__ */ __name(() => ColorInformation, "ColorInformation"),
ColorPresentation: /* @__PURE__ */ __name(() => ColorPresentation, "ColorPresentation"),
Command: /* @__PURE__ */ __name(() => Command, "Command"),
CompletionItem: /* @__PURE__ */ __name(() => CompletionItem, "CompletionItem"),
CompletionItemKind: /* @__PURE__ */ __name(() => CompletionItemKind, "CompletionItemKind"),
CompletionItemLabelDetails: /* @__PURE__ */ __name(() => CompletionItemLabelDetails, "CompletionItemLabelDetails"),
CompletionItemTag: /* @__PURE__ */ __name(() => CompletionItemTag, "CompletionItemTag"),
CompletionList: /* @__PURE__ */ __name(() => CompletionList, "CompletionList"),
CreateFile: /* @__PURE__ */ __name(() => CreateFile, "CreateFile"),
DeleteFile: /* @__PURE__ */ __name(() => DeleteFile, "DeleteFile"),
Diagnostic: /* @__PURE__ */ __name(() => Diagnostic, "Diagnostic"),
DiagnosticRelatedInformation: /* @__PURE__ */ __name(() => DiagnosticRelatedInformation, "DiagnosticRelatedInformation"),
DiagnosticSeverity: /* @__PURE__ */ __name(() => DiagnosticSeverity, "DiagnosticSeverity"),
DiagnosticTag: /* @__PURE__ */ __name(() => DiagnosticTag, "DiagnosticTag"),
DocumentHighlight: /* @__PURE__ */ __name(() => DocumentHighlight, "DocumentHighlight"),
DocumentHighlightKind: /* @__PURE__ */ __name(() => DocumentHighlightKind, "DocumentHighlightKind"),
DocumentLink: /* @__PURE__ */ __name(() => DocumentLink, "DocumentLink"),
DocumentSymbol: /* @__PURE__ */ __name(() => DocumentSymbol, "DocumentSymbol"),
DocumentUri: /* @__PURE__ */ __name(() => DocumentUri, "DocumentUri"),
EOL: /* @__PURE__ */ __name(() => EOL, "EOL"),
FoldingRange: /* @__PURE__ */ __name(() => FoldingRange, "FoldingRange"),
FoldingRangeKind: /* @__PURE__ */ __name(() => FoldingRangeKind, "FoldingRangeKind"),
FormattingOptions: /* @__PURE__ */ __name(() => FormattingOptions, "FormattingOptions"),
Hover: /* @__PURE__ */ __name(() => Hover, "Hover"),
InlayHint: /* @__PURE__ */ __name(() => InlayHint, "InlayHint"),
InlayHintKind: /* @__PURE__ */ __name(() => InlayHintKind, "InlayHintKind"),
InlayHintLabelPart: /* @__PURE__ */ __name(() => InlayHintLabelPart, "InlayHintLabelPart"),
InlineCompletionContext: /* @__PURE__ */ __name(() => InlineCompletionContext, "InlineCompletionContext"),
InlineCompletionItem: /* @__PURE__ */ __name(() => InlineCompletionItem, "InlineCompletionItem"),
InlineCompletionList: /* @__PURE__ */ __name(() => InlineCompletionList, "InlineCompletionList"),
InlineCompletionTriggerKind: /* @__PURE__ */ __name(() => InlineCompletionTriggerKind, "InlineCompletionTriggerKind"),
InlineValueContext: /* @__PURE__ */ __name(() => InlineValueContext, "InlineValueContext"),
InlineValueEvaluatableExpression: /* @__PURE__ */ __name(() => InlineValueEvaluatableExpression, "InlineValueEvaluatableExpression"),
InlineValueText: /* @__PURE__ */ __name(() => InlineValueText, "InlineValueText"),
InlineValueVariableLookup: /* @__PURE__ */ __name(() => InlineValueVariableLookup, "InlineValueVariableLookup"),
InsertReplaceEdit: /* @__PURE__ */ __name(() => InsertReplaceEdit, "InsertReplaceEdit"),
InsertTextFormat: /* @__PURE__ */ __name(() => InsertTextFormat, "InsertTextFormat"),
InsertTextMode: /* @__PURE__ */ __name(() => InsertTextMode, "InsertTextMode"),
Location: /* @__PURE__ */ __name(() => Location, "Location"),
LocationLink: /* @__PURE__ */ __name(() => LocationLink, "LocationLink"),
MarkedString: /* @__PURE__ */ __name(() => MarkedString, "MarkedString"),
MarkupContent: /* @__PURE__ */ __name(() => MarkupContent, "MarkupContent"),
MarkupKind: /* @__PURE__ */ __name(() => MarkupKind, "MarkupKind"),
OptionalVersionedTextDocumentIdentifier: /* @__PURE__ */ __name(() => OptionalVersionedTextDocumentIdentifier, "OptionalVersionedTextDocumentIdentifier"),
ParameterInformation: /* @__PURE__ */ __name(() => ParameterInformation, "ParameterInformation"),
Position: /* @__PURE__ */ __name(() => Position, "Position"),
Range: /* @__PURE__ */ __name(() => Range, "Range"),
RenameFile: /* @__PURE__ */ __name(() => RenameFile, "RenameFile"),
SelectedCompletionInfo: /* @__PURE__ */ __name(() => SelectedCompletionInfo, "SelectedCompletionInfo"),
SelectionRange: /* @__PURE__ */ __name(() => SelectionRange, "SelectionRange"),
SemanticTokenModifiers: /* @__PURE__ */ __name(() => SemanticTokenModifiers, "SemanticTokenModifiers"),
SemanticTokenTypes: /* @__PURE__ */ __name(() => SemanticTokenTypes, "SemanticTokenTypes"),
SemanticTokens: /* @__PURE__ */ __name(() => SemanticTokens, "SemanticTokens"),
SignatureInformation: /* @__PURE__ */ __name(() => SignatureInformation, "SignatureInformation"),
StringValue: /* @__PURE__ */ __name(() => StringValue, "StringValue"),
SymbolInformation: /* @__PURE__ */ __name(() => SymbolInformation, "SymbolInformation"),
SymbolKind: /* @__PURE__ */ __name(() => SymbolKind, "SymbolKind"),
SymbolTag: /* @__PURE__ */ __name(() => SymbolTag, "SymbolTag"),
TextDocument: /* @__PURE__ */ __name(() => TextDocument, "TextDocument"),
TextDocumentEdit: /* @__PURE__ */ __name(() => TextDocumentEdit, "TextDocumentEdit"),
TextDocumentIdentifier: /* @__PURE__ */ __name(() => TextDocumentIdentifier, "TextDocumentIdentifier"),
TextDocumentItem: /* @__PURE__ */ __name(() => TextDocumentItem, "TextDocumentItem"),
TextEdit: /* @__PURE__ */ __name(() => TextEdit, "TextEdit"),
URI: /* @__PURE__ */ __name(() => URI, "URI"),
VersionedTextDocumentIdentifier: /* @__PURE__ */ __name(() => VersionedTextDocumentIdentifier, "VersionedTextDocumentIdentifier"),
WorkspaceChange: /* @__PURE__ */ __name(() => WorkspaceChange, "WorkspaceChange"),
WorkspaceEdit: /* @__PURE__ */ __name(() => WorkspaceEdit, "WorkspaceEdit"),
WorkspaceFolder: /* @__PURE__ */ __name(() => WorkspaceFolder, "WorkspaceFolder"),
WorkspaceSymbol: /* @__PURE__ */ __name(() => WorkspaceSymbol, "WorkspaceSymbol"),
integer: /* @__PURE__ */ __name(() => integer, "integer"),
uinteger: /* @__PURE__ */ __name(() => uinteger, "uinteger")
});
var DocumentUri;
var URI;
var integer;
var uinteger;
var Position;
var Range;
var Location;
var LocationLink;
var Color;
var ColorInformation;
var ColorPresentation;
var FoldingRangeKind;
var FoldingRange;
var DiagnosticRelatedInformation;
var DiagnosticSeverity;
var DiagnosticTag;
var CodeDescription;
var Diagnostic;
var Command;
var TextEdit;
var ChangeAnnotation;
var ChangeAnnotationIdentifier;
var AnnotatedTextEdit;
var TextDocumentEdit;
var CreateFile;
var RenameFile;
var DeleteFile;
var WorkspaceEdit;
var TextEditChangeImpl;
var ChangeAnnotations;
var WorkspaceChange;
var TextDocumentIdentifier;
var VersionedTextDocumentIdentifier;
var OptionalVersionedTextDocumentIdentifier;
var TextDocumentItem;
var MarkupKind;
var MarkupContent;
var CompletionItemKind;
var InsertTextFormat;
var CompletionItemTag;
var InsertReplaceEdit;
var InsertTextMode;
var CompletionItemLabelDetails;
var CompletionItem;
var CompletionList;
var MarkedString;
var Hover;
var ParameterInformation;
var SignatureInformation;
var DocumentHighlightKind;
var DocumentHighlight;
var SymbolKind;
var SymbolTag;
var SymbolInformation;
var WorkspaceSymbol;
var DocumentSymbol;
var CodeActionKind;
var CodeActionTriggerKind;
var CodeActionContext;
var CodeAction;
var CodeLens;
var FormattingOptions;
var DocumentLink;
var SelectionRange;
var SemanticTokenTypes;
var SemanticTokenModifiers;
var SemanticTokens;
var InlineValueText;
var InlineValueVariableLookup;
var InlineValueEvaluatableExpression;
var InlineValueContext;
var InlayHintKind;
var InlayHintLabelPart;
var InlayHint;
var StringValue;
var InlineCompletionItem;
var InlineCompletionList;
var InlineCompletionTriggerKind;
var SelectedCompletionInfo;
var InlineCompletionContext;
var WorkspaceFolder;
var EOL;
var TextDocument;
var FullTextDocument;
var Is;
var init_main = __esm({
"../../node_modules/.pnpm/vscode-languageserver-types@3.17.5/node_modules/vscode-languageserver-types/lib/esm/main.js"() {
"use strict";
(function(DocumentUri2) {
function is(value) {
return typeof value === "string";
}
__name(is, "is");
__name2(is, "is");
DocumentUri2.is = is;
})(DocumentUri || (DocumentUri = {}));
(function(URI3) {
function is(value) {
return typeof value === "string";
}
__name(is, "is");
__name2(is, "is");
URI3.is = is;
})(URI || (URI = {}));
(function(integer2) {
integer2.MIN_VALUE = -2147483648;
integer2.MAX_VALUE = 2147483647;
function is(value) {
return typeof value === "number" && integer2.MIN_VALUE <= value && value <= integer2.MAX_VALUE;
}
__name(is, "is");
__name2(is, "is");
integer2.is = is;
})(integer || (integer = {}));
(function(uinteger2) {
uinteger2.MIN_VALUE = 0;
uinteger2.MAX_VALUE = 2147483647;
function is(value) {
return typeof value === "number" && uinteger2.MIN_VALUE <= value && value <= uinteger2.MAX_VALUE;
}
__name(is, "is");
__name2(is, "is");
uinteger2.is = is;
})(uinteger || (uinteger = {}));
(function(Position2) {
function create(line, character) {
if (line === Number.MAX_VALUE) {
line = uinteger.MAX_VALUE;
}
if (character === Number.MAX_VALUE) {
character = uinteger.MAX_VALUE;
}
return { line, character };
}
__name(create, "create");
__name2(create, "create");
Position2.create = create;
function is(value) {
let candidate = value;
return Is.objectLiteral(candidate) && Is.uinteger(candidate.line) && Is.uinteger(candidate.character);
}
__name(is, "is");
__name2(is, "is");
Position2.is = is;
})(Position || (Position = {}));
(function(Range2) {
function create(one, two, three, four) {
if (Is.uinteger(one) && Is.uinteger(two) && Is.uinteger(three) && Is.uinteger(four)) {
return { start: Position.create(one, two), end: Position.create(three, four) };
} else if (Position.is(one) && Position.is(two)) {
return { start: one, end: two };
} else {
throw new Error(`Range#create called with invalid arguments[${one}, ${two}, ${three}, ${four}]`);
}
}
__name(create, "create");
__name2(create, "create");
Range2.create = create;
function is(value) {
let candidate = value;
return Is.objectLiteral(candidate) && Position.is(candidate.start) && Position.is(candidate.end);
}
__name(is, "is");
__name2(is, "is");
Range2.is = is;
})(Range || (Range = {}));
(function(Location2) {
function create(uri, range) {
return { uri, range };
}
__name(create, "create");
__name2(create, "create");
Location2.create = create;
function is(value) {
let candidate = value;
return Is.objectLiteral(candidate) && Range.is(candidate.range) && (Is.string(candidate.uri) || Is.undefined(candidate.uri));
}
__name(is, "is");
__name2(is, "is");
Location2.is = is;
})(Location || (Location = {}));
(function(LocationLink2) {
function create(targetUri, targetRange, targetSelectionRange, originSelectionRange) {
return { targetUri, targetRange, targetSelectionRange, originSelectionRange };
}
__name(create, "create");
__name2(create, "create");
LocationLink2.create = create;
function is(value) {
let candidate = value;
return Is.objectLiteral(candidate) && Range.is(candidate.targetRange) && Is.string(candidate.targetUri) && Range.is(candidate.targetSelectionRange) && (Range.is(candidate.originSelectionRange) || Is.undefined(candidate.originSelectionRange));
}
__name(is, "is");
__name2(is, "is");
LocationLink2.is = is;
})(LocationLink || (LocationLink = {}));
(function(Color2) {
function create(red, green, blue, alpha) {
return {
red,
green,
blue,
alpha
};
}
__name(create, "create");
__name2(create, "create");
Color2.create = create;
function is(value) {
const candidate = value;
return Is.objectLiteral(candidate) && Is.numberRange(candidate.red, 0, 1) && Is.numberRange(candidate.green, 0, 1) && Is.numberRange(candidate.blue, 0, 1) && Is.numberRange(candidate.alpha, 0, 1);
}
__name(is, "is");
__name2(is, "is");
Color2.is = is;
})(Color || (Color = {}));
(function(ColorInformation2) {
function create(range, color) {
return {
range,
color
};
}
__name(create, "create");
__name2(create, "create");
ColorInformation2.create = create;
function is(value) {
const candidate = value;
return Is.objectLiteral(candidate) && Range.is(candidate.range) && Color.is(candidate.color);
}
__name(is, "is");
__name2(is, "is");
ColorInformation2.is = is;
})(ColorInformation || (ColorInformation = {}));
(function(ColorPresentation2) {
function create(label, textEdit, additionalTextEdits) {
return {
label,
textEdit,
additionalTextEdits
};
}
__name(create, "create");
__name2(create, "create");
ColorPresentation2.create = create;
function is(value) {
const candidate = value;
return Is.objectLiteral(candidate) && Is.string(candidate.label) && (Is.undefined(candidate.textEdit) || TextEdit.is(candidate)) && (Is.undefined(candidate.additionalTextEdits) || Is.typedArray(candidate.additionalTextEdits, TextEdit.is));
}
__name(is, "is");
__name2(is, "is");
ColorPresentation2.is = is;
})(ColorPresentation || (ColorPresentation = {}));
(function(FoldingRangeKind2) {
FoldingRangeKind2.Comment = "comment";
FoldingRangeKind2.Imports = "imports";
FoldingRangeKind2.Region = "region";
})(FoldingRangeKind || (FoldingRangeKind = {}));
(function(FoldingRange2) {
function create(startLine, endLine, startCharacter, endCharacter, kind, collapsedText) {
const result = {
startLine,
endLine
};
if (Is.defined(startCharacter)) {
result.startCharacter = startCharacter;
}
if (Is.defined(endCharacter)) {
result.endCharacter = endCharacter;
}
if (Is.defined(kind)) {
result.kind = kind;
}
if (Is.defined(collapsedText)) {
result.collapsedText = collapsedText;
}
return result;
}
__name(create, "create");
__name2(create, "create");
FoldingRange2.create = create;
function is(value) {
const candidate = value;
return Is.objectLiteral(candidate) && Is.uinteger(candidate.startLine) && Is.uinteger(candidate.startLine) && (Is.undefined(candidate.startCharacter) || Is.uinteger(candidate.startCharacter)) && (Is.undefined(candidate.endCharacter) || Is.uinteger(candidate.endCharacter)) && (Is.undefined(candidate.kind) || Is.string(candidate.kind));
}
__name(is, "is");
__name2(is, "is");
FoldingRange2.is = is;
})(FoldingRange || (FoldingRange = {}));
(function(DiagnosticRelatedInformation2) {
function create(location, message) {
return {
location,
message
};
}
__name(create, "create");
__name2(create, "create");
DiagnosticRelatedInformation2.create = create;
function is(value) {
let candidate = value;
return Is.defined(candidate) && Location.is(candidate.location) && Is.string(candidate.message);
}
__name(is, "is");
__name2(is, "is");
DiagnosticRelatedInformation2.is = is;
})(DiagnosticRelatedInformation || (DiagnosticRelatedInformation = {}));
(function(DiagnosticSeverity2) {
DiagnosticSeverity2.Error = 1;
DiagnosticSeverity2.Warning = 2;
DiagnosticSeverity2.Information = 3;
DiagnosticSeverity2.Hint = 4;
})(DiagnosticSeverity || (DiagnosticSeverity = {}));
(function(DiagnosticTag2) {
DiagnosticTag2.Unnecessary = 1;
DiagnosticTag2.Deprecated = 2;
})(DiagnosticTag || (DiagnosticTag = {}));
(function(CodeDescription2) {
function is(value) {
const candidate = value;
return Is.objectLiteral(candidate) && Is.string(candidate.href);
}
__name(is, "is");
__name2(is, "is");
CodeDescription2.is = is;
})(CodeDescription || (CodeDescription = {}));
(function(Diagnostic2) {
function create(range, message, severity, code, source, relatedInformation) {
let result = { range, message };
if (Is.defined(severity)) {
result.severity = severity;
}
if (Is.defined(code)) {
result.code = code;
}
if (Is.defined(source)) {
result.source = source;
}
if (Is.defined(relatedInformation)) {
result.relatedInformation = relatedInformation;
}
return result;
}
__name(create, "create");
__name2(create, "create");
Diagnostic2.create = create;
function is(value) {
var _a;
let candidate = value;
return Is.defined(candidate) && Range.is(candidate.range) && Is.string(candidate.message) && (Is.number(candidate.severity) || Is.undefined(candidate.severity)) && (Is.integer(candidate.code) || Is.string(candidate.code) || Is.undefined(candidate.code)) && (Is.undefined(candidate.codeDescription) || Is.string((_a = candidate.codeDescription) === null || _a === void 0 ? void 0 : _a.href)) && (Is.string(candidate.source) || Is.undefined(candidate.source)) && (Is.undefined(candidate.relatedInformation) || Is.typedArray(candidate.relatedInformation, DiagnosticRelatedInformation.is));
}
__name(is, "is");
__name2(is, "is");
Diagnostic2.is = is;
})(Diagnostic || (Diagnostic = {}));
(function(Command2) {
function create(title, command, ...args) {
let result = { title, command };
if (Is.defined(args) && args.length > 0) {
result.arguments = args;
}
return result;
}
__name(create, "create");
__name2(create, "create");
Command2.create = create;
function is(value) {
let candidate = value;
return Is.defined(candidate) && Is.string(candidate.title) && Is.string(candidate.command);
}
__name(is, "is");
__name2(is, "is");
Command2.is = is;
})(Command || (Command = {}));
(function(TextEdit2) {
function replace(range, newText) {
return { range, newText };
}
__name(replace, "replace");
__name2(replace, "replace");
TextEdit2.replace = replace;
function insert(position, newText) {
return { range: { start: position, end: position }, newText };
}
__name(insert, "insert");
__name2(insert, "insert");
TextEdit2.insert = insert;
function del(range) {
return { range, newText: "" };
}
__name(del, "del");
__name2(del, "del");
TextEdit2.del = del;
function is(value) {
const candidate = value;
return Is.objectLiteral(candidate) && Is.string(candidate.newText) && Range.is(candidate.range);
}
__name(is, "is");
__name2(is, "is");
TextEdit2.is = is;
})(TextEdit || (TextEdit = {}));
(function(ChangeAnnotation2) {
function create(label, needsConfirmation, description) {
const result = { label };
if (needsConfirmation !== void 0) {
result.needsConfirmation = needsConfirmation;
}
if (description !== void 0) {
result.description = description;
}
return result;
}
__name(create, "create");
__name2(create, "create");
ChangeAnnotation2.create = create;
function is(value) {
const candidate = value;
return Is.objectLiteral(candidate) && Is.string(candidate.label) && (Is.boolean(candidate.needsConfirmation) || candidate.needsConfirmation === void 0) && (Is.string(candidate.description) || candidate.description === void 0);
}
__name(is, "is");
__name2(is, "is");
ChangeAnnotation2.is = is;
})(ChangeAnnotation || (ChangeAnnotation = {}));
(function(ChangeAnnotationIdentifier2) {
function is(value) {
const candidate = value;
return Is.string(candidate);
}
__name(is, "is");
__name2(is, "is");
ChangeAnnotationIdentifier2.is = is;
})(ChangeAnnotationIdentifier || (ChangeAnnotationIdentifier = {}));
(function(AnnotatedTextEdit2) {
function replace(range, newText, annotation) {
return { range, newText, annotationId: annotation };
}
__name(replace, "replace");
__name2(replace, "replace");
AnnotatedTextEdit2.replace = replace;
function insert(position, newText, annotation) {
return { range: { start: position, end: position }, newText, annotationId: annotation };
}
__name(insert, "insert");
__name2(insert, "insert");
AnnotatedTextEdit2.insert = insert;
function del(range, annotation) {
return { range, newText: "", annotationId: annotation };
}
__name(del, "del");
__name2(del, "del");
AnnotatedTextEdit2.del = del;
function is(value) {
const candidate = value;
return TextEdit.is(candidate) && (ChangeAnnotation.is(candidate.annotationId) || ChangeAnnotationIdentifier.is(candidate.annotationId));
}
__name(is, "is");
__name2(is, "is");
AnnotatedTextEdit2.is = is;
})(AnnotatedTextEdit || (AnnotatedTextEdit = {}));
(function(TextDocumentEdit2) {
function create(textDocument, edits) {
return { textDocument, edits };
}
__name(create, "create");
__name2(create, "create");
TextDocumentEdit2.create = create;
function is(value) {
let candidate = value;
return Is.defined(candidate) && OptionalVersionedTextDocumentIdentifier.is(candidate.textDocument) && Array.isArray(candidate.edits);
}
__name(is, "is");
__name2(is, "is");
TextDocumentEdit2.is = is;
})(TextDocumentEdit || (TextDocumentEdit = {}));
(function(CreateFile2) {
function create(uri, options, annotation) {
let result = {
kind: "create",
uri
};
if (options !== void 0 && (options.overwrite !== void 0 || options.ignoreIfExists !== void 0)) {
result.options = options;
}
if (annotation !== void 0) {
result.annotationId = annotation;
}
return result;
}
__name(create, "create");
__name2(create, "create");
CreateFile2.create = create;
function is(value) {
let candidate = value;
return candidate && candidate.kind === "create" && Is.string(candidate.uri) && (candidate.options === void 0 || (candidate.options.overwrite === void 0 || Is.boolean(candidate.options.overwrite)) && (candidate.options.ignoreIfExists === void 0 || Is.boolean(candidate.options.ignoreIfExists))) && (candidate.annotationId === void 0 || ChangeAnnotationIdentifier.is(candidate.annotationId));
}
__name(is, "is");
__name2(is, "is");
CreateFile2.is = is;
})(CreateFile || (CreateFile = {}));
(function(RenameFile2) {
function create(oldUri, newUri, options, annotation) {
let result = {
kind: "rename",
oldUri,
newUri
};
if (options !== void 0 && (options.overwrite !== void 0 || options.ignoreIfExists !== void 0)) {
result.options = options;
}
if (annotation !== void 0) {
result.annotationId = annotation;
}
return result;
}
__name(create, "create");
__name2(create, "create");
RenameFile2.create = create;
function is(value) {
let candidate = value;
return candidate && candidate.kind === "rename" && Is.string(candidate.oldUri) && Is.string(candidate.newUri) && (candidate.options === void 0 || (candidate.options.overwrite === void 0 || Is.boolean(candidate.options.overwrite)) && (candidate.options.ignoreIfExists === void 0 || Is.boolean(candidate.options.ignoreIfExists))) && (candidate.annotationId === void 0 || ChangeAnnotationIdentifier.is(candidate.annotationId));
}
__name(is, "is");
__name2(is, "is");
RenameFile2.is = is;
})(RenameFile || (RenameFile = {}));
(function(DeleteFile2) {
function create(uri, options, annotation) {
let result = {
kind: "delete",
uri
};
if (options !== void 0 && (options.recursive !== void 0 || options.ignoreIfNotExists !== void 0)) {
result.options = options;
}
if (annotation !== void 0) {
result.annotationId = annotation;
}
return result;
}
__name(create, "create");
__name2(create, "create");
DeleteFile2.create = create;
function is(value) {
let candidate = value;
return candidate && candidate.kind === "delete" && Is.string(candidate.uri) && (candidate.options === void 0 || (candidate.options.recursive === void 0 || Is.boolean(candidate.options.recursive)) && (candidate.options.ignoreIfNotExists === void 0 || Is.boolean(candidate.options.ignoreIfNotExists))) && (candidate.annotationId === void 0 || ChangeAnnotationIdentifier.is(candidate.annotationId));
}
__name(is, "is");
__name2(is, "is");
DeleteFile2.is = is;
})(DeleteFile || (DeleteFile = {}));
(function(WorkspaceEdit2) {
function is(value) {
let candidate = value;
return candidate && (candidate.changes !== void 0 || candidate.documentChanges !== void 0) && (candidate.documentChanges === void 0 || candidate.documentChanges.every((change) => {
if (Is.string(change.kind)) {
return CreateFile.is(change) || RenameFile.is(change) || DeleteFile.is(change);
} else {
return TextDocumentEdit.is(change);
}
}));
}
__name(is, "is");
__name2(is, "is");
WorkspaceEdit2.is = is;
})(WorkspaceEdit || (WorkspaceEdit = {}));
TextEditChangeImpl = class {
static {
__name(this, "TextEditChangeImpl");
}
static {
__name2(this, "TextEditChangeImpl");
}
constructor(edits, changeAnnotations) {
this.edits = edits;
this.changeAnnotations = changeAnnotations;
}
insert(position, newText, annotation) {
let edit;
let id;
if (annotation === void 0) {
edit = TextEdit.insert(position, newText);
} else if (ChangeAnnotationIdentifier.is(annotation)) {
id = annotation;
edit = AnnotatedTextEdit.insert(position, newText, annotation);
} else {
this.assertChangeAnnotations(this.changeAnnotations);
id = this.changeAnnotations.manage(annotation);
edit = AnnotatedTextEdit.insert(position, newText, id);
}
this.edits.push(edit);
if (id !== void 0) {
return id;
}
}
replace(range, newText, annotation) {
let edit;
let id;
if (annotation === void 0) {
edit = TextEdit.replace(range, newText);
} else if (ChangeAnnotationIdentifier.is(annotation)) {
id = annotation;
edit = AnnotatedTextEdit.replace(range, newText, annotation);
} else {
this.assertChangeAnnotations(this.changeAnnotations);
id = this.changeAnnotations.manage(annotation);
edit = AnnotatedTextEdit.replace(range, newText, id);
}
this.edits.push(edit);
if (id !== void 0) {
return id;
}
}
delete(range, annotation) {
let edit;
let id;
if (annotation === void 0) {
edit = TextEdit.del(range);
} else if (ChangeAnnotationIdentifier.is(annotation)) {
id = annotation;
edit = AnnotatedTextEdit.del(range, annotation);
} else {
this.assertChangeAnnotations(this.changeAnnotations);
id = this.changeAnnotations.manage(annotation);
edit = AnnotatedTextEdit.del(range, id);
}
this.edits.push(edit);
if (id !== void 0) {
return id;
}
}
add(edit) {
this.edits.push(edit);
}
all() {
return this.edits;
}
clear() {
this.edits.splice(0, this.edits.length);
}
assertChangeAnnotations(value) {
if (value === void 0) {
throw new Error(`Text edit change is not configured to manage change annotations.`);
}
}
};
ChangeAnnotations = class {
static {
__name(this, "ChangeAnnotations");
}
static {
__name2(this, "ChangeAnnotations");
}
constructor(annotations) {
this._annotations = annotations === void 0 ? /* @__PURE__ */ Object.create(null) : annotations;
this._counter = 0;
this._size = 0;
}
all() {
return this._annotations;
}
get size() {
return this._size;
}
manage(idOrAnnotation, annotation) {
let id;
if (ChangeAnnotationIdentifier.is(idOrAnnotation)) {
id = idOrAnnotation;
} else {
id = this.nextId();
annotation = idOrAnnotation;
}
if (this._annotations[id] !== void 0) {
throw new Error(`Id ${id} is already in use.`);
}
if (annotation === void 0) {
throw new Error(`No annotation provided for id ${id}`);
}
this._annotations[id] = annotation;
this._size++;
return id;
}
nextId() {
this._counter++;
return this._counter.toString();
}
};
WorkspaceChange = class {
static {
__name(this, "WorkspaceChange");
}
static {
__name2(this, "WorkspaceChange");
}
constructor(workspaceEdit) {
this._textEditChanges = /* @__PURE__ */ Object.create(null);
if (workspaceEdit !== void 0) {
this._workspaceEdit = workspaceEdit;
if (workspaceEdit.documentChanges) {
this._changeAnnotations = new ChangeAnnotations(workspaceEdit.changeAnnotations);
workspaceEdit.changeAnnotations = this._changeAnnotations.all();
workspaceEdit.documentChanges.forEach((change) => {
if (TextDocumentEdit.is(change)) {
const textEditChange = new TextEditChangeImpl(change.edits, this._changeAnnotations);
this._textEditChanges[change.textDocument.uri] = textEditChange;
}
});
} else if (workspaceEdit.changes) {
Object.keys(workspaceEdit.changes).forEach((key) => {
const textEditChange = new TextEditChangeImpl(workspaceEdit.changes[key]);
this._textEditChanges[key] = textEditChange;
});
}
} else {
this._workspaceEdit = {};
}
}
/**
* Returns the underlying {@link WorkspaceEdit} literal
* use to be returned from a workspace edit operation like rename.
*/
get edit() {
this.initDocumentChanges();
if (this._changeAnnotations !== void 0) {
if (this._changeAnnotations.size === 0) {
this._workspaceEdit.changeAnnotations = void 0;
} else {
this._workspaceEdit.changeAnnotations = this._changeAnnotations.all();
}
}
return this._workspaceEdit;
}
getTextEditChange(key) {
if (OptionalVersionedTextDocumentIdentifier.is(key)) {
this.initDocumentChanges();
if (this._workspaceEdit.documentChanges === void 0) {
throw new Error("Workspace edit is not configured for document changes.");
}
const textDocument = { uri: key.uri, version: key.version };
let result = this._textEditChanges[textDocument.uri];
if (!result) {
const edits = [];
const textDocumentEdit = {
textDocument,
edits
};
this._workspaceEdit.documentChanges.push(textDocumentEdit);
result = new TextEditChangeImpl(edits, this._changeAnnotations);
this._textEditChanges[textDocument.uri] = result;
}
return result;
} else {
this.initChanges();
if (this._workspaceEdit.changes === void 0) {
throw new Error("Workspace edit is not configured for normal text edit changes.");
}
let result = this._textEditChanges[key];
if (!result) {
let edits = [];
this._workspaceEdit.changes[key] = edits;
result = new TextEditChangeImpl(edits);
this._textEditChanges[key] = result;
}
return result;
}
}
initDocumentChanges() {
if (this._workspaceEdit.documentChanges === void 0 && this._workspaceEdit.changes === void 0) {
this._changeAnnotations = new ChangeAnnotations();
this._workspaceEdit.documentChanges = [];
this._workspaceEdit.changeAnnotations = this._changeAnnotations.all();
}
}
initChanges() {
if (this._workspaceEdit.documentChanges === void 0 && this._workspaceEdit.changes === void 0) {
this._workspaceEdit.changes = /* @__PURE__ */ Object.create(null);
}
}
createFile(uri, optionsOrAnnotation, options) {
this.initDocumentChanges();
if (this._workspaceEdit.documentChanges === void 0) {
throw new Error("Workspace edit is not configured for document changes.");
}
let annotation;
if (ChangeAnnotation.is(optionsOrAnnotation) || ChangeAnnotationIdentifier.is(optionsOrAnnotation)) {
annotation = optionsOrAnnotation;
} else {
options = optionsOrAnnotation;
}
let operation;
let id;
if (annotation === void 0) {
operation = CreateFile.create(uri, options);
} else {
id = ChangeAnnotationIdentifier.is(annotation) ? annotation : this._changeAnnotations.manage(annotation);
operation = CreateFile.create(uri, options, id);
}
this._workspaceEdit.documentChanges.push(operation);
if (id !== void 0) {
return id;
}
}
renameFile(oldUri, newUri, optionsOrAnnotation, options) {
this.initDocumentChanges();
if (this._workspaceEdit.documentChanges === void 0) {
throw new Error("Workspace edit is not configured for document changes.");
}
let annotation;
if (ChangeAnnotation.is(optionsOrAnnotation) || ChangeAnnotationIdentifier.is(optionsOrAnnotation)) {
annotation = optionsOrAnnotation;
} else {
options = optionsOrAnnotation;
}
let operation;
let id;
if (annotation === void 0) {
operation = RenameFile.create(oldUri, newUri, options);
} else {
id = ChangeAnnotationIdentifier.is(annotation) ? annotation : this._changeAnnotations.manage(annotation);
operation = RenameFile.create(oldUri, newUri, options, id);
}
this._workspaceEdit.documentChanges.push(operation);
if (id !== void 0) {
return id;
}
}
deleteFile(uri, optionsOrAnnotation, options) {
this.initDocumentChanges();
if (this._workspaceEdit.documentChanges === void 0) {
throw new Error("Workspace edit is not configured for document changes.");
}
let annotation;
if (ChangeAnnotation.is(optionsOrAnnotation) || ChangeAnnotationIdentifier.is(optionsOrAnnotation)) {
annotation = optionsOrAnnotation;
} else {
options = optionsOrAnnotation;
}
let operation;
let id;
if (annotation === void 0) {
operation = DeleteFile.create(uri, options);
} else {
id = ChangeAnnotationIdentifier.is(annotation) ? annotation : this._changeAnnotations.manage(annotation);
operation = DeleteFile.create(uri, options, id);
}
this._workspaceEdit.documentChanges.push(operation);
if (id !== void 0) {
return id;
}
}
};
(function(TextDocumentIdentifier2) {
function create(uri) {
return { uri };
}
__name(create, "create");
__name2(create, "create");
TextDocumentIdentifier2.create = create;
function is(value) {
let candidate = value;
return Is.defined(candidate) && Is.string(candidate.uri);
}
__name(is, "is");
__name2(is, "is");
TextDocumentIdentifier2.is = is;
})(TextDocumentIdentifier || (TextDocumentIdentifier = {}));
(function(VersionedTextDocumentIdentifier2) {
function create(uri, version) {
return { uri, version };
}
__name(create, "create");
__name2(create, "create");
VersionedTextDocumentIdentifier2.create = create;
function is(value) {
let candidate = value;
return Is.defined(candidate) && Is.string(candidate.uri) && Is.integer(candidate.version);
}
__name(is, "is");
__name2(is, "is");
VersionedTextDocumentIdentifier2.is = is;
})(VersionedTextDocumentIdentifier || (VersionedTextDocumentIdentifier = {}));
(function(OptionalVersionedTextDocumentIdentifier2) {
function create(uri, version) {
return { uri, version };
}
__name(create, "create");
__name2(create, "create");
OptionalVersionedTextDocumentIdentifier2.create = create;
function is(value) {
let candidate = value;
return Is.defined(candidate) && Is.string(candidate.uri) && (candidate.version === null || Is.integer(candidate.version));
}
__name(is, "is");
__name2(is, "is");
OptionalVersionedTextDocumentIdentifier2.is = is;
})(OptionalVersionedTextDocumentIdentifier || (OptionalVersionedTextDocumentIdentifier = {}));
(function(TextDocumentItem2) {
function create(uri, languageId, version, text) {
return { uri, languageId, version, text };
}
__name(create, "create");
__name2(create, "create");
TextDocumentItem2.create = create;
function is(value) {
let candidate = value;
return Is.defined(candidate) && Is.string(candidate.uri) && Is.string(candidate.languageId) && Is.integer(candidate.version) && Is.string(candidate.text);
}
__name(is, "is");
__name2(is, "is");
TextDocumentItem2.is = is;
})(TextDocumentItem || (TextDocumentItem = {}));
(function(MarkupKind2) {
MarkupKind2.PlainText = "plaintext";
MarkupKind2.Markdown = "markdown";
function is(value) {
const candidate = value;
return candidate === MarkupKind2.PlainText || candidate === MarkupKind2.Markdown;
}
__name(is, "is");
__name2(is, "is");
MarkupKind2.is = is;
})(MarkupKind || (MarkupKind = {}));
(function(MarkupContent2) {
function is(value) {
const candidate = value;
return Is.objectLiteral(value) && MarkupKind.is(candidate.kind) && Is.string(candidate.value);
}
__name(is, "is");
__name2(is, "is");
MarkupContent2.is = is;
})(MarkupContent || (MarkupContent = {}));
(function(CompletionItemKind2) {
CompletionItemKind2.Text = 1;
CompletionItemKind2.Method = 2;
CompletionItemKind2.Function = 3;
CompletionItemKind2.Constructor = 4;
CompletionItemKind2.Field = 5;
CompletionItemKind2.Variable = 6;
CompletionItemKind2.Class = 7;
CompletionItemKind2.Interface = 8;
CompletionItemKind2.Module = 9;
CompletionItemKind2.Property = 10;
CompletionItemKind2.Unit = 11;
CompletionItemKind2.Value = 12;
CompletionItemKind2.Enum = 13;
CompletionItemKind2.Keyword = 14;
CompletionItemKind2.Snippet = 15;
CompletionItemKind2.Color = 16;
CompletionItemKind2.File = 17;
CompletionItemKind2.Reference = 18;
CompletionItemKind2.Folder = 19;
CompletionItemKind2.EnumMember = 20;
CompletionItemKind2.Constant = 21;
CompletionItemKind2.Struct = 22;
CompletionItemKind2.Event = 23;
CompletionItemKind2.Operator = 24;
CompletionItemKind2.TypeParameter = 25;
})(CompletionItemKind || (CompletionItemKind = {}));
(function(InsertTextFormat2) {
InsertTextFormat2.PlainText = 1;
InsertTextFormat2.Snippet = 2;
})(InsertTextFormat || (InsertTextFormat = {}));
(function(CompletionItemTag2) {
CompletionItemTag2.Deprecated = 1;
})(CompletionItemTag || (CompletionItemTag = {}));
(function(InsertReplaceEdit2) {
function create(newText, insert, replace) {
return { newText, insert, replace };
}
__name(create, "create");
__name2(create, "create");
InsertReplaceEdit2.create = create;
function is(value) {
const candidate = value;
return candidate && Is.string(candidate.newText) && Range.is(candidate.insert) && Range.is(candidate.replace);
}
__name(is, "is");
__name2(is, "is");
InsertReplaceEdit2.is = is;
})(InsertReplaceEdit || (InsertReplaceEdit = {}));
(function(InsertTextMode2) {
InsertTextMode2.asIs = 1;
InsertTextMode2.adjustIndentation = 2;
})(InsertTextMode || (InsertTextMode = {}));
(function(CompletionItemLabelDetails2) {
function is(value) {
const candidate = value;
return candidate && (Is.string(candidate.detail) || candidate.detail === void 0) && (Is.string(candidate.description) || candidate.description === void 0);
}
__name(is, "is");
__name2(is, "is");
CompletionItemLabelDetails2.is = is;
})(CompletionItemLabelDetails || (CompletionItemLabelDetails = {}));
(function(CompletionItem2) {
function create(label) {
return { label };
}
__name(create, "create");
__name2(create, "create");
CompletionItem2.create = create;
})(CompletionItem || (CompletionItem = {}));
(function(CompletionList2) {
function create(items, isIncomplete) {
return { items: items ? items : [], isIncomplete: !!isIncomplete };
}
__name(create, "create");
__name2(create, "create");
CompletionList2.create = create;
})(CompletionList || (CompletionList = {}));
(function(MarkedString2) {
function fromPlainText(plainText) {
return plainText.replace(/[\\`*_{}[\]()#+\-.!]/g, "\\$&");
}
__name(fromPlainText, "fromPlainText");
__name2(fromPlainText, "fromPlainText");
MarkedString2.fromPlainText = fromPlainText;
function is(value) {
const candidate = value;
return Is.string(candidate) || Is.objectLiteral(candidate) && Is.string(candidate.language) && Is.string(candidate.value);
}
__name(is, "is");
__name2(is, "is");
MarkedString2.is = is;
})(MarkedString || (MarkedString = {}));
(function(Hover2) {
function is(value) {
let candidate = value;
return !!candidate && Is.objectLiteral(candidate) && (MarkupContent.is(candidate.contents) || MarkedString.is(candidate.contents) || Is.typedArray(candidate.contents, MarkedString.is)) && (value.range === void 0 || Range.is(value.range));
}
__name(is, "is");
__name2(is, "is");
Hover2.is = is;
})(Hover || (Hover = {}));
(function(ParameterInformation2) {
function create(label, documentation) {
return documentation ? { label, documentation } : { label };
}
__name(create, "create");
__name2(create, "create");
ParameterInformation2.create = create;
})(ParameterInformation || (ParameterInformation = {}));
(function(SignatureInformation2) {
function create(label, documentation, ...parameters) {
let result = { label };
if (Is.defined(documentation)) {
result.documentation = documentation;
}
if (Is.defined(parameters)) {
result.parameters = parameters;
} else {
result.parameters = [];
}
return result;
}
__name(create, "create");
__name2(create, "create");
SignatureInformation2.create = create;
})(SignatureInformation || (SignatureInformation = {}));
(function(DocumentHighlightKind2) {
DocumentHighlightKind2.Text = 1;
DocumentHighlightKind2.Read = 2;
DocumentHighlightKind2.Write = 3;
})(DocumentHighlightKind || (DocumentHighlightKind = {}));
(function(DocumentHighlight2) {
function create(range, kind) {
let result = { range };
if (Is.number(kind)) {
result.kind = kind;
}
return result;
}
__name(create, "create");
__name2(create, "create");
DocumentHighlight2.create = create;
})(DocumentHighlight || (DocumentHighlight = {}));
(function(SymbolKind2) {
SymbolKind2.File = 1;
SymbolKind2.Module = 2;
SymbolKind2.Namespace = 3;
SymbolKind2.Package = 4;
SymbolKind2.Class = 5;
SymbolKind2.Method = 6;
SymbolKind2.Property = 7;
SymbolKind2.Field = 8;
SymbolKind2.Constructor = 9;
SymbolKind2.Enum = 10;
SymbolKind2.Interface = 11;
SymbolKind2.Function = 12;
SymbolKind2.Variable = 13;
SymbolKind2.Constant = 14;
SymbolKind2.String = 15;
SymbolKind2.Number = 16;
SymbolKind2.Boolean = 17;
SymbolKind2.Array = 18;
SymbolKind2.Object = 19;
SymbolKind2.Key = 20;
SymbolKind2.Null = 21;
SymbolKind2.EnumMember = 22;
SymbolKind2.Struct = 23;
SymbolKind2.Event = 24;
SymbolKind2.Operator = 25;
SymbolKind2.TypeParameter = 26;
})(SymbolKind || (SymbolKind = {}));
(function(SymbolTag2) {
SymbolTag2.Deprecated = 1;
})(SymbolTag || (SymbolTag = {}));
(function(SymbolInformation2) {
function create(name, kind, range, uri, containerName) {
let result = {
name,
kind,
location: { uri, range }
};
if (containerName) {
result.containerName = containerName;
}
return result;
}
__name(create, "create");
__name2(create, "create");
SymbolInformation2.create = create;
})(SymbolInformation || (SymbolInformation = {}));
(function(WorkspaceSymbol2) {
function create(name, kind, uri, range) {
return range !== void 0 ? { name, kind, location: { uri, range } } : { name, kind, location: { uri } };
}
__name(create, "create");
__name2(create, "create");
WorkspaceSymbol2.create = create;
})(WorkspaceSymbol || (WorkspaceSymbol = {}));
(function(DocumentSymbol2) {
function create(name, detail, kind, range, selectionRange, children) {
let result = {
name,
detail,
kind,
range,
selectionRange
};
if (children !== void 0) {
result.children = children;
}
return result;
}
__name(create, "create");
__name2(create, "create");
DocumentSymbol2.create = create;
function is(value) {
let candidate = value;
return candidate && Is.string(candidate.name) && Is.number(candidate.kind) && Range.is(candidate.range) && Range.is(candidate.selectionRange) && (candidate.detail === void 0 || Is.string(candidate.detail)) && (candidate.deprecated === void 0 || Is.boolean(candidate.deprecated)) && (candidate.children === void 0 || Array.isArray(candidate.children)) && (candidate.tags === void 0 || Array.isArray(candidate.tags));
}
__name(is, "is");
__name2(is, "is");
DocumentSymbol2.is = is;
})(DocumentSymbol || (DocumentSymbol = {}));
(function(CodeActionKind2) {
CodeActionKind2.Empty = "";
CodeActionKind2.QuickFix = "quickfix";
CodeActionKind2.Refactor = "refactor";
CodeActionKind2.RefactorExtract = "refactor.extract";
CodeActionKind2.RefactorInline = "refactor.inline";
CodeActionKind2.RefactorRewrite = "refactor.rewrite";
CodeActionKind2.Source = "source";
CodeActionKind2.SourceOrganizeImports = "source.organizeImports";
CodeActionKind2.SourceFixAll = "source.fixAll";
})(CodeActionKind || (CodeActionKind = {}));
(function(CodeActionTriggerKind2) {
CodeActionTriggerKind2.Invoked = 1;
CodeActionTriggerKind2.Automatic = 2;
})(CodeActionTriggerKind || (CodeActionTriggerKind = {}));
(function(CodeActionContext2) {
function create(diagnostics, only, triggerKind) {
let result = { diagnostics };
if (only !== void 0 && only !== null) {
result.only = only;
}
if (triggerKind !== void 0 && triggerKind !== null) {
result.triggerKind = triggerKind;
}
return result;
}
__name(create, "create");
__name2(create, "create");
CodeActionContext2.create = create;
function is(value) {
let candidate = value;
return Is.defined(candidate) && Is.typedArray(candidate.diagnostics, Diagnostic.is) && (candidate.only === void 0 || Is.typedArray(candidate.only, Is.string)) && (candidate.triggerKind === void 0 || candidate.triggerKind === CodeActionTriggerKind.Invoked || candidate.triggerKind === CodeActionTriggerKind.Automatic);
}
__name(is, "is");
__name2(is, "is");
CodeActionContext2.is = is;
})(CodeActionContext || (CodeActionContext = {}));
(function(CodeAction2) {
function create(title, kindOrCommandOrEdit, kind) {
let result = { title };
let checkKind = true;
if (typeof kindOrCommandOrEdit === "string") {
checkKind = false;
result.kind = kindOrCommandOrEdit;
} else if (Command.is(kindOrCommandOrEdit)) {
result.command = kindOrCommandOrEdit;
} else {
result.edit = kindOrCommandOrEdit;
}
if (checkKind && kind !== void 0) {
result.kind = kind;
}
return result;
}
__name(create, "create");
__name2(create, "create");
CodeAction2.create = create;
function is(value) {
let candidate = value;
return candidate && Is.string(candidate.title) && (candidate.diagnostics === void 0 || Is.typedArray(candidate.diagnostics, Diagnostic.is)) && (candidate.kind === void 0 || Is.string(candidate.kind)) && (candidate.edit !== void 0 || candidate.command !== void 0) && (candidate.command === void 0 || Command.is(candidate.command)) && (candidate.isPreferred === void 0 || Is.boolean(candidate.isPreferred)) && (candidate.edit === void 0 || WorkspaceEdit.is(candidate.edit));
}
__name(is, "is");
__name2(is, "is");
CodeAction2.is = is;
})(CodeAction || (CodeAction = {}));
(function(CodeLens2) {
function create(range, data) {
let result = { range };
if (Is.defined(data)) {
result.data = data;
}
return result;
}
__name(create, "create");
__name2(create, "create");
CodeLens2.create = create;
function is(value) {
let candidate = value;
return Is.defined(candidate) && Range.is(candidate.range) && (Is.undefined(candidate.command) || Command.is(candidate.command));
}
__name(is, "is");
__name2(is, "is");
CodeLens2.is = is;
})(CodeLens || (CodeLens = {}));
(function(FormattingOptions2) {
function create(tabSize, insertSpaces) {
return { tabSize, insertSpaces };
}
__name(create, "create");
__name2(create, "create");
FormattingOptions2.create = create;
function is(value) {
let candidate = value;
return Is.defined(candidate) && Is.uinteger(candidate.tabSize) && Is.boolean(candidate.insertSpaces);
}
__name(is, "is");
__name2(is, "is");
FormattingOptions2.is = is;
})(FormattingOptions || (FormattingOptions = {}));
(function(DocumentLink2) {
function create(range, target, data) {
return { range, target, data };
}
__name(create, "create");
__name2(create, "create");
DocumentLink2.create = create;
function is(value) {
let candidate = value;
return Is.defined(candidate) && Range.is(candidate.range) && (Is.undefined(candidate.target) || Is.string(candidate.target));
}
__name(is, "is");
__name2(is, "is");
DocumentLink2.is = is;
})(DocumentLink || (DocumentLink = {}));
(function(SelectionRange2) {
function create(range, parent) {
return { range, parent };
}
__name(create, "create");
__name2(create, "create");
SelectionRange2.create = create;
function is(value) {
let candidate = value;
return Is.objectLiteral(candidate) && Range.is(candidate.range) && (candidate.parent === void 0 || SelectionRange2.is(candidate.parent));
}
__name(is, "is");
__name2(is, "is");
SelectionRange2.is = is;
})(SelectionRange || (SelectionRange = {}));
(function(SemanticTokenTypes2) {
SemanticTokenTypes2["namespace"] = "namespace";
SemanticTokenTypes2["type"] = "type";
SemanticTokenTypes2["class"] = "class";
SemanticTokenTypes2["enum"] = "enum";
SemanticTokenTypes2["interface"] = "interface";
SemanticTokenTypes2["struct"] = "struct";
SemanticTokenTypes2["typeParameter"] = "typeParameter";
SemanticTokenTypes2["parameter"] = "parameter";
SemanticTokenTypes2["variable"] = "variable";
SemanticTokenTypes2["property"] = "property";
SemanticTokenTypes2["enumMember"] = "enumMember";
SemanticTokenTypes2["event"] = "event";
SemanticTokenTypes2["function"] = "function";
SemanticTokenTypes2["method"] = "method";
SemanticTokenTypes2["macro"] = "macro";
SemanticTokenTypes2["keyword"] = "keyword";
SemanticTokenTypes2["modifier"] = "modifier";
SemanticTokenTypes2["comment"] = "comment";
SemanticTokenTypes2["string"] = "string";
SemanticTokenTypes2["number"] = "number";
SemanticTokenTypes2["regexp"] = "regexp";
SemanticTokenTypes2["operator"] = "operator";
SemanticTokenTypes2["decorator"] = "decorator";
})(SemanticTokenTypes || (SemanticTokenTypes = {}));
(function(SemanticTokenModifiers2) {
SemanticTokenModifiers2["declaration"] = "declaration";
SemanticTokenModifiers2["definition"] = "definition";
SemanticTokenModifiers2["readonly"] = "readonly";
SemanticTokenModifiers2["static"] = "static";
SemanticTokenModifiers2["deprecated"] = "deprecated";
SemanticTokenModifiers2["abstract"] = "abstract";
SemanticTokenModifiers2["async"] = "async";
SemanticTokenModifiers2["modification"] = "modification";
SemanticTokenModifiers2["documentation"] = "documentation";
SemanticTokenModifiers2["defaultLibrary"] = "defaultLibrary";
})(SemanticTokenModifiers || (SemanticTokenModifiers = {}));
(function(SemanticTokens2) {
function is(value) {
const candidate = value;
return Is.objectLiteral(candidate) && (candidate.resultId === void 0 || typeof candidate.resultId === "string") && Array.isArray(candidate.data) && (candidate.data.length === 0 || typeof candidate.data[0] === "number");
}
__name(is, "is");
__name2(is, "is");
SemanticTokens2.is = is;
})(SemanticTokens || (SemanticTokens = {}));
(function(InlineValueText2) {
function create(range, text) {
return { range, text };
}
__name(create, "create");
__name2(create, "create");
InlineValueText2.create = create;
function is(value) {
const candidate = value;
return candidate !== void 0 && candidate !== null && Range.is(candidate.range) && Is.string(candidate.text);
}
__name(is, "is");
__name2(is, "is");
InlineValueText2.is = is;
})(InlineValueText || (InlineValueText = {}));
(function(InlineValueVariableLookup2) {
function create(range, variableName, caseSensitiveLookup) {
return { range, variableName, caseSensitiveLookup };
}
__name(create, "create");
__name2(create, "create");
InlineValueVariableLookup2.create = create;
function is(value) {
const candidate = value;
return candidate !== void 0 && candidate !== null && Range.is(candidate.range) && Is.boolean(candidate.caseSensitiveLookup) && (Is.string(candidate.variableName) || candidate.variableName === void 0);
}
__name(is, "is");
__name2(is, "is");
InlineValueVariableLookup2.is = is;
})(InlineValueVariableLookup || (InlineValueVariableLookup = {}));
(function(InlineValueEvaluatableExpression2) {
function create(range, expression) {
return { range, expression };
}
__name(create, "create");
__name2(create, "create");
InlineValueEvaluatableExpression2.create = create;
function is(value) {
const candidate = value;
return candidate !== void 0 && candidate !== null && Range.is(candidate.range) && (Is.string(candidate.expression) || candidate.expression === void 0);
}
__name(is, "is");
__name2(is, "is");
InlineValueEvaluatableExpression2.is = is;
})(InlineValueEvaluatableExpression || (InlineValueEvaluatableExpression = {}));
(function(InlineValueContext2) {
function create(frameId, stoppedLocation) {
return { frameId, stoppedLocation };
}
__name(create, "create");
__name2(create, "create");
InlineValueContext2.create = create;
function is(value) {
const candidate = value;
return Is.defined(candidate) && Range.is(value.stoppedLocation);
}
__name(is, "is");
__name2(is, "is");
InlineValueContext2.is = is;
})(InlineValueContext || (InlineValueContext = {}));
(function(InlayHintKind2) {
InlayHintKind2.Type = 1;
InlayHintKind2.Parameter = 2;
function is(value) {
return value === 1 || value === 2;
}
__name(is, "is");
__name2(is, "is");
InlayHintKind2.is = is;
})(InlayHintKind || (InlayHintKind = {}));
(function(InlayHintLabelPart2) {
function create(value) {
return { value };
}
__name(create, "create");
__name2(create, "create");
InlayHintLabelPart2.create = create;
function is(value) {
const candidate = value;
return Is.objectLiteral(candidate) && (candidate.tooltip === void 0 || Is.string(candidate.tooltip) || MarkupContent.is(candidate.tooltip)) && (candidate.location === void 0 || Location.is(candidate.location)) && (candidate.command === void 0 || Command.is(candidate.command));
}
__name(is, "is");
__name2(is, "is");
InlayHintLabelPart2.is = is;
})(InlayHintLabelPart || (InlayHintLabelPart = {}));
(function(InlayHint2) {
function create(position, label, kind) {
const result = { position, label };
if (kind !== void 0) {
result.kind = kind;
}
return result;
}
__name(create, "create");
__name2(create, "create");
InlayHint2.create = create;
function is(value) {
const candidate = value;
return Is.objectLiteral(candidate) && Position.is(candidate.position) && (Is.string(candidate.label) || Is.typedArray(candidate.label, InlayHintLabelPart.is)) && (candidate.kind === void 0 || InlayHintKind.is(candidate.kind)) && candidate.textEdits === void 0 || Is.typedArray(candidate.textEdits, TextEdit.is) && (candidate.tooltip === void 0 || Is.string(candidate.tooltip) || MarkupContent.is(candidate.tooltip)) && (candidate.paddingLeft === void 0 || Is.boolean(candidate.paddingLeft)) && (candidate.paddingRight === void 0 || Is.boolean(candidate.paddingRight));
}
__name(is, "is");
__name2(is, "is");
InlayHint2.is = is;
})(InlayHint || (InlayHint = {}));
(function(StringValue2) {
function createSnippet(value) {
return { kind: "snippet", value };
}
__name(createSnippet, "createSnippet");
__name2(createSnippet, "createSnippet");
StringValue2.createSnippet = createSnippet;
})(StringValue || (StringValue = {}));
(function(InlineCompletionItem2) {
function create(insertText, filterText, range, command) {
return { insertText, filterText, range, command };
}
__name(create, "create");
__name2(create, "create");
InlineCompletionItem2.create = create;
})(InlineCompletionItem || (InlineCompletionItem = {}));
(function(InlineCompletionList2) {
function create(items) {
return { items };
}
__name(create, "create");
__name2(create, "create");
InlineCompletionList2.create = create;
})(InlineCompletionList || (InlineCompletionList = {}));
(function(InlineCompletionTriggerKind2) {
InlineCompletionTriggerKind2.Invoked = 0;
InlineCompletionTriggerKind2.Automatic = 1;
})(InlineCompletionTriggerKind || (InlineCompletionTriggerKind = {}));
(function(SelectedCompletionInfo2) {
function create(range, text) {
return { range, text };
}
__name(create, "create");
__name2(create, "create");
SelectedCompletionInfo2.create = create;
})(SelectedCompletionInfo || (SelectedCompletionInfo = {}));
(function(InlineCompletionContext2) {
function create(triggerKind, selectedCompletionInfo) {
return { triggerKind, selectedCompletionInfo };
}
__name(create, "create");
__name2(create, "create");
InlineCompletionContext2.create = create;
})(InlineCompletionContext || (InlineCompletionContext = {}));
(function(WorkspaceFolder2) {
function is(value) {
const candidate = value;
return Is.objectLiteral(candidate) && URI.is(candidate.uri) && Is.string(candidate.name);
}
__name(is, "is");
__name2(is, "is");
WorkspaceFolder2.is = is;
})(WorkspaceFolder || (WorkspaceFolder = {}));
EOL = ["\n", "\r\n", "\r"];
(function(TextDocument3) {
function create(uri, languageId, version, content) {
return new FullTextDocument(uri, languageId, version, content);
}
__name(create, "create");
__name2(create, "create");
TextDocument3.create = create;
function is(value) {
let candidate = value;
return Is.defined(candidate) && Is.string(candidate.uri) && (Is.undefined(candidate.languageId) || Is.string(candidate.languageId)) && Is.uinteger(candidate.lineCount) && Is.func(candidate.getText) && Is.func(candidate.positionAt) && Is.func(candidate.offsetAt) ? true : false;
}
__name(is, "is");
__name2(is, "is");
TextDocument3.is = is;
function applyEdits(document, edits) {
let text = document.getText();
let sortedEdits = mergeSort2(edits, (a, b) => {
let diff = a.range.start.line - b.range.start.line;
if (diff === 0) {
return a.range.start.character - b.range.start.character;
}
return diff;
});
let lastModifiedOffset = text.length;
for (let i = sortedEdits.length - 1; i >= 0; i--) {
let e = sortedEdits[i];
let startOffset = document.offsetAt(e.range.start);
let endOffset = document.offsetAt(e.range.end);
if (endOffset <= lastModifiedOffset) {
text = text.substring(0, startOffset) + e.newText + text.substring(endOffset, text.length);
} else {
throw new Error("Overlapping edit");
}
lastModifiedOffset = startOffset;
}
return text;
}
__name(applyEdits, "applyEdits");
__name2(applyEdits, "applyEdits");
TextDocument3.applyEdits = applyEdits;
function mergeSort2(data, compare) {
if (data.length <= 1) {
return data;
}
const p = data.length / 2 | 0;
const left = data.slice(0, p);
const right = data.slice(p);
mergeSort2(left, compare);
mergeSort2(right, compare);
let leftIdx = 0;
let rightIdx = 0;
let i = 0;
while (leftIdx < left.length && rightIdx < right.length) {
let ret = compare(left[leftIdx], right[rightIdx]);
if (ret <= 0) {
data[i++] = left[leftIdx++];
} else {
data[i++] = right[rightIdx++];
}
}
while (leftIdx < left.length) {
data[i++] = left[leftIdx++];
}
while (rightIdx < right.length) {
data[i++] = right[rightIdx++];
}
return data;
}
__name(mergeSort2, "mergeSort2");
__name2(mergeSort2, "mergeSort");
})(TextDocument || (TextDocument = {}));
FullTextDocument = class {
static {
__name(this, "FullTextDocument");
}
static {
__name2(this, "FullTextDocument");
}
constructor(uri, languageId, version, content) {
this._uri = uri;
this._languageId = languageId;
this._version = version;
this._content = content;
this._lineOffsets = void 0;
}
get uri() {
return this._uri;
}
get languageId() {
return this._languageId;
}
get version() {
return this._version;
}
getText(range) {
if (range) {
let start = this.offsetAt(range.start);
let end = this.offsetAt(range.end);
return this._content.substring(start, end);
}
return this._content;
}
update(event, version) {
this._content = event.text;
this._version = version;
this._lineOffsets = void 0;
}
getLineOffsets() {
if (this._lineOffsets === void 0) {
let lineOffsets = [];
let text = this._content;
let isLineStart = true;
for (let i = 0; i < text.length; i++) {
if (isLineStart) {
lineOffsets.push(i);
isLineStart = false;
}
let ch = text.charAt(i);
isLineStart = ch === "\r" || ch === "\n";
if (ch === "\r" && i + 1 < text.length && text.charAt(i + 1) === "\n") {
i++;
}
}
if (isLineStart && text.length > 0) {
lineOffsets.push(text.length);
}
this._lineOffsets = lineOffsets;
}
return this._lineOffsets;
}
positionAt(offset) {
offset = Math.max(Math.min(offset, this._content.length), 0);
let lineOffsets = this.getLineOffsets();
let low = 0, high = lineOffsets.length;
if (high === 0) {
return Position.create(0, offset);
}
while (low < high) {
let mid = Math.floor((low + high) / 2);
if (lineOffsets[mid] > offset) {
high = mid;
} else {
low = mid + 1;
}
}
let line = low - 1;
return Position.create(line, offset - lineOffsets[line]);
}
offsetAt(position) {
let lineOffsets = this.getLineOffsets();
if (position.line >= lineOffsets.length) {
return this._content.length;
} else if (position.line < 0) {
return 0;
}
let lineOffset = lineOffsets[position.line];
let nextLineOffset = position.line + 1 < lineOffsets.length ? lineOffsets[position.line + 1] : this._content.length;
return Math.max(Math.min(lineOffset + position.character, nextLineOffset), lineOffset);
}
get lineCount() {
return this.getLineOffsets().length;
}
};
(function(Is2) {
const toString4 = Object.prototype.toString;
function defined(value) {
return typeof value !== "undefined";
}
__name(defined, "defined");
__name2(defined, "defined");
Is2.defined = defined;
function undefined2(value) {
return typeof value === "undefined";
}
__name(undefined2, "undefined2");
__name2(undefined2, "undefined");
Is2.undefined = undefined2;
function boolean(value) {
return value === true || value === false;
}
__name(boolean, "boolean");
__name2(boolean, "boolean");
Is2.boolean = boolean;
function string(value) {
return toString4.call(value) === "[object String]";
}
__name(string, "string");
__name2(string, "string");
Is2.string = string;
function number(value) {
return toString4.call(value) === "[object Number]";
}
__name(number, "number");
__name2(number, "number");
Is2.number = number;
function numberRange(value, min2, max) {
return toString4.call(value) === "[object Number]" && min2 <= value && value <= max;
}
__name(numberRange, "numberRange");
__name2(numberRange, "numberRange");
Is2.numberRange = numberRange;
function integer2(value) {
return toString4.call(value) === "[object Number]" && -2147483648 <= value && value <= 2147483647;
}
__name(integer2, "integer2");
__name2(integer2, "integer");
Is2.integer = integer2;
function uinteger2(value) {
return toString4.call(value) === "[object Number]" && 0 <= value && value <= 2147483647;
}
__name(uinteger2, "uinteger2");
__name2(uinteger2, "uinteger");
Is2.uinteger = uinteger2;
function func(value) {
return toString4.call(value) === "[object Function]";
}
__name(func, "func");
__name2(func, "func");
Is2.func = func;
function objectLiteral(value) {
return value !== null && typeof value === "object";
}
__name(objectLiteral, "objectLiteral");
__name2(objectLiteral, "objectLiteral");
Is2.objectLiteral = objectLiteral;
function typedArray(value, check) {
return Array.isArray(value) && value.every(check);
}
__name(typedArray, "typedArray");
__name2(typedArray, "typedArray");
Is2.typedArray = typedArray;
})(Is || (Is = {}));
}
});
var require_ral = __commonJS({
"../../node_modules/.pnpm/vscode-jsonrpc@8.2.0/node_modules/vscode-jsonrpc/lib/common/ral.js"(exports2) {
"use strict";
Object.defineProperty(exports2, "__esModule", { value: true });
var _ral;
function RAL() {
if (_ral === void 0) {
throw new Error(`No runtime abstraction layer installed`);
}
return _ral;
}
__name(RAL, "RAL");
__name2(RAL, "RAL");
(function(RAL2) {
function install(ral) {
if (ral === void 0) {
throw new Error(`No runtime abstraction layer provided`);
}
_ral = ral;
}
__name(install, "install");
__name2(install, "install");
RAL2.install = install;
})(RAL || (RAL = {}));
exports2.default = RAL;
}
});
var require_is = __commonJS({
"../../node_modules/.pnpm/vscode-jsonrpc@8.2.0/node_modules/vscode-jsonrpc/lib/common/is.js"(exports2) {
"use strict";
Object.defineProperty(exports2, "__esModule", { value: true });
exports2.stringArray = exports2.array = exports2.func = exports2.error = exports2.number = exports2.string = exports2.boolean = void 0;
function boolean(value) {
return value === true || value === false;
}
__name(boolean, "boolean");
__name2(boolean, "boolean");
exports2.boolean = boolean;
function string(value) {
return typeof value === "string" || value instanceof String;
}
__name(string, "string");
__name2(string, "string");
exports2.string = string;
function number(value) {
return typeof value === "number" || value instanceof Number;
}
__name(number, "number");
__name2(number, "number");
exports2.number = number;
function error(value) {
return value instanceof Error;
}
__name(error, "error");
__name2(error, "error");
exports2.error = error;
function func(value) {
return typeof value === "function";
}
__name(func, "func");
__name2(func, "func");
exports2.func = func;
function array(value) {
return Array.isArray(value);
}
__name(array, "array");
__name2(array, "array");
exports2.array = array;
function stringArray(value) {
return array(value) && value.every((elem) => string(elem));
}
__name(stringArray, "stringArray");
__name2(stringArray, "stringArray");
exports2.stringArray = stringArray;
}
});
var require_events = __commonJS({
"../../node_modules/.pnpm/vscode-jsonrpc@8.2.0/node_modules/vscode-jsonrpc/lib/common/events.js"(exports2) {
"use strict";
Object.defineProperty(exports2, "__esModule", { value: true });
exports2.Emitter = exports2.Event = void 0;
var ral_1 = require_ral();
var Event;
(function(Event2) {
const _disposable = { dispose() {
} };
Event2.None = function() {
return _disposable;
};
})(Event || (exports2.Event = Event = {}));
var CallbackList = class {
static {
__name(this, "CallbackList");
}
static {
__name2(this, "CallbackList");
}
add(callback, context = null, bucket) {
if (!this._callbacks) {
this._callbacks = [];
this._contexts = [];
}
this._callbacks.push(callback);
this._contexts.push(context);
if (Array.isArray(bucket)) {
bucket.push({ dispose: /* @__PURE__ */ __name2(() => this.remove(callback, context), "dispose") });
}
}
remove(callback, context = null) {
if (!this._callbacks) {
return;
}
let foundCallbackWithDifferentContext = false;
for (let i = 0, len = this._callbacks.length; i < len; i++) {
if (this._callbacks[i] === callback) {
if (this._contexts[i] === context) {
this._callbacks.splice(i, 1);
this._contexts.splice(i, 1);
return;
} else {
foundCallbackWithDifferentContext = true;
}
}
}
if (foundCallbackWithDifferentContext) {
throw new Error("When adding a listener with a context, you should remove it with the same context");
}
}
invoke(...args) {
if (!this._callbacks) {
return [];
}
const ret = [], callbacks = this._callbacks.slice(0), contexts = this._contexts.slice(0);
for (let i = 0, len = callbacks.length; i < len; i++) {
try {
ret.push(callbacks[i].apply(contexts[i], args));
} catch (e) {
(0, ral_1.default)().console.error(e);
}
}
return ret;
}
isEmpty() {
return !this._callbacks || this._callbacks.length === 0;
}
dispose() {
this._callbacks = void 0;
this._contexts = void 0;
}
};
var Emitter3 = class _Emitter {
static {
__name(this, "_Emitter");
}
static {
__name2(this, "Emitter");
}
constructor(_options) {
this._options = _options;
}
/**
* For the public to allow to subscribe
* to events from this Emitter
*/
get event() {
if (!this._event) {
this._event = (listener, thisArgs, disposables) => {
if (!this._callbacks) {
this._callbacks = new CallbackList();
}
if (this._options && this._options.onFirstListenerAdd && this._callbacks.isEmpty()) {
this._options.onFirstListenerAdd(this);
}
this._callbacks.add(listener, thisArgs);
const result = {
dispose: /* @__PURE__ */ __name2(() => {
if (!this._callbacks) {
return;
}
this._callbacks.remove(listener, thisArgs);
result.dispose = _Emitter._noop;
if (this._options && this._options.onLastListenerRemove && this._callbacks.isEmpty()) {
this._options.onLastListenerRemove(this);
}
}, "dispose")
};
if (Array.isArray(disposables)) {
disposables.push(result);
}
return result;
};
}
return this._event;
}
/**
* To be kept private to fire an event to
* subscribers
*/
fire(event) {
if (this._callbacks) {
this._callbacks.invoke.call(this._callbacks, event);
}
}
dispose() {
if (this._callbacks) {
this._callbacks.dispose();
this._callbacks = void 0;
}
}
};
exports2.Emitter = Emitter3;
Emitter3._noop = function() {
};
}
});
var require_cancellation = __commonJS({
"../../node_modules/.pnpm/vscode-jsonrpc@8.2.0/node_modules/vscode-jsonrpc/lib/common/cancellation.js"(exports2) {
"use strict";
Object.defineProperty(exports2, "__esModule", { value: true });
exports2.CancellationTokenSource = exports2.CancellationToken = void 0;
var ral_1 = require_ral();
var Is2 = require_is();
var events_1 = require_events();
var CancellationToken11;
(function(CancellationToken12) {
CancellationToken12.None = Object.freeze({
isCancellationRequested: false,
onCancellationRequested: events_1.Event.None
});
CancellationToken12.Cancelled = Object.freeze({
isCancellationRequested: true,
onCancellationRequested: events_1.Event.None
});
function is(value) {
const candidate = value;
return candidate && (candidate === CancellationToken12.None || candidate === CancellationToken12.Cancelled || Is2.boolean(candidate.isCancellationRequested) && !!candidate.onCancellationRequested);
}
__name(is, "is");
__name2(is, "is");
CancellationToken12.is = is;
})(CancellationToken11 || (exports2.CancellationToken = CancellationToken11 = {}));
var shortcutEvent = Object.freeze(function(callback, context) {
const handle = (0, ral_1.default)().timer.setTimeout(callback.bind(context), 0);
return { dispose() {
handle.dispose();
} };
});
var MutableToken = class {
static {
__name(this, "MutableToken");
}
static {
__name2(this, "MutableToken");
}
constructor() {
this._isCancelled = false;
}
cancel() {
if (!this._isCancelled) {
this._isCancelled = true;
if (this._emitter) {
this._emitter.fire(void 0);
this.dispose();
}
}
}
get isCancellationRequested() {
return this._isCancelled;
}
get onCancellationRequested() {
if (this._isCancelled) {
return shortcutEvent;
}
if (!this._emitter) {
this._emitter = new events_1.Emitter();
}
return this._emitter.event;
}
dispose() {
if (this._emitter) {
this._emitter.dispose();
this._emitter = void 0;
}
}
};
var CancellationTokenSource3 = class {
static {
__name(this, "CancellationTokenSource3");
}
static {
__name2(this, "CancellationTokenSource");
}
get token() {
if (!this._token) {
this._token = new MutableToken();
}
return this._token;
}
cancel() {
if (!this._token) {
this._token = CancellationToken11.Cancelled;
} else {
this._token.cancel();
}
}
dispose() {
if (!this._token) {
this._token = CancellationToken11.None;
} else if (this._token instanceof MutableToken) {
this._token.dispose();
}
}
};
exports2.CancellationTokenSource = CancellationTokenSource3;
}
});
var require_messages = __commonJS({
"../../node_modules/.pnpm/vscode-jsonrpc@8.2.0/node_modules/vscode-jsonrpc/lib/common/messages.js"(exports2) {
"use strict";
Object.defineProperty(exports2, "__esModule", { value: true });
exports2.Message = exports2.NotificationType9 = exports2.NotificationType8 = exports2.NotificationType7 = exports2.NotificationType6 = exports2.NotificationType5 = exports2.NotificationType4 = exports2.NotificationType3 = exports2.NotificationType2 = exports2.NotificationType1 = exports2.NotificationType0 = exports2.NotificationType = exports2.RequestType9 = exports2.RequestType8 = exports2.RequestType7 = exports2.RequestType6 = exports2.RequestType5 = exports2.RequestType4 = exports2.RequestType3 = exports2.RequestType2 = exports2.RequestType1 = exports2.RequestType = exports2.RequestType0 = exports2.AbstractMessageSignature = exports2.ParameterStructures = exports2.ResponseError = exports2.ErrorCodes = void 0;
var is = require_is();
var ErrorCodes;
(function(ErrorCodes2) {
ErrorCodes2.ParseError = -32700;
ErrorCodes2.InvalidRequest = -32600;
ErrorCodes2.MethodNotFound = -32601;
ErrorCodes2.InvalidParams = -32602;
ErrorCodes2.InternalError = -32603;
ErrorCodes2.jsonrpcReservedErrorRangeStart = -32099;
ErrorCodes2.serverErrorStart = -32099;
ErrorCodes2.MessageWriteError = -32099;
ErrorCodes2.MessageReadError = -32098;
ErrorCodes2.PendingResponseRejected = -32097;
ErrorCodes2.ConnectionInactive = -32096;
ErrorCodes2.ServerNotInitialized = -32002;
ErrorCodes2.UnknownErrorCode = -32001;
ErrorCodes2.jsonrpcReservedErrorRangeEnd = -32e3;
ErrorCodes2.serverErrorEnd = -32e3;
})(ErrorCodes || (exports2.ErrorCodes = ErrorCodes = {}));
var ResponseError2 = class _ResponseError extends Error {
static {
__name(this, "_ResponseError");
}
static {
__name2(this, "ResponseError");
}
constructor(code, message, data) {
super(message);
this.code = is.number(code) ? code : ErrorCodes.UnknownErrorCode;
this.data = data;
Object.setPrototypeOf(this, _ResponseError.prototype);
}
toJson() {
const result = {
code: this.code,
message: this.message
};
if (this.data !== void 0) {
result.data = this.data;
}
return result;
}
};
exports2.ResponseError = ResponseError2;
var ParameterStructures = class _ParameterStructures {
static {
__name(this, "_ParameterStructures");
}
static {
__name2(this, "ParameterStructures");
}
constructor(kind) {
this.kind = kind;
}
static is(value) {
return value === _ParameterStructures.auto || value === _ParameterStructures.byName || value === _ParameterStructures.byPosition;
}
toString() {
return this.kind;
}
};
exports2.ParameterStructures = ParameterStructures;
ParameterStructures.auto = new ParameterStructures("auto");
ParameterStructures.byPosition = new ParameterStructures("byPosition");
ParameterStructures.byName = new ParameterStructures("byName");
var AbstractMessageSignature = class {
static {
__name(this, "AbstractMessageSignature");
}
static {
__name2(this, "AbstractMessageSignature");
}
constructor(method, numberOfParams) {
this.method = method;
this.numberOfParams = numberOfParams;
}
get parameterStructures() {
return ParameterStructures.auto;
}
};
exports2.AbstractMessageSignature = AbstractMessageSignature;
var RequestType0 = class extends AbstractMessageSignature {
static {
__name(this, "RequestType0");
}
static {
__name2(this, "RequestType0");
}
constructor(method) {
super(method, 0);
}
};
exports2.RequestType0 = RequestType0;
var RequestType = class extends AbstractMessageSignature {
static {
__name(this, "RequestType");
}
static {
__name2(this, "RequestType");
}
constructor(method, _parameterStructures = ParameterStructures.auto) {
super(method, 1);
this._parameterStructures = _parameterStructures;
}
get parameterStructures() {
return this._parameterStructures;
}
};
exports2.RequestType = RequestType;
var RequestType1 = class extends AbstractMessageSignature {
static {
__name(this, "RequestType1");
}
static {
__name2(this, "RequestType1");
}
constructor(method, _parameterStructures = ParameterStructures.auto) {
super(method, 1);
this._parameterStructures = _parameterStructures;
}
get parameterStructures() {
return this._parameterStructures;
}
};
exports2.RequestType1 = RequestType1;
var RequestType2 = class extends AbstractMessageSignature {
static {
__name(this, "RequestType2");
}
static {
__name2(this, "RequestType2");
}
constructor(method) {
super(method, 2);
}
};
exports2.RequestType2 = RequestType2;
var RequestType3 = class extends AbstractMessageSignature {
static {
__name(this, "RequestType3");
}
static {
__name2(this, "RequestType3");
}
constructor(method) {
super(method, 3);
}
};
exports2.RequestType3 = RequestType3;
var RequestType4 = class extends AbstractMessageSignature {
static {
__name(this, "RequestType4");
}
static {
__name2(this, "RequestType4");
}
constructor(method) {
super(method, 4);
}
};
exports2.RequestType4 = RequestType4;
var RequestType5 = class extends AbstractMessageSignature {
static {
__name(this, "RequestType5");
}
static {
__name2(this, "RequestType5");
}
constructor(method) {
super(method, 5);
}
};
exports2.RequestType5 = RequestType5;
var RequestType6 = class extends AbstractMessageSignature {
static {
__name(this, "RequestType6");
}
static {
__name2(this, "RequestType6");
}
constructor(method) {
super(method, 6);
}
};
exports2.RequestType6 = RequestType6;
var RequestType7 = class extends AbstractMessageSignature {
static {
__name(this, "RequestType7");
}
static {
__name2(this, "RequestType7");
}
constructor(method) {
super(method, 7);
}
};
exports2.RequestType7 = RequestType7;
var RequestType8 = class extends AbstractMessageSignature {
static {
__name(this, "RequestType8");
}
static {
__name2(this, "RequestType8");
}
constructor(method) {
super(method, 8);
}
};
exports2.RequestType8 = RequestType8;
var RequestType9 = class extends AbstractMessageSignature {
static {
__name(this, "RequestType9");
}
static {
__name2(this, "RequestType9");
}
constructor(method) {
super(method, 9);
}
};
exports2.RequestType9 = RequestType9;
var NotificationType = class extends AbstractMessageSignature {
static {
__name(this, "NotificationType");
}
static {
__name2(this, "NotificationType");
}
constructor(method, _parameterStructures = ParameterStructures.auto) {
super(method, 1);
this._parameterStructures = _parameterStructures;
}
get parameterStructures() {
return this._parameterStructures;
}
};
exports2.NotificationType = NotificationType;
var NotificationType0 = class extends AbstractMessageSignature {
static {
__name(this, "NotificationType0");
}
static {
__name2(this, "NotificationType0");
}
constructor(method) {
super(method, 0);
}
};
exports2.NotificationType0 = NotificationType0;
var NotificationType1 = class extends AbstractMessageSignature {
static {
__name(this, "NotificationType1");
}
static {
__name2(this, "NotificationType1");
}
constructor(method, _parameterStructures = ParameterStructures.auto) {
super(method, 1);
this._parameterStructures = _parameterStructures;
}
get parameterStructures() {
return this._parameterStructures;
}
};
exports2.NotificationType1 = NotificationType1;
var NotificationType2 = class extends AbstractMessageSignature {
static {
__name(this, "NotificationType2");
}
static {
__name2(this, "NotificationType2");
}
constructor(method) {
super(method, 2);
}
};
exports2.NotificationType2 = NotificationType2;
var NotificationType3 = class extends AbstractMessageSignature {
static {
__name(this, "NotificationType3");
}
static {
__name2(this, "NotificationType3");
}
constructor(method) {
super(method, 3);
}
};
exports2.NotificationType3 = NotificationType3;
var NotificationType4 = class extends AbstractMessageSignature {
static {
__name(this, "NotificationType4");
}
static {
__name2(this, "NotificationType4");
}
constructor(method) {
super(method, 4);
}
};
exports2.NotificationType4 = NotificationType4;
var NotificationType5 = class extends AbstractMessageSignature {
static {
__name(this, "NotificationType5");
}
static {
__name2(this, "NotificationType5");
}
constructor(method) {
super(method, 5);
}
};
exports2.NotificationType5 = NotificationType5;
var NotificationType6 = class extends AbstractMessageSignature {
static {
__name(this, "NotificationType6");
}
static {
__name2(this, "NotificationType6");
}
constructor(method) {
super(method, 6);
}
};
exports2.NotificationType6 = NotificationType6;
var NotificationType7 = class extends AbstractMessageSignature {
static {
__name(this, "NotificationType7");
}
static {
__name2(this, "NotificationType7");
}
constructor(method) {
super(method, 7);
}
};
exports2.NotificationType7 = NotificationType7;
var NotificationType8 = class extends AbstractMessageSignature {
static {
__name(this, "NotificationType8");
}
static {
__name2(this, "NotificationType8");
}
constructor(method) {
super(method, 8);
}
};
exports2.NotificationType8 = NotificationType8;
var NotificationType9 = class extends AbstractMessageSignature {
static {
__name(this, "NotificationType9");
}
static {
__name2(this, "NotificationType9");
}
constructor(method) {
super(method, 9);
}
};
exports2.NotificationType9 = NotificationType9;
var Message;
(function(Message2) {
function isRequest(message) {
const candidate = message;
return candidate && is.string(candidate.method) && (is.string(candidate.id) || is.number(candidate.id));
}
__name(isRequest, "isRequest");
__name2(isRequest, "isRequest");
Message2.isRequest = isRequest;
function isNotification(message) {
const candidate = message;
return candidate && is.string(candidate.method) && message.id === void 0;
}
__name(isNotification, "isNotification");
__name2(isNotification, "isNotification");
Message2.isNotification = isNotification;
function isResponse(message) {
const candidate = message;
return candidate && (candidate.result !== void 0 || !!candidate.error) && (is.string(candidate.id) || is.number(candidate.id) || candidate.id === null);
}
__name(isResponse, "isResponse");
__name2(isResponse, "isResponse");
Message2.isResponse = isResponse;
})(Message || (exports2.Message = Message = {}));
}
});
var require_linkedMap = __commonJS({
"../../node_modules/.pnpm/vscode-jsonrpc@8.2.0/node_modules/vscode-jsonrpc/lib/common/linkedMap.js"(exports2) {
"use strict";
var _a;
Object.defineProperty(exports2, "__esModule", { value: true });
exports2.LRUCache = exports2.LinkedMap = exports2.Touch = void 0;
var Touch;
(function(Touch2) {
Touch2.None = 0;
Touch2.First = 1;
Touch2.AsOld = Touch2.First;
Touch2.Last = 2;
Touch2.AsNew = Touch2.Last;
})(Touch || (exports2.Touch = Touch = {}));
var LinkedMap = class {
static {
__name(this, "LinkedMap");
}
static {
__name2(this, "LinkedMap");
}
constructor() {
this[_a] = "LinkedMap";
this._map = /* @__PURE__ */ new Map();
this._head = void 0;
this._tail = void 0;
this._size = 0;
this._state = 0;
}
clear() {
this._map.clear();
this._head = void 0;
this._tail = void 0;
this._size = 0;
this._state++;
}
isEmpty() {
return !this._head && !this._tail;
}
get size() {
return this._size;
}
get first() {
return this._head?.value;
}
get last() {
return this._tail?.value;
}
has(key) {
return this._map.has(key);
}
get(key, touch = Touch.None) {
const item = this._map.get(key);
if (!item) {
return void 0;
}
if (touch !== Touch.None) {
this.touch(item, touch);
}
return item.value;
}
set(key, value, touch = Touch.None) {
let item = this._map.get(key);
if (item) {
item.value = value;
if (touch !== Touch.None) {
this.touch(item, touch);
}
} else {
item = { key, value, next: void 0, previous: void 0 };
switch (touch) {
case Touch.None:
this.addItemLast(item);
break;
case Touch.First:
this.addItemFirst(item);
break;
case Touch.Last:
this.addItemLast(item);
break;
default:
this.addItemLast(item);
break;
}
this._map.set(key, item);
this._size++;
}
return this;
}
delete(key) {
return !!this.remove(key);
}
remove(key) {
const item = this._map.get(key);
if (!item) {
return void 0;
}
this._map.delete(key);
this.removeItem(item);
this._size--;
return item.value;
}
shift() {
if (!this._head && !this._tail) {
return void 0;
}
if (!this._head || !this._tail) {
throw new Error("Invalid list");
}
const item = this._head;
this._map.delete(item.key);
this.removeItem(item);
this._size--;
return item.value;
}
forEach(callbackfn, thisArg) {
const state = this._state;
let current = this._head;
while (current) {
if (thisArg) {
callbackfn.bind(thisArg)(current.value, current.key, this);
} else {
callbackfn(current.value, current.key, this);
}
if (this._state !== state) {
throw new Error(`LinkedMap got modified during iteration.`);
}
current = current.next;
}
}
keys() {
const state = this._state;
let current = this._head;
const iterator = {
[Symbol.iterator]: () => {
return iterator;
},
next: /* @__PURE__ */ __name2(() => {
if (this._state !== state) {
throw new Error(`LinkedMap got modified during iteration.`);
}
if (current) {
const result = { value: current.key, done: false };
current = current.next;
return result;
} else {
return { value: void 0, done: true };
}
}, "next")
};
return iterator;
}
values() {
const state = this._state;
let current = this._head;
const iterator = {
[Symbol.iterator]: () => {
return iterator;
},
next: /* @__PURE__ */ __name2(() => {
if (this._state !== state) {
throw new Error(`LinkedMap got modified during iteration.`);
}
if (current) {
const result = { value: current.value, done: false };
current = current.next;
return result;
} else {
return { value: void 0, done: true };
}
}, "next")
};
return iterator;
}
entries() {
const state = this._state;
let current = this._head;
const iterator = {
[Symbol.iterator]: () => {
return iterator;
},
next: /* @__PURE__ */ __name2(() => {
if (this._state !== state) {
throw new Error(`LinkedMap got modified during iteration.`);
}
if (current) {
const result = { value: [current.key, current.value], done: false };
current = current.next;
return result;
} else {
return { value: void 0, done: true };
}
}, "next")
};
return iterator;
}
[(_a = Symbol.toStringTag, Symbol.iterator)]() {
return this.entries();
}
trimOld(newSize) {
if (newSize >= this.size) {
return;
}
if (newSize === 0) {
this.clear();
return;
}
let current = this._head;
let currentSize = this.size;
while (current && currentSize > newSize) {
this._map.delete(current.key);
current = current.next;
currentSize--;
}
this._head = current;
this._size = currentSize;
if (current) {
current.previous = void 0;
}
this._state++;
}
addItemFirst(item) {
if (!this._head && !this._tail) {
this._tail = item;
} else if (!this._head) {
throw new Error("Invalid list");
} else {
item.next = this._head;
this._head.previous = item;
}
this._head = item;
this._state++;
}
addItemLast(item) {
if (!this._head && !this._tail) {
this._head = item;
} else if (!this._tail) {
throw new Error("Invalid list");
} else {
item.previous = this._tail;
this._tail.next = item;
}
this._tail = item;
this._state++;
}
removeItem(item) {
if (item === this._head && item === this._tail) {
this._head = void 0;
this._tail = void 0;
} else if (item === this._head) {
if (!item.next) {
throw new Error("Invalid list");
}
item.next.previous = void 0;
this._head = item.next;
} else if (item === this._tail) {
if (!item.previous) {
throw new Error("Invalid list");
}
item.previous.next = void 0;
this._tail = item.previous;
} else {
const next = item.next;
const previous = item.previous;
if (!next || !previous) {
throw new Error("Invalid list");
}
next.previous = previous;
previous.next = next;
}
item.next = void 0;
item.previous = void 0;
this._state++;
}
touch(item, touch) {
if (!this._head || !this._tail) {
throw new Error("Invalid list");
}
if (touch !== Touch.First && touch !== Touch.Last) {
return;
}
if (touch === Touch.First) {
if (item === this._head) {
return;
}
const next = item.next;
const previous = item.previous;
if (item === this._tail) {
previous.next = void 0;
this._tail = previous;
} else {
next.previous = previous;
previous.next = next;
}
item.previous = void 0;
item.next = this._head;
this._head.previous = item;
this._head = item;
this._state++;
} else if (touch === Touch.Last) {
if (item === this._tail) {
return;
}
const next = item.next;
const previous = item.previous;
if (item === this._head) {
next.previous = void 0;
this._head = next;
} else {
next.previous = previous;
previous.next = next;
}
item.next = void 0;
item.previous = this._tail;
this._tail.next = item;
this._tail = item;
this._state++;
}
}
toJSON() {
const data = [];
this.forEach((value, key) => {
data.push([key, value]);
});
return data;
}
fromJSON(data) {
this.clear();
for (const [key, value] of data) {
this.set(key, value);
}
}
};
exports2.LinkedMap = LinkedMap;
var LRUCache = class extends LinkedMap {
static {
__name(this, "LRUCache");
}
static {
__name2(this, "LRUCache");
}
constructor(limit, ratio = 1) {
super();
this._limit = limit;
this._ratio = Math.min(Math.max(0, ratio), 1);
}
get limit() {
return this._limit;
}
set limit(limit) {
this._limit = limit;
this.checkTrim();
}
get ratio() {
return this._ratio;
}
set ratio(ratio) {
this._ratio = Math.min(Math.max(0, ratio), 1);
this.checkTrim();
}
get(key, touch = Touch.AsNew) {
return super.get(key, touch);
}
peek(key) {
return super.get(key, Touch.None);
}
set(key, value) {
super.set(key, value, Touch.Last);
this.checkTrim();
return this;
}
checkTrim() {
if (this.size > this._limit) {
this.trimOld(Math.round(this._limit * this._ratio));
}
}
};
exports2.LRUCache = LRUCache;
}
});
var require_disposable = __commonJS({
"../../node_modules/.pnpm/vscode-jsonrpc@8.2.0/node_modules/vscode-jsonrpc/lib/common/disposable.js"(exports2) {
"use strict";
Object.defineProperty(exports2, "__esModule", { value: true });
exports2.Disposable = void 0;
var Disposable2;
(function(Disposable3) {
function create(func) {
return {
dispose: func
};
}
__name(create, "create");
__name2(create, "create");
Disposable3.create = create;
})(Disposable2 || (exports2.Disposable = Disposable2 = {}));
}
});
var require_sharedArrayCancellation = __commonJS({
"../../node_modules/.pnpm/vscode-jsonrpc@8.2.0/node_modules/vscode-jsonrpc/lib/common/sharedArrayCancellation.js"(exports2) {
"use strict";
Object.defineProperty(exports2, "__esModule", { value: true });
exports2.SharedArrayReceiverStrategy = exports2.SharedArraySenderStrategy = void 0;
var cancellation_1 = require_cancellation();
var CancellationState;
(function(CancellationState2) {
CancellationState2.Continue = 0;
CancellationState2.Cancelled = 1;
})(CancellationState || (CancellationState = {}));
var SharedArraySenderStrategy = class {
static {
__name(this, "SharedArraySenderStrategy");
}
static {
__name2(this, "SharedArraySenderStrategy");
}
constructor() {
this.buffers = /* @__PURE__ */ new Map();
}
enableCancellation(request) {
if (request.id === null) {
return;
}
const buffer = new SharedArrayBuffer(4);
const data = new Int32Array(buffer, 0, 1);
data[0] = CancellationState.Continue;
this.buffers.set(request.id, buffer);
request.$cancellationData = buffer;
}
async sendCancellation(_conn, id) {
const buffer = this.buffers.get(id);
if (buffer === void 0) {
return;
}
const data = new Int32Array(buffer, 0, 1);
Atomics.store(data, 0, CancellationState.Cancelled);
}
cleanup(id) {
this.buffers.delete(id);
}
dispose() {
this.buffers.clear();
}
};
exports2.SharedArraySenderStrategy = SharedArraySenderStrategy;
var SharedArrayBufferCancellationToken = class {
static {
__name(this, "SharedArrayBufferCancellationToken");
}
static {
__name2(this, "SharedArrayBufferCancellationToken");
}
constructor(buffer) {
this.data = new Int32Array(buffer, 0, 1);
}
get isCancellationRequested() {
return Atomics.load(this.data, 0) === CancellationState.Cancelled;
}
get onCancellationRequested() {
throw new Error(`Cancellation over SharedArrayBuffer doesn't support cancellation events`);
}
};
var SharedArrayBufferCancellationTokenSource = class {
static {
__name(this, "SharedArrayBufferCancellationTokenSource");
}
static {
__name2(this, "SharedArrayBufferCancellationTokenSource");
}
constructor(buffer) {
this.token = new SharedArrayBufferCancellationToken(buffer);
}
cancel() {
}
dispose() {
}
};
var SharedArrayReceiverStrategy = class {
static {
__name(this, "SharedArrayReceiverStrategy");
}
static {
__name2(this, "SharedArrayReceiverStrategy");
}
constructor() {
this.kind = "request";
}
createCancellationTokenSource(request) {
const buffer = request.$cancellationData;
if (buffer === void 0) {
return new cancellation_1.CancellationTokenSource();
}
return new SharedArrayBufferCancellationTokenSource(buffer);
}
};
exports2.SharedArrayReceiverStrategy = SharedArrayReceiverStrategy;
}
});
var require_semaphore = __commonJS({
"../../node_modules/.pnpm/vscode-jsonrpc@8.2.0/node_modules/vscode-jsonrpc/lib/common/semaphore.js"(exports2) {
"use strict";
Object.defineProperty(exports2, "__esModule", { value: true });
exports2.Semaphore = void 0;
var ral_1 = require_ral();
var Semaphore = class {
static {
__name(this, "Semaphore");
}
static {
__name2(this, "Semaphore");
}
constructor(capacity = 1) {
if (capacity <= 0) {
throw new Error("Capacity must be greater than 0");
}
this._capacity = capacity;
this._active = 0;
this._waiting = [];
}
lock(thunk) {
return new Promise((resolve, reject2) => {
this._waiting.push({ thunk, resolve, reject: reject2 });
this.runNext();
});
}
get active() {
return this._active;
}
runNext() {
if (this._waiting.length === 0 || this._active === this._capacity) {
return;
}
(0, ral_1.default)().timer.setImmediate(() => this.doRunNext());
}
doRunNext() {
if (this._waiting.length === 0 || this._active === this._capacity) {
return;
}
const next = this._waiting.shift();
this._active++;
if (this._active > this._capacity) {
throw new Error(`To many thunks active`);
}
try {
const result = next.thunk();
if (result instanceof Promise) {
result.then((value) => {
this._active--;
next.resolve(value);
this.runNext();
}, (err) => {
this._active--;
next.reject(err);
this.runNext();
});
} else {
this._active--;
next.resolve(result);
this.runNext();
}
} catch (err) {
this._active--;
next.reject(err);
this.runNext();
}
}
};
exports2.Semaphore = Semaphore;
}
});
var require_messageReader = __commonJS({
"../../node_modules/.pnpm/vscode-jsonrpc@8.2.0/node_modules/vscode-jsonrpc/lib/common/messageReader.js"(exports2) {
"use strict";
Object.defineProperty(exports2, "__esModule", { value: true });
exports2.ReadableStreamMessageReader = exports2.AbstractMessageReader = exports2.MessageReader = void 0;
var ral_1 = require_ral();
var Is2 = require_is();
var events_1 = require_events();
var semaphore_1 = require_semaphore();
var MessageReader;
(function(MessageReader2) {
function is(value) {
let candidate = value;
return candidate && Is2.func(candidate.listen) && Is2.func(candidate.dispose) && Is2.func(candidate.onError) && Is2.func(candidate.onClose) && Is2.func(candidate.onPartialMessage);
}
__name(is, "is");
__name2(is, "is");
MessageReader2.is = is;
})(MessageReader || (exports2.MessageReader = MessageReader = {}));
var AbstractMessageReader = class {
static {
__name(this, "AbstractMessageReader");
}
static {
__name2(this, "AbstractMessageReader");
}
constructor() {
this.errorEmitter = new events_1.Emitter();
this.closeEmitter = new events_1.Emitter();
this.partialMessageEmitter = new events_1.Emitter();
}
dispose() {
this.errorEmitter.dispose();
this.closeEmitter.dispose();
}
get onError() {
return this.errorEmitter.event;
}
fireError(error) {
this.errorEmitter.fire(this.asError(error));
}
get onClose() {
return this.closeEmitter.event;
}
fireClose() {
this.closeEmitter.fire(void 0);
}
get onPartialMessage() {
return this.partialMessageEmitter.event;
}
firePartialMessage(info) {
this.partialMessageEmitter.fire(info);
}
asError(error) {
if (error instanceof Error) {
return error;
} else {
return new Error(`Reader received error. Reason: ${Is2.string(error.message) ? error.message : "unknown"}`);
}
}
};
exports2.AbstractMessageReader = AbstractMessageReader;
var ResolvedMessageReaderOptions;
(function(ResolvedMessageReaderOptions2) {
function fromOptions(options) {
let charset;
let result;
let contentDecoder;
const contentDecoders = /* @__PURE__ */ new Map();
let contentTypeDecoder;
const contentTypeDecoders = /* @__PURE__ */ new Map();
if (options === void 0 || typeof options === "string") {
charset = options ?? "utf-8";
} else {
charset = options.charset ?? "utf-8";
if (options.contentDecoder !== void 0) {
contentDecoder = options.contentDecoder;
contentDecoders.set(contentDecoder.name, contentDecoder);
}
if (options.contentDecoders !== void 0) {
for (const decoder of options.contentDecoders) {
contentDecoders.set(decoder.name, decoder);
}
}
if (options.contentTypeDecoder !== void 0) {
contentTypeDecoder = options.contentTypeDecoder;
contentTypeDecoders.set(contentTypeDecoder.name, contentTypeDecoder);
}
if (options.contentTypeDecoders !== void 0) {
for (const decoder of options.contentTypeDecoders) {
contentTypeDecoders.set(decoder.name, decoder);
}
}
}
if (contentTypeDecoder === void 0) {
contentTypeDecoder = (0, ral_1.default)().applicationJson.decoder;
contentTypeDecoders.set(contentTypeDecoder.name, contentTypeDecoder);
}
return { charset, contentDecoder, contentDecoders, contentTypeDecoder, contentTypeDecoders };
}
__name(fromOptions, "fromOptions");
__name2(fromOptions, "fromOptions");
ResolvedMessageReaderOptions2.fromOptions = fromOptions;
})(ResolvedMessageReaderOptions || (ResolvedMessageReaderOptions = {}));
var ReadableStreamMessageReader = class extends AbstractMessageReader {
static {
__name(this, "ReadableStreamMessageReader");
}
static {
__name2(this, "ReadableStreamMessageReader");
}
constructor(readable, options) {
super();
this.readable = readable;
this.options = ResolvedMessageReaderOptions.fromOptions(options);
this.buffer = (0, ral_1.default)().messageBuffer.create(this.options.charset);
this._partialMessageTimeout = 1e4;
this.nextMessageLength = -1;
this.messageToken = 0;
this.readSemaphore = new semaphore_1.Semaphore(1);
}
set partialMessageTimeout(timeout) {
this._partialMessageTimeout = timeout;
}
get partialMessageTimeout() {
return this._partialMessageTimeout;
}
listen(callback) {
this.nextMessageLength = -1;
this.messageToken = 0;
this.partialMessageTimer = void 0;
this.callback = callback;
const result = this.readable.onData((data) => {
this.onData(data);
});
this.readable.onError((error) => this.fireError(error));
this.readable.onClose(() => this.fireClose());
return result;
}
onData(data) {
try {
this.buffer.append(data);
while (true) {
if (this.nextMessageLength === -1) {
const headers = this.buffer.tryReadHeaders(true);
if (!headers) {
return;
}
const contentLength = headers.get("content-length");
if (!contentLength) {
this.fireError(new Error(`Header must provide a Content-Length property.
${JSON.stringify(Object.fromEntries(headers))}`));
return;
}
const length = parseInt(contentLength);
if (isNaN(length)) {
this.fireError(new Error(`Content-Length value must be a number. Got ${contentLength}`));
return;
}
this.nextMessageLength = length;
}
const body = this.buffer.tryReadBody(this.nextMessageLength);
if (body === void 0) {
this.setPartialMessageTimer();
return;
}
this.clearPartialMessageTimer();
this.nextMessageLength = -1;
this.readSemaphore.lock(async () => {
const bytes = this.options.contentDecoder !== void 0 ? await this.options.contentDecoder.decode(body) : body;
const message = await this.options.contentTypeDecoder.decode(bytes, this.options);
this.callback(message);
}).catch((error) => {
this.fireError(error);
});
}
} catch (error) {
this.fireError(error);
}
}
clearPartialMessageTimer() {
if (this.partialMessageTimer) {
this.partialMessageTimer.dispose();
this.partialMessageTimer = void 0;
}
}
setPartialMessageTimer() {
this.clearPartialMessageTimer();
if (this._partialMessageTimeout <= 0) {
return;
}
this.partialMessageTimer = (0, ral_1.default)().timer.setTimeout((token, timeout) => {
this.partialMessageTimer = void 0;
if (token === this.messageToken) {
this.firePartialMessage({ messageToken: token, waitingTime: timeout });
this.setPartialMessageTimer();
}
}, this._partialMessageTimeout, this.messageToken, this._partialMessageTimeout);
}
};
exports2.ReadableStreamMessageReader = ReadableStreamMessageReader;
}
});
var require_messageWriter = __commonJS({
"../../node_modules/.pnpm/vscode-jsonrpc@8.2.0/node_modules/vscode-jsonrpc/lib/common/messageWriter.js"(exports2) {
"use strict";
Object.defineProperty(exports2, "__esModule", { value: true });
exports2.WriteableStreamMessageWriter = exports2.AbstractMessageWriter = exports2.MessageWriter = void 0;
var ral_1 = require_ral();
var Is2 = require_is();
var semaphore_1 = require_semaphore();
var events_1 = require_events();
var ContentLength = "Content-Length: ";
var CRLF = "\r\n";
var MessageWriter;
(function(MessageWriter2) {
function is(value) {
let candidate = value;
return candidate && Is2.func(candidate.dispose) && Is2.func(candidate.onClose) && Is2.func(candidate.onError) && Is2.func(candidate.write);
}
__name(is, "is");
__name2(is, "is");
MessageWriter2.is = is;
})(MessageWriter || (exports2.MessageWriter = MessageWriter = {}));
var AbstractMessageWriter = class {
static {
__name(this, "AbstractMessageWriter");
}
static {
__name2(this, "AbstractMessageWriter");
}
constructor() {
this.errorEmitter = new events_1.Emitter();
this.closeEmitter = new events_1.Emitter();
}
dispose() {
this.errorEmitter.dispose();
this.closeEmitter.dispose();
}
get onError() {
return this.errorEmitter.event;
}
fireError(error, message, count) {
this.errorEmitter.fire([this.asError(error), message, count]);
}
get onClose() {
return this.closeEmitter.event;
}
fireClose() {
this.closeEmitter.fire(void 0);
}
asError(error) {
if (error instanceof Error) {
return error;
} else {
return new Error(`Writer received error. Reason: ${Is2.string(error.message) ? error.message : "unknown"}`);
}
}
};
exports2.AbstractMessageWriter = AbstractMessageWriter;
var ResolvedMessageWriterOptions;
(function(ResolvedMessageWriterOptions2) {
function fromOptions(options) {
if (options === void 0 || typeof options === "string") {
return { charset: options ?? "utf-8", contentTypeEncoder: (0, ral_1.default)().applicationJson.encoder };
} else {
return { charset: options.charset ?? "utf-8", contentEncoder: options.contentEncoder, contentTypeEncoder: options.contentTypeEncoder ?? (0, ral_1.default)().applicationJson.encoder };
}
}
__name(fromOptions, "fromOptions");
__name2(fromOptions, "fromOptions");
ResolvedMessageWriterOptions2.fromOptions = fromOptions;
})(ResolvedMessageWriterOptions || (ResolvedMessageWriterOptions = {}));
var WriteableStreamMessageWriter = class extends AbstractMessageWriter {
static {
__name(this, "WriteableStreamMessageWriter");
}
static {
__name2(this, "WriteableStreamMessageWriter");
}
constructor(writable, options) {
super();
this.writable = writable;
this.options = ResolvedMessageWriterOptions.fromOptions(options);
this.errorCount = 0;
this.writeSemaphore = new semaphore_1.Semaphore(1);
this.writable.onError((error) => this.fireError(error));
this.writable.onClose(() => this.fireClose());
}
async write(msg) {
return this.writeSemaphore.lock(async () => {
const payload = this.options.contentTypeEncoder.encode(msg, this.options).then((buffer) => {
if (this.options.contentEncoder !== void 0) {
return this.options.contentEncoder.encode(buffer);
} else {
return buffer;
}
});
return payload.then((buffer) => {
const headers = [];
headers.push(ContentLength, buffer.byteLength.toString(), CRLF);
headers.push(CRLF);
return this.doWrite(msg, headers, buffer);
}, (error) => {
this.fireError(error);
throw error;
});
});
}
async doWrite(msg, headers, data) {
try {
await this.writable.write(headers.join(""), "ascii");
return this.writable.write(data);
} catch (error) {
this.handleError(error, msg);
return Promise.reject(error);
}
}
handleError(error, msg) {
this.errorCount++;
this.fireError(error, msg, this.errorCount);
}
end() {
this.writable.end();
}
};
exports2.WriteableStreamMessageWriter = WriteableStreamMessageWriter;
}
});
var require_messageBuffer = __commonJS({
"../../node_modules/.pnpm/vscode-jsonrpc@8.2.0/node_modules/vscode-jsonrpc/lib/common/messageBuffer.js"(exports2) {
"use strict";
Object.defineProperty(exports2, "__esModule", { value: true });
exports2.AbstractMessageBuffer = void 0;
var CR = 13;
var LF = 10;
var CRLF = "\r\n";
var AbstractMessageBuffer = class {
static {
__name(this, "AbstractMessageBuffer");
}
static {
__name2(this, "AbstractMessageBuffer");
}
constructor(encoding = "utf-8") {
this._encoding = encoding;
this._chunks = [];
this._totalLength = 0;
}
get encoding() {
return this._encoding;
}
append(chunk) {
const toAppend = typeof chunk === "string" ? this.fromString(chunk, this._encoding) : chunk;
this._chunks.push(toAppend);
this._totalLength += toAppend.byteLength;
}
tryReadHeaders(lowerCaseKeys = false) {
if (this._chunks.length === 0) {
return void 0;
}
let state = 0;
let chunkIndex = 0;
let offset = 0;
let chunkBytesRead = 0;
row: while (chunkIndex < this._chunks.length) {
const chunk = this._chunks[chunkIndex];
offset = 0;
column: while (offset < chunk.length) {
const value = chunk[offset];
switch (value) {
case CR:
switch (state) {
case 0:
state = 1;
break;
case 2:
state = 3;
break;
default:
state = 0;
}
break;
case LF:
switch (state) {
case 1:
state = 2;
break;
case 3:
state = 4;
offset++;
break row;
default:
state = 0;
}
break;
default:
state = 0;
}
offset++;
}
chunkBytesRead += chunk.byteLength;
chunkIndex++;
}
if (state !== 4) {
return void 0;
}
const buffer = this._read(chunkBytesRead + offset);
const result = /* @__PURE__ */ new Map();
const headers = this.toString(buffer, "ascii").split(CRLF);
if (headers.length < 2) {
return result;
}
for (let i = 0; i < headers.length - 2; i++) {
const header = headers[i];
const index = header.indexOf(":");
if (index === -1) {
throw new Error(`Message header must separate key and value using ':'
${header}`);
}
const key = header.substr(0, index);
const value = header.substr(index + 1).trim();
result.set(lowerCaseKeys ? key.toLowerCase() : key, value);
}
return result;
}
tryReadBody(length) {
if (this._totalLength < length) {
return void 0;
}
return this._read(length);
}
get numberOfBytes() {
return this._totalLength;
}
_read(byteCount) {
if (byteCount === 0) {
return this.emptyBuffer();
}
if (byteCount > this._totalLength) {
throw new Error(`Cannot read so many bytes!`);
}
if (this._chunks[0].byteLength === byteCount) {
const chunk = this._chunks[0];
this._chunks.shift();
this._totalLength -= byteCount;
return this.asNative(chunk);
}
if (this._chunks[0].byteLength > byteCount) {
const chunk = this._chunks[0];
const result2 = this.asNative(chunk, byteCount);
this._chunks[0] = chunk.slice(byteCount);
this._totalLength -= byteCount;
return result2;
}
const result = this.allocNative(byteCount);
let resultOffset = 0;
let chunkIndex = 0;
while (byteCount > 0) {
const chunk = this._chunks[chunkIndex];
if (chunk.byteLength > byteCount) {
const chunkPart = chunk.slice(0, byteCount);
result.set(chunkPart, resultOffset);
resultOffset += byteCount;
this._chunks[chunkIndex] = chunk.slice(byteCount);
this._totalLength -= byteCount;
byteCount -= byteCount;
} else {
result.set(chunk, resultOffset);
resultOffset += chunk.byteLength;
this._chunks.shift();
this._totalLength -= chunk.byteLength;
byteCount -= chunk.byteLength;
}
}
return result;
}
};
exports2.AbstractMessageBuffer = AbstractMessageBuffer;
}
});
var require_connection = __commonJS({
"../../node_modules/.pnpm/vscode-jsonrpc@8.2.0/node_modules/vscode-jsonrpc/lib/common/connection.js"(exports2) {
"use strict";
Object.defineProperty(exports2, "__esModule", { value: true });
exports2.createMessageConnection = exports2.ConnectionOptions = exports2.MessageStrategy = exports2.CancellationStrategy = exports2.CancellationSenderStrategy = exports2.CancellationReceiverStrategy = exports2.RequestCancellationReceiverStrategy = exports2.IdCancellationReceiverStrategy = exports2.ConnectionStrategy = exports2.ConnectionError = exports2.ConnectionErrors = exports2.LogTraceNotification = exports2.SetTraceNotification = exports2.TraceFormat = exports2.TraceValues = exports2.Trace = exports2.NullLogger = exports2.ProgressType = exports2.ProgressToken = void 0;
var ral_1 = require_ral();
var Is2 = require_is();
var messages_1 = require_messages();
var linkedMap_1 = require_linkedMap();
var events_1 = require_events();
var cancellation_1 = require_cancellation();
var CancelNotification;
(function(CancelNotification2) {
CancelNotification2.type = new messages_1.NotificationType("$/cancelRequest");
})(CancelNotification || (CancelNotification = {}));
var ProgressToken;
(function(ProgressToken2) {
function is(value) {
return typeof value === "string" || typeof value === "number";
}
__name(is, "is");
__name2(is, "is");
ProgressToken2.is = is;
})(ProgressToken || (exports2.ProgressToken = ProgressToken = {}));
var ProgressNotification;
(function(ProgressNotification2) {
ProgressNotification2.type = new messages_1.NotificationType("$/progress");
})(ProgressNotification || (ProgressNotification = {}));
var ProgressType = class {
static {
__name(this, "ProgressType");
}
static {
__name2(this, "ProgressType");
}
constructor() {
}
};
exports2.ProgressType = ProgressType;
var StarRequestHandler;
(function(StarRequestHandler2) {
function is(value) {
return Is2.func(value);
}
__name(is, "is");
__name2(is, "is");
StarRequestHandler2.is = is;
})(StarRequestHandler || (StarRequestHandler = {}));
exports2.NullLogger = Object.freeze({
error: /* @__PURE__ */ __name2(() => {
}, "error"),
warn: /* @__PURE__ */ __name2(() => {
}, "warn"),
info: /* @__PURE__ */ __name2(() => {
}, "info"),
log: /* @__PURE__ */ __name2(() => {
}, "log")
});
var Trace;
(function(Trace2) {
Trace2[Trace2["Off"] = 0] = "Off";
Trace2[Trace2["Messages"] = 1] = "Messages";
Trace2[Trace2["Compact"] = 2] = "Compact";
Trace2[Trace2["Verbose"] = 3] = "Verbose";
})(Trace || (exports2.Trace = Trace = {}));
var TraceValues;
(function(TraceValues2) {
TraceValues2.Off = "off";
TraceValues2.Messages = "messages";
TraceValues2.Compact = "compact";
TraceValues2.Verbose = "verbose";
})(TraceValues || (exports2.TraceValues = TraceValues = {}));
(function(Trace2) {
function fromString(value) {
if (!Is2.string(value)) {
return Trace2.Off;
}
value = value.toLowerCase();
switch (value) {
case "off":
return Trace2.Off;
case "messages":
return Trace2.Messages;
case "compact":
return Trace2.Compact;
case "verbose":
return Trace2.Verbose;
default:
return Trace2.Off;
}
}
__name(fromString, "fromString");
__name2(fromString, "fromString");
Trace2.fromString = fromString;
function toString4(value) {
switch (value) {
case Trace2.Off:
return "off";
case Trace2.Messages:
return "messages";
case Trace2.Compact:
return "compact";
case Trace2.Verbose:
return "verbose";
default:
return "off";
}
}
__name(toString4, "toString4");
__name2(toString4, "toString");
Trace2.toString = toString4;
})(Trace || (exports2.Trace = Trace = {}));
var TraceFormat;
(function(TraceFormat2) {
TraceFormat2["Text"] = "text";
TraceFormat2["JSON"] = "json";
})(TraceFormat || (exports2.TraceFormat = TraceFormat = {}));
(function(TraceFormat2) {
function fromString(value) {
if (!Is2.string(value)) {
return TraceFormat2.Text;
}
value = value.toLowerCase();
if (value === "json") {
return TraceFormat2.JSON;
} else {
return TraceFormat2.Text;
}
}
__name(fromString, "fromString");
__name2(fromString, "fromString");
TraceFormat2.fromString = fromString;
})(TraceFormat || (exports2.TraceFormat = TraceFormat = {}));
var SetTraceNotification;
(function(SetTraceNotification2) {
SetTraceNotification2.type = new messages_1.NotificationType("$/setTrace");
})(SetTraceNotification || (exports2.SetTraceNotification = SetTraceNotification = {}));
var LogTraceNotification;
(function(LogTraceNotification2) {
LogTraceNotification2.type = new messages_1.NotificationType("$/logTrace");
})(LogTraceNotification || (exports2.LogTraceNotification = LogTraceNotification = {}));
var ConnectionErrors;
(function(ConnectionErrors2) {
ConnectionErrors2[ConnectionErrors2["Closed"] = 1] = "Closed";
ConnectionErrors2[ConnectionErrors2["Disposed"] = 2] = "Disposed";
ConnectionErrors2[ConnectionErrors2["AlreadyListening"] = 3] = "AlreadyListening";
})(ConnectionErrors || (exports2.ConnectionErrors = ConnectionErrors = {}));
var ConnectionError = class _ConnectionError extends Error {
static {
__name(this, "_ConnectionError");
}
static {
__name2(this, "ConnectionError");
}
constructor(code, message) {
super(message);
this.code = code;
Object.setPrototypeOf(this, _ConnectionError.prototype);
}
};
exports2.ConnectionError = ConnectionError;
var ConnectionStrategy;
(function(ConnectionStrategy2) {
function is(value) {
const candidate = value;
return candidate && Is2.func(candidate.cancelUndispatched);
}
__name(is, "is");
__name2(is, "is");
ConnectionStrategy2.is = is;
})(ConnectionStrategy || (exports2.ConnectionStrategy = ConnectionStrategy = {}));
var IdCancellationReceiverStrategy;
(function(IdCancellationReceiverStrategy2) {
function is(value) {
const candidate = value;
return candidate && (candidate.kind === void 0 || candidate.kind === "id") && Is2.func(candidate.createCancellationTokenSource) && (candidate.dispose === void 0 || Is2.func(candidate.dispose));
}
__name(is, "is");
__name2(is, "is");
IdCancellationReceiverStrategy2.is = is;
})(IdCancellationReceiverStrategy || (exports2.IdCancellationReceiverStrategy = IdCancellationReceiverStrategy = {}));
var RequestCancellationReceiverStrategy;
(function(RequestCancellationReceiverStrategy2) {
function is(value) {
const candidate = value;
return candidate && candidate.kind === "request" && Is2.func(candidate.createCancellationTokenSource) && (candidate.dispose === void 0 || Is2.func(candidate.dispose));
}
__name(is, "is");
__name2(is, "is");
RequestCancellationReceiverStrategy2.is = is;
})(RequestCancellationReceiverStrategy || (exports2.RequestCancellationReceiverStrategy = RequestCancellationReceiverStrategy = {}));
var CancellationReceiverStrategy;
(function(CancellationReceiverStrategy2) {
CancellationReceiverStrategy2.Message = Object.freeze({
createCancellationTokenSource(_) {
return new cancellation_1.CancellationTokenSource();
}
});
function is(value) {
return IdCancellationReceiverStrategy.is(value) || RequestCancellationReceiverStrategy.is(value);
}
__name(is, "is");
__name2(is, "is");
CancellationReceiverStrategy2.is = is;
})(CancellationReceiverStrategy || (exports2.CancellationReceiverStrategy = CancellationReceiverStrategy = {}));
var CancellationSenderStrategy;
(function(CancellationSenderStrategy2) {
CancellationSenderStrategy2.Message = Object.freeze({
sendCancellation(conn, id) {
return conn.sendNotification(CancelNotification.type, { id });
},
cleanup(_) {
}
});
function is(value) {
const candidate = value;
return candidate && Is2.func(candidate.sendCancellation) && Is2.func(candidate.cleanup);
}
__name(is, "is");
__name2(is, "is");
CancellationSenderStrategy2.is = is;
})(CancellationSenderStrategy || (exports2.CancellationSenderStrategy = CancellationSenderStrategy = {}));
var CancellationStrategy;
(function(CancellationStrategy2) {
CancellationStrategy2.Message = Object.freeze({
receiver: CancellationReceiverStrategy.Message,
sender: CancellationSenderStrategy.Message
});
function is(value) {
const candidate = value;
return candidate && CancellationReceiverStrategy.is(candidate.receiver) && CancellationSenderStrategy.is(candidate.sender);
}
__name(is, "is");
__name2(is, "is");
CancellationStrategy2.is = is;
})(CancellationStrategy || (exports2.CancellationStrategy = CancellationStrategy = {}));
var MessageStrategy;
(function(MessageStrategy2) {
function is(value) {
const candidate = value;
return candidate && Is2.func(candidate.handleMessage);
}
__name(is, "is");
__name2(is, "is");
MessageStrategy2.is = is;
})(MessageStrategy || (exports2.MessageStrategy = MessageStrategy = {}));
var ConnectionOptions;
(function(ConnectionOptions2) {
function is(value) {
const candidate = value;
return candidate && (CancellationStrategy.is(candidate.cancellationStrategy) || ConnectionStrategy.is(candidate.connectionStrategy) || MessageStrategy.is(candidate.messageStrategy));
}
__name(is, "is");
__name2(is, "is");
ConnectionOptions2.is = is;
})(ConnectionOptions || (exports2.ConnectionOptions = ConnectionOptions = {}));
var ConnectionState;
(function(ConnectionState2) {
ConnectionState2[ConnectionState2["New"] = 1] = "New";
ConnectionState2[ConnectionState2["Listening"] = 2] = "Listening";
ConnectionState2[ConnectionState2["Closed"] = 3] = "Closed";
ConnectionState2[ConnectionState2["Disposed"] = 4] = "Disposed";
})(ConnectionState || (ConnectionState = {}));
function createMessageConnection(messageReader, messageWriter, _logger, options) {
const logger = _logger !== void 0 ? _logger : exports2.NullLogger;
let sequenceNumber = 0;
let notificationSequenceNumber = 0;
let unknownResponseSequenceNumber = 0;
const version = "2.0";
let starRequestHandler = void 0;
const requestHandlers = /* @__PURE__ */ new Map();
let starNotificationHandler = void 0;
const notificationHandlers = /* @__PURE__ */ new Map();
const progressHandlers = /* @__PURE__ */ new Map();
let timer2;
let messageQueue = new linkedMap_1.LinkedMap();
let responsePromises = /* @__PURE__ */ new Map();
let knownCanceledRequests = /* @__PURE__ */ new Set();
let requestTokens = /* @__PURE__ */ new Map();
let trace = Trace.Off;
let traceFormat = TraceFormat.Text;
let tracer;
let state = ConnectionState.New;
const errorEmitter = new events_1.Emitter();
const closeEmitter = new events_1.Emitter();
const unhandledNotificationEmitter = new events_1.Emitter();
const unhandledProgressEmitter = new events_1.Emitter();
const disposeEmitter = new events_1.Emitter();
const cancellationStrategy = options && options.cancellationStrategy ? options.cancellationStrategy : CancellationStrategy.Message;
function createRequestQueueKey(id) {
if (id === null) {
throw new Error(`Can't send requests with id null since the response can't be correlated.`);
}
return "req-" + id.toString();
}
__name(createRequestQueueKey, "createRequestQueueKey");
__name2(createRequestQueueKey, "createRequestQueueKey");
function createResponseQueueKey(id) {
if (id === null) {
return "res-unknown-" + (++unknownResponseSequenceNumber).toString();
} else {
return "res-" + id.toString();
}
}
__name(createResponseQueueKey, "createResponseQueueKey");
__name2(createResponseQueueKey, "createResponseQueueKey");
function createNotificationQueueKey() {
return "not-" + (++notificationSequenceNumber).toString();
}
__name(createNotificationQueueKey, "createNotificationQueueKey");
__name2(createNotificationQueueKey, "createNotificationQueueKey");
function addMessageToQueue(queue, message) {
if (messages_1.Message.isRequest(message)) {
queue.set(createRequestQueueKey(message.id), message);
} else if (messages_1.Message.isResponse(message)) {
queue.set(createResponseQueueKey(message.id), message);
} else {
queue.set(createNotificationQueueKey(), message);
}
}
__name(addMessageToQueue, "addMessageToQueue");
__name2(addMessageToQueue, "addMessageToQueue");
function cancelUndispatched(_message) {
return void 0;
}
__name(cancelUndispatched, "cancelUndispatched");
__name2(cancelUndispatched, "cancelUndispatched");
function isListening() {
return state === ConnectionState.Listening;
}
__name(isListening, "isListening");
__name2(isListening, "isListening");
function isClosed() {
return state === ConnectionState.Closed;
}
__name(isClosed, "isClosed");
__name2(isClosed, "isClosed");
function isDisposed() {
return state === ConnectionState.Disposed;
}
__name(isDisposed, "isDisposed");
__name2(isDisposed, "isDisposed");
function closeHandler() {
if (state === ConnectionState.New || state === ConnectionState.Listening) {
state = ConnectionState.Closed;
closeEmitter.fire(void 0);
}
}
__name(closeHandler, "closeHandler");
__name2(closeHandler, "closeHandler");
function readErrorHandler(error) {
errorEmitter.fire([error, void 0, void 0]);
}
__name(readErrorHandler, "readErrorHandler");
__name2(readErrorHandler, "readErrorHandler");
function writeErrorHandler(data) {
errorEmitter.fire(data);
}
__name(writeErrorHandler, "writeErrorHandler");
__name2(writeErrorHandler, "writeErrorHandler");
messageReader.onClose(closeHandler);
messageReader.onError(readErrorHandler);
messageWriter.onClose(closeHandler);
messageWriter.onError(writeErrorHandler);
function triggerMessageQueue() {
if (timer2 || messageQueue.size === 0) {
return;
}
timer2 = (0, ral_1.default)().timer.setImmediate(() => {
timer2 = void 0;
processMessageQueue();
});
}
__name(triggerMessageQueue, "triggerMessageQueue");
__name2(triggerMessageQueue, "triggerMessageQueue");
function handleMessage(message) {
if (messages_1.Message.isRequest(message)) {
handleRequest(message);
} else if (messages_1.Message.isNotification(message)) {
handleNotification(message);
} else if (messages_1.Message.isResponse(message)) {
handleResponse(message);
} else {
handleInvalidMessage(message);
}
}
__name(handleMessage, "handleMessage");
__name2(handleMessage, "handleMessage");
function processMessageQueue() {
if (messageQueue.size === 0) {
return;
}
const message = messageQueue.shift();
try {
const messageStrategy = options?.messageStrategy;
if (MessageStrategy.is(messageStrategy)) {
messageStrategy.handleMessage(message, handleMessage);
} else {
handleMessage(message);
}
} finally {
triggerMessageQueue();
}
}
__name(processMessageQueue, "processMessageQueue");
__name2(processMessageQueue, "processMessageQueue");
const callback = /* @__PURE__ */ __name2((message) => {
try {
if (messages_1.Message.isNotification(message) && message.method === CancelNotification.type.method) {
const cancelId = message.params.id;
const key = createRequestQueueKey(cancelId);
const toCancel = messageQueue.get(key);
if (messages_1.Message.isRequest(toCancel)) {
const strategy = options?.connectionStrategy;
const response = strategy && strategy.cancelUndispatched ? strategy.cancelUndispatched(toCancel, cancelUndispatched) : cancelUndispatched(toCancel);
if (response && (response.error !== void 0 || response.result !== void 0)) {
messageQueue.delete(key);
requestTokens.delete(cancelId);
response.id = toCancel.id;
traceSendingResponse(response, message.method, Date.now());
messageWriter.write(response).catch(() => logger.error(`Sending response for canceled message failed.`));
return;
}
}
const cancellationToken = requestTokens.get(cancelId);
if (cancellationToken !== void 0) {
cancellationToken.cancel();
traceReceivedNotification(message);
return;
} else {
knownCanceledRequests.add(cancelId);
}
}
addMessageToQueue(messageQueue, message);
} finally {
triggerMessageQueue();
}
}, "callback");
function handleRequest(requestMessage) {
if (isDisposed()) {
return;
}
function reply(resultOrError, method, startTime2) {
const message = {
jsonrpc: version,
id: requestMessage.id
};
if (resultOrError instanceof messages_1.ResponseError) {
message.error = resultOrError.toJson();
} else {
message.result = resultOrError === void 0 ? null : resultOrError;
}
traceSendingResponse(message, method, startTime2);
messageWriter.write(message).catch(() => logger.error(`Sending response failed.`));
}
__name(reply, "reply");
__name2(reply, "reply");
function replyError(error, method, startTime2) {
const message = {
jsonrpc: version,
id: requestMessage.id,
error: error.toJson()
};
traceSendingResponse(message, method, startTime2);
messageWriter.write(message).catch(() => logger.error(`Sending response failed.`));
}
__name(replyError, "replyError");
__name2(replyError, "replyError");
function replySuccess(result, method, startTime2) {
if (result === void 0) {
result = null;
}
const message = {
jsonrpc: version,
id: requestMessage.id,
result
};
traceSendingResponse(message, method, startTime2);
messageWriter.write(message).catch(() => logger.error(`Sending response failed.`));
}
__name(replySuccess, "replySuccess");
__name2(replySuccess, "replySuccess");
traceReceivedRequest(requestMessage);
const element = requestHandlers.get(requestMessage.method);
let type;
let requestHandler;
if (element) {
type = element.type;
requestHandler = element.handler;
}
const startTime = Date.now();
if (requestHandler || starRequestHandler) {
const tokenKey = requestMessage.id ?? String(Date.now());
const cancellationSource = IdCancellationReceiverStrategy.is(cancellationStrategy.receiver) ? cancellationStrategy.receiver.createCancellationTokenSource(tokenKey) : cancellationStrategy.receiver.createCancellationTokenSource(requestMessage);
if (requestMessage.id !== null && knownCanceledRequests.has(requestMessage.id)) {
cancellationSource.cancel();
}
if (requestMessage.id !== null) {
requestTokens.set(tokenKey, cancellationSource);
}
try {
let handlerResult;
if (requestHandler) {
if (requestMessage.params === void 0) {
if (type !== void 0 && type.numberOfParams !== 0) {
replyError(new messages_1.ResponseError(messages_1.ErrorCodes.InvalidParams, `Request ${requestMessage.method} defines ${type.numberOfParams} params but received none.`), requestMessage.method, startTime);
return;
}
handlerResult = requestHandler(cancellationSource.token);
} else if (Array.isArray(requestMessage.params)) {
if (type !== void 0 && type.parameterStructures === messages_1.ParameterStructures.byName) {
replyError(new messages_1.ResponseError(messages_1.ErrorCodes.InvalidParams, `Request ${requestMessage.method} defines parameters by name but received parameters by position`), requestMessage.method, startTime);
return;
}
handlerResult = requestHandler(...requestMessage.params, cancellationSource.token);
} else {
if (type !== void 0 && type.parameterStructures === messages_1.ParameterStructures.byPosition) {
replyError(new messages_1.ResponseError(messages_1.ErrorCodes.InvalidParams, `Request ${requestMessage.method} defines parameters by position but received parameters by name`), requestMessage.method, startTime);
return;
}
handlerResult = requestHandler(requestMessage.params, cancellationSource.token);
}
} else if (starRequestHandler) {
handlerResult = starRequestHandler(requestMessage.method, requestMessage.params, cancellationSource.token);
}
const promise = handlerResult;
if (!handlerResult) {
requestTokens.delete(tokenKey);
replySuccess(handlerResult, requestMessage.method, startTime);
} else if (promise.then) {
promise.then((resultOrError) => {
requestTokens.delete(tokenKey);
reply(resultOrError, requestMessage.method, startTime);
}, (error) => {
requestTokens.delete(tokenKey);
if (error instanceof messages_1.ResponseError) {
replyError(error, requestMessage.method, startTime);
} else if (error && Is2.string(error.message)) {
replyError(new messages_1.ResponseError(messages_1.ErrorCodes.InternalError, `Request ${requestMessage.method} failed with message: ${error.message}`), requestMessage.method, startTime);
} else {
replyError(new messages_1.ResponseError(messages_1.ErrorCodes.InternalError, `Request ${requestMessage.method} failed unexpectedly without providing any details.`), requestMessage.method, startTime);
}
});
} else {
requestTokens.delete(tokenKey);
reply(handlerResult, requestMessage.method, startTime);
}
} catch (error) {
requestTokens.delete(tokenKey);
if (error instanceof messages_1.ResponseError) {
reply(error, requestMessage.method, startTime);
} else if (error && Is2.string(error.message)) {
replyError(new messages_1.ResponseError(messages_1.ErrorCodes.InternalError, `Request ${requestMessage.method} failed with message: ${error.message}`), requestMessage.method, startTime);
} else {
replyError(new messages_1.ResponseError(messages_1.ErrorCodes.InternalError, `Request ${requestMessage.method} failed unexpectedly without providing any details.`), requestMessage.method, startTime);
}
}
} else {
replyError(new messages_1.ResponseError(messages_1.ErrorCodes.MethodNotFound, `Unhandled method ${requestMessage.method}`), requestMessage.method, startTime);
}
}
__name(handleRequest, "handleRequest");
__name2(handleRequest, "handleRequest");
function handleResponse(responseMessage) {
if (isDisposed()) {
return;
}
if (responseMessage.id === null) {
if (responseMessage.error) {
logger.error(`Received response message without id: Error is:
${JSON.stringify(responseMessage.error, void 0, 4)}`);
} else {
logger.error(`Received response message without id. No further error information provided.`);
}
} else {
const key = responseMessage.id;
const responsePromise = responsePromises.get(key);
traceReceivedResponse(responseMessage, responsePromise);
if (responsePromise !== void 0) {
responsePromises.delete(key);
try {
if (responseMessage.error) {
const error = responseMessage.error;
responsePromise.reject(new messages_1.ResponseError(error.code, error.message, error.data));
} else if (responseMessage.result !== void 0) {
responsePromise.resolve(responseMessage.result);
} else {
throw new Error("Should never happen.");
}
} catch (error) {
if (error.message) {
logger.error(`Response handler '${responsePromise.method}' failed with message: ${error.message}`);
} else {
logger.error(`Response handler '${responsePromise.method}' failed unexpectedly.`);
}
}
}
}
}
__name(handleResponse, "handleResponse");
__name2(handleResponse, "handleResponse");
function handleNotification(message) {
if (isDisposed()) {
return;
}
let type = void 0;
let notificationHandler;
if (message.method === CancelNotification.type.method) {
const cancelId = message.params.id;
knownCanceledRequests.delete(cancelId);
traceReceivedNotification(message);
return;
} else {
const element = notificationHandlers.get(message.method);
if (element) {
notificationHandler = element.handler;
type = element.type;
}
}
if (notificationHandler || starNotificationHandler) {
try {
traceReceivedNotification(message);
if (notificationHandler) {
if (message.params === void 0) {
if (type !== void 0) {
if (type.numberOfParams !== 0 && type.parameterStructures !== messages_1.ParameterStructures.byName) {
logger.error(`Notification ${message.method} defines ${type.numberOfParams} params but received none.`);
}
}
notificationHandler();
} else if (Array.isArray(message.params)) {
const params = message.params;
if (message.method === ProgressNotification.type.method && params.length === 2 && ProgressToken.is(params[0])) {
notificationHandler({ token: params[0], value: params[1] });
} else {
if (type !== void 0) {
if (type.parameterStructures === messages_1.ParameterStructures.byName) {
logger.error(`Notification ${message.method} defines parameters by name but received parameters by position`);
}
if (type.numberOfParams !== message.params.length) {
logger.error(`Notification ${message.method} defines ${type.numberOfParams} params but received ${params.length} arguments`);
}
}
notificationHandler(...params);
}
} else {
if (type !== void 0 && type.parameterStructures === messages_1.ParameterStructures.byPosition) {
logger.error(`Notification ${message.method} defines parameters by position but received parameters by name`);
}
notificationHandler(message.params);
}
} else if (starNotificationHandler) {
starNotificationHandler(message.method, message.params);
}
} catch (error) {
if (error.message) {
logger.error(`Notification handler '${message.method}' failed with message: ${error.message}`);
} else {
logger.error(`Notification handler '${message.method}' failed unexpectedly.`);
}
}
} else {
unhandledNotificationEmitter.fire(message);
}
}
__name(handleNotification, "handleNotification");
__name2(handleNotification, "handleNotification");
function handleInvalidMessage(message) {
if (!message) {
logger.error("Received empty message.");
return;
}
logger.error(`Received message which is neither a response nor a notification message:
${JSON.stringify(message, null, 4)}`);
const responseMessage = message;
if (Is2.string(responseMessage.id) || Is2.number(responseMessage.id)) {
const key = responseMessage.id;
const responseHandler = responsePromises.get(key);
if (responseHandler) {
responseHandler.reject(new Error("The received response has neither a result nor an error property."));
}
}
}
__name(handleInvalidMessage, "handleInvalidMessage");
__name2(handleInvalidMessage, "handleInvalidMessage");
function stringifyTrace(params) {
if (params === void 0 || params === null) {
return void 0;
}
switch (trace) {
case Trace.Verbose:
return JSON.stringify(params, null, 4);
case Trace.Compact:
return JSON.stringify(params);
default:
return void 0;
}
}
__name(stringifyTrace, "stringifyTrace");
__name2(stringifyTrace, "stringifyTrace");
function traceSendingRequest(message) {
if (trace === Trace.Off || !tracer) {
return;
}
if (traceFormat === TraceFormat.Text) {
let data = void 0;
if ((trace === Trace.Verbose || trace === Trace.Compact) && message.params) {
data = `Params: ${stringifyTrace(message.params)}
`;
}
tracer.log(`Sending request '${message.method} - (${message.id})'.`, data);
} else {
logLSPMessage("send-request", message);
}
}
__name(traceSendingRequest, "traceSendingRequest");
__name2(traceSendingRequest, "traceSendingRequest");
function traceSendingNotification(message) {
if (trace === Trace.Off || !tracer) {
return;
}
if (traceFormat === TraceFormat.Text) {
let data = void 0;
if (trace === Trace.Verbose || trace === Trace.Compact) {
if (message.params) {
data = `Params: ${stringifyTrace(message.params)}
`;
} else {
data = "No parameters provided.\n\n";
}
}
tracer.log(`Sending notification '${message.method}'.`, data);
} else {
logLSPMessage("send-notification", message);
}
}
__name(traceSendingNotification, "traceSendingNotification");
__name2(traceSendingNotification, "traceSendingNotification");
function traceSendingResponse(message, method, startTime) {
if (trace === Trace.Off || !tracer) {
return;
}
if (traceFormat === TraceFormat.Text) {
let data = void 0;
if (trace === Trace.Verbose || trace === Trace.Compact) {
if (message.error && message.error.data) {
data = `Error data: ${stringifyTrace(message.error.data)}
`;
} else {
if (message.result) {
data = `Result: ${stringifyTrace(message.result)}
`;
} else if (message.error === void 0) {
data = "No result returned.\n\n";
}
}
}
tracer.log(`Sending response '${method} - (${message.id})'. Processing request took ${Date.now() - startTime}ms`, data);
} else {
logLSPMessage("send-response", message);
}
}
__name(traceSendingResponse, "traceSendingResponse");
__name2(traceSendingResponse, "traceSendingResponse");
function traceReceivedRequest(message) {
if (trace === Trace.Off || !tracer) {
return;
}
if (traceFormat === TraceFormat.Text) {
let data = void 0;
if ((trace === Trace.Verbose || trace === Trace.Compact) && message.params) {
data = `Params: ${stringifyTrace(message.params)}
`;
}
tracer.log(`Received request '${message.method} - (${message.id})'.`, data);
} else {
logLSPMessage("receive-request", message);
}
}
__name(traceReceivedRequest, "traceReceivedRequest");
__name2(traceReceivedRequest, "traceReceivedRequest");
function traceReceivedNotification(message) {
if (trace === Trace.Off || !tracer || message.method === LogTraceNotification.type.method) {
return;
}
if (traceFormat === TraceFormat.Text) {
let data = void 0;
if (trace === Trace.Verbose || trace === Trace.Compact) {
if (message.params) {
data = `Params: ${stringifyTrace(message.params)}
`;
} else {
data = "No parameters provided.\n\n";
}
}
tracer.log(`Received notification '${message.method}'.`, data);
} else {
logLSPMessage("receive-notification", message);
}
}
__name(traceReceivedNotification, "traceReceivedNotification");
__name2(traceReceivedNotification, "traceReceivedNotification");
function traceReceivedResponse(message, responsePromise) {
if (trace === Trace.Off || !tracer) {
return;
}
if (traceFormat === TraceFormat.Text) {
let data = void 0;
if (trace === Trace.Verbose || trace === Trace.Compact) {
if (message.error && message.error.data) {
data = `Error data: ${stringifyTrace(message.error.data)}
`;
} else {
if (message.result) {
data = `Result: ${stringifyTrace(message.result)}
`;
} else if (message.error === void 0) {
data = "No result returned.\n\n";
}
}
}
if (responsePromise) {
const error = message.error ? ` Request failed: ${message.error.message} (${message.error.code}).` : "";
tracer.log(`Received response '${responsePromise.method} - (${message.id})' in ${Date.now() - responsePromise.timerStart}ms.${error}`, data);
} else {
tracer.log(`Received response ${message.id} without active response promise.`, data);
}
} else {
logLSPMessage("receive-response", message);
}
}
__name(traceReceivedResponse, "traceReceivedResponse");
__name2(traceReceivedResponse, "traceReceivedResponse");
function logLSPMessage(type, message) {
if (!tracer || trace === Trace.Off) {
return;
}
const lspMessage = {
isLSPMessage: true,
type,
message,
timestamp: Date.now()
};
tracer.log(lspMessage);
}
__name(logLSPMessage, "logLSPMessage");
__name2(logLSPMessage, "logLSPMessage");
function throwIfClosedOrDisposed() {
if (isClosed()) {
throw new ConnectionError(ConnectionErrors.Closed, "Connection is closed.");
}
if (isDisposed()) {
throw new ConnectionError(ConnectionErrors.Disposed, "Connection is disposed.");
}
}
__name(throwIfClosedOrDisposed, "throwIfClosedOrDisposed");
__name2(throwIfClosedOrDisposed, "throwIfClosedOrDisposed");
function throwIfListening() {
if (isListening()) {
throw new ConnectionError(ConnectionErrors.AlreadyListening, "Connection is already listening");
}
}
__name(throwIfListening, "throwIfListening");
__name2(throwIfListening, "throwIfListening");
function throwIfNotListening() {
if (!isListening()) {
throw new Error("Call listen() first.");
}
}
__name(throwIfNotListening, "throwIfNotListening");
__name2(throwIfNotListening, "throwIfNotListening");
function undefinedToNull(param) {
if (param === void 0) {
return null;
} else {
return param;
}
}
__name(undefinedToNull, "undefinedToNull");
__name2(undefinedToNull, "undefinedToNull");
function nullToUndefined(param) {
if (param === null) {
return void 0;
} else {
return param;
}
}
__name(nullToUndefined, "nullToUndefined");
__name2(nullToUndefined, "nullToUndefined");
function isNamedParam(param) {
return param !== void 0 && param !== null && !Array.isArray(param) && typeof param === "object";
}
__name(isNamedParam, "isNamedParam");
__name2(isNamedParam, "isNamedParam");
function computeSingleParam(parameterStructures, param) {
switch (parameterStructures) {
case messages_1.ParameterStructures.auto:
if (isNamedParam(param)) {
return nullToUndefined(param);
} else {
return [undefinedToNull(param)];
}
case messages_1.ParameterStructures.byName:
if (!isNamedParam(param)) {
throw new Error(`Received parameters by name but param is not an object literal.`);
}
return nullToUndefined(param);
case messages_1.ParameterStructures.byPosition:
return [undefinedToNull(param)];
default:
throw new Error(`Unknown parameter structure ${parameterStructures.toString()}`);
}
}
__name(computeSingleParam, "computeSingleParam");
__name2(computeSingleParam, "computeSingleParam");
function computeMessageParams(type, params) {
let result;
const numberOfParams = type.numberOfParams;
switch (numberOfParams) {
case 0:
result = void 0;
break;
case 1:
result = computeSingleParam(type.parameterStructures, params[0]);
break;
default:
result = [];
for (let i = 0; i < params.length && i < numberOfParams; i++) {
result.push(undefinedToNull(params[i]));
}
if (params.length < numberOfParams) {
for (let i = params.length; i < numberOfParams; i++) {
result.push(null);
}
}
break;
}
return result;
}
__name(computeMessageParams, "computeMessageParams");
__name2(computeMessageParams, "computeMessageParams");
const connection = {
sendNotification: /* @__PURE__ */ __name2((type, ...args) => {
throwIfClosedOrDisposed();
let method;
let messageParams;
if (Is2.string(type)) {
method = type;
const first2 = args[0];
let paramStart = 0;
let parameterStructures = messages_1.ParameterStructures.auto;
if (messages_1.ParameterStructures.is(first2)) {
paramStart = 1;
parameterStructures = first2;
}
let paramEnd = args.length;
const numberOfParams = paramEnd - paramStart;
switch (numberOfParams) {
case 0:
messageParams = void 0;
break;
case 1:
messageParams = computeSingleParam(parameterStructures, args[paramStart]);
break;
default:
if (parameterStructures === messages_1.ParameterStructures.byName) {
throw new Error(`Received ${numberOfParams} parameters for 'by Name' notification parameter structure.`);
}
messageParams = args.slice(paramStart, paramEnd).map((value) => undefinedToNull(value));
break;
}
} else {
const params = args;
method = type.method;
messageParams = computeMessageParams(type, params);
}
const notificationMessage = {
jsonrpc: version,
method,
params: messageParams
};
traceSendingNotification(notificationMessage);
return messageWriter.write(notificationMessage).catch((error) => {
logger.error(`Sending notification failed.`);
throw error;
});
}, "sendNotification"),
onNotification: /* @__PURE__ */ __name2((type, handler) => {
throwIfClosedOrDisposed();
let method;
if (Is2.func(type)) {
starNotificationHandler = type;
} else if (handler) {
if (Is2.string(type)) {
method = type;
notificationHandlers.set(type, { type: void 0, handler });
} else {
method = type.method;
notificationHandlers.set(type.method, { type, handler });
}
}
return {
dispose: /* @__PURE__ */ __name2(() => {
if (method !== void 0) {
notificationHandlers.delete(method);
} else {
starNotificationHandler = void 0;
}
}, "dispose")
};
}, "onNotification"),
onProgress: /* @__PURE__ */ __name2((_type, token, handler) => {
if (progressHandlers.has(token)) {
throw new Error(`Progress handler for token ${token} already registered`);
}
progressHandlers.set(token, handler);
return {
dispose: /* @__PURE__ */ __name2(() => {
progressHandlers.delete(token);
}, "dispose")
};
}, "onProgress"),
sendProgress: /* @__PURE__ */ __name2((_type, token, value) => {
return connection.sendNotification(ProgressNotification.type, { token, value });
}, "sendProgress"),
onUnhandledProgress: unhandledProgressEmitter.event,
sendRequest: /* @__PURE__ */ __name2((type, ...args) => {
throwIfClosedOrDisposed();
throwIfNotListening();
let method;
let messageParams;
let token = void 0;
if (Is2.string(type)) {
method = type;
const first2 = args[0];
const last2 = args[args.length - 1];
let paramStart = 0;
let parameterStructures = messages_1.ParameterStructures.auto;
if (messages_1.ParameterStructures.is(first2)) {
paramStart = 1;
parameterStructures = first2;
}
let paramEnd = args.length;
if (cancellation_1.CancellationToken.is(last2)) {
paramEnd = paramEnd - 1;
token = last2;
}
const numberOfParams = paramEnd - paramStart;
switch (numberOfParams) {
case 0:
messageParams = void 0;
break;
case 1:
messageParams = computeSingleParam(parameterStructures, args[paramStart]);
break;
default:
if (parameterStructures === messages_1.ParameterStructures.byName) {
throw new Error(`Received ${numberOfParams} parameters for 'by Name' request parameter structure.`);
}
messageParams = args.slice(paramStart, paramEnd).map((value) => undefinedToNull(value));
break;
}
} else {
const params = args;
method = type.method;
messageParams = computeMessageParams(type, params);
const numberOfParams = type.numberOfParams;
token = cancellation_1.CancellationToken.is(params[numberOfParams]) ? params[numberOfParams] : void 0;
}
const id = sequenceNumber++;
let disposable;
if (token) {
disposable = token.onCancellationRequested(() => {
const p = cancellationStrategy.sender.sendCancellation(connection, id);
if (p === void 0) {
logger.log(`Received no promise from cancellation strategy when cancelling id ${id}`);
return Promise.resolve();
} else {
return p.catch(() => {
logger.log(`Sending cancellation messages for id ${id} failed`);
});
}
});
}
const requestMessage = {
jsonrpc: version,
id,
method,
params: messageParams
};
traceSendingRequest(requestMessage);
if (typeof cancellationStrategy.sender.enableCancellation === "function") {
cancellationStrategy.sender.enableCancellation(requestMessage);
}
return new Promise(async (resolve, reject2) => {
const resolveWithCleanup = /* @__PURE__ */ __name2((r) => {
resolve(r);
cancellationStrategy.sender.cleanup(id);
disposable?.dispose();
}, "resolveWithCleanup");
const rejectWithCleanup = /* @__PURE__ */ __name2((r) => {
reject2(r);
cancellationStrategy.sender.cleanup(id);
disposable?.dispose();
}, "rejectWithCleanup");
const responsePromise = { method, timerStart: Date.now(), resolve: resolveWithCleanup, reject: rejectWithCleanup };
try {
await messageWriter.write(requestMessage);
responsePromises.set(id, responsePromise);
} catch (error) {
logger.error(`Sending request failed.`);
responsePromise.reject(new messages_1.ResponseError(messages_1.ErrorCodes.MessageWriteError, error.message ? error.message : "Unknown reason"));
throw error;
}
});
}, "sendRequest"),
onRequest: /* @__PURE__ */ __name2((type, handler) => {
throwIfClosedOrDisposed();
let method = null;
if (StarRequestHandler.is(type)) {
method = void 0;
starRequestHandler = type;
} else if (Is2.string(type)) {
method = null;
if (handler !== void 0) {
method = type;
requestHandlers.set(type, { handler, type: void 0 });
}
} else {
if (handler !== void 0) {
method = type.method;
requestHandlers.set(type.method, { type, handler });
}
}
return {
dispose: /* @__PURE__ */ __name2(() => {
if (method === null) {
return;
}
if (method !== void 0) {
requestHandlers.delete(method);
} else {
starRequestHandler = void 0;
}
}, "dispose")
};
}, "onRequest"),
hasPendingResponse: /* @__PURE__ */ __name2(() => {
return responsePromises.size > 0;
}, "hasPendingResponse"),
trace: /* @__PURE__ */ __name2(async (_value, _tracer, sendNotificationOrTraceOptions) => {
let _sendNotification = false;
let _traceFormat = TraceFormat.Text;
if (sendNotificationOrTraceOptions !== void 0) {
if (Is2.boolean(sendNotificationOrTraceOptions)) {
_sendNotification = sendNotificationOrTraceOptions;
} else {
_sendNotification = sendNotificationOrTraceOptions.sendNotification || false;
_traceFormat = sendNotificationOrTraceOptions.traceFormat || TraceFormat.Text;
}
}
trace = _value;
traceFormat = _traceFormat;
if (trace === Trace.Off) {
tracer = void 0;
} else {
tracer = _tracer;
}
if (_sendNotification && !isClosed() && !isDisposed()) {
await connection.sendNotification(SetTraceNotification.type, { value: Trace.toString(_value) });
}
}, "trace"),
onError: errorEmitter.event,
onClose: closeEmitter.event,
onUnhandledNotification: unhandledNotificationEmitter.event,
onDispose: disposeEmitter.event,
end: /* @__PURE__ */ __name2(() => {
messageWriter.end();
}, "end"),
dispose: /* @__PURE__ */ __name2(() => {
if (isDisposed()) {
return;
}
state = ConnectionState.Disposed;
disposeEmitter.fire(void 0);
const error = new messages_1.ResponseError(messages_1.ErrorCodes.PendingResponseRejected, "Pending response rejected since connection got disposed");
for (const promise of responsePromises.values()) {
promise.reject(error);
}
responsePromises = /* @__PURE__ */ new Map();
requestTokens = /* @__PURE__ */ new Map();
knownCanceledRequests = /* @__PURE__ */ new Set();
messageQueue = new linkedMap_1.LinkedMap();
if (Is2.func(messageWriter.dispose)) {
messageWriter.dispose();
}
if (Is2.func(messageReader.dispose)) {
messageReader.dispose();
}
}, "dispose"),
listen: /* @__PURE__ */ __name2(() => {
throwIfClosedOrDisposed();
throwIfListening();
state = ConnectionState.Listening;
messageReader.listen(callback);
}, "listen"),
inspect: /* @__PURE__ */ __name2(() => {
(0, ral_1.default)().console.log("inspect");
}, "inspect")
};
connection.onNotification(LogTraceNotification.type, (params) => {
if (trace === Trace.Off || !tracer) {
return;
}
const verbose = trace === Trace.Verbose || trace === Trace.Compact;
tracer.log(params.message, verbose ? params.verbose : void 0);
});
connection.onNotification(ProgressNotification.type, (params) => {
const handler = progressHandlers.get(params.token);
if (handler) {
handler(params.value);
} else {
unhandledProgressEmitter.fire(params);
}
});
return connection;
}
__name(createMessageConnection, "createMessageConnection");
__name2(createMessageConnection, "createMessageConnection");
exports2.createMessageConnection = createMessageConnection;
}
});
var require_api = __commonJS({
"../../node_modules/.pnpm/vscode-jsonrpc@8.2.0/node_modules/vscode-jsonrpc/lib/common/api.js"(exports2) {
"use strict";
Object.defineProperty(exports2, "__esModule", { value: true });
exports2.ProgressType = exports2.ProgressToken = exports2.createMessageConnection = exports2.NullLogger = exports2.ConnectionOptions = exports2.ConnectionStrategy = exports2.AbstractMessageBuffer = exports2.WriteableStreamMessageWriter = exports2.AbstractMessageWriter = exports2.MessageWriter = exports2.ReadableStreamMessageReader = exports2.AbstractMessageReader = exports2.MessageReader = exports2.SharedArrayReceiverStrategy = exports2.SharedArraySenderStrategy = exports2.CancellationToken = exports2.CancellationTokenSource = exports2.Emitter = exports2.Event = exports2.Disposable = exports2.LRUCache = exports2.Touch = exports2.LinkedMap = exports2.ParameterStructures = exports2.NotificationType9 = exports2.NotificationType8 = exports2.NotificationType7 = exports2.NotificationType6 = exports2.NotificationType5 = exports2.NotificationType4 = exports2.NotificationType3 = exports2.NotificationType2 = exports2.NotificationType1 = exports2.NotificationType0 = exports2.NotificationType = exports2.ErrorCodes = exports2.ResponseError = exports2.RequestType9 = exports2.RequestType8 = exports2.RequestType7 = exports2.RequestType6 = exports2.RequestType5 = exports2.RequestType4 = exports2.RequestType3 = exports2.RequestType2 = exports2.RequestType1 = exports2.RequestType0 = exports2.RequestType = exports2.Message = exports2.RAL = void 0;
exports2.MessageStrategy = exports2.CancellationStrategy = exports2.CancellationSenderStrategy = exports2.CancellationReceiverStrategy = exports2.ConnectionError = exports2.ConnectionErrors = exports2.LogTraceNotification = exports2.SetTraceNotification = exports2.TraceFormat = exports2.TraceValues = exports2.Trace = void 0;
var messages_1 = require_messages();
Object.defineProperty(exports2, "Message", { enumerable: true, get: /* @__PURE__ */ __name2(function() {
return messages_1.Message;
}, "get") });
Object.defineProperty(exports2, "RequestType", { enumerable: true, get: /* @__PURE__ */ __name2(function() {
return messages_1.RequestType;
}, "get") });
Object.defineProperty(exports2, "RequestType0", { enumerable: true, get: /* @__PURE__ */ __name2(function() {
return messages_1.RequestType0;
}, "get") });
Object.defineProperty(exports2, "RequestType1", { enumerable: true, get: /* @__PURE__ */ __name2(function() {
return messages_1.RequestType1;
}, "get") });
Object.defineProperty(exports2, "RequestType2", { enumerable: true, get: /* @__PURE__ */ __name2(function() {
return messages_1.RequestType2;
}, "get") });
Object.defineProperty(exports2, "RequestType3", { enumerable: true, get: /* @__PURE__ */ __name2(function() {
return messages_1.RequestType3;
}, "get") });
Object.defineProperty(exports2, "RequestType4", { enumerable: true, get: /* @__PURE__ */ __name2(function() {
return messages_1.RequestType4;
}, "get") });
Object.defineProperty(exports2, "RequestType5", { enumerable: true, get: /* @__PURE__ */ __name2(function() {
return messages_1.RequestType5;
}, "get") });
Object.defineProperty(exports2, "RequestType6", { enumerable: true, get: /* @__PURE__ */ __name2(function() {
return messages_1.RequestType6;
}, "get") });
Object.defineProperty(exports2, "RequestType7", { enumerable: true, get: /* @__PURE__ */ __name2(function() {
return messages_1.RequestType7;
}, "get") });
Object.defineProperty(exports2, "RequestType8", { enumerable: true, get: /* @__PURE__ */ __name2(function() {
return messages_1.RequestType8;
}, "get") });
Object.defineProperty(exports2, "RequestType9", { enumerable: true, get: /* @__PURE__ */ __name2(function() {
return messages_1.RequestType9;
}, "get") });
Object.defineProperty(exports2, "ResponseError", { enumerable: true, get: /* @__PURE__ */ __name2(function() {
return messages_1.ResponseError;
}, "get") });
Object.defineProperty(exports2, "ErrorCodes", { enumerable: true, get: /* @__PURE__ */ __name2(function() {
return messages_1.ErrorCodes;
}, "get") });
Object.defineProperty(exports2, "NotificationType", { enumerable: true, get: /* @__PURE__ */ __name2(function() {
return messages_1.NotificationType;
}, "get") });
Object.defineProperty(exports2, "NotificationType0", { enumerable: true, get: /* @__PURE__ */ __name2(function() {
return messages_1.NotificationType0;
}, "get") });
Object.defineProperty(exports2, "NotificationType1", { enumerable: true, get: /* @__PURE__ */ __name2(function() {
return messages_1.NotificationType1;
}, "get") });
Object.defineProperty(exports2, "NotificationType2", { enumerable: true, get: /* @__PURE__ */ __name2(function() {
return messages_1.NotificationType2;
}, "get") });
Object.defineProperty(exports2, "NotificationType3", { enumerable: true, get: /* @__PURE__ */ __name2(function() {
return messages_1.NotificationType3;
}, "get") });
Object.defineProperty(exports2, "NotificationType4", { enumerable: true, get: /* @__PURE__ */ __name2(function() {
return messages_1.NotificationType4;
}, "get") });
Object.defineProperty(exports2, "NotificationType5", { enumerable: true, get: /* @__PURE__ */ __name2(function() {
return messages_1.NotificationType5;
}, "get") });
Object.defineProperty(exports2, "NotificationType6", { enumerable: true, get: /* @__PURE__ */ __name2(function() {
return messages_1.NotificationType6;
}, "get") });
Object.defineProperty(exports2, "NotificationType7", { enumerable: true, get: /* @__PURE__ */ __name2(function() {
return messages_1.NotificationType7;
}, "get") });
Object.defineProperty(exports2, "NotificationType8", { enumerable: true, get: /* @__PURE__ */ __name2(function() {
return messages_1.NotificationType8;
}, "get") });
Object.defineProperty(exports2, "NotificationType9", { enumerable: true, get: /* @__PURE__ */ __name2(function() {
return messages_1.NotificationType9;
}, "get") });
Object.defineProperty(exports2, "ParameterStructures", { enumerable: true, get: /* @__PURE__ */ __name2(function() {
return messages_1.ParameterStructures;
}, "get") });
var linkedMap_1 = require_linkedMap();
Object.defineProperty(exports2, "LinkedMap", { enumerable: true, get: /* @__PURE__ */ __name2(function() {
return linkedMap_1.LinkedMap;
}, "get") });
Object.defineProperty(exports2, "LRUCache", { enumerable: true, get: /* @__PURE__ */ __name2(function() {
return linkedMap_1.LRUCache;
}, "get") });
Object.defineProperty(exports2, "Touch", { enumerable: true, get: /* @__PURE__ */ __name2(function() {
return linkedMap_1.Touch;
}, "get") });
var disposable_1 = require_disposable();
Object.defineProperty(exports2, "Disposable", { enumerable: true, get: /* @__PURE__ */ __name2(function() {
return disposable_1.Disposable;
}, "get") });
var events_1 = require_events();
Object.defineProperty(exports2, "Event", { enumerable: true, get: /* @__PURE__ */ __name2(function() {
return events_1.Event;
}, "get") });
Object.defineProperty(exports2, "Emitter", { enumerable: true, get: /* @__PURE__ */ __name2(function() {
return events_1.Emitter;
}, "get") });
var cancellation_1 = require_cancellation();
Object.defineProperty(exports2, "CancellationTokenSource", { enumerable: true, get: /* @__PURE__ */ __name2(function() {
return cancellation_1.CancellationTokenSource;
}, "get") });
Object.defineProperty(exports2, "CancellationToken", { enumerable: true, get: /* @__PURE__ */ __name2(function() {
return cancellation_1.CancellationToken;
}, "get") });
var sharedArrayCancellation_1 = require_sharedArrayCancellation();
Object.defineProperty(exports2, "SharedArraySenderStrategy", { enumerable: true, get: /* @__PURE__ */ __name2(function() {
return sharedArrayCancellation_1.SharedArraySenderStrategy;
}, "get") });
Object.defineProperty(exports2, "SharedArrayReceiverStrategy", { enumerable: true, get: /* @__PURE__ */ __name2(function() {
return sharedArrayCancellation_1.SharedArrayReceiverStrategy;
}, "get") });
var messageReader_1 = require_messageReader();
Object.defineProperty(exports2, "MessageReader", { enumerable: true, get: /* @__PURE__ */ __name2(function() {
return messageReader_1.MessageReader;
}, "get") });
Object.defineProperty(exports2, "AbstractMessageReader", { enumerable: true, get: /* @__PURE__ */ __name2(function() {
return messageReader_1.AbstractMessageReader;
}, "get") });
Object.defineProperty(exports2, "ReadableStreamMessageReader", { enumerable: true, get: /* @__PURE__ */ __name2(function() {
return messageReader_1.ReadableStreamMessageReader;
}, "get") });
var messageWriter_1 = require_messageWriter();
Object.defineProperty(exports2, "MessageWriter", { enumerable: true, get: /* @__PURE__ */ __name2(function() {
return messageWriter_1.MessageWriter;
}, "get") });
Object.defineProperty(exports2, "AbstractMessageWriter", { enumerable: true, get: /* @__PURE__ */ __name2(function() {
return messageWriter_1.AbstractMessageWriter;
}, "get") });
Object.defineProperty(exports2, "WriteableStreamMessageWriter", { enumerable: true, get: /* @__PURE__ */ __name2(function() {
return messageWriter_1.WriteableStreamMessageWriter;
}, "get") });
var messageBuffer_1 = require_messageBuffer();
Object.defineProperty(exports2, "AbstractMessageBuffer", { enumerable: true, get: /* @__PURE__ */ __name2(function() {
return messageBuffer_1.AbstractMessageBuffer;
}, "get") });
var connection_1 = require_connection();
Object.defineProperty(exports2, "ConnectionStrategy", { enumerable: true, get: /* @__PURE__ */ __name2(function() {
return connection_1.ConnectionStrategy;
}, "get") });
Object.defineProperty(exports2, "ConnectionOptions", { enumerable: true, get: /* @__PURE__ */ __name2(function() {
return connection_1.ConnectionOptions;
}, "get") });
Object.defineProperty(exports2, "NullLogger", { enumerable: true, get: /* @__PURE__ */ __name2(function() {
return connection_1.NullLogger;
}, "get") });
Object.defineProperty(exports2, "createMessageConnection", { enumerable: true, get: /* @__PURE__ */ __name2(function() {
return connection_1.createMessageConnection;
}, "get") });
Object.defineProperty(exports2, "ProgressToken", { enumerable: true, get: /* @__PURE__ */ __name2(function() {
return connection_1.ProgressToken;
}, "get") });
Object.defineProperty(exports2, "ProgressType", { enumerable: true, get: /* @__PURE__ */ __name2(function() {
return connection_1.ProgressType;
}, "get") });
Object.defineProperty(exports2, "Trace", { enumerable: true, get: /* @__PURE__ */ __name2(function() {
return connection_1.Trace;
}, "get") });
Object.defineProperty(exports2, "TraceValues", { enumerable: true, get: /* @__PURE__ */ __name2(function() {
return connection_1.TraceValues;
}, "get") });
Object.defineProperty(exports2, "TraceFormat", { enumerable: true, get: /* @__PURE__ */ __name2(function() {
return connection_1.TraceFormat;
}, "get") });
Object.defineProperty(exports2, "SetTraceNotification", { enumerable: true, get: /* @__PURE__ */ __name2(function() {
return connection_1.SetTraceNotification;
}, "get") });
Object.defineProperty(exports2, "LogTraceNotification", { enumerable: true, get: /* @__PURE__ */ __name2(function() {
return connection_1.LogTraceNotification;
}, "get") });
Object.defineProperty(exports2, "ConnectionErrors", { enumerable: true, get: /* @__PURE__ */ __name2(function() {
return connection_1.ConnectionErrors;
}, "get") });
Object.defineProperty(exports2, "ConnectionError", { enumerable: true, get: /* @__PURE__ */ __name2(function() {
return connection_1.ConnectionError;
}, "get") });
Object.defineProperty(exports2, "CancellationReceiverStrategy", { enumerable: true, get: /* @__PURE__ */ __name2(function() {
return connection_1.CancellationReceiverStrategy;
}, "get") });
Object.defineProperty(exports2, "CancellationSenderStrategy", { enumerable: true, get: /* @__PURE__ */ __name2(function() {
return connection_1.CancellationSenderStrategy;
}, "get") });
Object.defineProperty(exports2, "CancellationStrategy", { enumerable: true, get: /* @__PURE__ */ __name2(function() {
return connection_1.CancellationStrategy;
}, "get") });
Object.defineProperty(exports2, "MessageStrategy", { enumerable: true, get: /* @__PURE__ */ __name2(function() {
return connection_1.MessageStrategy;
}, "get") });
var ral_1 = require_ral();
exports2.RAL = ral_1.default;
}
});
var require_ril = __commonJS({
"../../node_modules/.pnpm/vscode-jsonrpc@8.2.0/node_modules/vscode-jsonrpc/lib/browser/ril.js"(exports2) {
"use strict";
Object.defineProperty(exports2, "__esModule", { value: true });
var api_1 = require_api();
var MessageBuffer = class _MessageBuffer extends api_1.AbstractMessageBuffer {
static {
__name(this, "_MessageBuffer");
}
static {
__name2(this, "MessageBuffer");
}
constructor(encoding = "utf-8") {
super(encoding);
this.asciiDecoder = new TextDecoder("ascii");
}
emptyBuffer() {
return _MessageBuffer.emptyBuffer;
}
fromString(value, _encoding) {
return new TextEncoder().encode(value);
}
toString(value, encoding) {
if (encoding === "ascii") {
return this.asciiDecoder.decode(value);
} else {
return new TextDecoder(encoding).decode(value);
}
}
asNative(buffer, length) {
if (length === void 0) {
return buffer;
} else {
return buffer.slice(0, length);
}
}
allocNative(length) {
return new Uint8Array(length);
}
};
MessageBuffer.emptyBuffer = new Uint8Array(0);
var ReadableStreamWrapper = class {
static {
__name(this, "ReadableStreamWrapper");
}
static {
__name2(this, "ReadableStreamWrapper");
}
constructor(socket) {
this.socket = socket;
this._onData = new api_1.Emitter();
this._messageListener = (event) => {
const blob = event.data;
blob.arrayBuffer().then((buffer) => {
this._onData.fire(new Uint8Array(buffer));
}, () => {
(0, api_1.RAL)().console.error(`Converting blob to array buffer failed.`);
});
};
this.socket.addEventListener("message", this._messageListener);
}
onClose(listener) {
this.socket.addEventListener("close", listener);
return api_1.Disposable.create(() => this.socket.removeEventListener("close", listener));
}
onError(listener) {
this.socket.addEventListener("error", listener);
return api_1.Disposable.create(() => this.socket.removeEventListener("error", listener));
}
onEnd(listener) {
this.socket.addEventListener("end", listener);
return api_1.Disposable.create(() => this.socket.removeEventListener("end", listener));
}
onData(listener) {
return this._onData.event(listener);
}
};
var WritableStreamWrapper = class {
static {
__name(this, "WritableStreamWrapper");
}
static {
__name2(this, "WritableStreamWrapper");
}
constructor(socket) {
this.socket = socket;
}
onClose(listener) {
this.socket.addEventListener("close", listener);
return api_1.Disposable.create(() => this.socket.removeEventListener("close", listener));
}
onError(listener) {
this.socket.addEventListener("error", listener);
return api_1.Disposable.create(() => this.socket.removeEventListener("error", listener));
}
onEnd(listener) {
this.socket.addEventListener("end", listener);
return api_1.Disposable.create(() => this.socket.removeEventListener("end", listener));
}
write(data, encoding) {
if (typeof data === "string") {
if (encoding !== void 0 && encoding !== "utf-8") {
throw new Error(`In a Browser environments only utf-8 text encoding is supported. But got encoding: ${encoding}`);
}
this.socket.send(data);
} else {
this.socket.send(data);
}
return Promise.resolve();
}
end() {
this.socket.close();
}
};
var _textEncoder = new TextEncoder();
var _ril = Object.freeze({
messageBuffer: Object.freeze({
create: /* @__PURE__ */ __name2((encoding) => new MessageBuffer(encoding), "create")
}),
applicationJson: Object.freeze({
encoder: Object.freeze({
name: "application/json",
encode: /* @__PURE__ */ __name2((msg, options) => {
if (options.charset !== "utf-8") {
throw new Error(`In a Browser environments only utf-8 text encoding is supported. But got encoding: ${options.charset}`);
}
return Promise.resolve(_textEncoder.encode(JSON.stringify(msg, void 0, 0)));
}, "encode")
}),
decoder: Object.freeze({
name: "application/json",
decode: /* @__PURE__ */ __name2((buffer, options) => {
if (!(buffer instanceof Uint8Array)) {
throw new Error(`In a Browser environments only Uint8Arrays are supported.`);
}
return Promise.resolve(JSON.parse(new TextDecoder(options.charset).decode(buffer)));
}, "decode")
})
}),
stream: Object.freeze({
asReadableStream: /* @__PURE__ */ __name2((socket) => new ReadableStreamWrapper(socket), "asReadableStream"),
asWritableStream: /* @__PURE__ */ __name2((socket) => new WritableStreamWrapper(socket), "asWritableStream")
}),
console,
timer: Object.freeze({
setTimeout(callback, ms, ...args) {
const handle = setTimeout(callback, ms, ...args);
return { dispose: /* @__PURE__ */ __name2(() => clearTimeout(handle), "dispose") };
},
setImmediate(callback, ...args) {
const handle = setTimeout(callback, 0, ...args);
return { dispose: /* @__PURE__ */ __name2(() => clearTimeout(handle), "dispose") };
},
setInterval(callback, ms, ...args) {
const handle = setInterval(callback, ms, ...args);
return { dispose: /* @__PURE__ */ __name2(() => clearInterval(handle), "dispose") };
}
})
});
function RIL() {
return _ril;
}
__name(RIL, "RIL");
__name2(RIL, "RIL");
(function(RIL2) {
function install() {
api_1.RAL.install(_ril);
}
__name(install, "install");
__name2(install, "install");
RIL2.install = install;
})(RIL || (RIL = {}));
exports2.default = RIL;
}
});
var require_main = __commonJS({
"../../node_modules/.pnpm/vscode-jsonrpc@8.2.0/node_modules/vscode-jsonrpc/lib/browser/main.js"(exports2) {
"use strict";
var __createBinding = exports2 && exports2.__createBinding || (Object.create ? (function(o, m, k, k2) {
if (k2 === void 0) k2 = k;
var desc = Object.getOwnPropertyDescriptor(m, k);
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: /* @__PURE__ */ __name2(function() {
return m[k];
}, "get") };
}
Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
if (k2 === void 0) k2 = k;
o[k2] = m[k];
}));
var __exportStar = exports2 && exports2.__exportStar || function(m, exports3) {
for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports3, p)) __createBinding(exports3, m, p);
};
Object.defineProperty(exports2, "__esModule", { value: true });
exports2.createMessageConnection = exports2.BrowserMessageWriter = exports2.BrowserMessageReader = void 0;
var ril_1 = require_ril();
ril_1.default.install();
var api_1 = require_api();
__exportStar(require_api(), exports2);
var BrowserMessageReader = class extends api_1.AbstractMessageReader {
static {
__name(this, "BrowserMessageReader");
}
static {
__name2(this, "BrowserMessageReader");
}
constructor(port) {
super();
this._onData = new api_1.Emitter();
this._messageListener = (event) => {
this._onData.fire(event.data);
};
port.addEventListener("error", (event) => this.fireError(event));
port.onmessage = this._messageListener;
}
listen(callback) {
return this._onData.event(callback);
}
};
exports2.BrowserMessageReader = BrowserMessageReader;
var BrowserMessageWriter = class extends api_1.AbstractMessageWriter {
static {
__name(this, "BrowserMessageWriter");
}
static {
__name2(this, "BrowserMessageWriter");
}
constructor(port) {
super();
this.port = port;
this.errorCount = 0;
port.addEventListener("error", (event) => this.fireError(event));
}
write(msg) {
try {
this.port.postMessage(msg);
return Promise.resolve();
} catch (error) {
this.handleError(error, msg);
return Promise.reject(error);
}
}
handleError(error, msg) {
this.errorCount++;
this.fireError(error, msg, this.errorCount);
}
end() {
}
};
exports2.BrowserMessageWriter = BrowserMessageWriter;
function createMessageConnection(reader, writer, logger, options) {
if (logger === void 0) {
logger = api_1.NullLogger;
}
if (api_1.ConnectionStrategy.is(options)) {
options = { connectionStrategy: options };
}
return (0, api_1.createMessageConnection)(reader, writer, logger, options);
}
__name(createMessageConnection, "createMessageConnection");
__name2(createMessageConnection, "createMessageConnection");
exports2.createMessageConnection = createMessageConnection;
}
});
var require_browser = __commonJS({
"../../node_modules/.pnpm/vscode-jsonrpc@8.2.0/node_modules/vscode-jsonrpc/browser.js"(exports2, module2) {
"use strict";
module2.exports = require_main();
}
});
var require_messages2 = __commonJS({
"../../node_modules/.pnpm/vscode-languageserver-protocol@3.17.5/node_modules/vscode-languageserver-protocol/lib/common/messages.js"(exports2) {
"use strict";
Object.defineProperty(exports2, "__esModule", { value: true });
exports2.ProtocolNotificationType = exports2.ProtocolNotificationType0 = exports2.ProtocolRequestType = exports2.ProtocolRequestType0 = exports2.RegistrationType = exports2.MessageDirection = void 0;
var vscode_jsonrpc_1 = require_main();
var MessageDirection;
(function(MessageDirection2) {
MessageDirection2["clientToServer"] = "clientToServer";
MessageDirection2["serverToClient"] = "serverToClient";
MessageDirection2["both"] = "both";
})(MessageDirection || (exports2.MessageDirection = MessageDirection = {}));
var RegistrationType = class {
static {
__name(this, "RegistrationType");
}
static {
__name2(this, "RegistrationType");
}
constructor(method) {
this.method = method;
}
};
exports2.RegistrationType = RegistrationType;
var ProtocolRequestType0 = class extends vscode_jsonrpc_1.RequestType0 {
static {
__name(this, "ProtocolRequestType0");
}
static {
__name2(this, "ProtocolRequestType0");
}
constructor(method) {
super(method);
}
};
exports2.ProtocolRequestType0 = ProtocolRequestType0;
var ProtocolRequestType = class extends vscode_jsonrpc_1.RequestType {
static {
__name(this, "ProtocolRequestType");
}
static {
__name2(this, "ProtocolRequestType");
}
constructor(method) {
super(method, vscode_jsonrpc_1.ParameterStructures.byName);
}
};
exports2.ProtocolRequestType = ProtocolRequestType;
var ProtocolNotificationType0 = class extends vscode_jsonrpc_1.NotificationType0 {
static {
__name(this, "ProtocolNotificationType0");
}
static {
__name2(this, "ProtocolNotificationType0");
}
constructor(method) {
super(method);
}
};
exports2.ProtocolNotificationType0 = ProtocolNotificationType0;
var ProtocolNotificationType = class extends vscode_jsonrpc_1.NotificationType {
static {
__name(this, "ProtocolNotificationType");
}
static {
__name2(this, "ProtocolNotificationType");
}
constructor(method) {
super(method, vscode_jsonrpc_1.ParameterStructures.byName);
}
};
exports2.ProtocolNotificationType = ProtocolNotificationType;
}
});
var require_is2 = __commonJS({
"../../node_modules/.pnpm/vscode-languageserver-protocol@3.17.5/node_modules/vscode-languageserver-protocol/lib/common/utils/is.js"(exports2) {
"use strict";
Object.defineProperty(exports2, "__esModule", { value: true });
exports2.objectLiteral = exports2.typedArray = exports2.stringArray = exports2.array = exports2.func = exports2.error = exports2.number = exports2.string = exports2.boolean = void 0;
function boolean(value) {
return value === true || value === false;
}
__name(boolean, "boolean");
__name2(boolean, "boolean");
exports2.boolean = boolean;
function string(value) {
return typeof value === "string" || value instanceof String;
}
__name(string, "string");
__name2(string, "string");
exports2.string = string;
function number(value) {
return typeof value === "number" || value instanceof Number;
}
__name(number, "number");
__name2(number, "number");
exports2.number = number;
function error(value) {
return value instanceof Error;
}
__name(error, "error");
__name2(error, "error");
exports2.error = error;
function func(value) {
return typeof value === "function";
}
__name(func, "func");
__name2(func, "func");
exports2.func = func;
function array(value) {
return Array.isArray(value);
}
__name(array, "array");
__name2(array, "array");
exports2.array = array;
function stringArray(value) {
return array(value) && value.every((elem) => string(elem));
}
__name(stringArray, "stringArray");
__name2(stringArray, "stringArray");
exports2.stringArray = stringArray;
function typedArray(value, check) {
return Array.isArray(value) && value.every(check);
}
__name(typedArray, "typedArray");
__name2(typedArray, "typedArray");
exports2.typedArray = typedArray;
function objectLiteral(value) {
return value !== null && typeof value === "object";
}
__name(objectLiteral, "objectLiteral");
__name2(objectLiteral, "objectLiteral");
exports2.objectLiteral = objectLiteral;
}
});
var require_protocol_implementation = __commonJS({
"../../node_modules/.pnpm/vscode-languageserver-protocol@3.17.5/node_modules/vscode-languageserver-protocol/lib/common/protocol.implementation.js"(exports2) {
"use strict";
Object.defineProperty(exports2, "__esModule", { value: true });
exports2.ImplementationRequest = void 0;
var messages_1 = require_messages2();
var ImplementationRequest;
(function(ImplementationRequest2) {
ImplementationRequest2.method = "textDocument/implementation";
ImplementationRequest2.messageDirection = messages_1.MessageDirection.clientToServer;
ImplementationRequest2.type = new messages_1.ProtocolRequestType(ImplementationRequest2.method);
})(ImplementationRequest || (exports2.ImplementationRequest = ImplementationRequest = {}));
}
});
var require_protocol_typeDefinition = __commonJS({
"../../node_modules/.pnpm/vscode-languageserver-protocol@3.17.5/node_modules/vscode-languageserver-protocol/lib/common/protocol.typeDefinition.js"(exports2) {
"use strict";
Object.defineProperty(exports2, "__esModule", { value: true });
exports2.TypeDefinitionRequest = void 0;
var messages_1 = require_messages2();
var TypeDefinitionRequest;
(function(TypeDefinitionRequest2) {
TypeDefinitionRequest2.method = "textDocument/typeDefinition";
TypeDefinitionRequest2.messageDirection = messages_1.MessageDirection.clientToServer;
TypeDefinitionRequest2.type = new messages_1.ProtocolRequestType(TypeDefinitionRequest2.method);
})(TypeDefinitionRequest || (exports2.TypeDefinitionRequest = TypeDefinitionRequest = {}));
}
});
var require_protocol_workspaceFolder = __commonJS({
"../../node_modules/.pnpm/vscode-languageserver-protocol@3.17.5/node_modules/vscode-languageserver-protocol/lib/common/protocol.workspaceFolder.js"(exports2) {
"use strict";
Object.defineProperty(exports2, "__esModule", { value: true });
exports2.DidChangeWorkspaceFoldersNotification = exports2.WorkspaceFoldersRequest = void 0;
var messages_1 = require_messages2();
var WorkspaceFoldersRequest;
(function(WorkspaceFoldersRequest2) {
WorkspaceFoldersRequest2.method = "workspace/workspaceFolders";
WorkspaceFoldersRequest2.messageDirection = messages_1.MessageDirection.serverToClient;
WorkspaceFoldersRequest2.type = new messages_1.ProtocolRequestType0(WorkspaceFoldersRequest2.method);
})(WorkspaceFoldersRequest || (exports2.WorkspaceFoldersRequest = WorkspaceFoldersRequest = {}));
var DidChangeWorkspaceFoldersNotification;
(function(DidChangeWorkspaceFoldersNotification2) {
DidChangeWorkspaceFoldersNotification2.method = "workspace/didChangeWorkspaceFolders";
DidChangeWorkspaceFoldersNotification2.messageDirection = messages_1.MessageDirection.clientToServer;
DidChangeWorkspaceFoldersNotification2.type = new messages_1.ProtocolNotificationType(DidChangeWorkspaceFoldersNotification2.method);
})(DidChangeWorkspaceFoldersNotification || (exports2.DidChangeWorkspaceFoldersNotification = DidChangeWorkspaceFoldersNotification = {}));
}
});
var require_protocol_configuration = __commonJS({
"../../node_modules/.pnpm/vscode-languageserver-protocol@3.17.5/node_modules/vscode-languageserver-protocol/lib/common/protocol.configuration.js"(exports2) {
"use strict";
Object.defineProperty(exports2, "__esModule", { value: true });
exports2.ConfigurationRequest = void 0;
var messages_1 = require_messages2();
var ConfigurationRequest;
(function(ConfigurationRequest2) {
ConfigurationRequest2.method = "workspace/configuration";
ConfigurationRequest2.messageDirection = messages_1.MessageDirection.serverToClient;
ConfigurationRequest2.type = new messages_1.ProtocolRequestType(ConfigurationRequest2.method);
})(ConfigurationRequest || (exports2.ConfigurationRequest = ConfigurationRequest = {}));
}
});
var require_protocol_colorProvider = __commonJS({
"../../node_modules/.pnpm/vscode-languageserver-protocol@3.17.5/node_modules/vscode-languageserver-protocol/lib/common/protocol.colorProvider.js"(exports2) {
"use strict";
Object.defineProperty(exports2, "__esModule", { value: true });
exports2.ColorPresentationRequest = exports2.DocumentColorRequest = void 0;
var messages_1 = require_messages2();
var DocumentColorRequest;
(function(DocumentColorRequest2) {
DocumentColorRequest2.method = "textDocument/documentColor";
DocumentColorRequest2.messageDirection = messages_1.MessageDirection.clientToServer;
DocumentColorRequest2.type = new messages_1.ProtocolRequestType(DocumentColorRequest2.method);
})(DocumentColorRequest || (exports2.DocumentColorRequest = DocumentColorRequest = {}));
var ColorPresentationRequest;
(function(ColorPresentationRequest2) {
ColorPresentationRequest2.method = "textDocument/colorPresentation";
ColorPresentationRequest2.messageDirection = messages_1.MessageDirection.clientToServer;
ColorPresentationRequest2.type = new messages_1.ProtocolRequestType(ColorPresentationRequest2.method);
})(ColorPresentationRequest || (exports2.ColorPresentationRequest = ColorPresentationRequest = {}));
}
});
var require_protocol_foldingRange = __commonJS({
"../../node_modules/.pnpm/vscode-languageserver-protocol@3.17.5/node_modules/vscode-languageserver-protocol/lib/common/protocol.foldingRange.js"(exports2) {
"use strict";
Object.defineProperty(exports2, "__esModule", { value: true });
exports2.FoldingRangeRefreshRequest = exports2.FoldingRangeRequest = void 0;
var messages_1 = require_messages2();
var FoldingRangeRequest;
(function(FoldingRangeRequest2) {
FoldingRangeRequest2.method = "textDocument/foldingRange";
FoldingRangeRequest2.messageDirection = messages_1.MessageDirection.clientToServer;
FoldingRangeRequest2.type = new messages_1.ProtocolRequestType(FoldingRangeRequest2.method);
})(FoldingRangeRequest || (exports2.FoldingRangeRequest = FoldingRangeRequest = {}));
var FoldingRangeRefreshRequest;
(function(FoldingRangeRefreshRequest2) {
FoldingRangeRefreshRequest2.method = `workspace/foldingRange/refresh`;
FoldingRangeRefreshRequest2.messageDirection = messages_1.MessageDirection.serverToClient;
FoldingRangeRefreshRequest2.type = new messages_1.ProtocolRequestType0(FoldingRangeRefreshRequest2.method);
})(FoldingRangeRefreshRequest || (exports2.FoldingRangeRefreshRequest = FoldingRangeRefreshRequest = {}));
}
});
var require_protocol_declaration = __commonJS({
"../../node_modules/.pnpm/vscode-languageserver-protocol@3.17.5/node_modules/vscode-languageserver-protocol/lib/common/protocol.declaration.js"(exports2) {
"use strict";
Object.defineProperty(exports2, "__esModule", { value: true });
exports2.DeclarationRequest = void 0;
var messages_1 = require_messages2();
var DeclarationRequest;
(function(DeclarationRequest2) {
DeclarationRequest2.method = "textDocument/declaration";
DeclarationRequest2.messageDirection = messages_1.MessageDirection.clientToServer;
DeclarationRequest2.type = new messages_1.ProtocolRequestType(DeclarationRequest2.method);
})(DeclarationRequest || (exports2.DeclarationRequest = DeclarationRequest = {}));
}
});
var require_protocol_selectionRange = __commonJS({
"../../node_modules/.pnpm/vscode-languageserver-protocol@3.17.5/node_modules/vscode-languageserver-protocol/lib/common/protocol.selectionRange.js"(exports2) {
"use strict";
Object.defineProperty(exports2, "__esModule", { value: true });
exports2.SelectionRangeRequest = void 0;
var messages_1 = require_messages2();
var SelectionRangeRequest;
(function(SelectionRangeRequest2) {
SelectionRangeRequest2.method = "textDocument/selectionRange";
SelectionRangeRequest2.messageDirection = messages_1.MessageDirection.clientToServer;
SelectionRangeRequest2.type = new messages_1.ProtocolRequestType(SelectionRangeRequest2.method);
})(SelectionRangeRequest || (exports2.SelectionRangeRequest = SelectionRangeRequest = {}));
}
});
var require_protocol_progress = __commonJS({
"../../node_modules/.pnpm/vscode-languageserver-protocol@3.17.5/node_modules/vscode-languageserver-protocol/lib/common/protocol.progress.js"(exports2) {
"use strict";
Object.defineProperty(exports2, "__esModule", { value: true });
exports2.WorkDoneProgressCancelNotification = exports2.WorkDoneProgressCreateRequest = exports2.WorkDoneProgress = void 0;
var vscode_jsonrpc_1 = require_main();
var messages_1 = require_messages2();
var WorkDoneProgress;
(function(WorkDoneProgress2) {
WorkDoneProgress2.type = new vscode_jsonrpc_1.ProgressType();
function is(value) {
return value === WorkDoneProgress2.type;
}
__name(is, "is");
__name2(is, "is");
WorkDoneProgress2.is = is;
})(WorkDoneProgress || (exports2.WorkDoneProgress = WorkDoneProgress = {}));
var WorkDoneProgressCreateRequest;
(function(WorkDoneProgressCreateRequest2) {
WorkDoneProgressCreateRequest2.method = "window/workDoneProgress/create";
WorkDoneProgressCreateRequest2.messageDirection = messages_1.MessageDirection.serverToClient;
WorkDoneProgressCreateRequest2.type = new messages_1.ProtocolRequestType(WorkDoneProgressCreateRequest2.method);
})(WorkDoneProgressCreateRequest || (exports2.WorkDoneProgressCreateRequest = WorkDoneProgressCreateRequest = {}));
var WorkDoneProgressCancelNotification;
(function(WorkDoneProgressCancelNotification2) {
WorkDoneProgressCancelNotification2.method = "window/workDoneProgress/cancel";
WorkDoneProgressCancelNotification2.messageDirection = messages_1.MessageDirection.clientToServer;
WorkDoneProgressCancelNotification2.type = new messages_1.ProtocolNotificationType(WorkDoneProgressCancelNotification2.method);
})(WorkDoneProgressCancelNotification || (exports2.WorkDoneProgressCancelNotification = WorkDoneProgressCancelNotification = {}));
}
});
var require_protocol_callHierarchy = __commonJS({
"../../node_modules/.pnpm/vscode-languageserver-protocol@3.17.5/node_modules/vscode-languageserver-protocol/lib/common/protocol.callHierarchy.js"(exports2) {
"use strict";
Object.defineProperty(exports2, "__esModule", { value: true });
exports2.CallHierarchyOutgoingCallsRequest = exports2.CallHierarchyIncomingCallsRequest = exports2.CallHierarchyPrepareRequest = void 0;
var messages_1 = require_messages2();
var CallHierarchyPrepareRequest;
(function(CallHierarchyPrepareRequest2) {
CallHierarchyPrepareRequest2.method = "textDocument/prepareCallHierarchy";
CallHierarchyPrepareRequest2.messageDirection = messages_1.MessageDirection.clientToServer;
CallHierarchyPrepareRequest2.type = new messages_1.ProtocolRequestType(CallHierarchyPrepareRequest2.method);
})(CallHierarchyPrepareRequest || (exports2.CallHierarchyPrepareRequest = CallHierarchyPrepareRequest = {}));
var CallHierarchyIncomingCallsRequest;
(function(CallHierarchyIncomingCallsRequest2) {
CallHierarchyIncomingCallsRequest2.method = "callHierarchy/incomingCalls";
CallHierarchyIncomingCallsRequest2.messageDirection = messages_1.MessageDirection.clientToServer;
CallHierarchyIncomingCallsRequest2.type = new messages_1.ProtocolRequestType(CallHierarchyIncomingCallsRequest2.method);
})(CallHierarchyIncomingCallsRequest || (exports2.CallHierarchyIncomingCallsRequest = CallHierarchyIncomingCallsRequest = {}));
var CallHierarchyOutgoingCallsRequest;
(function(CallHierarchyOutgoingCallsRequest2) {
CallHierarchyOutgoingCallsRequest2.method = "callHierarchy/outgoingCalls";
CallHierarchyOutgoingCallsRequest2.messageDirection = messages_1.MessageDirection.clientToServer;
CallHierarchyOutgoingCallsRequest2.type = new messages_1.ProtocolRequestType(CallHierarchyOutgoingCallsRequest2.method);
})(CallHierarchyOutgoingCallsRequest || (exports2.CallHierarchyOutgoingCallsRequest = CallHierarchyOutgoingCallsRequest = {}));
}
});
var require_protocol_semanticTokens = __commonJS({
"../../node_modules/.pnpm/vscode-languageserver-protocol@3.17.5/node_modules/vscode-languageserver-protocol/lib/common/protocol.semanticTokens.js"(exports2) {
"use strict";
Object.defineProperty(exports2, "__esModule", { value: true });
exports2.SemanticTokensRefreshRequest = exports2.SemanticTokensRangeRequest = exports2.SemanticTokensDeltaRequest = exports2.SemanticTokensRequest = exports2.SemanticTokensRegistrationType = exports2.TokenFormat = void 0;
var messages_1 = require_messages2();
var TokenFormat;
(function(TokenFormat2) {
TokenFormat2.Relative = "relative";
})(TokenFormat || (exports2.TokenFormat = TokenFormat = {}));
var SemanticTokensRegistrationType;
(function(SemanticTokensRegistrationType2) {
SemanticTokensRegistrationType2.method = "textDocument/semanticTokens";
SemanticTokensRegistrationType2.type = new messages_1.RegistrationType(SemanticTokensRegistrationType2.method);
})(SemanticTokensRegistrationType || (exports2.SemanticTokensRegistrationType = SemanticTokensRegistrationType = {}));
var SemanticTokensRequest;
(function(SemanticTokensRequest2) {
SemanticTokensRequest2.method = "textDocument/semanticTokens/full";
SemanticTokensRequest2.messageDirection = messages_1.MessageDirection.clientToServer;
SemanticTokensRequest2.type = new messages_1.ProtocolRequestType(SemanticTokensRequest2.method);
SemanticTokensRequest2.registrationMethod = SemanticTokensRegistrationType.method;
})(SemanticTokensRequest || (exports2.SemanticTokensRequest = SemanticTokensRequest = {}));
var SemanticTokensDeltaRequest;
(function(SemanticTokensDeltaRequest2) {
SemanticTokensDeltaRequest2.method = "textDocument/semanticTokens/full/delta";
SemanticTokensDeltaRequest2.messageDirection = messages_1.MessageDirection.clientToServer;
SemanticTokensDeltaRequest2.type = new messages_1.ProtocolRequestType(SemanticTokensDeltaRequest2.method);
SemanticTokensDeltaRequest2.registrationMethod = SemanticTokensRegistrationType.method;
})(SemanticTokensDeltaRequest || (exports2.SemanticTokensDeltaRequest = SemanticTokensDeltaRequest = {}));
var SemanticTokensRangeRequest;
(function(SemanticTokensRangeRequest2) {
SemanticTokensRangeRequest2.method = "textDocument/semanticTokens/range";
SemanticTokensRangeRequest2.messageDirection = messages_1.MessageDirection.clientToServer;
SemanticTokensRangeRequest2.type = new messages_1.ProtocolRequestType(SemanticTokensRangeRequest2.method);
SemanticTokensRangeRequest2.registrationMethod = SemanticTokensRegistrationType.method;
})(SemanticTokensRangeRequest || (exports2.SemanticTokensRangeRequest = SemanticTokensRangeRequest = {}));
var SemanticTokensRefreshRequest;
(function(SemanticTokensRefreshRequest2) {
SemanticTokensRefreshRequest2.method = `workspace/semanticTokens/refresh`;
SemanticTokensRefreshRequest2.messageDirection = messages_1.MessageDirection.serverToClient;
SemanticTokensRefreshRequest2.type = new messages_1.ProtocolRequestType0(SemanticTokensRefreshRequest2.method);
})(SemanticTokensRefreshRequest || (exports2.SemanticTokensRefreshRequest = SemanticTokensRefreshRequest = {}));
}
});
var require_protocol_showDocument = __commonJS({
"../../node_modules/.pnpm/vscode-languageserver-protocol@3.17.5/node_modules/vscode-languageserver-protocol/lib/common/protocol.showDocument.js"(exports2) {
"use strict";
Object.defineProperty(exports2, "__esModule", { value: true });
exports2.ShowDocumentRequest = void 0;
var messages_1 = require_messages2();
var ShowDocumentRequest;
(function(ShowDocumentRequest2) {
ShowDocumentRequest2.method = "window/showDocument";
ShowDocumentRequest2.messageDirection = messages_1.MessageDirection.serverToClient;
ShowDocumentRequest2.type = new messages_1.ProtocolRequestType(ShowDocumentRequest2.method);
})(ShowDocumentRequest || (exports2.ShowDocumentRequest = ShowDocumentRequest = {}));
}
});
var require_protocol_linkedEditingRange = __commonJS({
"../../node_modules/.pnpm/vscode-languageserver-protocol@3.17.5/node_modules/vscode-languageserver-protocol/lib/common/protocol.linkedEditingRange.js"(exports2) {
"use strict";
Object.defineProperty(exports2, "__esModule", { value: true });
exports2.LinkedEditingRangeRequest = void 0;
var messages_1 = require_messages2();
var LinkedEditingRangeRequest;
(function(LinkedEditingRangeRequest2) {
LinkedEditingRangeRequest2.method = "textDocument/linkedEditingRange";
LinkedEditingRangeRequest2.messageDirection = messages_1.MessageDirection.clientToServer;
LinkedEditingRangeRequest2.type = new messages_1.ProtocolRequestType(LinkedEditingRangeRequest2.method);
})(LinkedEditingRangeRequest || (exports2.LinkedEditingRangeRequest = LinkedEditingRangeRequest = {}));
}
});
var require_protocol_fileOperations = __commonJS({
"../../node_modules/.pnpm/vscode-languageserver-protocol@3.17.5/node_modules/vscode-languageserver-protocol/lib/common/protocol.fileOperations.js"(exports2) {
"use strict";
Object.defineProperty(exports2, "__esModule", { value: true });
exports2.WillDeleteFilesRequest = exports2.DidDeleteFilesNotification = exports2.DidRenameFilesNotification = exports2.WillRenameFilesRequest = exports2.DidCreateFilesNotification = exports2.WillCreateFilesRequest = exports2.FileOperationPatternKind = void 0;
var messages_1 = require_messages2();
var FileOperationPatternKind;
(function(FileOperationPatternKind2) {
FileOperationPatternKind2.file = "file";
FileOperationPatternKind2.folder = "folder";
})(FileOperationPatternKind || (exports2.FileOperationPatternKind = FileOperationPatternKind = {}));
var WillCreateFilesRequest;
(function(WillCreateFilesRequest2) {
WillCreateFilesRequest2.method = "workspace/willCreateFiles";
WillCreateFilesRequest2.messageDirection = messages_1.MessageDirection.clientToServer;
WillCreateFilesRequest2.type = new messages_1.ProtocolRequestType(WillCreateFilesRequest2.method);
})(WillCreateFilesRequest || (exports2.WillCreateFilesRequest = WillCreateFilesRequest = {}));
var DidCreateFilesNotification;
(function(DidCreateFilesNotification2) {
DidCreateFilesNotification2.method = "workspace/didCreateFiles";
DidCreateFilesNotification2.messageDirection = messages_1.MessageDirection.clientToServer;
DidCreateFilesNotification2.type = new messages_1.ProtocolNotificationType(DidCreateFilesNotification2.method);
})(DidCreateFilesNotification || (exports2.DidCreateFilesNotification = DidCreateFilesNotification = {}));
var WillRenameFilesRequest;
(function(WillRenameFilesRequest2) {
WillRenameFilesRequest2.method = "workspace/willRenameFiles";
WillRenameFilesRequest2.messageDirection = messages_1.MessageDirection.clientToServer;
WillRenameFilesRequest2.type = new messages_1.ProtocolRequestType(WillRenameFilesRequest2.method);
})(WillRenameFilesRequest || (exports2.WillRenameFilesRequest = WillRenameFilesRequest = {}));
var DidRenameFilesNotification;
(function(DidRenameFilesNotification2) {
DidRenameFilesNotification2.method = "workspace/didRenameFiles";
DidRenameFilesNotification2.messageDirection = messages_1.MessageDirection.clientToServer;
DidRenameFilesNotification2.type = new messages_1.ProtocolNotificationType(DidRenameFilesNotification2.method);
})(DidRenameFilesNotification || (exports2.DidRenameFilesNotification = DidRenameFilesNotification = {}));
var DidDeleteFilesNotification;
(function(DidDeleteFilesNotification2) {
DidDeleteFilesNotification2.method = "workspace/didDeleteFiles";
DidDeleteFilesNotification2.messageDirection = messages_1.MessageDirection.clientToServer;
DidDeleteFilesNotification2.type = new messages_1.ProtocolNotificationType(DidDeleteFilesNotification2.method);
})(DidDeleteFilesNotification || (exports2.DidDeleteFilesNotification = DidDeleteFilesNotification = {}));
var WillDeleteFilesRequest;
(function(WillDeleteFilesRequest2) {
WillDeleteFilesRequest2.method = "workspace/willDeleteFiles";
WillDeleteFilesRequest2.messageDirection = messages_1.MessageDirection.clientToServer;
WillDeleteFilesRequest2.type = new messages_1.ProtocolRequestType(WillDeleteFilesRequest2.method);
})(WillDeleteFilesRequest || (exports2.WillDeleteFilesRequest = WillDeleteFilesRequest = {}));
}
});
var require_protocol_moniker = __commonJS({
"../../node_modules/.pnpm/vscode-languageserver-protocol@3.17.5/node_modules/vscode-languageserver-protocol/lib/common/protocol.moniker.js"(exports2) {
"use strict";
Object.defineProperty(exports2, "__esModule", { value: true });
exports2.MonikerRequest = exports2.MonikerKind = exports2.UniquenessLevel = void 0;
var messages_1 = require_messages2();
var UniquenessLevel;
(function(UniquenessLevel2) {
UniquenessLevel2.document = "document";
UniquenessLevel2.project = "project";
UniquenessLevel2.group = "group";
UniquenessLevel2.scheme = "scheme";
UniquenessLevel2.global = "global";
})(UniquenessLevel || (exports2.UniquenessLevel = UniquenessLevel = {}));
var MonikerKind;
(function(MonikerKind2) {
MonikerKind2.$import = "import";
MonikerKind2.$export = "export";
MonikerKind2.local = "local";
})(MonikerKind || (exports2.MonikerKind = MonikerKind = {}));
var MonikerRequest;
(function(MonikerRequest2) {
MonikerRequest2.method = "textDocument/moniker";
MonikerRequest2.messageDirection = messages_1.MessageDirection.clientToServer;
MonikerRequest2.type = new messages_1.ProtocolRequestType(MonikerRequest2.method);
})(MonikerRequest || (exports2.MonikerRequest = MonikerRequest = {}));
}
});
var require_protocol_typeHierarchy = __commonJS({
"../../node_modules/.pnpm/vscode-languageserver-protocol@3.17.5/node_modules/vscode-languageserver-protocol/lib/common/protocol.typeHierarchy.js"(exports2) {
"use strict";
Object.defineProperty(exports2, "__esModule", { value: true });
exports2.TypeHierarchySubtypesRequest = exports2.TypeHierarchySupertypesRequest = exports2.TypeHierarchyPrepareRequest = void 0;
var messages_1 = require_messages2();
var TypeHierarchyPrepareRequest;
(function(TypeHierarchyPrepareRequest2) {
TypeHierarchyPrepareRequest2.method = "textDocument/prepareTypeHierarchy";
TypeHierarchyPrepareRequest2.messageDirection = messages_1.MessageDirection.clientToServer;
TypeHierarchyPrepareRequest2.type = new messages_1.ProtocolRequestType(TypeHierarchyPrepareRequest2.method);
})(TypeHierarchyPrepareRequest || (exports2.TypeHierarchyPrepareRequest = TypeHierarchyPrepareRequest = {}));
var TypeHierarchySupertypesRequest;
(function(TypeHierarchySupertypesRequest2) {
TypeHierarchySupertypesRequest2.method = "typeHierarchy/supertypes";
TypeHierarchySupertypesRequest2.messageDirection = messages_1.MessageDirection.clientToServer;
TypeHierarchySupertypesRequest2.type = new messages_1.ProtocolRequestType(TypeHierarchySupertypesRequest2.method);
})(TypeHierarchySupertypesRequest || (exports2.TypeHierarchySupertypesRequest = TypeHierarchySupertypesRequest = {}));
var TypeHierarchySubtypesRequest;
(function(TypeHierarchySubtypesRequest2) {
TypeHierarchySubtypesRequest2.method = "typeHierarchy/subtypes";
TypeHierarchySubtypesRequest2.messageDirection = messages_1.MessageDirection.clientToServer;
TypeHierarchySubtypesRequest2.type = new messages_1.ProtocolRequestType(TypeHierarchySubtypesRequest2.method);
})(TypeHierarchySubtypesRequest || (exports2.TypeHierarchySubtypesRequest = TypeHierarchySubtypesRequest = {}));
}
});
var require_protocol_inlineValue = __commonJS({
"../../node_modules/.pnpm/vscode-languageserver-protocol@3.17.5/node_modules/vscode-languageserver-protocol/lib/common/protocol.inlineValue.js"(exports2) {
"use strict";
Object.defineProperty(exports2, "__esModule", { value: true });
exports2.InlineValueRefreshRequest = exports2.InlineValueRequest = void 0;
var messages_1 = require_messages2();
var InlineValueRequest;
(function(InlineValueRequest2) {
InlineValueRequest2.method = "textDocument/inlineValue";
InlineValueRequest2.messageDirection = messages_1.MessageDirection.clientToServer;
InlineValueRequest2.type = new messages_1.ProtocolRequestType(InlineValueRequest2.method);
})(InlineValueRequest || (exports2.InlineValueRequest = InlineValueRequest = {}));
var InlineValueRefreshRequest;
(function(InlineValueRefreshRequest2) {
InlineValueRefreshRequest2.method = `workspace/inlineValue/refresh`;
InlineValueRefreshRequest2.messageDirection = messages_1.MessageDirection.serverToClient;
InlineValueRefreshRequest2.type = new messages_1.ProtocolRequestType0(InlineValueRefreshRequest2.method);
})(InlineValueRefreshRequest || (exports2.InlineValueRefreshRequest = InlineValueRefreshRequest = {}));
}
});
var require_protocol_inlayHint = __commonJS({
"../../node_modules/.pnpm/vscode-languageserver-protocol@3.17.5/node_modules/vscode-languageserver-protocol/lib/common/protocol.inlayHint.js"(exports2) {
"use strict";
Object.defineProperty(exports2, "__esModule", { value: true });
exports2.InlayHintRefreshRequest = exports2.InlayHintResolveRequest = exports2.InlayHintRequest = void 0;
var messages_1 = require_messages2();
var InlayHintRequest;
(function(InlayHintRequest2) {
InlayHintRequest2.method = "textDocument/inlayHint";
InlayHintRequest2.messageDirection = messages_1.MessageDirection.clientToServer;
InlayHintRequest2.type = new messages_1.ProtocolRequestType(InlayHintRequest2.method);
})(InlayHintRequest || (exports2.InlayHintRequest = InlayHintRequest = {}));
var InlayHintResolveRequest;
(function(InlayHintResolveRequest2) {
InlayHintResolveRequest2.method = "inlayHint/resolve";
InlayHintResolveRequest2.messageDirection = messages_1.MessageDirection.clientToServer;
InlayHintResolveRequest2.type = new messages_1.ProtocolRequestType(InlayHintResolveRequest2.method);
})(InlayHintResolveRequest || (exports2.InlayHintResolveRequest = InlayHintResolveRequest = {}));
var InlayHintRefreshRequest;
(function(InlayHintRefreshRequest2) {
InlayHintRefreshRequest2.method = `workspace/inlayHint/refresh`;
InlayHintRefreshRequest2.messageDirection = messages_1.MessageDirection.serverToClient;
InlayHintRefreshRequest2.type = new messages_1.ProtocolRequestType0(InlayHintRefreshRequest2.method);
})(InlayHintRefreshRequest || (exports2.InlayHintRefreshRequest = InlayHintRefreshRequest = {}));
}
});
var require_protocol_diagnostic = __commonJS({
"../../node_modules/.pnpm/vscode-languageserver-protocol@3.17.5/node_modules/vscode-languageserver-protocol/lib/common/protocol.diagnostic.js"(exports2) {
"use strict";
Object.defineProperty(exports2, "__esModule", { value: true });
exports2.DiagnosticRefreshRequest = exports2.WorkspaceDiagnosticRequest = exports2.DocumentDiagnosticRequest = exports2.DocumentDiagnosticReportKind = exports2.DiagnosticServerCancellationData = void 0;
var vscode_jsonrpc_1 = require_main();
var Is2 = require_is2();
var messages_1 = require_messages2();
var DiagnosticServerCancellationData;
(function(DiagnosticServerCancellationData2) {
function is(value) {
const candidate = value;
return candidate && Is2.boolean(candidate.retriggerRequest);
}
__name(is, "is");
__name2(is, "is");
DiagnosticServerCancellationData2.is = is;
})(DiagnosticServerCancellationData || (exports2.DiagnosticServerCancellationData = DiagnosticServerCancellationData = {}));
var DocumentDiagnosticReportKind;
(function(DocumentDiagnosticReportKind2) {
DocumentDiagnosticReportKind2.Full = "full";
DocumentDiagnosticReportKind2.Unchanged = "unchanged";
})(DocumentDiagnosticReportKind || (exports2.DocumentDiagnosticReportKind = DocumentDiagnosticReportKind = {}));
var DocumentDiagnosticRequest;
(function(DocumentDiagnosticRequest2) {
DocumentDiagnosticRequest2.method = "textDocument/diagnostic";
DocumentDiagnosticRequest2.messageDirection = messages_1.MessageDirection.clientToServer;
DocumentDiagnosticRequest2.type = new messages_1.ProtocolRequestType(DocumentDiagnosticRequest2.method);
DocumentDiagnosticRequest2.partialResult = new vscode_jsonrpc_1.ProgressType();
})(DocumentDiagnosticRequest || (exports2.DocumentDiagnosticRequest = DocumentDiagnosticRequest = {}));
var WorkspaceDiagnosticRequest;
(function(WorkspaceDiagnosticRequest2) {
WorkspaceDiagnosticRequest2.method = "workspace/diagnostic";
WorkspaceDiagnosticRequest2.messageDirection = messages_1.MessageDirection.clientToServer;
WorkspaceDiagnosticRequest2.type = new messages_1.ProtocolRequestType(WorkspaceDiagnosticRequest2.method);
WorkspaceDiagnosticRequest2.partialResult = new vscode_jsonrpc_1.ProgressType();
})(WorkspaceDiagnosticRequest || (exports2.WorkspaceDiagnosticRequest = WorkspaceDiagnosticRequest = {}));
var DiagnosticRefreshRequest;
(function(DiagnosticRefreshRequest2) {
DiagnosticRefreshRequest2.method = `workspace/diagnostic/refresh`;
DiagnosticRefreshRequest2.messageDirection = messages_1.MessageDirection.serverToClient;
DiagnosticRefreshRequest2.type = new messages_1.ProtocolRequestType0(DiagnosticRefreshRequest2.method);
})(DiagnosticRefreshRequest || (exports2.DiagnosticRefreshRequest = DiagnosticRefreshRequest = {}));
}
});
var require_protocol_notebook = __commonJS({
"../../node_modules/.pnpm/vscode-languageserver-protocol@3.17.5/node_modules/vscode-languageserver-protocol/lib/common/protocol.notebook.js"(exports2) {
"use strict";
Object.defineProperty(exports2, "__esModule", { value: true });
exports2.DidCloseNotebookDocumentNotification = exports2.DidSaveNotebookDocumentNotification = exports2.DidChangeNotebookDocumentNotification = exports2.NotebookCellArrayChange = exports2.DidOpenNotebookDocumentNotification = exports2.NotebookDocumentSyncRegistrationType = exports2.NotebookDocument = exports2.NotebookCell = exports2.ExecutionSummary = exports2.NotebookCellKind = void 0;
var vscode_languageserver_types_1 = (init_main(), __toCommonJS(main_exports));
var Is2 = require_is2();
var messages_1 = require_messages2();
var NotebookCellKind;
(function(NotebookCellKind2) {
NotebookCellKind2.Markup = 1;
NotebookCellKind2.Code = 2;
function is(value) {
return value === 1 || value === 2;
}
__name(is, "is");
__name2(is, "is");
NotebookCellKind2.is = is;
})(NotebookCellKind || (exports2.NotebookCellKind = NotebookCellKind = {}));
var ExecutionSummary;
(function(ExecutionSummary2) {
function create(executionOrder, success) {
const result = { executionOrder };
if (success === true || success === false) {
result.success = success;
}
return result;
}
__name(create, "create");
__name2(create, "create");
ExecutionSummary2.create = create;
function is(value) {
const candidate = value;
return Is2.objectLiteral(candidate) && vscode_languageserver_types_1.uinteger.is(candidate.executionOrder) && (candidate.success === void 0 || Is2.boolean(candidate.success));
}
__name(is, "is");
__name2(is, "is");
ExecutionSummary2.is = is;
function equals(one, other) {
if (one === other) {
return true;
}
if (one === null || one === void 0 || other === null || other === void 0) {
return false;
}
return one.executionOrder === other.executionOrder && one.success === other.success;
}
__name(equals, "equals");
__name2(equals, "equals");
ExecutionSummary2.equals = equals;
})(ExecutionSummary || (exports2.ExecutionSummary = ExecutionSummary = {}));
var NotebookCell;
(function(NotebookCell2) {
function create(kind, document) {
return { kind, document };
}
__name(create, "create");
__name2(create, "create");
NotebookCell2.create = create;
function is(value) {
const candidate = value;
return Is2.objectLiteral(candidate) && NotebookCellKind.is(candidate.kind) && vscode_languageserver_types_1.DocumentUri.is(candidate.document) && (candidate.metadata === void 0 || Is2.objectLiteral(candidate.metadata));
}
__name(is, "is");
__name2(is, "is");
NotebookCell2.is = is;
function diff(one, two) {
const result = /* @__PURE__ */ new Set();
if (one.document !== two.document) {
result.add("document");
}
if (one.kind !== two.kind) {
result.add("kind");
}
if (one.executionSummary !== two.executionSummary) {
result.add("executionSummary");
}
if ((one.metadata !== void 0 || two.metadata !== void 0) && !equalsMetadata(one.metadata, two.metadata)) {
result.add("metadata");
}
if ((one.executionSummary !== void 0 || two.executionSummary !== void 0) && !ExecutionSummary.equals(one.executionSummary, two.executionSummary)) {
result.add("executionSummary");
}
return result;
}
__name(diff, "diff");
__name2(diff, "diff");
NotebookCell2.diff = diff;
function equalsMetadata(one, other) {
if (one === other) {
return true;
}
if (one === null || one === void 0 || other === null || other === void 0) {
return false;
}
if (typeof one !== typeof other) {
return false;
}
if (typeof one !== "object") {
return false;
}
const oneArray = Array.isArray(one);
const otherArray = Array.isArray(other);
if (oneArray !== otherArray) {
return false;
}
if (oneArray && otherArray) {
if (one.length !== other.length) {
return false;
}
for (let i = 0; i < one.length; i++) {
if (!equalsMetadata(one[i], other[i])) {
return false;
}
}
}
if (Is2.objectLiteral(one) && Is2.objectLiteral(other)) {
const oneKeys = Object.keys(one);
const otherKeys = Object.keys(other);
if (oneKeys.length !== otherKeys.length) {
return false;
}
oneKeys.sort();
otherKeys.sort();
if (!equalsMetadata(oneKeys, otherKeys)) {
return false;
}
for (let i = 0; i < oneKeys.length; i++) {
const prop = oneKeys[i];
if (!equalsMetadata(one[prop], other[prop])) {
return false;
}
}
}
return true;
}
__name(equalsMetadata, "equalsMetadata");
__name2(equalsMetadata, "equalsMetadata");
})(NotebookCell || (exports2.NotebookCell = NotebookCell = {}));
var NotebookDocument;
(function(NotebookDocument2) {
function create(uri, notebookType, version, cells) {
return { uri, notebookType, version, cells };
}
__name(create, "create");
__name2(create, "create");
NotebookDocument2.create = create;
function is(value) {
const candidate = value;
return Is2.objectLiteral(candidate) && Is2.string(candidate.uri) && vscode_languageserver_types_1.integer.is(candidate.version) && Is2.typedArray(candidate.cells, NotebookCell.is);
}
__name(is, "is");
__name2(is, "is");
NotebookDocument2.is = is;
})(NotebookDocument || (exports2.NotebookDocument = NotebookDocument = {}));
var NotebookDocumentSyncRegistrationType;
(function(NotebookDocumentSyncRegistrationType2) {
NotebookDocumentSyncRegistrationType2.method = "notebookDocument/sync";
NotebookDocumentSyncRegistrationType2.messageDirection = messages_1.MessageDirection.clientToServer;
NotebookDocumentSyncRegistrationType2.type = new messages_1.RegistrationType(NotebookDocumentSyncRegistrationType2.method);
})(NotebookDocumentSyncRegistrationType || (exports2.NotebookDocumentSyncRegistrationType = NotebookDocumentSyncRegistrationType = {}));
var DidOpenNotebookDocumentNotification;
(function(DidOpenNotebookDocumentNotification2) {
DidOpenNotebookDocumentNotification2.method = "notebookDocument/didOpen";
DidOpenNotebookDocumentNotification2.messageDirection = messages_1.MessageDirection.clientToServer;
DidOpenNotebookDocumentNotification2.type = new messages_1.ProtocolNotificationType(DidOpenNotebookDocumentNotification2.method);
DidOpenNotebookDocumentNotification2.registrationMethod = NotebookDocumentSyncRegistrationType.method;
})(DidOpenNotebookDocumentNotification || (exports2.DidOpenNotebookDocumentNotification = DidOpenNotebookDocumentNotification = {}));
var NotebookCellArrayChange;
(function(NotebookCellArrayChange2) {
function is(value) {
const candidate = value;
return Is2.objectLiteral(candidate) && vscode_languageserver_types_1.uinteger.is(candidate.start) && vscode_languageserver_types_1.uinteger.is(candidate.deleteCount) && (candidate.cells === void 0 || Is2.typedArray(candidate.cells, NotebookCell.is));
}
__name(is, "is");
__name2(is, "is");
NotebookCellArrayChange2.is = is;
function create(start, deleteCount, cells) {
const result = { start, deleteCount };
if (cells !== void 0) {
result.cells = cells;
}
return result;
}
__name(create, "create");
__name2(create, "create");
NotebookCellArrayChange2.create = create;
})(NotebookCellArrayChange || (exports2.NotebookCellArrayChange = NotebookCellArrayChange = {}));
var DidChangeNotebookDocumentNotification;
(function(DidChangeNotebookDocumentNotification2) {
DidChangeNotebookDocumentNotification2.method = "notebookDocument/didChange";
DidChangeNotebookDocumentNotification2.messageDirection = messages_1.MessageDirection.clientToServer;
DidChangeNotebookDocumentNotification2.type = new messages_1.ProtocolNotificationType(DidChangeNotebookDocumentNotification2.method);
DidChangeNotebookDocumentNotification2.registrationMethod = NotebookDocumentSyncRegistrationType.method;
})(DidChangeNotebookDocumentNotification || (exports2.DidChangeNotebookDocumentNotification = DidChangeNotebookDocumentNotification = {}));
var DidSaveNotebookDocumentNotification;
(function(DidSaveNotebookDocumentNotification2) {
DidSaveNotebookDocumentNotification2.method = "notebookDocument/didSave";
DidSaveNotebookDocumentNotification2.messageDirection = messages_1.MessageDirection.clientToServer;
DidSaveNotebookDocumentNotification2.type = new messages_1.ProtocolNotificationType(DidSaveNotebookDocumentNotification2.method);
DidSaveNotebookDocumentNotification2.registrationMethod = NotebookDocumentSyncRegistrationType.method;
})(DidSaveNotebookDocumentNotification || (exports2.DidSaveNotebookDocumentNotification = DidSaveNotebookDocumentNotification = {}));
var DidCloseNotebookDocumentNotification;
(function(DidCloseNotebookDocumentNotification2) {
DidCloseNotebookDocumentNotification2.method = "notebookDocument/didClose";
DidCloseNotebookDocumentNotification2.messageDirection = messages_1.MessageDirection.clientToServer;
DidCloseNotebookDocumentNotification2.type = new messages_1.ProtocolNotificationType(DidCloseNotebookDocumentNotification2.method);
DidCloseNotebookDocumentNotification2.registrationMethod = NotebookDocumentSyncRegistrationType.method;
})(DidCloseNotebookDocumentNotification || (exports2.DidCloseNotebookDocumentNotification = DidCloseNotebookDocumentNotification = {}));
}
});
var require_protocol_inlineCompletion = __commonJS({
"../../node_modules/.pnpm/vscode-languageserver-protocol@3.17.5/node_modules/vscode-languageserver-protocol/lib/common/protocol.inlineCompletion.js"(exports2) {
"use strict";
Object.defineProperty(exports2, "__esModule", { value: true });
exports2.InlineCompletionRequest = void 0;
var messages_1 = require_messages2();
var InlineCompletionRequest;
(function(InlineCompletionRequest2) {
InlineCompletionRequest2.method = "textDocument/inlineCompletion";
InlineCompletionRequest2.messageDirection = messages_1.MessageDirection.clientToServer;
InlineCompletionRequest2.type = new messages_1.ProtocolRequestType(InlineCompletionRequest2.method);
})(InlineCompletionRequest || (exports2.InlineCompletionRequest = InlineCompletionRequest = {}));
}
});
var require_protocol = __commonJS({
"../../node_modules/.pnpm/vscode-languageserver-protocol@3.17.5/node_modules/vscode-languageserver-protocol/lib/common/protocol.js"(exports2) {
"use strict";
Object.defineProperty(exports2, "__esModule", { value: true });
exports2.WorkspaceSymbolRequest = exports2.CodeActionResolveRequest = exports2.CodeActionRequest = exports2.DocumentSymbolRequest = exports2.DocumentHighlightRequest = exports2.ReferencesRequest = exports2.DefinitionRequest = exports2.SignatureHelpRequest = exports2.SignatureHelpTriggerKind = exports2.HoverRequest = exports2.CompletionResolveRequest = exports2.CompletionRequest = exports2.CompletionTriggerKind = exports2.PublishDiagnosticsNotification = exports2.WatchKind = exports2.RelativePattern = exports2.FileChangeType = exports2.DidChangeWatchedFilesNotification = exports2.WillSaveTextDocumentWaitUntilRequest = exports2.WillSaveTextDocumentNotification = exports2.TextDocumentSaveReason = exports2.DidSaveTextDocumentNotification = exports2.DidCloseTextDocumentNotification = exports2.DidChangeTextDocumentNotification = exports2.TextDocumentContentChangeEvent = exports2.DidOpenTextDocumentNotification = exports2.TextDocumentSyncKind = exports2.TelemetryEventNotification = exports2.LogMessageNotification = exports2.ShowMessageRequest = exports2.ShowMessageNotification = exports2.MessageType = exports2.DidChangeConfigurationNotification = exports2.ExitNotification = exports2.ShutdownRequest = exports2.InitializedNotification = exports2.InitializeErrorCodes = exports2.InitializeRequest = exports2.WorkDoneProgressOptions = exports2.TextDocumentRegistrationOptions = exports2.StaticRegistrationOptions = exports2.PositionEncodingKind = exports2.FailureHandlingKind = exports2.ResourceOperationKind = exports2.UnregistrationRequest = exports2.RegistrationRequest = exports2.DocumentSelector = exports2.NotebookCellTextDocumentFilter = exports2.NotebookDocumentFilter = exports2.TextDocumentFilter = void 0;
exports2.MonikerRequest = exports2.MonikerKind = exports2.UniquenessLevel = exports2.WillDeleteFilesRequest = exports2.DidDeleteFilesNotification = exports2.WillRenameFilesRequest = exports2.DidRenameFilesNotification = exports2.WillCreateFilesRequest = exports2.DidCreateFilesNotification = exports2.FileOperationPatternKind = exports2.LinkedEditingRangeRequest = exports2.ShowDocumentRequest = exports2.SemanticTokensRegistrationType = exports2.SemanticTokensRefreshRequest = exports2.SemanticTokensRangeRequest = exports2.SemanticTokensDeltaRequest = exports2.SemanticTokensRequest = exports2.TokenFormat = exports2.CallHierarchyPrepareRequest = exports2.CallHierarchyOutgoingCallsRequest = exports2.CallHierarchyIncomingCallsRequest = exports2.WorkDoneProgressCancelNotification = exports2.WorkDoneProgressCreateRequest = exports2.WorkDoneProgress = exports2.SelectionRangeRequest = exports2.DeclarationRequest = exports2.FoldingRangeRefreshRequest = exports2.FoldingRangeRequest = exports2.ColorPresentationRequest = exports2.DocumentColorRequest = exports2.ConfigurationRequest = exports2.DidChangeWorkspaceFoldersNotification = exports2.WorkspaceFoldersRequest = exports2.TypeDefinitionRequest = exports2.ImplementationRequest = exports2.ApplyWorkspaceEditRequest = exports2.ExecuteCommandRequest = exports2.PrepareRenameRequest = exports2.RenameRequest = exports2.PrepareSupportDefaultBehavior = exports2.DocumentOnTypeFormattingRequest = exports2.DocumentRangesFormattingRequest = exports2.DocumentRangeFormattingRequest = exports2.DocumentFormattingRequest = exports2.DocumentLinkResolveRequest = exports2.DocumentLinkRequest = exports2.CodeLensRefreshRequest = exports2.CodeLensResolveRequest = exports2.CodeLensRequest = exports2.WorkspaceSymbolResolveRequest = void 0;
exports2.InlineCompletionRequest = exports2.DidCloseNotebookDocumentNotification = exports2.DidSaveNotebookDocumentNotification = exports2.DidChangeNotebookDocumentNotification = exports2.NotebookCellArrayChange = exports2.DidOpenNotebookDocumentNotification = exports2.NotebookDocumentSyncRegistrationType = exports2.NotebookDocument = exports2.NotebookCell = exports2.ExecutionSummary = exports2.NotebookCellKind = exports2.DiagnosticRefreshRequest = exports2.WorkspaceDiagnosticRequest = exports2.DocumentDiagnosticRequest = exports2.DocumentDiagnosticReportKind = exports2.DiagnosticServerCancellationData = exports2.InlayHintRefreshRequest = exports2.InlayHintResolveRequest = exports2.InlayHintRequest = exports2.InlineValueRefreshRequest = exports2.InlineValueRequest = exports2.TypeHierarchySupertypesRequest = exports2.TypeHierarchySubtypesRequest = exports2.TypeHierarchyPrepareRequest = void 0;
var messages_1 = require_messages2();
var vscode_languageserver_types_1 = (init_main(), __toCommonJS(main_exports));
var Is2 = require_is2();
var protocol_implementation_1 = require_protocol_implementation();
Object.defineProperty(exports2, "ImplementationRequest", { enumerable: true, get: /* @__PURE__ */ __name2(function() {
return protocol_implementation_1.ImplementationRequest;
}, "get") });
var protocol_typeDefinition_1 = require_protocol_typeDefinition();
Object.defineProperty(exports2, "TypeDefinitionRequest", { enumerable: true, get: /* @__PURE__ */ __name2(function() {
return protocol_typeDefinition_1.TypeDefinitionRequest;
}, "get") });
var protocol_workspaceFolder_1 = require_protocol_workspaceFolder();
Object.defineProperty(exports2, "WorkspaceFoldersRequest", { enumerable: true, get: /* @__PURE__ */ __name2(function() {
return protocol_workspaceFolder_1.WorkspaceFoldersRequest;
}, "get") });
Object.defineProperty(exports2, "DidChangeWorkspaceFoldersNotification", { enumerable: true, get: /* @__PURE__ */ __name2(function() {
return protocol_workspaceFolder_1.DidChangeWorkspaceFoldersNotification;
}, "get") });
var protocol_configuration_1 = require_protocol_configuration();
Object.defineProperty(exports2, "ConfigurationRequest", { enumerable: true, get: /* @__PURE__ */ __name2(function() {
return protocol_configuration_1.ConfigurationRequest;
}, "get") });
var protocol_colorProvider_1 = require_protocol_colorProvider();
Object.defineProperty(exports2, "DocumentColorRequest", { enumerable: true, get: /* @__PURE__ */ __name2(function() {
return protocol_colorProvider_1.DocumentColorRequest;
}, "get") });
Object.defineProperty(exports2, "ColorPresentationRequest", { enumerable: true, get: /* @__PURE__ */ __name2(function() {
return protocol_colorProvider_1.ColorPresentationRequest;
}, "get") });
var protocol_foldingRange_1 = require_protocol_foldingRange();
Object.defineProperty(exports2, "FoldingRangeRequest", { enumerable: true, get: /* @__PURE__ */ __name2(function() {
return protocol_foldingRange_1.FoldingRangeRequest;
}, "get") });
Object.defineProperty(exports2, "FoldingRangeRefreshRequest", { enumerable: true, get: /* @__PURE__ */ __name2(function() {
return protocol_foldingRange_1.FoldingRangeRefreshRequest;
}, "get") });
var protocol_declaration_1 = require_protocol_declaration();
Object.defineProperty(exports2, "DeclarationRequest", { enumerable: true, get: /* @__PURE__ */ __name2(function() {
return protocol_declaration_1.DeclarationRequest;
}, "get") });
var protocol_selectionRange_1 = require_protocol_selectionRange();
Object.defineProperty(exports2, "SelectionRangeRequest", { enumerable: true, get: /* @__PURE__ */ __name2(function() {
return protocol_selectionRange_1.SelectionRangeRequest;
}, "get") });
var protocol_progress_1 = require_protocol_progress();
Object.defineProperty(exports2, "WorkDoneProgress", { enumerable: true, get: /* @__PURE__ */ __name2(function() {
return protocol_progress_1.WorkDoneProgress;
}, "get") });
Object.defineProperty(exports2, "WorkDoneProgressCreateRequest", { enumerable: true, get: /* @__PURE__ */ __name2(function() {
return protocol_progress_1.WorkDoneProgressCreateRequest;
}, "get") });
Object.defineProperty(exports2, "WorkDoneProgressCancelNotification", { enumerable: true, get: /* @__PURE__ */ __name2(function() {
return protocol_progress_1.WorkDoneProgressCancelNotification;
}, "get") });
var protocol_callHierarchy_1 = require_protocol_callHierarchy();
Object.defineProperty(exports2, "CallHierarchyIncomingCallsRequest", { enumerable: true, get: /* @__PURE__ */ __name2(function() {
return protocol_callHierarchy_1.CallHierarchyIncomingCallsRequest;
}, "get") });
Object.defineProperty(exports2, "CallHierarchyOutgoingCallsRequest", { enumerable: true, get: /* @__PURE__ */ __name2(function() {
return protocol_callHierarchy_1.CallHierarchyOutgoingCallsRequest;
}, "get") });
Object.defineProperty(exports2, "CallHierarchyPrepareRequest", { enumerable: true, get: /* @__PURE__ */ __name2(function() {
return protocol_callHierarchy_1.CallHierarchyPrepareRequest;
}, "get") });
var protocol_semanticTokens_1 = require_protocol_semanticTokens();
Object.defineProperty(exports2, "TokenFormat", { enumerable: true, get: /* @__PURE__ */ __name2(function() {
return protocol_semanticTokens_1.TokenFormat;
}, "get") });
Object.defineProperty(exports2, "SemanticTokensRequest", { enumerable: true, get: /* @__PURE__ */ __name2(function() {
return protocol_semanticTokens_1.SemanticTokensRequest;
}, "get") });
Object.defineProperty(exports2, "SemanticTokensDeltaRequest", { enumerable: true, get: /* @__PURE__ */ __name2(function() {
return protocol_semanticTokens_1.SemanticTokensDeltaRequest;
}, "get") });
Object.defineProperty(exports2, "SemanticTokensRangeRequest", { enumerable: true, get: /* @__PURE__ */ __name2(function() {
return protocol_semanticTokens_1.SemanticTokensRangeRequest;
}, "get") });
Object.defineProperty(exports2, "SemanticTokensRefreshRequest", { enumerable: true, get: /* @__PURE__ */ __name2(function() {
return protocol_semanticTokens_1.SemanticTokensRefreshRequest;
}, "get") });
Object.defineProperty(exports2, "SemanticTokensRegistrationType", { enumerable: true, get: /* @__PURE__ */ __name2(function() {
return protocol_semanticTokens_1.SemanticTokensRegistrationType;
}, "get") });
var protocol_showDocument_1 = require_protocol_showDocument();
Object.defineProperty(exports2, "ShowDocumentRequest", { enumerable: true, get: /* @__PURE__ */ __name2(function() {
return protocol_showDocument_1.ShowDocumentRequest;
}, "get") });
var protocol_linkedEditingRange_1 = require_protocol_linkedEditingRange();
Object.defineProperty(exports2, "LinkedEditingRangeRequest", { enumerable: true, get: /* @__PURE__ */ __name2(function() {
return protocol_linkedEditingRange_1.LinkedEditingRangeRequest;
}, "get") });
var protocol_fileOperations_1 = require_protocol_fileOperations();
Object.defineProperty(exports2, "FileOperationPatternKind", { enumerable: true, get: /* @__PURE__ */ __name2(function() {
return protocol_fileOperations_1.FileOperationPatternKind;
}, "get") });
Object.defineProperty(exports2, "DidCreateFilesNotification", { enumerable: true, get: /* @__PURE__ */ __name2(function() {
return protocol_fileOperations_1.DidCreateFilesNotification;
}, "get") });
Object.defineProperty(exports2, "WillCreateFilesRequest", { enumerable: true, get: /* @__PURE__ */ __name2(function() {
return protocol_fileOperations_1.WillCreateFilesRequest;
}, "get") });
Object.defineProperty(exports2, "DidRenameFilesNotification", { enumerable: true, get: /* @__PURE__ */ __name2(function() {
return protocol_fileOperations_1.DidRenameFilesNotification;
}, "get") });
Object.defineProperty(exports2, "WillRenameFilesRequest", { enumerable: true, get: /* @__PURE__ */ __name2(function() {
return protocol_fileOperations_1.WillRenameFilesRequest;
}, "get") });
Object.defineProperty(exports2, "DidDeleteFilesNotification", { enumerable: true, get: /* @__PURE__ */ __name2(function() {
return protocol_fileOperations_1.DidDeleteFilesNotification;
}, "get") });
Object.defineProperty(exports2, "WillDeleteFilesRequest", { enumerable: true, get: /* @__PURE__ */ __name2(function() {
return protocol_fileOperations_1.WillDeleteFilesRequest;
}, "get") });
var protocol_moniker_1 = require_protocol_moniker();
Object.defineProperty(exports2, "UniquenessLevel", { enumerable: true, get: /* @__PURE__ */ __name2(function() {
return protocol_moniker_1.UniquenessLevel;
}, "get") });
Object.defineProperty(exports2, "MonikerKind", { enumerable: true, get: /* @__PURE__ */ __name2(function() {
return protocol_moniker_1.MonikerKind;
}, "get") });
Object.defineProperty(exports2, "MonikerRequest", { enumerable: true, get: /* @__PURE__ */ __name2(function() {
return protocol_moniker_1.MonikerRequest;
}, "get") });
var protocol_typeHierarchy_1 = require_protocol_typeHierarchy();
Object.defineProperty(exports2, "TypeHierarchyPrepareRequest", { enumerable: true, get: /* @__PURE__ */ __name2(function() {
return protocol_typeHierarchy_1.TypeHierarchyPrepareRequest;
}, "get") });
Object.defineProperty(exports2, "TypeHierarchySubtypesRequest", { enumerable: true, get: /* @__PURE__ */ __name2(function() {
return protocol_typeHierarchy_1.TypeHierarchySubtypesRequest;
}, "get") });
Object.defineProperty(exports2, "TypeHierarchySupertypesRequest", { enumerable: true, get: /* @__PURE__ */ __name2(function() {
return protocol_typeHierarchy_1.TypeHierarchySupertypesRequest;
}, "get") });
var protocol_inlineValue_1 = require_protocol_inlineValue();
Object.defineProperty(exports2, "InlineValueRequest", { enumerable: true, get: /* @__PURE__ */ __name2(function() {
return protocol_inlineValue_1.InlineValueRequest;
}, "get") });
Object.defineProperty(exports2, "InlineValueRefreshRequest", { enumerable: true, get: /* @__PURE__ */ __name2(function() {
return protocol_inlineValue_1.InlineValueRefreshRequest;
}, "get") });
var protocol_inlayHint_1 = require_protocol_inlayHint();
Object.defineProperty(exports2, "InlayHintRequest", { enumerable: true, get: /* @__PURE__ */ __name2(function() {
return protocol_inlayHint_1.InlayHintRequest;
}, "get") });
Object.defineProperty(exports2, "InlayHintResolveRequest", { enumerable: true, get: /* @__PURE__ */ __name2(function() {
return protocol_inlayHint_1.InlayHintResolveRequest;
}, "get") });
Object.defineProperty(exports2, "InlayHintRefreshRequest", { enumerable: true, get: /* @__PURE__ */ __name2(function() {
return protocol_inlayHint_1.InlayHintRefreshRequest;
}, "get") });
var protocol_diagnostic_1 = require_protocol_diagnostic();
Object.defineProperty(exports2, "DiagnosticServerCancellationData", { enumerable: true, get: /* @__PURE__ */ __name2(function() {
return protocol_diagnostic_1.DiagnosticServerCancellationData;
}, "get") });
Object.defineProperty(exports2, "DocumentDiagnosticReportKind", { enumerable: true, get: /* @__PURE__ */ __name2(function() {
return protocol_diagnostic_1.DocumentDiagnosticReportKind;
}, "get") });
Object.defineProperty(exports2, "DocumentDiagnosticRequest", { enumerable: true, get: /* @__PURE__ */ __name2(function() {
return protocol_diagnostic_1.DocumentDiagnosticRequest;
}, "get") });
Object.defineProperty(exports2, "WorkspaceDiagnosticRequest", { enumerable: true, get: /* @__PURE__ */ __name2(function() {
return protocol_diagnostic_1.WorkspaceDiagnosticRequest;
}, "get") });
Object.defineProperty(exports2, "DiagnosticRefreshRequest", { enumerable: true, get: /* @__PURE__ */ __name2(function() {
return protocol_diagnostic_1.DiagnosticRefreshRequest;
}, "get") });
var protocol_notebook_1 = require_protocol_notebook();
Object.defineProperty(exports2, "NotebookCellKind", { enumerable: true, get: /* @__PURE__ */ __name2(function() {
return protocol_notebook_1.NotebookCellKind;
}, "get") });
Object.defineProperty(exports2, "ExecutionSummary", { enumerable: true, get: /* @__PURE__ */ __name2(function() {
return protocol_notebook_1.ExecutionSummary;
}, "get") });
Object.defineProperty(exports2, "NotebookCell", { enumerable: true, get: /* @__PURE__ */ __name2(function() {
return protocol_notebook_1.NotebookCell;
}, "get") });
Object.defineProperty(exports2, "NotebookDocument", { enumerable: true, get: /* @__PURE__ */ __name2(function() {
return protocol_notebook_1.NotebookDocument;
}, "get") });
Object.defineProperty(exports2, "NotebookDocumentSyncRegistrationType", { enumerable: true, get: /* @__PURE__ */ __name2(function() {
return protocol_notebook_1.NotebookDocumentSyncRegistrationType;
}, "get") });
Object.defineProperty(exports2, "DidOpenNotebookDocumentNotification", { enumerable: true, get: /* @__PURE__ */ __name2(function() {
return protocol_notebook_1.DidOpenNotebookDocumentNotification;
}, "get") });
Object.defineProperty(exports2, "NotebookCellArrayChange", { enumerable: true, get: /* @__PURE__ */ __name2(function() {
return protocol_notebook_1.NotebookCellArrayChange;
}, "get") });
Object.defineProperty(exports2, "DidChangeNotebookDocumentNotification", { enumerable: true, get: /* @__PURE__ */ __name2(function() {
return protocol_notebook_1.DidChangeNotebookDocumentNotification;
}, "get") });
Object.defineProperty(exports2, "DidSaveNotebookDocumentNotification", { enumerable: true, get: /* @__PURE__ */ __name2(function() {
return protocol_notebook_1.DidSaveNotebookDocumentNotification;
}, "get") });
Object.defineProperty(exports2, "DidCloseNotebookDocumentNotification", { enumerable: true, get: /* @__PURE__ */ __name2(function() {
return protocol_notebook_1.DidCloseNotebookDocumentNotification;
}, "get") });
var protocol_inlineCompletion_1 = require_protocol_inlineCompletion();
Object.defineProperty(exports2, "InlineCompletionRequest", { enumerable: true, get: /* @__PURE__ */ __name2(function() {
return protocol_inlineCompletion_1.InlineCompletionRequest;
}, "get") });
var TextDocumentFilter;
(function(TextDocumentFilter2) {
function is(value) {
const candidate = value;
return Is2.string(candidate) || (Is2.string(candidate.language) || Is2.string(candidate.scheme) || Is2.string(candidate.pattern));
}
__name(is, "is");
__name2(is, "is");
TextDocumentFilter2.is = is;
})(TextDocumentFilter || (exports2.TextDocumentFilter = TextDocumentFilter = {}));
var NotebookDocumentFilter;
(function(NotebookDocumentFilter2) {
function is(value) {
const candidate = value;
return Is2.objectLiteral(candidate) && (Is2.string(candidate.notebookType) || Is2.string(candidate.scheme) || Is2.string(candidate.pattern));
}
__name(is, "is");
__name2(is, "is");
NotebookDocumentFilter2.is = is;
})(NotebookDocumentFilter || (exports2.NotebookDocumentFilter = NotebookDocumentFilter = {}));
var NotebookCellTextDocumentFilter;
(function(NotebookCellTextDocumentFilter2) {
function is(value) {
const candidate = value;
return Is2.objectLiteral(candidate) && (Is2.string(candidate.notebook) || NotebookDocumentFilter.is(candidate.notebook)) && (candidate.language === void 0 || Is2.string(candidate.language));
}
__name(is, "is");
__name2(is, "is");
NotebookCellTextDocumentFilter2.is = is;
})(NotebookCellTextDocumentFilter || (exports2.NotebookCellTextDocumentFilter = NotebookCellTextDocumentFilter = {}));
var DocumentSelector;
(function(DocumentSelector2) {
function is(value) {
if (!Array.isArray(value)) {
return false;
}
for (let elem of value) {
if (!Is2.string(elem) && !TextDocumentFilter.is(elem) && !NotebookCellTextDocumentFilter.is(elem)) {
return false;
}
}
return true;
}
__name(is, "is");
__name2(is, "is");
DocumentSelector2.is = is;
})(DocumentSelector || (exports2.DocumentSelector = DocumentSelector = {}));
var RegistrationRequest;
(function(RegistrationRequest2) {
RegistrationRequest2.method = "client/registerCapability";
RegistrationRequest2.messageDirection = messages_1.MessageDirection.serverToClient;
RegistrationRequest2.type = new messages_1.ProtocolRequestType(RegistrationRequest2.method);
})(RegistrationRequest || (exports2.RegistrationRequest = RegistrationRequest = {}));
var UnregistrationRequest;
(function(UnregistrationRequest2) {
UnregistrationRequest2.method = "client/unregisterCapability";
UnregistrationRequest2.messageDirection = messages_1.MessageDirection.serverToClient;
UnregistrationRequest2.type = new messages_1.ProtocolRequestType(UnregistrationRequest2.method);
})(UnregistrationRequest || (exports2.UnregistrationRequest = UnregistrationRequest = {}));
var ResourceOperationKind;
(function(ResourceOperationKind2) {
ResourceOperationKind2.Create = "create";
ResourceOperationKind2.Rename = "rename";
ResourceOperationKind2.Delete = "delete";
})(ResourceOperationKind || (exports2.ResourceOperationKind = ResourceOperationKind = {}));
var FailureHandlingKind;
(function(FailureHandlingKind2) {
FailureHandlingKind2.Abort = "abort";
FailureHandlingKind2.Transactional = "transactional";
FailureHandlingKind2.TextOnlyTransactional = "textOnlyTransactional";
FailureHandlingKind2.Undo = "undo";
})(FailureHandlingKind || (exports2.FailureHandlingKind = FailureHandlingKind = {}));
var PositionEncodingKind;
(function(PositionEncodingKind2) {
PositionEncodingKind2.UTF8 = "utf-8";
PositionEncodingKind2.UTF16 = "utf-16";
PositionEncodingKind2.UTF32 = "utf-32";
})(PositionEncodingKind || (exports2.PositionEncodingKind = PositionEncodingKind = {}));
var StaticRegistrationOptions;
(function(StaticRegistrationOptions2) {
function hasId(value) {
const candidate = value;
return candidate && Is2.string(candidate.id) && candidate.id.length > 0;
}
__name(hasId, "hasId");
__name2(hasId, "hasId");
StaticRegistrationOptions2.hasId = hasId;
})(StaticRegistrationOptions || (exports2.StaticRegistrationOptions = StaticRegistrationOptions = {}));
var TextDocumentRegistrationOptions;
(function(TextDocumentRegistrationOptions2) {
function is(value) {
const candidate = value;
return candidate && (candidate.documentSelector === null || DocumentSelector.is(candidate.documentSelector));
}
__name(is, "is");
__name2(is, "is");
TextDocumentRegistrationOptions2.is = is;
})(TextDocumentRegistrationOptions || (exports2.TextDocumentRegistrationOptions = TextDocumentRegistrationOptions = {}));
var WorkDoneProgressOptions;
(function(WorkDoneProgressOptions2) {
function is(value) {
const candidate = value;
return Is2.objectLiteral(candidate) && (candidate.workDoneProgress === void 0 || Is2.boolean(candidate.workDoneProgress));
}
__name(is, "is");
__name2(is, "is");
WorkDoneProgressOptions2.is = is;
function hasWorkDoneProgress(value) {
const candidate = value;
return candidate && Is2.boolean(candidate.workDoneProgress);
}
__name(hasWorkDoneProgress, "hasWorkDoneProgress");
__name2(hasWorkDoneProgress, "hasWorkDoneProgress");
WorkDoneProgressOptions2.hasWorkDoneProgress = hasWorkDoneProgress;
})(WorkDoneProgressOptions || (exports2.WorkDoneProgressOptions = WorkDoneProgressOptions = {}));
var InitializeRequest;
(function(InitializeRequest2) {
InitializeRequest2.method = "initialize";
InitializeRequest2.messageDirection = messages_1.MessageDirection.clientToServer;
InitializeRequest2.type = new messages_1.ProtocolRequestType(InitializeRequest2.method);
})(InitializeRequest || (exports2.InitializeRequest = InitializeRequest = {}));
var InitializeErrorCodes;
(function(InitializeErrorCodes2) {
InitializeErrorCodes2.unknownProtocolVersion = 1;
})(InitializeErrorCodes || (exports2.InitializeErrorCodes = InitializeErrorCodes = {}));
var InitializedNotification;
(function(InitializedNotification2) {
InitializedNotification2.method = "initialized";
InitializedNotification2.messageDirection = messages_1.MessageDirection.clientToServer;
InitializedNotification2.type = new messages_1.ProtocolNotificationType(InitializedNotification2.method);
})(InitializedNotification || (exports2.InitializedNotification = InitializedNotification = {}));
var ShutdownRequest;
(function(ShutdownRequest2) {
ShutdownRequest2.method = "shutdown";
ShutdownRequest2.messageDirection = messages_1.MessageDirection.clientToServer;
ShutdownRequest2.type = new messages_1.ProtocolRequestType0(ShutdownRequest2.method);
})(ShutdownRequest || (exports2.ShutdownRequest = ShutdownRequest = {}));
var ExitNotification;
(function(ExitNotification2) {
ExitNotification2.method = "exit";
ExitNotification2.messageDirection = messages_1.MessageDirection.clientToServer;
ExitNotification2.type = new messages_1.ProtocolNotificationType0(ExitNotification2.method);
})(ExitNotification || (exports2.ExitNotification = ExitNotification = {}));
var DidChangeConfigurationNotification;
(function(DidChangeConfigurationNotification2) {
DidChangeConfigurationNotification2.method = "workspace/didChangeConfiguration";
DidChangeConfigurationNotification2.messageDirection = messages_1.MessageDirection.clientToServer;
DidChangeConfigurationNotification2.type = new messages_1.ProtocolNotificationType(DidChangeConfigurationNotification2.method);
})(DidChangeConfigurationNotification || (exports2.DidChangeConfigurationNotification = DidChangeConfigurationNotification = {}));
var MessageType;
(function(MessageType2) {
MessageType2.Error = 1;
MessageType2.Warning = 2;
MessageType2.Info = 3;
MessageType2.Log = 4;
MessageType2.Debug = 5;
})(MessageType || (exports2.MessageType = MessageType = {}));
var ShowMessageNotification;
(function(ShowMessageNotification2) {
ShowMessageNotification2.method = "window/showMessage";
ShowMessageNotification2.messageDirection = messages_1.MessageDirection.serverToClient;
ShowMessageNotification2.type = new messages_1.ProtocolNotificationType(ShowMessageNotification2.method);
})(ShowMessageNotification || (exports2.ShowMessageNotification = ShowMessageNotification = {}));
var ShowMessageRequest;
(function(ShowMessageRequest2) {
ShowMessageRequest2.method = "window/showMessageRequest";
ShowMessageRequest2.messageDirection = messages_1.MessageDirection.serverToClient;
ShowMessageRequest2.type = new messages_1.ProtocolRequestType(ShowMessageRequest2.method);
})(ShowMessageRequest || (exports2.ShowMessageRequest = ShowMessageRequest = {}));
var LogMessageNotification;
(function(LogMessageNotification2) {
LogMessageNotification2.method = "window/logMessage";
LogMessageNotification2.messageDirection = messages_1.MessageDirection.serverToClient;
LogMessageNotification2.type = new messages_1.ProtocolNotificationType(LogMessageNotification2.method);
})(LogMessageNotification || (exports2.LogMessageNotification = LogMessageNotification = {}));
var TelemetryEventNotification;
(function(TelemetryEventNotification2) {
TelemetryEventNotification2.method = "telemetry/event";
TelemetryEventNotification2.messageDirection = messages_1.MessageDirection.serverToClient;
TelemetryEventNotification2.type = new messages_1.ProtocolNotificationType(TelemetryEventNotification2.method);
})(TelemetryEventNotification || (exports2.TelemetryEventNotification = TelemetryEventNotification = {}));
var TextDocumentSyncKind;
(function(TextDocumentSyncKind2) {
TextDocumentSyncKind2.None = 0;
TextDocumentSyncKind2.Full = 1;
TextDocumentSyncKind2.Incremental = 2;
})(TextDocumentSyncKind || (exports2.TextDocumentSyncKind = TextDocumentSyncKind = {}));
var DidOpenTextDocumentNotification;
(function(DidOpenTextDocumentNotification2) {
DidOpenTextDocumentNotification2.method = "textDocument/didOpen";
DidOpenTextDocumentNotification2.messageDirection = messages_1.MessageDirection.clientToServer;
DidOpenTextDocumentNotification2.type = new messages_1.ProtocolNotificationType(DidOpenTextDocumentNotification2.method);
})(DidOpenTextDocumentNotification || (exports2.DidOpenTextDocumentNotification = DidOpenTextDocumentNotification = {}));
var TextDocumentContentChangeEvent;
(function(TextDocumentContentChangeEvent2) {
function isIncremental(event) {
let candidate = event;
return candidate !== void 0 && candidate !== null && typeof candidate.text === "string" && candidate.range !== void 0 && (candidate.rangeLength === void 0 || typeof candidate.rangeLength === "number");
}
__name(isIncremental, "isIncremental");
__name2(isIncremental, "isIncremental");
TextDocumentContentChangeEvent2.isIncremental = isIncremental;
function isFull(event) {
let candidate = event;
return candidate !== void 0 && candidate !== null && typeof candidate.text === "string" && candidate.range === void 0 && candidate.rangeLength === void 0;
}
__name(isFull, "isFull");
__name2(isFull, "isFull");
TextDocumentContentChangeEvent2.isFull = isFull;
})(TextDocumentContentChangeEvent || (exports2.TextDocumentContentChangeEvent = TextDocumentContentChangeEvent = {}));
var DidChangeTextDocumentNotification;
(function(DidChangeTextDocumentNotification2) {
DidChangeTextDocumentNotification2.method = "textDocument/didChange";
DidChangeTextDocumentNotification2.messageDirection = messages_1.MessageDirection.clientToServer;
DidChangeTextDocumentNotification2.type = new messages_1.ProtocolNotificationType(DidChangeTextDocumentNotification2.method);
})(DidChangeTextDocumentNotification || (exports2.DidChangeTextDocumentNotification = DidChangeTextDocumentNotification = {}));
var DidCloseTextDocumentNotification;
(function(DidCloseTextDocumentNotification2) {
DidCloseTextDocumentNotification2.method = "textDocument/didClose";
DidCloseTextDocumentNotification2.messageDirection = messages_1.MessageDirection.clientToServer;
DidCloseTextDocumentNotification2.type = new messages_1.ProtocolNotificationType(DidCloseTextDocumentNotification2.method);
})(DidCloseTextDocumentNotification || (exports2.DidCloseTextDocumentNotification = DidCloseTextDocumentNotification = {}));
var DidSaveTextDocumentNotification;
(function(DidSaveTextDocumentNotification2) {
DidSaveTextDocumentNotification2.method = "textDocument/didSave";
DidSaveTextDocumentNotification2.messageDirection = messages_1.MessageDirection.clientToServer;
DidSaveTextDocumentNotification2.type = new messages_1.ProtocolNotificationType(DidSaveTextDocumentNotification2.method);
})(DidSaveTextDocumentNotification || (exports2.DidSaveTextDocumentNotification = DidSaveTextDocumentNotification = {}));
var TextDocumentSaveReason;
(function(TextDocumentSaveReason2) {
TextDocumentSaveReason2.Manual = 1;
TextDocumentSaveReason2.AfterDelay = 2;
TextDocumentSaveReason2.FocusOut = 3;
})(TextDocumentSaveReason || (exports2.TextDocumentSaveReason = TextDocumentSaveReason = {}));
var WillSaveTextDocumentNotification;
(function(WillSaveTextDocumentNotification2) {
WillSaveTextDocumentNotification2.method = "textDocument/willSave";
WillSaveTextDocumentNotification2.messageDirection = messages_1.MessageDirection.clientToServer;
WillSaveTextDocumentNotification2.type = new messages_1.ProtocolNotificationType(WillSaveTextDocumentNotification2.method);
})(WillSaveTextDocumentNotification || (exports2.WillSaveTextDocumentNotification = WillSaveTextDocumentNotification = {}));
var WillSaveTextDocumentWaitUntilRequest;
(function(WillSaveTextDocumentWaitUntilRequest2) {
WillSaveTextDocumentWaitUntilRequest2.method = "textDocument/willSaveWaitUntil";
WillSaveTextDocumentWaitUntilRequest2.messageDirection = messages_1.MessageDirection.clientToServer;
WillSaveTextDocumentWaitUntilRequest2.type = new messages_1.ProtocolRequestType(WillSaveTextDocumentWaitUntilRequest2.method);
})(WillSaveTextDocumentWaitUntilRequest || (exports2.WillSaveTextDocumentWaitUntilRequest = WillSaveTextDocumentWaitUntilRequest = {}));
var DidChangeWatchedFilesNotification;
(function(DidChangeWatchedFilesNotification2) {
DidChangeWatchedFilesNotification2.method = "workspace/didChangeWatchedFiles";
DidChangeWatchedFilesNotification2.messageDirection = messages_1.MessageDirection.clientToServer;
DidChangeWatchedFilesNotification2.type = new messages_1.ProtocolNotificationType(DidChangeWatchedFilesNotification2.method);
})(DidChangeWatchedFilesNotification || (exports2.DidChangeWatchedFilesNotification = DidChangeWatchedFilesNotification = {}));
var FileChangeType;
(function(FileChangeType2) {
FileChangeType2.Created = 1;
FileChangeType2.Changed = 2;
FileChangeType2.Deleted = 3;
})(FileChangeType || (exports2.FileChangeType = FileChangeType = {}));
var RelativePattern;
(function(RelativePattern2) {
function is(value) {
const candidate = value;
return Is2.objectLiteral(candidate) && (vscode_languageserver_types_1.URI.is(candidate.baseUri) || vscode_languageserver_types_1.WorkspaceFolder.is(candidate.baseUri)) && Is2.string(candidate.pattern);
}
__name(is, "is");
__name2(is, "is");
RelativePattern2.is = is;
})(RelativePattern || (exports2.RelativePattern = RelativePattern = {}));
var WatchKind;
(function(WatchKind2) {
WatchKind2.Create = 1;
WatchKind2.Change = 2;
WatchKind2.Delete = 4;
})(WatchKind || (exports2.WatchKind = WatchKind = {}));
var PublishDiagnosticsNotification;
(function(PublishDiagnosticsNotification2) {
PublishDiagnosticsNotification2.method = "textDocument/publishDiagnostics";
PublishDiagnosticsNotification2.messageDirection = messages_1.MessageDirection.serverToClient;
PublishDiagnosticsNotification2.type = new messages_1.ProtocolNotificationType(PublishDiagnosticsNotification2.method);
})(PublishDiagnosticsNotification || (exports2.PublishDiagnosticsNotification = PublishDiagnosticsNotification = {}));
var CompletionTriggerKind;
(function(CompletionTriggerKind2) {
CompletionTriggerKind2.Invoked = 1;
CompletionTriggerKind2.TriggerCharacter = 2;
CompletionTriggerKind2.TriggerForIncompleteCompletions = 3;
})(CompletionTriggerKind || (exports2.CompletionTriggerKind = CompletionTriggerKind = {}));
var CompletionRequest;
(function(CompletionRequest2) {
CompletionRequest2.method = "textDocument/completion";
CompletionRequest2.messageDirection = messages_1.MessageDirection.clientToServer;
CompletionRequest2.type = new messages_1.ProtocolRequestType(CompletionRequest2.method);
})(CompletionRequest || (exports2.CompletionRequest = CompletionRequest = {}));
var CompletionResolveRequest;
(function(CompletionResolveRequest2) {
CompletionResolveRequest2.method = "completionItem/resolve";
CompletionResolveRequest2.messageDirection = messages_1.MessageDirection.clientToServer;
CompletionResolveRequest2.type = new messages_1.ProtocolRequestType(CompletionResolveRequest2.method);
})(CompletionResolveRequest || (exports2.CompletionResolveRequest = CompletionResolveRequest = {}));
var HoverRequest;
(function(HoverRequest2) {
HoverRequest2.method = "textDocument/hover";
HoverRequest2.messageDirection = messages_1.MessageDirection.clientToServer;
HoverRequest2.type = new messages_1.ProtocolRequestType(HoverRequest2.method);
})(HoverRequest || (exports2.HoverRequest = HoverRequest = {}));
var SignatureHelpTriggerKind;
(function(SignatureHelpTriggerKind2) {
SignatureHelpTriggerKind2.Invoked = 1;
SignatureHelpTriggerKind2.TriggerCharacter = 2;
SignatureHelpTriggerKind2.ContentChange = 3;
})(SignatureHelpTriggerKind || (exports2.SignatureHelpTriggerKind = SignatureHelpTriggerKind = {}));
var SignatureHelpRequest;
(function(SignatureHelpRequest2) {
SignatureHelpRequest2.method = "textDocument/signatureHelp";
SignatureHelpRequest2.messageDirection = messages_1.MessageDirection.clientToServer;
SignatureHelpRequest2.type = new messages_1.ProtocolRequestType(SignatureHelpRequest2.method);
})(SignatureHelpRequest || (exports2.SignatureHelpRequest = SignatureHelpRequest = {}));
var DefinitionRequest;
(function(DefinitionRequest2) {
DefinitionRequest2.method = "textDocument/definition";
DefinitionRequest2.messageDirection = messages_1.MessageDirection.clientToServer;
DefinitionRequest2.type = new messages_1.ProtocolRequestType(DefinitionRequest2.method);
})(DefinitionRequest || (exports2.DefinitionRequest = DefinitionRequest = {}));
var ReferencesRequest;
(function(ReferencesRequest2) {
ReferencesRequest2.method = "textDocument/references";
ReferencesRequest2.messageDirection = messages_1.MessageDirection.clientToServer;
ReferencesRequest2.type = new messages_1.ProtocolRequestType(ReferencesRequest2.method);
})(ReferencesRequest || (exports2.ReferencesRequest = ReferencesRequest = {}));
var DocumentHighlightRequest;
(function(DocumentHighlightRequest2) {
DocumentHighlightRequest2.method = "textDocument/documentHighlight";
DocumentHighlightRequest2.messageDirection = messages_1.MessageDirection.clientToServer;
DocumentHighlightRequest2.type = new messages_1.ProtocolRequestType(DocumentHighlightRequest2.method);
})(DocumentHighlightRequest || (exports2.DocumentHighlightRequest = DocumentHighlightRequest = {}));
var DocumentSymbolRequest;
(function(DocumentSymbolRequest2) {
DocumentSymbolRequest2.method = "textDocument/documentSymbol";
DocumentSymbolRequest2.messageDirection = messages_1.MessageDirection.clientToServer;
DocumentSymbolRequest2.type = new messages_1.ProtocolRequestType(DocumentSymbolRequest2.method);
})(DocumentSymbolRequest || (exports2.DocumentSymbolRequest = DocumentSymbolRequest = {}));
var CodeActionRequest;
(function(CodeActionRequest2) {
CodeActionRequest2.method = "textDocument/codeAction";
CodeActionRequest2.messageDirection = messages_1.MessageDirection.clientToServer;
CodeActionRequest2.type = new messages_1.ProtocolRequestType(CodeActionRequest2.method);
})(CodeActionRequest || (exports2.CodeActionRequest = CodeActionRequest = {}));
var CodeActionResolveRequest;
(function(CodeActionResolveRequest2) {
CodeActionResolveRequest2.method = "codeAction/resolve";
CodeActionResolveRequest2.messageDirection = messages_1.MessageDirection.clientToServer;
CodeActionResolveRequest2.type = new messages_1.ProtocolRequestType(CodeActionResolveRequest2.method);
})(CodeActionResolveRequest || (exports2.CodeActionResolveRequest = CodeActionResolveRequest = {}));
var WorkspaceSymbolRequest;
(function(WorkspaceSymbolRequest2) {
WorkspaceSymbolRequest2.method = "workspace/symbol";
WorkspaceSymbolRequest2.messageDirection = messages_1.MessageDirection.clientToServer;
WorkspaceSymbolRequest2.type = new messages_1.ProtocolRequestType(WorkspaceSymbolRequest2.method);
})(WorkspaceSymbolRequest || (exports2.WorkspaceSymbolRequest = WorkspaceSymbolRequest = {}));
var WorkspaceSymbolResolveRequest;
(function(WorkspaceSymbolResolveRequest2) {
WorkspaceSymbolResolveRequest2.method = "workspaceSymbol/resolve";
WorkspaceSymbolResolveRequest2.messageDirection = messages_1.MessageDirection.clientToServer;
WorkspaceSymbolResolveRequest2.type = new messages_1.ProtocolRequestType(WorkspaceSymbolResolveRequest2.method);
})(WorkspaceSymbolResolveRequest || (exports2.WorkspaceSymbolResolveRequest = WorkspaceSymbolResolveRequest = {}));
var CodeLensRequest;
(function(CodeLensRequest2) {
CodeLensRequest2.method = "textDocument/codeLens";
CodeLensRequest2.messageDirection = messages_1.MessageDirection.clientToServer;
CodeLensRequest2.type = new messages_1.ProtocolRequestType(CodeLensRequest2.method);
})(CodeLensRequest || (exports2.CodeLensRequest = CodeLensRequest = {}));
var CodeLensResolveRequest;
(function(CodeLensResolveRequest2) {
CodeLensResolveRequest2.method = "codeLens/resolve";
CodeLensResolveRequest2.messageDirection = messages_1.MessageDirection.clientToServer;
CodeLensResolveRequest2.type = new messages_1.ProtocolRequestType(CodeLensResolveRequest2.method);
})(CodeLensResolveRequest || (exports2.CodeLensResolveRequest = CodeLensResolveRequest = {}));
var CodeLensRefreshRequest;
(function(CodeLensRefreshRequest2) {
CodeLensRefreshRequest2.method = `workspace/codeLens/refresh`;
CodeLensRefreshRequest2.messageDirection = messages_1.MessageDirection.serverToClient;
CodeLensRefreshRequest2.type = new messages_1.ProtocolRequestType0(CodeLensRefreshRequest2.method);
})(CodeLensRefreshRequest || (exports2.CodeLensRefreshRequest = CodeLensRefreshRequest = {}));
var DocumentLinkRequest;
(function(DocumentLinkRequest2) {
DocumentLinkRequest2.method = "textDocument/documentLink";
DocumentLinkRequest2.messageDirection = messages_1.MessageDirection.clientToServer;
DocumentLinkRequest2.type = new messages_1.ProtocolRequestType(DocumentLinkRequest2.method);
})(DocumentLinkRequest || (exports2.DocumentLinkRequest = DocumentLinkRequest = {}));
var DocumentLinkResolveRequest;
(function(DocumentLinkResolveRequest2) {
DocumentLinkResolveRequest2.method = "documentLink/resolve";
DocumentLinkResolveRequest2.messageDirection = messages_1.MessageDirection.clientToServer;
DocumentLinkResolveRequest2.type = new messages_1.ProtocolRequestType(DocumentLinkResolveRequest2.method);
})(DocumentLinkResolveRequest || (exports2.DocumentLinkResolveRequest = DocumentLinkResolveRequest = {}));
var DocumentFormattingRequest;
(function(DocumentFormattingRequest2) {
DocumentFormattingRequest2.method = "textDocument/formatting";
DocumentFormattingRequest2.messageDirection = messages_1.MessageDirection.clientToServer;
DocumentFormattingRequest2.type = new messages_1.ProtocolRequestType(DocumentFormattingRequest2.method);
})(DocumentFormattingRequest || (exports2.DocumentFormattingRequest = DocumentFormattingRequest = {}));
var DocumentRangeFormattingRequest;
(function(DocumentRangeFormattingRequest2) {
DocumentRangeFormattingRequest2.method = "textDocument/rangeFormatting";
DocumentRangeFormattingRequest2.messageDirection = messages_1.MessageDirection.clientToServer;
DocumentRangeFormattingRequest2.type = new messages_1.ProtocolRequestType(DocumentRangeFormattingRequest2.method);
})(DocumentRangeFormattingRequest || (exports2.DocumentRangeFormattingRequest = DocumentRangeFormattingRequest = {}));
var DocumentRangesFormattingRequest;
(function(DocumentRangesFormattingRequest2) {
DocumentRangesFormattingRequest2.method = "textDocument/rangesFormatting";
DocumentRangesFormattingRequest2.messageDirection = messages_1.MessageDirection.clientToServer;
DocumentRangesFormattingRequest2.type = new messages_1.ProtocolRequestType(DocumentRangesFormattingRequest2.method);
})(DocumentRangesFormattingRequest || (exports2.DocumentRangesFormattingRequest = DocumentRangesFormattingRequest = {}));
var DocumentOnTypeFormattingRequest;
(function(DocumentOnTypeFormattingRequest2) {
DocumentOnTypeFormattingRequest2.method = "textDocument/onTypeFormatting";
DocumentOnTypeFormattingRequest2.messageDirection = messages_1.MessageDirection.clientToServer;
DocumentOnTypeFormattingRequest2.type = new messages_1.ProtocolRequestType(DocumentOnTypeFormattingRequest2.method);
})(DocumentOnTypeFormattingRequest || (exports2.DocumentOnTypeFormattingRequest = DocumentOnTypeFormattingRequest = {}));
var PrepareSupportDefaultBehavior;
(function(PrepareSupportDefaultBehavior2) {
PrepareSupportDefaultBehavior2.Identifier = 1;
})(PrepareSupportDefaultBehavior || (exports2.PrepareSupportDefaultBehavior = PrepareSupportDefaultBehavior = {}));
var RenameRequest;
(function(RenameRequest2) {
RenameRequest2.method = "textDocument/rename";
RenameRequest2.messageDirection = messages_1.MessageDirection.clientToServer;
RenameRequest2.type = new messages_1.ProtocolRequestType(RenameRequest2.method);
})(RenameRequest || (exports2.RenameRequest = RenameRequest = {}));
var PrepareRenameRequest;
(function(PrepareRenameRequest2) {
PrepareRenameRequest2.method = "textDocument/prepareRename";
PrepareRenameRequest2.messageDirection = messages_1.MessageDirection.clientToServer;
PrepareRenameRequest2.type = new messages_1.ProtocolRequestType(PrepareRenameRequest2.method);
})(PrepareRenameRequest || (exports2.PrepareRenameRequest = PrepareRenameRequest = {}));
var ExecuteCommandRequest;
(function(ExecuteCommandRequest2) {
ExecuteCommandRequest2.method = "workspace/executeCommand";
ExecuteCommandRequest2.messageDirection = messages_1.MessageDirection.clientToServer;
ExecuteCommandRequest2.type = new messages_1.ProtocolRequestType(ExecuteCommandRequest2.method);
})(ExecuteCommandRequest || (exports2.ExecuteCommandRequest = ExecuteCommandRequest = {}));
var ApplyWorkspaceEditRequest;
(function(ApplyWorkspaceEditRequest2) {
ApplyWorkspaceEditRequest2.method = "workspace/applyEdit";
ApplyWorkspaceEditRequest2.messageDirection = messages_1.MessageDirection.serverToClient;
ApplyWorkspaceEditRequest2.type = new messages_1.ProtocolRequestType("workspace/applyEdit");
})(ApplyWorkspaceEditRequest || (exports2.ApplyWorkspaceEditRequest = ApplyWorkspaceEditRequest = {}));
}
});
var require_connection2 = __commonJS({
"../../node_modules/.pnpm/vscode-languageserver-protocol@3.17.5/node_modules/vscode-languageserver-protocol/lib/common/connection.js"(exports2) {
"use strict";
Object.defineProperty(exports2, "__esModule", { value: true });
exports2.createProtocolConnection = void 0;
var vscode_jsonrpc_1 = require_main();
function createProtocolConnection(input, output, logger, options) {
if (vscode_jsonrpc_1.ConnectionStrategy.is(options)) {
options = { connectionStrategy: options };
}
return (0, vscode_jsonrpc_1.createMessageConnection)(input, output, logger, options);
}
__name(createProtocolConnection, "createProtocolConnection");
__name2(createProtocolConnection, "createProtocolConnection");
exports2.createProtocolConnection = createProtocolConnection;
}
});
var require_api2 = __commonJS({
"../../node_modules/.pnpm/vscode-languageserver-protocol@3.17.5/node_modules/vscode-languageserver-protocol/lib/common/api.js"(exports2) {
"use strict";
var __createBinding = exports2 && exports2.__createBinding || (Object.create ? (function(o, m, k, k2) {
if (k2 === void 0) k2 = k;
var desc = Object.getOwnPropertyDescriptor(m, k);
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: /* @__PURE__ */ __name2(function() {
return m[k];
}, "get") };
}
Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
if (k2 === void 0) k2 = k;
o[k2] = m[k];
}));
var __exportStar = exports2 && exports2.__exportStar || function(m, exports3) {
for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports3, p)) __createBinding(exports3, m, p);
};
Object.defineProperty(exports2, "__esModule", { value: true });
exports2.LSPErrorCodes = exports2.createProtocolConnection = void 0;
__exportStar(require_main(), exports2);
__exportStar((init_main(), __toCommonJS(main_exports)), exports2);
__exportStar(require_messages2(), exports2);
__exportStar(require_protocol(), exports2);
var connection_1 = require_connection2();
Object.defineProperty(exports2, "createProtocolConnection", { enumerable: true, get: /* @__PURE__ */ __name2(function() {
return connection_1.createProtocolConnection;
}, "get") });
var LSPErrorCodes2;
(function(LSPErrorCodes3) {
LSPErrorCodes3.lspReservedErrorRangeStart = -32899;
LSPErrorCodes3.RequestFailed = -32803;
LSPErrorCodes3.ServerCancelled = -32802;
LSPErrorCodes3.ContentModified = -32801;
LSPErrorCodes3.RequestCancelled = -32800;
LSPErrorCodes3.lspReservedErrorRangeEnd = -32800;
})(LSPErrorCodes2 || (exports2.LSPErrorCodes = LSPErrorCodes2 = {}));
}
});
var require_main2 = __commonJS({
"../../node_modules/.pnpm/vscode-languageserver-protocol@3.17.5/node_modules/vscode-languageserver-protocol/lib/browser/main.js"(exports2) {
"use strict";
var __createBinding = exports2 && exports2.__createBinding || (Object.create ? (function(o, m, k, k2) {
if (k2 === void 0) k2 = k;
var desc = Object.getOwnPropertyDescriptor(m, k);
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: /* @__PURE__ */ __name2(function() {
return m[k];
}, "get") };
}
Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
if (k2 === void 0) k2 = k;
o[k2] = m[k];
}));
var __exportStar = exports2 && exports2.__exportStar || function(m, exports3) {
for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports3, p)) __createBinding(exports3, m, p);
};
Object.defineProperty(exports2, "__esModule", { value: true });
exports2.createProtocolConnection = void 0;
var browser_1 = require_browser();
__exportStar(require_browser(), exports2);
__exportStar(require_api2(), exports2);
function createProtocolConnection(reader, writer, logger, options) {
return (0, browser_1.createMessageConnection)(reader, writer, logger, options);
}
__name(createProtocolConnection, "createProtocolConnection");
__name2(createProtocolConnection, "createProtocolConnection");
exports2.createProtocolConnection = createProtocolConnection;
}
});
var lib_exports = {};
__export(lib_exports, {
AbstractAstReflection: /* @__PURE__ */ __name(() => AbstractAstReflection, "AbstractAstReflection"),
AbstractCstNode: /* @__PURE__ */ __name(() => AbstractCstNode, "AbstractCstNode"),
AbstractLangiumParser: /* @__PURE__ */ __name(() => AbstractLangiumParser, "AbstractLangiumParser"),
AbstractParserErrorMessageProvider: /* @__PURE__ */ __name(() => AbstractParserErrorMessageProvider, "AbstractParserErrorMessageProvider"),
AbstractThreadedAsyncParser: /* @__PURE__ */ __name(() => AbstractThreadedAsyncParser, "AbstractThreadedAsyncParser"),
AstUtils: /* @__PURE__ */ __name(() => ast_utils_exports, "AstUtils"),
BiMap: /* @__PURE__ */ __name(() => BiMap, "BiMap"),
Cancellation: /* @__PURE__ */ __name(() => cancellation_exports, "Cancellation"),
CompositeCstNodeImpl: /* @__PURE__ */ __name(() => CompositeCstNodeImpl, "CompositeCstNodeImpl"),
ContextCache: /* @__PURE__ */ __name(() => ContextCache, "ContextCache"),
CstNodeBuilder: /* @__PURE__ */ __name(() => CstNodeBuilder, "CstNodeBuilder"),
CstUtils: /* @__PURE__ */ __name(() => cst_utils_exports, "CstUtils"),
DEFAULT_TOKENIZE_OPTIONS: /* @__PURE__ */ __name(() => DEFAULT_TOKENIZE_OPTIONS, "DEFAULT_TOKENIZE_OPTIONS"),
DONE_RESULT: /* @__PURE__ */ __name(() => DONE_RESULT, "DONE_RESULT"),
DatatypeSymbol: /* @__PURE__ */ __name(() => DatatypeSymbol, "DatatypeSymbol"),
DefaultAstNodeDescriptionProvider: /* @__PURE__ */ __name(() => DefaultAstNodeDescriptionProvider, "DefaultAstNodeDescriptionProvider"),
DefaultAstNodeLocator: /* @__PURE__ */ __name(() => DefaultAstNodeLocator, "DefaultAstNodeLocator"),
DefaultAsyncParser: /* @__PURE__ */ __name(() => DefaultAsyncParser, "DefaultAsyncParser"),
DefaultCommentProvider: /* @__PURE__ */ __name(() => DefaultCommentProvider, "DefaultCommentProvider"),
DefaultConfigurationProvider: /* @__PURE__ */ __name(() => DefaultConfigurationProvider, "DefaultConfigurationProvider"),
DefaultDocumentBuilder: /* @__PURE__ */ __name(() => DefaultDocumentBuilder, "DefaultDocumentBuilder"),
DefaultDocumentValidator: /* @__PURE__ */ __name(() => DefaultDocumentValidator, "DefaultDocumentValidator"),
DefaultHydrator: /* @__PURE__ */ __name(() => DefaultHydrator, "DefaultHydrator"),
DefaultIndexManager: /* @__PURE__ */ __name(() => DefaultIndexManager, "DefaultIndexManager"),
DefaultJsonSerializer: /* @__PURE__ */ __name(() => DefaultJsonSerializer, "DefaultJsonSerializer"),
DefaultLangiumDocumentFactory: /* @__PURE__ */ __name(() => DefaultLangiumDocumentFactory, "DefaultLangiumDocumentFactory"),
DefaultLangiumDocuments: /* @__PURE__ */ __name(() => DefaultLangiumDocuments, "DefaultLangiumDocuments"),
DefaultLangiumProfiler: /* @__PURE__ */ __name(() => DefaultLangiumProfiler, "DefaultLangiumProfiler"),
DefaultLexer: /* @__PURE__ */ __name(() => DefaultLexer, "DefaultLexer"),
DefaultLexerErrorMessageProvider: /* @__PURE__ */ __name(() => DefaultLexerErrorMessageProvider, "DefaultLexerErrorMessageProvider"),
DefaultLinker: /* @__PURE__ */ __name(() => DefaultLinker, "DefaultLinker"),
DefaultNameProvider: /* @__PURE__ */ __name(() => DefaultNameProvider, "DefaultNameProvider"),
DefaultReferenceDescriptionProvider: /* @__PURE__ */ __name(() => DefaultReferenceDescriptionProvider, "DefaultReferenceDescriptionProvider"),
DefaultReferences: /* @__PURE__ */ __name(() => DefaultReferences, "DefaultReferences"),
DefaultScopeComputation: /* @__PURE__ */ __name(() => DefaultScopeComputation, "DefaultScopeComputation"),
DefaultScopeProvider: /* @__PURE__ */ __name(() => DefaultScopeProvider, "DefaultScopeProvider"),
DefaultServiceRegistry: /* @__PURE__ */ __name(() => DefaultServiceRegistry, "DefaultServiceRegistry"),
DefaultTokenBuilder: /* @__PURE__ */ __name(() => DefaultTokenBuilder, "DefaultTokenBuilder"),
DefaultValueConverter: /* @__PURE__ */ __name(() => DefaultValueConverter, "DefaultValueConverter"),
DefaultWorkspaceLock: /* @__PURE__ */ __name(() => DefaultWorkspaceLock, "DefaultWorkspaceLock"),
DefaultWorkspaceManager: /* @__PURE__ */ __name(() => DefaultWorkspaceManager, "DefaultWorkspaceManager"),
Deferred: /* @__PURE__ */ __name(() => Deferred, "Deferred"),
Disposable: /* @__PURE__ */ __name(() => Disposable, "Disposable"),
DisposableCache: /* @__PURE__ */ __name(() => DisposableCache, "DisposableCache"),
DocumentCache: /* @__PURE__ */ __name(() => DocumentCache, "DocumentCache"),
DocumentState: /* @__PURE__ */ __name(() => DocumentState, "DocumentState"),
DocumentValidator: /* @__PURE__ */ __name(() => DocumentValidator, "DocumentValidator"),
EMPTY_SCOPE: /* @__PURE__ */ __name(() => EMPTY_SCOPE, "EMPTY_SCOPE"),
EMPTY_STREAM: /* @__PURE__ */ __name(() => EMPTY_STREAM, "EMPTY_STREAM"),
EmptyFileSystem: /* @__PURE__ */ __name(() => EmptyFileSystem, "EmptyFileSystem"),
EmptyFileSystemProvider: /* @__PURE__ */ __name(() => EmptyFileSystemProvider, "EmptyFileSystemProvider"),
ErrorWithLocation: /* @__PURE__ */ __name(() => ErrorWithLocation, "ErrorWithLocation"),
GrammarAST: /* @__PURE__ */ __name(() => ast_exports, "GrammarAST"),
GrammarUtils: /* @__PURE__ */ __name(() => grammar_utils_exports, "GrammarUtils"),
IndentationAwareLexer: /* @__PURE__ */ __name(() => IndentationAwareLexer, "IndentationAwareLexer"),
IndentationAwareTokenBuilder: /* @__PURE__ */ __name(() => IndentationAwareTokenBuilder, "IndentationAwareTokenBuilder"),
JSDocDocumentationProvider: /* @__PURE__ */ __name(() => JSDocDocumentationProvider, "JSDocDocumentationProvider"),
LangiumCompletionParser: /* @__PURE__ */ __name(() => LangiumCompletionParser, "LangiumCompletionParser"),
LangiumParser: /* @__PURE__ */ __name(() => LangiumParser, "LangiumParser"),
LangiumParserErrorMessageProvider: /* @__PURE__ */ __name(() => LangiumParserErrorMessageProvider, "LangiumParserErrorMessageProvider"),
LeafCstNodeImpl: /* @__PURE__ */ __name(() => LeafCstNodeImpl, "LeafCstNodeImpl"),
LexingMode: /* @__PURE__ */ __name(() => LexingMode, "LexingMode"),
MapScope: /* @__PURE__ */ __name(() => MapScope, "MapScope"),
Module: /* @__PURE__ */ __name(() => Module, "Module"),
MultiMap: /* @__PURE__ */ __name(() => MultiMap, "MultiMap"),
MultiMapScope: /* @__PURE__ */ __name(() => MultiMapScope, "MultiMapScope"),
OperationCancelled: /* @__PURE__ */ __name(() => OperationCancelled, "OperationCancelled"),
ParserWorker: /* @__PURE__ */ __name(() => ParserWorker, "ParserWorker"),
ProfilingTask: /* @__PURE__ */ __name(() => ProfilingTask, "ProfilingTask"),
Reduction: /* @__PURE__ */ __name(() => Reduction, "Reduction"),
RefResolving: /* @__PURE__ */ __name(() => RefResolving, "RefResolving"),
RegExpUtils: /* @__PURE__ */ __name(() => regexp_utils_exports, "RegExpUtils"),
RootCstNodeImpl: /* @__PURE__ */ __name(() => RootCstNodeImpl, "RootCstNodeImpl"),
SimpleCache: /* @__PURE__ */ __name(() => SimpleCache, "SimpleCache"),
StreamImpl: /* @__PURE__ */ __name(() => StreamImpl, "StreamImpl"),
StreamScope: /* @__PURE__ */ __name(() => StreamScope, "StreamScope"),
TextDocument: /* @__PURE__ */ __name(() => TextDocument2, "TextDocument"),
TreeStreamImpl: /* @__PURE__ */ __name(() => TreeStreamImpl, "TreeStreamImpl"),
URI: /* @__PURE__ */ __name(() => URI2, "URI"),
UriTrie: /* @__PURE__ */ __name(() => UriTrie, "UriTrie"),
UriUtils: /* @__PURE__ */ __name(() => UriUtils, "UriUtils"),
VALIDATE_EACH_NODE: /* @__PURE__ */ __name(() => VALIDATE_EACH_NODE, "VALIDATE_EACH_NODE"),
ValidationCategory: /* @__PURE__ */ __name(() => ValidationCategory, "ValidationCategory"),
ValidationRegistry: /* @__PURE__ */ __name(() => ValidationRegistry, "ValidationRegistry"),
ValueConverter: /* @__PURE__ */ __name(() => ValueConverter, "ValueConverter"),
WorkspaceCache: /* @__PURE__ */ __name(() => WorkspaceCache, "WorkspaceCache"),
assertCondition: /* @__PURE__ */ __name(() => assertCondition, "assertCondition"),
assertUnreachable: /* @__PURE__ */ __name(() => assertUnreachable, "assertUnreachable"),
createCompletionParser: /* @__PURE__ */ __name(() => createCompletionParser, "createCompletionParser"),
createDefaultCoreModule: /* @__PURE__ */ __name(() => createDefaultCoreModule, "createDefaultCoreModule"),
createDefaultSharedCoreModule: /* @__PURE__ */ __name(() => createDefaultSharedCoreModule, "createDefaultSharedCoreModule"),
createGrammarConfig: /* @__PURE__ */ __name(() => createGrammarConfig, "createGrammarConfig"),
createLangiumParser: /* @__PURE__ */ __name(() => createLangiumParser, "createLangiumParser"),
createParser: /* @__PURE__ */ __name(() => createParser, "createParser"),
delayNextTick: /* @__PURE__ */ __name(() => delayNextTick, "delayNextTick"),
diagnosticData: /* @__PURE__ */ __name(() => diagnosticData, "diagnosticData"),
eagerLoad: /* @__PURE__ */ __name(() => eagerLoad, "eagerLoad"),
getDiagnosticRange: /* @__PURE__ */ __name(() => getDiagnosticRange, "getDiagnosticRange"),
indentationBuilderDefaultOptions: /* @__PURE__ */ __name(() => indentationBuilderDefaultOptions, "indentationBuilderDefaultOptions"),
inject: /* @__PURE__ */ __name(() => inject, "inject"),
interruptAndCheck: /* @__PURE__ */ __name(() => interruptAndCheck, "interruptAndCheck"),
isAstNode: /* @__PURE__ */ __name(() => isAstNode, "isAstNode"),
isAstNodeDescription: /* @__PURE__ */ __name(() => isAstNodeDescription, "isAstNodeDescription"),
isAstNodeWithComment: /* @__PURE__ */ __name(() => isAstNodeWithComment, "isAstNodeWithComment"),
isCompositeCstNode: /* @__PURE__ */ __name(() => isCompositeCstNode, "isCompositeCstNode"),
isIMultiModeLexerDefinition: /* @__PURE__ */ __name(() => isIMultiModeLexerDefinition, "isIMultiModeLexerDefinition"),
isJSDoc: /* @__PURE__ */ __name(() => isJSDoc, "isJSDoc"),
isLeafCstNode: /* @__PURE__ */ __name(() => isLeafCstNode, "isLeafCstNode"),
isLinkingError: /* @__PURE__ */ __name(() => isLinkingError, "isLinkingError"),
isMultiReference: /* @__PURE__ */ __name(() => isMultiReference, "isMultiReference"),
isNamed: /* @__PURE__ */ __name(() => isNamed, "isNamed"),
isOperationCancelled: /* @__PURE__ */ __name(() => isOperationCancelled, "isOperationCancelled"),
isReference: /* @__PURE__ */ __name(() => isReference, "isReference"),
isRootCstNode: /* @__PURE__ */ __name(() => isRootCstNode, "isRootCstNode"),
isTokenTypeArray: /* @__PURE__ */ __name(() => isTokenTypeArray, "isTokenTypeArray"),
isTokenTypeDictionary: /* @__PURE__ */ __name(() => isTokenTypeDictionary, "isTokenTypeDictionary"),
loadGrammarFromJson: /* @__PURE__ */ __name(() => loadGrammarFromJson, "loadGrammarFromJson"),
parseJSDoc: /* @__PURE__ */ __name(() => parseJSDoc, "parseJSDoc"),
prepareLangiumParser: /* @__PURE__ */ __name(() => prepareLangiumParser, "prepareLangiumParser"),
setInterruptionPeriod: /* @__PURE__ */ __name(() => setInterruptionPeriod, "setInterruptionPeriod"),
startCancelableOperation: /* @__PURE__ */ __name(() => startCancelableOperation, "startCancelableOperation"),
stream: /* @__PURE__ */ __name(() => stream, "stream"),
toDiagnosticData: /* @__PURE__ */ __name(() => toDiagnosticData, "toDiagnosticData"),
toDiagnosticSeverity: /* @__PURE__ */ __name(() => toDiagnosticSeverity, "toDiagnosticSeverity")
});
var cst_utils_exports = {};
__export(cst_utils_exports, {
DefaultNameRegexp: /* @__PURE__ */ __name(() => DefaultNameRegexp, "DefaultNameRegexp"),
RangeComparison: /* @__PURE__ */ __name(() => RangeComparison, "RangeComparison"),
compareRange: /* @__PURE__ */ __name(() => compareRange, "compareRange"),
findCommentNode: /* @__PURE__ */ __name(() => findCommentNode, "findCommentNode"),
findDeclarationNodeAtOffset: /* @__PURE__ */ __name(() => findDeclarationNodeAtOffset, "findDeclarationNodeAtOffset"),
findLeafNodeAtOffset: /* @__PURE__ */ __name(() => findLeafNodeAtOffset, "findLeafNodeAtOffset"),
findLeafNodeBeforeOffset: /* @__PURE__ */ __name(() => findLeafNodeBeforeOffset, "findLeafNodeBeforeOffset"),
flattenCst: /* @__PURE__ */ __name(() => flattenCst, "flattenCst"),
getDatatypeNode: /* @__PURE__ */ __name(() => getDatatypeNode, "getDatatypeNode"),
getInteriorNodes: /* @__PURE__ */ __name(() => getInteriorNodes, "getInteriorNodes"),
getNextNode: /* @__PURE__ */ __name(() => getNextNode, "getNextNode"),
getPreviousNode: /* @__PURE__ */ __name(() => getPreviousNode, "getPreviousNode"),
getStartlineNode: /* @__PURE__ */ __name(() => getStartlineNode, "getStartlineNode"),
inRange: /* @__PURE__ */ __name(() => inRange, "inRange"),
isChildNode: /* @__PURE__ */ __name(() => isChildNode, "isChildNode"),
isCommentNode: /* @__PURE__ */ __name(() => isCommentNode, "isCommentNode"),
streamCst: /* @__PURE__ */ __name(() => streamCst, "streamCst"),
toDocumentSegment: /* @__PURE__ */ __name(() => toDocumentSegment, "toDocumentSegment"),
tokenToRange: /* @__PURE__ */ __name(() => tokenToRange, "tokenToRange")
});
function isAstNode(obj) {
return typeof obj === "object" && obj !== null && typeof obj.$type === "string";
}
__name(isAstNode, "isAstNode");
__name2(isAstNode, "isAstNode");
function isReference(obj) {
return typeof obj === "object" && obj !== null && typeof obj.$refText === "string" && "ref" in obj;
}
__name(isReference, "isReference");
__name2(isReference, "isReference");
function isMultiReference(obj) {
return typeof obj === "object" && obj !== null && typeof obj.$refText === "string" && "items" in obj;
}
__name(isMultiReference, "isMultiReference");
__name2(isMultiReference, "isMultiReference");
function isAstNodeDescription(obj) {
return typeof obj === "object" && obj !== null && typeof obj.name === "string" && typeof obj.type === "string" && typeof obj.path === "string";
}
__name(isAstNodeDescription, "isAstNodeDescription");
__name2(isAstNodeDescription, "isAstNodeDescription");
function isLinkingError(obj) {
return typeof obj === "object" && obj !== null && typeof obj.info === "object" && typeof obj.message === "string";
}
__name(isLinkingError, "isLinkingError");
__name2(isLinkingError, "isLinkingError");
var AbstractAstReflection = class {
static {
__name(this, "AbstractAstReflection");
}
static {
__name2(this, "AbstractAstReflection");
}
constructor() {
this.subtypes = {};
this.allSubtypes = {};
}
getAllTypes() {
return Object.keys(this.types);
}
getReferenceType(refInfo) {
const metaData = this.types[refInfo.container.$type];
if (!metaData) {
throw new Error(`Type ${refInfo.container.$type || "undefined"} not found.`);
}
const referenceType = metaData.properties[refInfo.property]?.referenceType;
if (!referenceType) {
throw new Error(`Property ${refInfo.property || "undefined"} of type ${refInfo.container.$type} is not a reference.`);
}
return referenceType;
}
getTypeMetaData(type) {
const result = this.types[type];
if (!result) {
return {
name: type,
properties: {},
superTypes: []
};
}
return result;
}
isInstance(node, type) {
return isAstNode(node) && this.isSubtype(node.$type, type);
}
isSubtype(subtype, supertype) {
if (subtype === supertype) {
return true;
}
let nested = this.subtypes[subtype];
if (!nested) {
nested = this.subtypes[subtype] = {};
}
const existing = nested[supertype];
if (existing !== void 0) {
return existing;
} else {
const metaData = this.types[subtype];
const result = metaData ? metaData.superTypes.some((s) => this.isSubtype(s, supertype)) : false;
nested[supertype] = result;
return result;
}
}
getAllSubTypes(type) {
const existing = this.allSubtypes[type];
if (existing) {
return existing;
} else {
const allTypes = this.getAllTypes();
const types = [];
for (const possibleSubType of allTypes) {
if (this.isSubtype(possibleSubType, type)) {
types.push(possibleSubType);
}
}
this.allSubtypes[type] = types;
return types;
}
}
};
function isCompositeCstNode(node) {
return typeof node === "object" && node !== null && Array.isArray(node.content);
}
__name(isCompositeCstNode, "isCompositeCstNode");
__name2(isCompositeCstNode, "isCompositeCstNode");
function isLeafCstNode(node) {
return typeof node === "object" && node !== null && typeof node.tokenType === "object";
}
__name(isLeafCstNode, "isLeafCstNode");
__name2(isLeafCstNode, "isLeafCstNode");
function isRootCstNode(node) {
return isCompositeCstNode(node) && typeof node.fullText === "string";
}
__name(isRootCstNode, "isRootCstNode");
__name2(isRootCstNode, "isRootCstNode");
var StreamImpl = class _StreamImpl {
static {
__name(this, "_StreamImpl");
}
static {
__name2(this, "StreamImpl");
}
constructor(startFn, nextFn) {
this.startFn = startFn;
this.nextFn = nextFn;
}
iterator() {
const iterator = {
state: this.startFn(),
next: /* @__PURE__ */ __name2(() => this.nextFn(iterator.state), "next"),
[Symbol.iterator]: () => iterator
};
return iterator;
}
[Symbol.iterator]() {
return this.iterator();
}
isEmpty() {
const iterator = this.iterator();
return Boolean(iterator.next().done);
}
count() {
const iterator = this.iterator();
let count = 0;
let next = iterator.next();
while (!next.done) {
count++;
next = iterator.next();
}
return count;
}
toArray() {
const result = [];
const iterator = this.iterator();
let next;
do {
next = iterator.next();
if (next.value !== void 0) {
result.push(next.value);
}
} while (!next.done);
return result;
}
toSet() {
return new Set(this);
}
toMap(keyFn, valueFn) {
const entryStream = this.map((element) => [
keyFn ? keyFn(element) : element,
valueFn ? valueFn(element) : element
]);
return new Map(entryStream);
}
toString() {
return this.join();
}
concat(other) {
return new _StreamImpl(() => ({ first: this.startFn(), firstDone: false, iterator: other[Symbol.iterator]() }), (state) => {
let result;
if (!state.firstDone) {
do {
result = this.nextFn(state.first);
if (!result.done) {
return result;
}
} while (!result.done);
state.firstDone = true;
}
do {
result = state.iterator.next();
if (!result.done) {
return result;
}
} while (!result.done);
return DONE_RESULT;
});
}
join(separator = ",") {
const iterator = this.iterator();
let value = "";
let result;
let addSeparator = false;
do {
result = iterator.next();
if (!result.done) {
if (addSeparator) {
value += separator;
}
value += toString(result.value);
}
addSeparator = true;
} while (!result.done);
return value;
}
indexOf(searchElement, fromIndex = 0) {
const iterator = this.iterator();
let index = 0;
let next = iterator.next();
while (!next.done) {
if (index >= fromIndex && next.value === searchElement) {
return index;
}
next = iterator.next();
index++;
}
return -1;
}
every(predicate) {
const iterator = this.iterator();
let next = iterator.next();
while (!next.done) {
if (!predicate(next.value)) {
return false;
}
next = iterator.next();
}
return true;
}
some(predicate) {
const iterator = this.iterator();
let next = iterator.next();
while (!next.done) {
if (predicate(next.value)) {
return true;
}
next = iterator.next();
}
return false;
}
forEach(callbackfn) {
const iterator = this.iterator();
let index = 0;
let next = iterator.next();
while (!next.done) {
callbackfn(next.value, index);
next = iterator.next();
index++;
}
}
map(callbackfn) {
return new _StreamImpl(this.startFn, (state) => {
const { done, value } = this.nextFn(state);
if (done) {
return DONE_RESULT;
} else {
return { done: false, value: callbackfn(value) };
}
});
}
filter(predicate) {
return new _StreamImpl(this.startFn, (state) => {
let result;
do {
result = this.nextFn(state);
if (!result.done && predicate(result.value)) {
return result;
}
} while (!result.done);
return DONE_RESULT;
});
}
nonNullable() {
return this.filter((e) => e !== void 0 && e !== null);
}
reduce(callbackfn, initialValue) {
const iterator = this.iterator();
let previousValue = initialValue;
let next = iterator.next();
while (!next.done) {
if (previousValue === void 0) {
previousValue = next.value;
} else {
previousValue = callbackfn(previousValue, next.value);
}
next = iterator.next();
}
return previousValue;
}
reduceRight(callbackfn, initialValue) {
return this.recursiveReduce(this.iterator(), callbackfn, initialValue);
}
recursiveReduce(iterator, callbackfn, initialValue) {
const next = iterator.next();
if (next.done) {
return initialValue;
}
const previousValue = this.recursiveReduce(iterator, callbackfn, initialValue);
if (previousValue === void 0) {
return next.value;
}
return callbackfn(previousValue, next.value);
}
find(predicate) {
const iterator = this.iterator();
let next = iterator.next();
while (!next.done) {
if (predicate(next.value)) {
return next.value;
}
next = iterator.next();
}
return void 0;
}
findIndex(predicate) {
const iterator = this.iterator();
let index = 0;
let next = iterator.next();
while (!next.done) {
if (predicate(next.value)) {
return index;
}
next = iterator.next();
index++;
}
return -1;
}
includes(searchElement) {
const iterator = this.iterator();
let next = iterator.next();
while (!next.done) {
if (next.value === searchElement) {
return true;
}
next = iterator.next();
}
return false;
}
flatMap(callbackfn) {
return new _StreamImpl(() => ({ this: this.startFn() }), (state) => {
do {
if (state.iterator) {
const next = state.iterator.next();
if (next.done) {
state.iterator = void 0;
} else {
return next;
}
}
const { done, value } = this.nextFn(state.this);
if (!done) {
const mapped = callbackfn(value);
if (isIterable(mapped)) {
state.iterator = mapped[Symbol.iterator]();
} else {
return { done: false, value: mapped };
}
}
} while (state.iterator);
return DONE_RESULT;
});
}
flat(depth) {
if (depth === void 0) {
depth = 1;
}
if (depth <= 0) {
return this;
}
const stream2 = depth > 1 ? this.flat(depth - 1) : this;
return new _StreamImpl(() => ({ this: stream2.startFn() }), (state) => {
do {
if (state.iterator) {
const next = state.iterator.next();
if (next.done) {
state.iterator = void 0;
} else {
return next;
}
}
const { done, value } = stream2.nextFn(state.this);
if (!done) {
if (isIterable(value)) {
state.iterator = value[Symbol.iterator]();
} else {
return { done: false, value };
}
}
} while (state.iterator);
return DONE_RESULT;
});
}
head() {
const iterator = this.iterator();
const result = iterator.next();
if (result.done) {
return void 0;
}
return result.value;
}
tail(skipCount = 1) {
return new _StreamImpl(() => {
const state = this.startFn();
for (let i = 0; i < skipCount; i++) {
const next = this.nextFn(state);
if (next.done) {
return state;
}
}
return state;
}, this.nextFn);
}
limit(maxSize) {
return new _StreamImpl(() => ({ size: 0, state: this.startFn() }), (state) => {
state.size++;
if (state.size > maxSize) {
return DONE_RESULT;
}
return this.nextFn(state.state);
});
}
distinct(by) {
return new _StreamImpl(() => ({ set: /* @__PURE__ */ new Set(), internalState: this.startFn() }), (state) => {
let result;
do {
result = this.nextFn(state.internalState);
if (!result.done) {
const value = by ? by(result.value) : result.value;
if (!state.set.has(value)) {
state.set.add(value);
return result;
}
}
} while (!result.done);
return DONE_RESULT;
});
}
exclude(other, key) {
const otherKeySet = /* @__PURE__ */ new Set();
for (const item of other) {
const value = key ? key(item) : item;
otherKeySet.add(value);
}
return this.filter((e) => {
const ownKey = key ? key(e) : e;
return !otherKeySet.has(ownKey);
});
}
};
function toString(item) {
if (typeof item === "string") {
return item;
}
if (typeof item === "undefined") {
return "undefined";
}
if (typeof item.toString === "function") {
return item.toString();
}
return Object.prototype.toString.call(item);
}
__name(toString, "toString");
__name2(toString, "toString");
function isIterable(obj) {
return !!obj && typeof obj[Symbol.iterator] === "function";
}
__name(isIterable, "isIterable");
__name2(isIterable, "isIterable");
var EMPTY_STREAM = new StreamImpl(() => void 0, () => DONE_RESULT);
var DONE_RESULT = Object.freeze({ done: true, value: void 0 });
function stream(...collections) {
if (collections.length === 1) {
const collection = collections[0];
if (collection instanceof StreamImpl) {
return collection;
}
if (isIterable(collection)) {
return new StreamImpl(() => collection[Symbol.iterator](), (iterator) => iterator.next());
}
if (typeof collection.length === "number") {
return new StreamImpl(() => ({ index: 0 }), (state) => {
if (state.index < collection.length) {
return { done: false, value: collection[state.index++] };
} else {
return DONE_RESULT;
}
});
}
}
if (collections.length > 1) {
return new StreamImpl(() => ({ collIndex: 0, arrIndex: 0 }), (state) => {
do {
if (state.iterator) {
const next = state.iterator.next();
if (!next.done) {
return next;
}
state.iterator = void 0;
}
if (state.array) {
if (state.arrIndex < state.array.length) {
return { done: false, value: state.array[state.arrIndex++] };
}
state.array = void 0;
state.arrIndex = 0;
}
if (state.collIndex < collections.length) {
const collection = collections[state.collIndex++];
if (isIterable(collection)) {
state.iterator = collection[Symbol.iterator]();
} else if (collection && typeof collection.length === "number") {
state.array = collection;
}
}
} while (state.iterator || state.array || state.collIndex < collections.length);
return DONE_RESULT;
});
}
return EMPTY_STREAM;
}
__name(stream, "stream");
__name2(stream, "stream");
var TreeStreamImpl = class extends StreamImpl {
static {
__name(this, "TreeStreamImpl");
}
static {
__name2(this, "TreeStreamImpl");
}
constructor(root3, children, options) {
super(() => ({
iterators: options?.includeRoot ? [[root3][Symbol.iterator]()] : [children(root3)[Symbol.iterator]()],
pruned: false
}), (state) => {
if (state.pruned) {
state.iterators.pop();
state.pruned = false;
}
while (state.iterators.length > 0) {
const iterator = state.iterators[state.iterators.length - 1];
const next = iterator.next();
if (next.done) {
state.iterators.pop();
} else {
state.iterators.push(children(next.value)[Symbol.iterator]());
return next;
}
}
return DONE_RESULT;
});
}
iterator() {
const iterator = {
state: this.startFn(),
next: /* @__PURE__ */ __name2(() => this.nextFn(iterator.state), "next"),
prune: /* @__PURE__ */ __name2(() => {
iterator.state.pruned = true;
}, "prune"),
[Symbol.iterator]: () => iterator
};
return iterator;
}
};
var Reduction;
(function(Reduction2) {
function sum(stream2) {
return stream2.reduce((a, b) => a + b, 0);
}
__name(sum, "sum");
__name2(sum, "sum");
Reduction2.sum = sum;
function product(stream2) {
return stream2.reduce((a, b) => a * b, 0);
}
__name(product, "product");
__name2(product, "product");
Reduction2.product = product;
function min2(stream2) {
return stream2.reduce((a, b) => Math.min(a, b));
}
__name(min2, "min2");
__name2(min2, "min");
Reduction2.min = min2;
function max(stream2) {
return stream2.reduce((a, b) => Math.max(a, b));
}
__name(max, "max");
__name2(max, "max");
Reduction2.max = max;
})(Reduction || (Reduction = {}));
var ast_utils_exports = {};
__export(ast_utils_exports, {
assignMandatoryProperties: /* @__PURE__ */ __name(() => assignMandatoryProperties, "assignMandatoryProperties"),
copyAstNode: /* @__PURE__ */ __name(() => copyAstNode, "copyAstNode"),
findRootNode: /* @__PURE__ */ __name(() => findRootNode, "findRootNode"),
getContainerOfType: /* @__PURE__ */ __name(() => getContainerOfType, "getContainerOfType"),
getDocument: /* @__PURE__ */ __name(() => getDocument, "getDocument"),
getReferenceNodes: /* @__PURE__ */ __name(() => getReferenceNodes, "getReferenceNodes"),
hasContainerOfType: /* @__PURE__ */ __name(() => hasContainerOfType, "hasContainerOfType"),
linkContentToContainer: /* @__PURE__ */ __name(() => linkContentToContainer, "linkContentToContainer"),
streamAllContents: /* @__PURE__ */ __name(() => streamAllContents, "streamAllContents"),
streamAst: /* @__PURE__ */ __name(() => streamAst, "streamAst"),
streamContents: /* @__PURE__ */ __name(() => streamContents, "streamContents"),
streamReferences: /* @__PURE__ */ __name(() => streamReferences, "streamReferences")
});
function linkContentToContainer(node, options = {}) {
for (const [name, value] of Object.entries(node)) {
if (!name.startsWith("$")) {
if (Array.isArray(value)) {
value.forEach((item, index) => {
if (isAstNode(item)) {
item.$container = node;
item.$containerProperty = name;
item.$containerIndex = index;
if (options.deep) {
linkContentToContainer(item, options);
}
}
});
} else if (isAstNode(value)) {
value.$container = node;
value.$containerProperty = name;
if (options.deep) {
linkContentToContainer(value, options);
}
}
}
}
}
__name(linkContentToContainer, "linkContentToContainer");
__name2(linkContentToContainer, "linkContentToContainer");
function getContainerOfType(node, typePredicate) {
let item = node;
while (item) {
if (typePredicate(item)) {
return item;
}
item = item.$container;
}
return void 0;
}
__name(getContainerOfType, "getContainerOfType");
__name2(getContainerOfType, "getContainerOfType");
function hasContainerOfType(node, predicate) {
let item = node;
while (item) {
if (predicate(item)) {
return true;
}
item = item.$container;
}
return false;
}
__name(hasContainerOfType, "hasContainerOfType");
__name2(hasContainerOfType, "hasContainerOfType");
function getDocument(node) {
const rootNode = findRootNode(node);
const result = rootNode.$document;
if (!result) {
throw new Error("AST node has no document.");
}
return result;
}
__name(getDocument, "getDocument");
__name2(getDocument, "getDocument");
function findRootNode(node) {
while (node.$container) {
node = node.$container;
}
return node;
}
__name(findRootNode, "findRootNode");
__name2(findRootNode, "findRootNode");
function getReferenceNodes(reference) {
if (isReference(reference)) {
return reference.ref ? [reference.ref] : [];
} else if (isMultiReference(reference)) {
return reference.items.map((item) => item.ref);
}
return [];
}
__name(getReferenceNodes, "getReferenceNodes");
__name2(getReferenceNodes, "getReferenceNodes");
function streamContents(node, options) {
if (!node) {
throw new Error("Node must be an AstNode.");
}
const range = options?.range;
return new StreamImpl(() => ({
keys: Object.keys(node),
keyIndex: 0,
arrayIndex: 0
}), (state) => {
while (state.keyIndex < state.keys.length) {
const property3 = state.keys[state.keyIndex];
if (!property3.startsWith("$")) {
const value = node[property3];
if (isAstNode(value)) {
state.keyIndex++;
if (isAstNodeInRange(value, range)) {
return { done: false, value };
}
} else if (Array.isArray(value)) {
while (state.arrayIndex < value.length) {
const index = state.arrayIndex++;
const element = value[index];
if (isAstNode(element) && isAstNodeInRange(element, range)) {
return { done: false, value: element };
}
}
state.arrayIndex = 0;
}
}
state.keyIndex++;
}
return DONE_RESULT;
});
}
__name(streamContents, "streamContents");
__name2(streamContents, "streamContents");
function streamAllContents(root3, options) {
if (!root3) {
throw new Error("Root node must be an AstNode.");
}
return new TreeStreamImpl(root3, (node) => streamContents(node, options));
}
__name(streamAllContents, "streamAllContents");
__name2(streamAllContents, "streamAllContents");
function streamAst(root3, options) {
if (!root3) {
throw new Error("Root node must be an AstNode.");
} else if (options?.range && !isAstNodeInRange(root3, options.range)) {
return new TreeStreamImpl(root3, () => []);
}
return new TreeStreamImpl(root3, (node) => streamContents(node, options), { includeRoot: true });
}
__name(streamAst, "streamAst");
__name2(streamAst, "streamAst");
function isAstNodeInRange(astNode, range) {
if (!range) {
return true;
}
const nodeRange = astNode.$cstNode?.range;
if (!nodeRange) {
return false;
}
return inRange(nodeRange, range);
}
__name(isAstNodeInRange, "isAstNodeInRange");
__name2(isAstNodeInRange, "isAstNodeInRange");
function streamReferences(node) {
return new StreamImpl(() => ({
keys: Object.keys(node),
keyIndex: 0,
arrayIndex: 0
}), (state) => {
while (state.keyIndex < state.keys.length) {
const property3 = state.keys[state.keyIndex];
if (!property3.startsWith("$")) {
const value = node[property3];
if (isReference(value) || isMultiReference(value)) {
state.keyIndex++;
return { done: false, value: { reference: value, container: node, property: property3 } };
} else if (Array.isArray(value)) {
while (state.arrayIndex < value.length) {
const index = state.arrayIndex++;
const element = value[index];
if (isReference(element) || isMultiReference(value)) {
return { done: false, value: { reference: element, container: node, property: property3, index } };
}
}
state.arrayIndex = 0;
}
}
state.keyIndex++;
}
return DONE_RESULT;
});
}
__name(streamReferences, "streamReferences");
__name2(streamReferences, "streamReferences");
function assignMandatoryProperties(reflection3, node) {
const typeMetaData = reflection3.getTypeMetaData(node.$type);
const genericNode = node;
for (const property3 of Object.values(typeMetaData.properties)) {
if (property3.defaultValue !== void 0 && genericNode[property3.name] === void 0) {
genericNode[property3.name] = copyDefaultValue(property3.defaultValue);
}
}
}
__name(assignMandatoryProperties, "assignMandatoryProperties");
__name2(assignMandatoryProperties, "assignMandatoryProperties");
function copyDefaultValue(propertyType) {
if (Array.isArray(propertyType)) {
return [...propertyType.map(copyDefaultValue)];
} else {
return propertyType;
}
}
__name(copyDefaultValue, "copyDefaultValue");
__name2(copyDefaultValue, "copyDefaultValue");
function copyAstNode(node, buildReference, trace) {
const copy = { $type: node.$type };
if (trace) {
trace.set(node, copy);
trace.set(copy, node);
}
for (const [name, value] of Object.entries(node)) {
if (!name.startsWith("$")) {
if (isAstNode(value)) {
copy[name] = copyAstNode(value, buildReference, trace);
} else if (isReference(value)) {
copy[name] = buildReference(copy, name, value.$refNode, value.$refText, value);
} else if (Array.isArray(value)) {
const copiedArray = [];
for (const element of value) {
if (isAstNode(element)) {
copiedArray.push(copyAstNode(element, buildReference, trace));
} else if (isReference(element)) {
copiedArray.push(buildReference(copy, name, element.$refNode, element.$refText, element));
} else {
copiedArray.push(element);
}
}
copy[name] = copiedArray;
} else {
copy[name] = value;
}
}
}
linkContentToContainer(copy, { deep: true });
return copy;
}
__name(copyAstNode, "copyAstNode");
__name2(copyAstNode, "copyAstNode");
var ast_exports = {};
__export(ast_exports, {
AbstractElement: /* @__PURE__ */ __name(() => AbstractElement, "AbstractElement"),
AbstractParserRule: /* @__PURE__ */ __name(() => AbstractParserRule, "AbstractParserRule"),
AbstractRule: /* @__PURE__ */ __name(() => AbstractRule, "AbstractRule"),
AbstractType: /* @__PURE__ */ __name(() => AbstractType, "AbstractType"),
Action: /* @__PURE__ */ __name(() => Action, "Action"),
Alternatives: /* @__PURE__ */ __name(() => Alternatives, "Alternatives"),
ArrayLiteral: /* @__PURE__ */ __name(() => ArrayLiteral, "ArrayLiteral"),
ArrayType: /* @__PURE__ */ __name(() => ArrayType, "ArrayType"),
Assignment: /* @__PURE__ */ __name(() => Assignment, "Assignment"),
BooleanLiteral: /* @__PURE__ */ __name(() => BooleanLiteral, "BooleanLiteral"),
CharacterRange: /* @__PURE__ */ __name(() => CharacterRange, "CharacterRange"),
Condition: /* @__PURE__ */ __name(() => Condition, "Condition"),
Conjunction: /* @__PURE__ */ __name(() => Conjunction, "Conjunction"),
CrossReference: /* @__PURE__ */ __name(() => CrossReference, "CrossReference"),
Disjunction: /* @__PURE__ */ __name(() => Disjunction, "Disjunction"),
EndOfFile: /* @__PURE__ */ __name(() => EndOfFile, "EndOfFile"),
Grammar: /* @__PURE__ */ __name(() => Grammar, "Grammar"),
GrammarImport: /* @__PURE__ */ __name(() => GrammarImport, "GrammarImport"),
Group: /* @__PURE__ */ __name(() => Group, "Group"),
InferredType: /* @__PURE__ */ __name(() => InferredType, "InferredType"),
InfixRule: /* @__PURE__ */ __name(() => InfixRule, "InfixRule"),
InfixRuleOperatorList: /* @__PURE__ */ __name(() => InfixRuleOperatorList, "InfixRuleOperatorList"),
InfixRuleOperators: /* @__PURE__ */ __name(() => InfixRuleOperators, "InfixRuleOperators"),
Interface: /* @__PURE__ */ __name(() => Interface, "Interface"),
Keyword: /* @__PURE__ */ __name(() => Keyword, "Keyword"),
LangiumGrammarAstReflection: /* @__PURE__ */ __name(() => LangiumGrammarAstReflection, "LangiumGrammarAstReflection"),
LangiumGrammarTerminals: /* @__PURE__ */ __name(() => LangiumGrammarTerminals, "LangiumGrammarTerminals"),
NamedArgument: /* @__PURE__ */ __name(() => NamedArgument, "NamedArgument"),
NegatedToken: /* @__PURE__ */ __name(() => NegatedToken, "NegatedToken"),
Negation: /* @__PURE__ */ __name(() => Negation, "Negation"),
NumberLiteral: /* @__PURE__ */ __name(() => NumberLiteral, "NumberLiteral"),
Parameter: /* @__PURE__ */ __name(() => Parameter, "Parameter"),
ParameterReference: /* @__PURE__ */ __name(() => ParameterReference, "ParameterReference"),
ParserRule: /* @__PURE__ */ __name(() => ParserRule, "ParserRule"),
ReferenceType: /* @__PURE__ */ __name(() => ReferenceType, "ReferenceType"),
RegexToken: /* @__PURE__ */ __name(() => RegexToken, "RegexToken"),
ReturnType: /* @__PURE__ */ __name(() => ReturnType, "ReturnType"),
RuleCall: /* @__PURE__ */ __name(() => RuleCall, "RuleCall"),
SimpleType: /* @__PURE__ */ __name(() => SimpleType, "SimpleType"),
StringLiteral: /* @__PURE__ */ __name(() => StringLiteral, "StringLiteral"),
TerminalAlternatives: /* @__PURE__ */ __name(() => TerminalAlternatives, "TerminalAlternatives"),
TerminalElement: /* @__PURE__ */ __name(() => TerminalElement, "TerminalElement"),
TerminalGroup: /* @__PURE__ */ __name(() => TerminalGroup, "TerminalGroup"),
TerminalRule: /* @__PURE__ */ __name(() => TerminalRule, "TerminalRule"),
TerminalRuleCall: /* @__PURE__ */ __name(() => TerminalRuleCall, "TerminalRuleCall"),
Type: /* @__PURE__ */ __name(() => Type, "Type"),
TypeAttribute: /* @__PURE__ */ __name(() => TypeAttribute, "TypeAttribute"),
TypeDefinition: /* @__PURE__ */ __name(() => TypeDefinition, "TypeDefinition"),
UnionType: /* @__PURE__ */ __name(() => UnionType, "UnionType"),
UnorderedGroup: /* @__PURE__ */ __name(() => UnorderedGroup, "UnorderedGroup"),
UntilToken: /* @__PURE__ */ __name(() => UntilToken, "UntilToken"),
ValueLiteral: /* @__PURE__ */ __name(() => ValueLiteral, "ValueLiteral"),
Wildcard: /* @__PURE__ */ __name(() => Wildcard, "Wildcard"),
isAbstractElement: /* @__PURE__ */ __name(() => isAbstractElement, "isAbstractElement"),
isAbstractParserRule: /* @__PURE__ */ __name(() => isAbstractParserRule, "isAbstractParserRule"),
isAbstractRule: /* @__PURE__ */ __name(() => isAbstractRule, "isAbstractRule"),
isAbstractType: /* @__PURE__ */ __name(() => isAbstractType, "isAbstractType"),
isAction: /* @__PURE__ */ __name(() => isAction, "isAction"),
isAlternatives: /* @__PURE__ */ __name(() => isAlternatives, "isAlternatives"),
isArrayLiteral: /* @__PURE__ */ __name(() => isArrayLiteral, "isArrayLiteral"),
isArrayType: /* @__PURE__ */ __name(() => isArrayType, "isArrayType"),
isAssignment: /* @__PURE__ */ __name(() => isAssignment, "isAssignment"),
isBooleanLiteral: /* @__PURE__ */ __name(() => isBooleanLiteral, "isBooleanLiteral"),
isCharacterRange: /* @__PURE__ */ __name(() => isCharacterRange, "isCharacterRange"),
isCondition: /* @__PURE__ */ __name(() => isCondition, "isCondition"),
isConjunction: /* @__PURE__ */ __name(() => isConjunction, "isConjunction"),
isCrossReference: /* @__PURE__ */ __name(() => isCrossReference, "isCrossReference"),
isDisjunction: /* @__PURE__ */ __name(() => isDisjunction, "isDisjunction"),
isEndOfFile: /* @__PURE__ */ __name(() => isEndOfFile, "isEndOfFile"),
isGrammar: /* @__PURE__ */ __name(() => isGrammar, "isGrammar"),
isGrammarImport: /* @__PURE__ */ __name(() => isGrammarImport, "isGrammarImport"),
isGroup: /* @__PURE__ */ __name(() => isGroup, "isGroup"),
isInferredType: /* @__PURE__ */ __name(() => isInferredType, "isInferredType"),
isInfixRule: /* @__PURE__ */ __name(() => isInfixRule, "isInfixRule"),
isInfixRuleOperatorList: /* @__PURE__ */ __name(() => isInfixRuleOperatorList, "isInfixRuleOperatorList"),
isInfixRuleOperators: /* @__PURE__ */ __name(() => isInfixRuleOperators, "isInfixRuleOperators"),
isInterface: /* @__PURE__ */ __name(() => isInterface, "isInterface"),
isKeyword: /* @__PURE__ */ __name(() => isKeyword, "isKeyword"),
isNamedArgument: /* @__PURE__ */ __name(() => isNamedArgument, "isNamedArgument"),
isNegatedToken: /* @__PURE__ */ __name(() => isNegatedToken, "isNegatedToken"),
isNegation: /* @__PURE__ */ __name(() => isNegation, "isNegation"),
isNumberLiteral: /* @__PURE__ */ __name(() => isNumberLiteral, "isNumberLiteral"),
isParameter: /* @__PURE__ */ __name(() => isParameter, "isParameter"),
isParameterReference: /* @__PURE__ */ __name(() => isParameterReference, "isParameterReference"),
isParserRule: /* @__PURE__ */ __name(() => isParserRule, "isParserRule"),
isReferenceType: /* @__PURE__ */ __name(() => isReferenceType, "isReferenceType"),
isRegexToken: /* @__PURE__ */ __name(() => isRegexToken, "isRegexToken"),
isReturnType: /* @__PURE__ */ __name(() => isReturnType, "isReturnType"),
isRuleCall: /* @__PURE__ */ __name(() => isRuleCall, "isRuleCall"),
isSimpleType: /* @__PURE__ */ __name(() => isSimpleType, "isSimpleType"),
isStringLiteral: /* @__PURE__ */ __name(() => isStringLiteral, "isStringLiteral"),
isTerminalAlternatives: /* @__PURE__ */ __name(() => isTerminalAlternatives, "isTerminalAlternatives"),
isTerminalElement: /* @__PURE__ */ __name(() => isTerminalElement, "isTerminalElement"),
isTerminalGroup: /* @__PURE__ */ __name(() => isTerminalGroup, "isTerminalGroup"),
isTerminalRule: /* @__PURE__ */ __name(() => isTerminalRule, "isTerminalRule"),
isTerminalRuleCall: /* @__PURE__ */ __name(() => isTerminalRuleCall, "isTerminalRuleCall"),
isType: /* @__PURE__ */ __name(() => isType, "isType"),
isTypeAttribute: /* @__PURE__ */ __name(() => isTypeAttribute, "isTypeAttribute"),
isTypeDefinition: /* @__PURE__ */ __name(() => isTypeDefinition, "isTypeDefinition"),
isUnionType: /* @__PURE__ */ __name(() => isUnionType, "isUnionType"),
isUnorderedGroup: /* @__PURE__ */ __name(() => isUnorderedGroup, "isUnorderedGroup"),
isUntilToken: /* @__PURE__ */ __name(() => isUntilToken, "isUntilToken"),
isValueLiteral: /* @__PURE__ */ __name(() => isValueLiteral, "isValueLiteral"),
isWildcard: /* @__PURE__ */ __name(() => isWildcard, "isWildcard"),
reflection: /* @__PURE__ */ __name(() => reflection, "reflection")
});
var LangiumGrammarTerminals = {
ID: /\^?[_a-zA-Z][\w_]*/,
STRING: /"(\\.|[^"\\])*"|'(\\.|[^'\\])*'/,
NUMBER: /NaN|-?((\d*\.\d+|\d+)([Ee][+-]?\d+)?|Infinity)/,
RegexLiteral: /\/(?![*+?])(?:[^\r\n\[/\\]|\\.|\[(?:[^\r\n\]\\]|\\.)*\])+\/[a-z]*/,
WS: /\s+/,
ML_COMMENT: /\/\*[\s\S]*?\*\//,
SL_COMMENT: /\/\/[^\n\r]*/
};
var AbstractElement = {
$type: "AbstractElement",
cardinality: "cardinality"
};
function isAbstractElement(item) {
return reflection.isInstance(item, AbstractElement.$type);
}
__name(isAbstractElement, "isAbstractElement");
__name2(isAbstractElement, "isAbstractElement");
var AbstractParserRule = {
$type: "AbstractParserRule"
};
function isAbstractParserRule(item) {
return reflection.isInstance(item, AbstractParserRule.$type);
}
__name(isAbstractParserRule, "isAbstractParserRule");
__name2(isAbstractParserRule, "isAbstractParserRule");
var AbstractRule = {
$type: "AbstractRule"
};
function isAbstractRule(item) {
return reflection.isInstance(item, AbstractRule.$type);
}
__name(isAbstractRule, "isAbstractRule");
__name2(isAbstractRule, "isAbstractRule");
var AbstractType = {
$type: "AbstractType"
};
function isAbstractType(item) {
return reflection.isInstance(item, AbstractType.$type);
}
__name(isAbstractType, "isAbstractType");
__name2(isAbstractType, "isAbstractType");
var Action = {
$type: "Action",
cardinality: "cardinality",
feature: "feature",
inferredType: "inferredType",
operator: "operator",
type: "type"
};
function isAction(item) {
return reflection.isInstance(item, Action.$type);
}
__name(isAction, "isAction");
__name2(isAction, "isAction");
var Alternatives = {
$type: "Alternatives",
cardinality: "cardinality",
elements: "elements"
};
function isAlternatives(item) {
return reflection.isInstance(item, Alternatives.$type);
}
__name(isAlternatives, "isAlternatives");
__name2(isAlternatives, "isAlternatives");
var ArrayLiteral = {
$type: "ArrayLiteral",
elements: "elements"
};
function isArrayLiteral(item) {
return reflection.isInstance(item, ArrayLiteral.$type);
}
__name(isArrayLiteral, "isArrayLiteral");
__name2(isArrayLiteral, "isArrayLiteral");
var ArrayType = {
$type: "ArrayType",
elementType: "elementType"
};
function isArrayType(item) {
return reflection.isInstance(item, ArrayType.$type);
}
__name(isArrayType, "isArrayType");
__name2(isArrayType, "isArrayType");
var Assignment = {
$type: "Assignment",
cardinality: "cardinality",
feature: "feature",
operator: "operator",
predicate: "predicate",
terminal: "terminal"
};
function isAssignment(item) {
return reflection.isInstance(item, Assignment.$type);
}
__name(isAssignment, "isAssignment");
__name2(isAssignment, "isAssignment");
var BooleanLiteral = {
$type: "BooleanLiteral",
true: "true"
};
function isBooleanLiteral(item) {
return reflection.isInstance(item, BooleanLiteral.$type);
}
__name(isBooleanLiteral, "isBooleanLiteral");
__name2(isBooleanLiteral, "isBooleanLiteral");
var CharacterRange = {
$type: "CharacterRange",
cardinality: "cardinality",
left: "left",
lookahead: "lookahead",
parenthesized: "parenthesized",
right: "right"
};
function isCharacterRange(item) {
return reflection.isInstance(item, CharacterRange.$type);
}
__name(isCharacterRange, "isCharacterRange");
__name2(isCharacterRange, "isCharacterRange");
var Condition = {
$type: "Condition"
};
function isCondition(item) {
return reflection.isInstance(item, Condition.$type);
}
__name(isCondition, "isCondition");
__name2(isCondition, "isCondition");
var Conjunction = {
$type: "Conjunction",
left: "left",
right: "right"
};
function isConjunction(item) {
return reflection.isInstance(item, Conjunction.$type);
}
__name(isConjunction, "isConjunction");
__name2(isConjunction, "isConjunction");
var CrossReference = {
$type: "CrossReference",
cardinality: "cardinality",
deprecatedSyntax: "deprecatedSyntax",
isMulti: "isMulti",
terminal: "terminal",
type: "type"
};
function isCrossReference(item) {
return reflection.isInstance(item, CrossReference.$type);
}
__name(isCrossReference, "isCrossReference");
__name2(isCrossReference, "isCrossReference");
var Disjunction = {
$type: "Disjunction",
left: "left",
right: "right"
};
function isDisjunction(item) {
return reflection.isInstance(item, Disjunction.$type);
}
__name(isDisjunction, "isDisjunction");
__name2(isDisjunction, "isDisjunction");
var EndOfFile = {
$type: "EndOfFile",
cardinality: "cardinality"
};
function isEndOfFile(item) {
return reflection.isInstance(item, EndOfFile.$type);
}
__name(isEndOfFile, "isEndOfFile");
__name2(isEndOfFile, "isEndOfFile");
var Grammar = {
$type: "Grammar",
imports: "imports",
interfaces: "interfaces",
isDeclared: "isDeclared",
name: "name",
rules: "rules",
types: "types"
};
function isGrammar(item) {
return reflection.isInstance(item, Grammar.$type);
}
__name(isGrammar, "isGrammar");
__name2(isGrammar, "isGrammar");
var GrammarImport = {
$type: "GrammarImport",
path: "path"
};
function isGrammarImport(item) {
return reflection.isInstance(item, GrammarImport.$type);
}
__name(isGrammarImport, "isGrammarImport");
__name2(isGrammarImport, "isGrammarImport");
var Group = {
$type: "Group",
cardinality: "cardinality",
elements: "elements",
guardCondition: "guardCondition",
predicate: "predicate"
};
function isGroup(item) {
return reflection.isInstance(item, Group.$type);
}
__name(isGroup, "isGroup");
__name2(isGroup, "isGroup");
var InferredType = {
$type: "InferredType",
name: "name"
};
function isInferredType(item) {
return reflection.isInstance(item, InferredType.$type);
}
__name(isInferredType, "isInferredType");
__name2(isInferredType, "isInferredType");
var InfixRule = {
$type: "InfixRule",
call: "call",
dataType: "dataType",
inferredType: "inferredType",
name: "name",
operators: "operators",
parameters: "parameters",
returnType: "returnType"
};
function isInfixRule(item) {
return reflection.isInstance(item, InfixRule.$type);
}
__name(isInfixRule, "isInfixRule");
__name2(isInfixRule, "isInfixRule");
var InfixRuleOperatorList = {
$type: "InfixRuleOperatorList",
associativity: "associativity",
operators: "operators"
};
function isInfixRuleOperatorList(item) {
return reflection.isInstance(item, InfixRuleOperatorList.$type);
}
__name(isInfixRuleOperatorList, "isInfixRuleOperatorList");
__name2(isInfixRuleOperatorList, "isInfixRuleOperatorList");
var InfixRuleOperators = {
$type: "InfixRuleOperators",
precedences: "precedences"
};
function isInfixRuleOperators(item) {
return reflection.isInstance(item, InfixRuleOperators.$type);
}
__name(isInfixRuleOperators, "isInfixRuleOperators");
__name2(isInfixRuleOperators, "isInfixRuleOperators");
var Interface = {
$type: "Interface",
attributes: "attributes",
name: "name",
superTypes: "superTypes"
};
function isInterface(item) {
return reflection.isInstance(item, Interface.$type);
}
__name(isInterface, "isInterface");
__name2(isInterface, "isInterface");
var Keyword = {
$type: "Keyword",
cardinality: "cardinality",
predicate: "predicate",
value: "value"
};
function isKeyword(item) {
return reflection.isInstance(item, Keyword.$type);
}
__name(isKeyword, "isKeyword");
__name2(isKeyword, "isKeyword");
var NamedArgument = {
$type: "NamedArgument",
calledByName: "calledByName",
parameter: "parameter",
value: "value"
};
function isNamedArgument(item) {
return reflection.isInstance(item, NamedArgument.$type);
}
__name(isNamedArgument, "isNamedArgument");
__name2(isNamedArgument, "isNamedArgument");
var NegatedToken = {
$type: "NegatedToken",
cardinality: "cardinality",
lookahead: "lookahead",
parenthesized: "parenthesized",
terminal: "terminal"
};
function isNegatedToken(item) {
return reflection.isInstance(item, NegatedToken.$type);
}
__name(isNegatedToken, "isNegatedToken");
__name2(isNegatedToken, "isNegatedToken");
var Negation = {
$type: "Negation",
value: "value"
};
function isNegation(item) {
return reflection.isInstance(item, Negation.$type);
}
__name(isNegation, "isNegation");
__name2(isNegation, "isNegation");
var NumberLiteral = {
$type: "NumberLiteral",
value: "value"
};
function isNumberLiteral(item) {
return reflection.isInstance(item, NumberLiteral.$type);
}
__name(isNumberLiteral, "isNumberLiteral");
__name2(isNumberLiteral, "isNumberLiteral");
var Parameter = {
$type: "Parameter",
name: "name"
};
function isParameter(item) {
return reflection.isInstance(item, Parameter.$type);
}
__name(isParameter, "isParameter");
__name2(isParameter, "isParameter");
var ParameterReference = {
$type: "ParameterReference",
parameter: "parameter"
};
function isParameterReference(item) {
return reflection.isInstance(item, ParameterReference.$type);
}
__name(isParameterReference, "isParameterReference");
__name2(isParameterReference, "isParameterReference");
var ParserRule = {
$type: "ParserRule",
dataType: "dataType",
definition: "definition",
entry: "entry",
fragment: "fragment",
inferredType: "inferredType",
name: "name",
parameters: "parameters",
returnType: "returnType"
};
function isParserRule(item) {
return reflection.isInstance(item, ParserRule.$type);
}
__name(isParserRule, "isParserRule");
__name2(isParserRule, "isParserRule");
var ReferenceType = {
$type: "ReferenceType",
isMulti: "isMulti",
referenceType: "referenceType"
};
function isReferenceType(item) {
return reflection.isInstance(item, ReferenceType.$type);
}
__name(isReferenceType, "isReferenceType");
__name2(isReferenceType, "isReferenceType");
var RegexToken = {
$type: "RegexToken",
cardinality: "cardinality",
lookahead: "lookahead",
parenthesized: "parenthesized",
regex: "regex"
};
function isRegexToken(item) {
return reflection.isInstance(item, RegexToken.$type);
}
__name(isRegexToken, "isRegexToken");
__name2(isRegexToken, "isRegexToken");
var ReturnType = {
$type: "ReturnType",
name: "name"
};
function isReturnType(item) {
return reflection.isInstance(item, ReturnType.$type);
}
__name(isReturnType, "isReturnType");
__name2(isReturnType, "isReturnType");
var RuleCall = {
$type: "RuleCall",
arguments: "arguments",
cardinality: "cardinality",
predicate: "predicate",
rule: "rule"
};
function isRuleCall(item) {
return reflection.isInstance(item, RuleCall.$type);
}
__name(isRuleCall, "isRuleCall");
__name2(isRuleCall, "isRuleCall");
var SimpleType = {
$type: "SimpleType",
primitiveType: "primitiveType",
stringType: "stringType",
typeRef: "typeRef"
};
function isSimpleType(item) {
return reflection.isInstance(item, SimpleType.$type);
}
__name(isSimpleType, "isSimpleType");
__name2(isSimpleType, "isSimpleType");
var StringLiteral = {
$type: "StringLiteral",
value: "value"
};
function isStringLiteral(item) {
return reflection.isInstance(item, StringLiteral.$type);
}
__name(isStringLiteral, "isStringLiteral");
__name2(isStringLiteral, "isStringLiteral");
var TerminalAlternatives = {
$type: "TerminalAlternatives",
cardinality: "cardinality",
elements: "elements",
lookahead: "lookahead",
parenthesized: "parenthesized"
};
function isTerminalAlternatives(item) {
return reflection.isInstance(item, TerminalAlternatives.$type);
}
__name(isTerminalAlternatives, "isTerminalAlternatives");
__name2(isTerminalAlternatives, "isTerminalAlternatives");
var TerminalElement = {
$type: "TerminalElement",
cardinality: "cardinality",
lookahead: "lookahead",
parenthesized: "parenthesized"
};
function isTerminalElement(item) {
return reflection.isInstance(item, TerminalElement.$type);
}
__name(isTerminalElement, "isTerminalElement");
__name2(isTerminalElement, "isTerminalElement");
var TerminalGroup = {
$type: "TerminalGroup",
cardinality: "cardinality",
elements: "elements",
lookahead: "lookahead",
parenthesized: "parenthesized"
};
function isTerminalGroup(item) {
return reflection.isInstance(item, TerminalGroup.$type);
}
__name(isTerminalGroup, "isTerminalGroup");
__name2(isTerminalGroup, "isTerminalGroup");
var TerminalRule = {
$type: "TerminalRule",
definition: "definition",
fragment: "fragment",
hidden: "hidden",
name: "name",
type: "type"
};
function isTerminalRule(item) {
return reflection.isInstance(item, TerminalRule.$type);
}
__name(isTerminalRule, "isTerminalRule");
__name2(isTerminalRule, "isTerminalRule");
var TerminalRuleCall = {
$type: "TerminalRuleCall",
cardinality: "cardinality",
lookahead: "lookahead",
parenthesized: "parenthesized",
rule: "rule"
};
function isTerminalRuleCall(item) {
return reflection.isInstance(item, TerminalRuleCall.$type);
}
__name(isTerminalRuleCall, "isTerminalRuleCall");
__name2(isTerminalRuleCall, "isTerminalRuleCall");
var Type = {
$type: "Type",
name: "name",
type: "type"
};
function isType(item) {
return reflection.isInstance(item, Type.$type);
}
__name(isType, "isType");
__name2(isType, "isType");
var TypeAttribute = {
$type: "TypeAttribute",
defaultValue: "defaultValue",
isOptional: "isOptional",
name: "name",
type: "type"
};
function isTypeAttribute(item) {
return reflection.isInstance(item, TypeAttribute.$type);
}
__name(isTypeAttribute, "isTypeAttribute");
__name2(isTypeAttribute, "isTypeAttribute");
var TypeDefinition = {
$type: "TypeDefinition"
};
function isTypeDefinition(item) {
return reflection.isInstance(item, TypeDefinition.$type);
}
__name(isTypeDefinition, "isTypeDefinition");
__name2(isTypeDefinition, "isTypeDefinition");
var UnionType = {
$type: "UnionType",
types: "types"
};
function isUnionType(item) {
return reflection.isInstance(item, UnionType.$type);
}
__name(isUnionType, "isUnionType");
__name2(isUnionType, "isUnionType");
var UnorderedGroup = {
$type: "UnorderedGroup",
cardinality: "cardinality",
elements: "elements"
};
function isUnorderedGroup(item) {
return reflection.isInstance(item, UnorderedGroup.$type);
}
__name(isUnorderedGroup, "isUnorderedGroup");
__name2(isUnorderedGroup, "isUnorderedGroup");
var UntilToken = {
$type: "UntilToken",
cardinality: "cardinality",
lookahead: "lookahead",
parenthesized: "parenthesized",
terminal: "terminal"
};
function isUntilToken(item) {
return reflection.isInstance(item, UntilToken.$type);
}
__name(isUntilToken, "isUntilToken");
__name2(isUntilToken, "isUntilToken");
var ValueLiteral = {
$type: "ValueLiteral"
};
function isValueLiteral(item) {
return reflection.isInstance(item, ValueLiteral.$type);
}
__name(isValueLiteral, "isValueLiteral");
__name2(isValueLiteral, "isValueLiteral");
var Wildcard = {
$type: "Wildcard",
cardinality: "cardinality",
lookahead: "lookahead",
parenthesized: "parenthesized"
};
function isWildcard(item) {
return reflection.isInstance(item, Wildcard.$type);
}
__name(isWildcard, "isWildcard");
__name2(isWildcard, "isWildcard");
var LangiumGrammarAstReflection = class extends AbstractAstReflection {
static {
__name(this, "LangiumGrammarAstReflection");
}
static {
__name2(this, "LangiumGrammarAstReflection");
}
constructor() {
super(...arguments);
this.types = {
AbstractElement: {
name: AbstractElement.$type,
properties: {
cardinality: {
name: AbstractElement.cardinality
}
},
superTypes: []
},
AbstractParserRule: {
name: AbstractParserRule.$type,
properties: {},
superTypes: [AbstractRule.$type, AbstractType.$type]
},
AbstractRule: {
name: AbstractRule.$type,
properties: {},
superTypes: []
},
AbstractType: {
name: AbstractType.$type,
properties: {},
superTypes: []
},
Action: {
name: Action.$type,
properties: {
cardinality: {
name: Action.cardinality
},
feature: {
name: Action.feature
},
inferredType: {
name: Action.inferredType
},
operator: {
name: Action.operator
},
type: {
name: Action.type,
referenceType: AbstractType.$type
}
},
superTypes: [AbstractElement.$type]
},
Alternatives: {
name: Alternatives.$type,
properties: {
cardinality: {
name: Alternatives.cardinality
},
elements: {
name: Alternatives.elements,
defaultValue: []
}
},
superTypes: [AbstractElement.$type]
},
ArrayLiteral: {
name: ArrayLiteral.$type,
properties: {
elements: {
name: ArrayLiteral.elements,
defaultValue: []
}
},
superTypes: [ValueLiteral.$type]
},
ArrayType: {
name: ArrayType.$type,
properties: {
elementType: {
name: ArrayType.elementType
}
},
superTypes: [TypeDefinition.$type]
},
Assignment: {
name: Assignment.$type,
properties: {
cardinality: {
name: Assignment.cardinality
},
feature: {
name: Assignment.feature
},
operator: {
name: Assignment.operator
},
predicate: {
name: Assignment.predicate
},
terminal: {
name: Assignment.terminal
}
},
superTypes: [AbstractElement.$type]
},
BooleanLiteral: {
name: BooleanLiteral.$type,
properties: {
true: {
name: BooleanLiteral.true,
defaultValue: false
}
},
superTypes: [Condition.$type, ValueLiteral.$type]
},
CharacterRange: {
name: CharacterRange.$type,
properties: {
cardinality: {
name: CharacterRange.cardinality
},
left: {
name: CharacterRange.left
},
lookahead: {
name: CharacterRange.lookahead
},
parenthesized: {
name: CharacterRange.parenthesized,
defaultValue: false
},
right: {
name: CharacterRange.right
}
},
superTypes: [TerminalElement.$type]
},
Condition: {
name: Condition.$type,
properties: {},
superTypes: []
},
Conjunction: {
name: Conjunction.$type,
properties: {
left: {
name: Conjunction.left
},
right: {
name: Conjunction.right
}
},
superTypes: [Condition.$type]
},
CrossReference: {
name: CrossReference.$type,
properties: {
cardinality: {
name: CrossReference.cardinality
},
deprecatedSyntax: {
name: CrossReference.deprecatedSyntax,
defaultValue: false
},
isMulti: {
name: CrossReference.isMulti,
defaultValue: false
},
terminal: {
name: CrossReference.terminal
},
type: {
name: CrossReference.type,
referenceType: AbstractType.$type
}
},
superTypes: [AbstractElement.$type]
},
Disjunction: {
name: Disjunction.$type,
properties: {
left: {
name: Disjunction.left
},
right: {
name: Disjunction.right
}
},
superTypes: [Condition.$type]
},
EndOfFile: {
name: EndOfFile.$type,
properties: {
cardinality: {
name: EndOfFile.cardinality
}
},
superTypes: [AbstractElement.$type]
},
Grammar: {
name: Grammar.$type,
properties: {
imports: {
name: Grammar.imports,
defaultValue: []
},
interfaces: {
name: Grammar.interfaces,
defaultValue: []
},
isDeclared: {
name: Grammar.isDeclared,
defaultValue: false
},
name: {
name: Grammar.name
},
rules: {
name: Grammar.rules,
defaultValue: []
},
types: {
name: Grammar.types,
defaultValue: []
}
},
superTypes: []
},
GrammarImport: {
name: GrammarImport.$type,
properties: {
path: {
name: GrammarImport.path
}
},
superTypes: []
},
Group: {
name: Group.$type,
properties: {
cardinality: {
name: Group.cardinality
},
elements: {
name: Group.elements,
defaultValue: []
},
guardCondition: {
name: Group.guardCondition
},
predicate: {
name: Group.predicate
}
},
superTypes: [AbstractElement.$type]
},
InferredType: {
name: InferredType.$type,
properties: {
name: {
name: InferredType.name
}
},
superTypes: [AbstractType.$type]
},
InfixRule: {
name: InfixRule.$type,
properties: {
call: {
name: InfixRule.call
},
dataType: {
name: InfixRule.dataType
},
inferredType: {
name: InfixRule.inferredType
},
name: {
name: InfixRule.name
},
operators: {
name: InfixRule.operators
},
parameters: {
name: InfixRule.parameters,
defaultValue: []
},
returnType: {
name: InfixRule.returnType,
referenceType: AbstractType.$type
}
},
superTypes: [AbstractParserRule.$type]
},
InfixRuleOperatorList: {
name: InfixRuleOperatorList.$type,
properties: {
associativity: {
name: InfixRuleOperatorList.associativity
},
operators: {
name: InfixRuleOperatorList.operators,
defaultValue: []
}
},
superTypes: []
},
InfixRuleOperators: {
name: InfixRuleOperators.$type,
properties: {
precedences: {
name: InfixRuleOperators.precedences,
defaultValue: []
}
},
superTypes: []
},
Interface: {
name: Interface.$type,
properties: {
attributes: {
name: Interface.attributes,
defaultValue: []
},
name: {
name: Interface.name
},
superTypes: {
name: Interface.superTypes,
defaultValue: [],
referenceType: AbstractType.$type
}
},
superTypes: [AbstractType.$type]
},
Keyword: {
name: Keyword.$type,
properties: {
cardinality: {
name: Keyword.cardinality
},
predicate: {
name: Keyword.predicate
},
value: {
name: Keyword.value
}
},
superTypes: [AbstractElement.$type]
},
NamedArgument: {
name: NamedArgument.$type,
properties: {
calledByName: {
name: NamedArgument.calledByName,
defaultValue: false
},
parameter: {
name: NamedArgument.parameter,
referenceType: Parameter.$type
},
value: {
name: NamedArgument.value
}
},
superTypes: []
},
NegatedToken: {
name: NegatedToken.$type,
properties: {
cardinality: {
name: NegatedToken.cardinality
},
lookahead: {
name: NegatedToken.lookahead
},
parenthesized: {
name: NegatedToken.parenthesized,
defaultValue: false
},
terminal: {
name: NegatedToken.terminal
}
},
superTypes: [TerminalElement.$type]
},
Negation: {
name: Negation.$type,
properties: {
value: {
name: Negation.value
}
},
superTypes: [Condition.$type]
},
NumberLiteral: {
name: NumberLiteral.$type,
properties: {
value: {
name: NumberLiteral.value
}
},
superTypes: [ValueLiteral.$type]
},
Parameter: {
name: Parameter.$type,
properties: {
name: {
name: Parameter.name
}
},
superTypes: []
},
ParameterReference: {
name: ParameterReference.$type,
properties: {
parameter: {
name: ParameterReference.parameter,
referenceType: Parameter.$type
}
},
superTypes: [Condition.$type]
},
ParserRule: {
name: ParserRule.$type,
properties: {
dataType: {
name: ParserRule.dataType
},
definition: {
name: ParserRule.definition
},
entry: {
name: ParserRule.entry,
defaultValue: false
},
fragment: {
name: ParserRule.fragment,
defaultValue: false
},
inferredType: {
name: ParserRule.inferredType
},
name: {
name: ParserRule.name
},
parameters: {
name: ParserRule.parameters,
defaultValue: []
},
returnType: {
name: ParserRule.returnType,
referenceType: AbstractType.$type
}
},
superTypes: [AbstractParserRule.$type]
},
ReferenceType: {
name: ReferenceType.$type,
properties: {
isMulti: {
name: ReferenceType.isMulti,
defaultValue: false
},
referenceType: {
name: ReferenceType.referenceType
}
},
superTypes: [TypeDefinition.$type]
},
RegexToken: {
name: RegexToken.$type,
properties: {
cardinality: {
name: RegexToken.cardinality
},
lookahead: {
name: RegexToken.lookahead
},
parenthesized: {
name: RegexToken.parenthesized,
defaultValue: false
},
regex: {
name: RegexToken.regex
}
},
superTypes: [TerminalElement.$type]
},
ReturnType: {
name: ReturnType.$type,
properties: {
name: {
name: ReturnType.name
}
},
superTypes: []
},
RuleCall: {
name: RuleCall.$type,
properties: {
arguments: {
name: RuleCall.arguments,
defaultValue: []
},
cardinality: {
name: RuleCall.cardinality
},
predicate: {
name: RuleCall.predicate
},
rule: {
name: RuleCall.rule,
referenceType: AbstractRule.$type
}
},
superTypes: [AbstractElement.$type]
},
SimpleType: {
name: SimpleType.$type,
properties: {
primitiveType: {
name: SimpleType.primitiveType
},
stringType: {
name: SimpleType.stringType
},
typeRef: {
name: SimpleType.typeRef,
referenceType: AbstractType.$type
}
},
superTypes: [TypeDefinition.$type]
},
StringLiteral: {
name: StringLiteral.$type,
properties: {
value: {
name: StringLiteral.value
}
},
superTypes: [ValueLiteral.$type]
},
TerminalAlternatives: {
name: TerminalAlternatives.$type,
properties: {
cardinality: {
name: TerminalAlternatives.cardinality
},
elements: {
name: TerminalAlternatives.elements,
defaultValue: []
},
lookahead: {
name: TerminalAlternatives.lookahead
},
parenthesized: {
name: TerminalAlternatives.parenthesized,
defaultValue: false
}
},
superTypes: [TerminalElement.$type]
},
TerminalElement: {
name: TerminalElement.$type,
properties: {
cardinality: {
name: TerminalElement.cardinality
},
lookahead: {
name: TerminalElement.lookahead
},
parenthesized: {
name: TerminalElement.parenthesized,
defaultValue: false
}
},
superTypes: [AbstractElement.$type]
},
TerminalGroup: {
name: TerminalGroup.$type,
properties: {
cardinality: {
name: TerminalGroup.cardinality
},
elements: {
name: TerminalGroup.elements,
defaultValue: []
},
lookahead: {
name: TerminalGroup.lookahead
},
parenthesized: {
name: TerminalGroup.parenthesized,
defaultValue: false
}
},
superTypes: [TerminalElement.$type]
},
TerminalRule: {
name: TerminalRule.$type,
properties: {
definition: {
name: TerminalRule.definition
},
fragment: {
name: TerminalRule.fragment,
defaultValue: false
},
hidden: {
name: TerminalRule.hidden,
defaultValue: false
},
name: {
name: TerminalRule.name
},
type: {
name: TerminalRule.type
}
},
superTypes: [AbstractRule.$type]
},
TerminalRuleCall: {
name: TerminalRuleCall.$type,
properties: {
cardinality: {
name: TerminalRuleCall.cardinality
},
lookahead: {
name: TerminalRuleCall.lookahead
},
parenthesized: {
name: TerminalRuleCall.parenthesized,
defaultValue: false
},
rule: {
name: TerminalRuleCall.rule,
referenceType: TerminalRule.$type
}
},
superTypes: [TerminalElement.$type]
},
Type: {
name: Type.$type,
properties: {
name: {
name: Type.name
},
type: {
name: Type.type
}
},
superTypes: [AbstractType.$type]
},
TypeAttribute: {
name: TypeAttribute.$type,
properties: {
defaultValue: {
name: TypeAttribute.defaultValue
},
isOptional: {
name: TypeAttribute.isOptional,
defaultValue: false
},
name: {
name: TypeAttribute.name
},
type: {
name: TypeAttribute.type
}
},
superTypes: []
},
TypeDefinition: {
name: TypeDefinition.$type,
properties: {},
superTypes: []
},
UnionType: {
name: UnionType.$type,
properties: {
types: {
name: UnionType.types,
defaultValue: []
}
},
superTypes: [TypeDefinition.$type]
},
UnorderedGroup: {
name: UnorderedGroup.$type,
properties: {
cardinality: {
name: UnorderedGroup.cardinality
},
elements: {
name: UnorderedGroup.elements,
defaultValue: []
}
},
superTypes: [AbstractElement.$type]
},
UntilToken: {
name: UntilToken.$type,
properties: {
cardinality: {
name: UntilToken.cardinality
},
lookahead: {
name: UntilToken.lookahead
},
parenthesized: {
name: UntilToken.parenthesized,
defaultValue: false
},
terminal: {
name: UntilToken.terminal
}
},
superTypes: [TerminalElement.$type]
},
ValueLiteral: {
name: ValueLiteral.$type,
properties: {},
superTypes: []
},
Wildcard: {
name: Wildcard.$type,
properties: {
cardinality: {
name: Wildcard.cardinality
},
lookahead: {
name: Wildcard.lookahead
},
parenthesized: {
name: Wildcard.parenthesized,
defaultValue: false
}
},
superTypes: [TerminalElement.$type]
}
};
}
};
var reflection = new LangiumGrammarAstReflection();
function getDatatypeNode(cstNode) {
let current = cstNode;
let found = false;
while (current) {
const definingRule = getContainerOfType(current.grammarSource, isParserRule);
if (definingRule && definingRule.dataType) {
current = current.container;
found = true;
} else if (found) {
return current;
} else {
return void 0;
}
}
return void 0;
}
__name(getDatatypeNode, "getDatatypeNode");
__name2(getDatatypeNode, "getDatatypeNode");
function streamCst(node) {
return new TreeStreamImpl(node, (element) => {
if (isCompositeCstNode(element)) {
return element.content;
} else {
return [];
}
}, { includeRoot: true });
}
__name(streamCst, "streamCst");
__name2(streamCst, "streamCst");
function flattenCst(node) {
return streamCst(node).filter(isLeafCstNode);
}
__name(flattenCst, "flattenCst");
__name2(flattenCst, "flattenCst");
function isChildNode(child, parent) {
while (child.container) {
child = child.container;
if (child === parent) {
return true;
}
}
return false;
}
__name(isChildNode, "isChildNode");
__name2(isChildNode, "isChildNode");
function tokenToRange(token) {
return {
start: {
character: token.startColumn - 1,
line: token.startLine - 1
},
end: {
character: token.endColumn,
// endColumn uses the correct index
line: token.endLine - 1
}
};
}
__name(tokenToRange, "tokenToRange");
__name2(tokenToRange, "tokenToRange");
function toDocumentSegment(node) {
if (!node) {
return void 0;
}
const { offset, end, range } = node;
return {
range,
offset,
end,
length: end - offset
};
}
__name(toDocumentSegment, "toDocumentSegment");
__name2(toDocumentSegment, "toDocumentSegment");
var RangeComparison;
(function(RangeComparison2) {
RangeComparison2[RangeComparison2["Before"] = 0] = "Before";
RangeComparison2[RangeComparison2["After"] = 1] = "After";
RangeComparison2[RangeComparison2["OverlapFront"] = 2] = "OverlapFront";
RangeComparison2[RangeComparison2["OverlapBack"] = 3] = "OverlapBack";
RangeComparison2[RangeComparison2["Inside"] = 4] = "Inside";
RangeComparison2[RangeComparison2["Outside"] = 5] = "Outside";
})(RangeComparison || (RangeComparison = {}));
function compareRange(range, to) {
if (range.end.line < to.start.line || range.end.line === to.start.line && range.end.character <= to.start.character) {
return RangeComparison.Before;
} else if (range.start.line > to.end.line || range.start.line === to.end.line && range.start.character >= to.end.character) {
return RangeComparison.After;
}
const startInside = range.start.line > to.start.line || range.start.line === to.start.line && range.start.character >= to.start.character;
const endInside = range.end.line < to.end.line || range.end.line === to.end.line && range.end.character <= to.end.character;
if (startInside && endInside) {
return RangeComparison.Inside;
} else if (startInside) {
return RangeComparison.OverlapBack;
} else if (endInside) {
return RangeComparison.OverlapFront;
} else {
return RangeComparison.Outside;
}
}
__name(compareRange, "compareRange");
__name2(compareRange, "compareRange");
function inRange(range, to) {
const comparison = compareRange(range, to);
return comparison > RangeComparison.After;
}
__name(inRange, "inRange");
__name2(inRange, "inRange");
var DefaultNameRegexp = /^[\w\p{L}]$/u;
function findDeclarationNodeAtOffset(cstNode, offset, nameRegexp = DefaultNameRegexp) {
if (cstNode) {
if (offset > 0) {
const localOffset = offset - cstNode.offset;
const textAtOffset = cstNode.text.charAt(localOffset);
if (!nameRegexp.test(textAtOffset)) {
offset--;
}
}
return findLeafNodeAtOffset(cstNode, offset);
}
return void 0;
}
__name(findDeclarationNodeAtOffset, "findDeclarationNodeAtOffset");
__name2(findDeclarationNodeAtOffset, "findDeclarationNodeAtOffset");
function findCommentNode(cstNode, commentNames) {
if (cstNode) {
const previous = getPreviousNode(cstNode, true);
if (previous && isCommentNode(previous, commentNames)) {
return previous;
}
if (isRootCstNode(cstNode)) {
const endIndex = cstNode.content.findIndex((e) => !e.hidden);
for (let i = endIndex - 1; i >= 0; i--) {
const child = cstNode.content[i];
if (isCommentNode(child, commentNames)) {
return child;
}
}
}
}
return void 0;
}
__name(findCommentNode, "findCommentNode");
__name2(findCommentNode, "findCommentNode");
function isCommentNode(cstNode, commentNames) {
return isLeafCstNode(cstNode) && commentNames.includes(cstNode.tokenType.name);
}
__name(isCommentNode, "isCommentNode");
__name2(isCommentNode, "isCommentNode");
function findLeafNodeAtOffset(node, offset) {
if (isLeafCstNode(node)) {
return node;
} else if (isCompositeCstNode(node)) {
const searchResult = binarySearch(node, offset, false);
if (searchResult) {
return findLeafNodeAtOffset(searchResult, offset);
}
}
return void 0;
}
__name(findLeafNodeAtOffset, "findLeafNodeAtOffset");
__name2(findLeafNodeAtOffset, "findLeafNodeAtOffset");
function findLeafNodeBeforeOffset(node, offset) {
if (isLeafCstNode(node)) {
return node;
} else if (isCompositeCstNode(node)) {
const searchResult = binarySearch(node, offset, true);
if (searchResult) {
return findLeafNodeBeforeOffset(searchResult, offset);
}
}
return void 0;
}
__name(findLeafNodeBeforeOffset, "findLeafNodeBeforeOffset");
__name2(findLeafNodeBeforeOffset, "findLeafNodeBeforeOffset");
function binarySearch(node, offset, closest) {
let left = 0;
let right = node.content.length - 1;
let closestNode = void 0;
while (left <= right) {
const middle = Math.floor((left + right) / 2);
const middleNode = node.content[middle];
if (middleNode.offset <= offset && middleNode.end > offset) {
return middleNode;
}
if (middleNode.end <= offset) {
closestNode = closest ? middleNode : void 0;
left = middle + 1;
} else {
right = middle - 1;
}
}
return closestNode;
}
__name(binarySearch, "binarySearch");
__name2(binarySearch, "binarySearch");
function getPreviousNode(node, hidden = true) {
while (node.container) {
const parent = node.container;
let index = parent.content.indexOf(node);
while (index > 0) {
index--;
const previous = parent.content[index];
if (hidden || !previous.hidden) {
return previous;
}
}
node = parent;
}
return void 0;
}
__name(getPreviousNode, "getPreviousNode");
__name2(getPreviousNode, "getPreviousNode");
function getNextNode(node, hidden = true) {
while (node.container) {
const parent = node.container;
let index = parent.content.indexOf(node);
const last2 = parent.content.length - 1;
while (index < last2) {
index++;
const next = parent.content[index];
if (hidden || !next.hidden) {
return next;
}
}
node = parent;
}
return void 0;
}
__name(getNextNode, "getNextNode");
__name2(getNextNode, "getNextNode");
function getStartlineNode(node) {
if (node.range.start.character === 0) {
return node;
}
const line = node.range.start.line;
let last2 = node;
let index;
while (node.container) {
const parent = node.container;
const selfIndex = index ?? parent.content.indexOf(node);
if (selfIndex === 0) {
node = parent;
index = void 0;
} else {
index = selfIndex - 1;
node = parent.content[index];
}
if (node.range.start.line !== line) {
break;
}
last2 = node;
}
return last2;
}
__name(getStartlineNode, "getStartlineNode");
__name2(getStartlineNode, "getStartlineNode");
function getInteriorNodes(start, end) {
const commonParent = getCommonParent(start, end);
if (!commonParent) {
return [];
}
return commonParent.parent.content.slice(commonParent.a + 1, commonParent.b);
}
__name(getInteriorNodes, "getInteriorNodes");
__name2(getInteriorNodes, "getInteriorNodes");
function getCommonParent(a, b) {
const aParents = getParentChain(a);
const bParents = getParentChain(b);
let current;
for (let i = 0; i < aParents.length && i < bParents.length; i++) {
const aParent = aParents[i];
const bParent = bParents[i];
if (aParent.parent === bParent.parent) {
current = {
parent: aParent.parent,
a: aParent.index,
b: bParent.index
};
} else {
break;
}
}
return current;
}
__name(getCommonParent, "getCommonParent");
__name2(getCommonParent, "getCommonParent");
function getParentChain(node) {
const chain = [];
while (node.container) {
const parent = node.container;
const index = parent.content.indexOf(node);
chain.push({
parent,
index
});
node = parent;
}
return chain.reverse();
}
__name(getParentChain, "getParentChain");
__name2(getParentChain, "getParentChain");
var grammar_utils_exports = {};
__export(grammar_utils_exports, {
findAssignment: /* @__PURE__ */ __name(() => findAssignment, "findAssignment"),
findNameAssignment: /* @__PURE__ */ __name(() => findNameAssignment, "findNameAssignment"),
findNodeForKeyword: /* @__PURE__ */ __name(() => findNodeForKeyword, "findNodeForKeyword"),
findNodeForProperty: /* @__PURE__ */ __name(() => findNodeForProperty, "findNodeForProperty"),
findNodesForKeyword: /* @__PURE__ */ __name(() => findNodesForKeyword, "findNodesForKeyword"),
findNodesForKeywordInternal: /* @__PURE__ */ __name(() => findNodesForKeywordInternal, "findNodesForKeywordInternal"),
findNodesForProperty: /* @__PURE__ */ __name(() => findNodesForProperty, "findNodesForProperty"),
getActionAtElement: /* @__PURE__ */ __name(() => getActionAtElement, "getActionAtElement"),
getActionType: /* @__PURE__ */ __name(() => getActionType, "getActionType"),
getAllReachableRules: /* @__PURE__ */ __name(() => getAllReachableRules, "getAllReachableRules"),
getAllRulesUsedForCrossReferences: /* @__PURE__ */ __name(() => getAllRulesUsedForCrossReferences, "getAllRulesUsedForCrossReferences"),
getCrossReferenceTerminal: /* @__PURE__ */ __name(() => getCrossReferenceTerminal, "getCrossReferenceTerminal"),
getEntryRule: /* @__PURE__ */ __name(() => getEntryRule, "getEntryRule"),
getExplicitRuleType: /* @__PURE__ */ __name(() => getExplicitRuleType, "getExplicitRuleType"),
getHiddenRules: /* @__PURE__ */ __name(() => getHiddenRules, "getHiddenRules"),
getRuleType: /* @__PURE__ */ __name(() => getRuleType, "getRuleType"),
getRuleTypeName: /* @__PURE__ */ __name(() => getRuleTypeName, "getRuleTypeName"),
getTypeName: /* @__PURE__ */ __name(() => getTypeName, "getTypeName"),
isArrayCardinality: /* @__PURE__ */ __name(() => isArrayCardinality, "isArrayCardinality"),
isArrayOperator: /* @__PURE__ */ __name(() => isArrayOperator, "isArrayOperator"),
isCommentTerminal: /* @__PURE__ */ __name(() => isCommentTerminal, "isCommentTerminal"),
isDataType: /* @__PURE__ */ __name(() => isDataType, "isDataType"),
isDataTypeRule: /* @__PURE__ */ __name(() => isDataTypeRule, "isDataTypeRule"),
isOptionalCardinality: /* @__PURE__ */ __name(() => isOptionalCardinality, "isOptionalCardinality"),
terminalRegex: /* @__PURE__ */ __name(() => terminalRegex, "terminalRegex")
});
var ErrorWithLocation = class extends Error {
static {
__name(this, "ErrorWithLocation");
}
static {
__name2(this, "ErrorWithLocation");
}
constructor(node, message) {
super(node ? `${message} at ${node.range.start.line}:${node.range.start.character}` : message);
}
};
function assertUnreachable(_, message = "Error: Got unexpected value.") {
throw new Error(message);
}
__name(assertUnreachable, "assertUnreachable");
__name2(assertUnreachable, "assertUnreachable");
function assertCondition(condition, message = "Error: Condition is violated.") {
if (!condition) {
throw new Error(message);
}
}
__name(assertCondition, "assertCondition");
__name2(assertCondition, "assertCondition");
var regexp_utils_exports = {};
__export(regexp_utils_exports, {
NEWLINE_REGEXP: /* @__PURE__ */ __name(() => NEWLINE_REGEXP, "NEWLINE_REGEXP"),
escapeRegExp: /* @__PURE__ */ __name(() => escapeRegExp, "escapeRegExp"),
getTerminalParts: /* @__PURE__ */ __name(() => getTerminalParts, "getTerminalParts"),
isMultilineComment: /* @__PURE__ */ __name(() => isMultilineComment, "isMultilineComment"),
isWhitespace: /* @__PURE__ */ __name(() => isWhitespace, "isWhitespace"),
partialMatches: /* @__PURE__ */ __name(() => partialMatches, "partialMatches"),
partialRegExp: /* @__PURE__ */ __name(() => partialRegExp, "partialRegExp"),
whitespaceCharacters: /* @__PURE__ */ __name(() => whitespaceCharacters, "whitespaceCharacters")
});
function cc(char) {
return char.charCodeAt(0);
}
__name(cc, "cc");
__name2(cc, "cc");
function insertToSet(item, set) {
if (Array.isArray(item)) {
item.forEach(function(subItem) {
set.push(subItem);
});
} else {
set.push(item);
}
}
__name(insertToSet, "insertToSet");
__name2(insertToSet, "insertToSet");
function addFlag(flagObj, flagKey) {
if (flagObj[flagKey] === true) {
throw "duplicate flag " + flagKey;
}
const x = flagObj[flagKey];
flagObj[flagKey] = true;
}
__name(addFlag, "addFlag");
__name2(addFlag, "addFlag");
function ASSERT_EXISTS(obj) {
if (obj === void 0) {
throw Error("Internal Error - Should never get here!");
}
return true;
}
__name(ASSERT_EXISTS, "ASSERT_EXISTS");
__name2(ASSERT_EXISTS, "ASSERT_EXISTS");
function ASSERT_NEVER_REACH_HERE() {
throw Error("Internal Error - Should never get here!");
}
__name(ASSERT_NEVER_REACH_HERE, "ASSERT_NEVER_REACH_HERE");
__name2(ASSERT_NEVER_REACH_HERE, "ASSERT_NEVER_REACH_HERE");
function isCharacter(obj) {
return obj["type"] === "Character";
}
__name(isCharacter, "isCharacter");
__name2(isCharacter, "isCharacter");
var digitsCharCodes = [];
for (let i = cc("0"); i <= cc("9"); i++) {
digitsCharCodes.push(i);
}
var wordCharCodes = [cc("_")].concat(digitsCharCodes);
for (let i = cc("a"); i <= cc("z"); i++) {
wordCharCodes.push(i);
}
for (let i = cc("A"); i <= cc("Z"); i++) {
wordCharCodes.push(i);
}
var whitespaceCodes = [
cc(" "),
cc("\f"),
cc("\n"),
cc("\r"),
cc(" "),
cc("\v"),
cc(" "),
cc("\xA0"),
cc("\u1680"),
cc("\u2000"),
cc("\u2001"),
cc("\u2002"),
cc("\u2003"),
cc("\u2004"),
cc("\u2005"),
cc("\u2006"),
cc("\u2007"),
cc("\u2008"),
cc("\u2009"),
cc("\u200A"),
cc("\u2028"),
cc("\u2029"),
cc("\u202F"),
cc("\u205F"),
cc("\u3000"),
cc("\uFEFF")
];
var hexDigitPattern = /[0-9a-fA-F]/;
var decimalPattern = /[0-9]/;
var decimalPatternNoZero = /[1-9]/;
var RegExpParser = class {
static {
__name(this, "RegExpParser");
}
static {
__name2(this, "RegExpParser");
}
constructor() {
this.idx = 0;
this.input = "";
this.groupIdx = 0;
}
saveState() {
return {
idx: this.idx,
input: this.input,
groupIdx: this.groupIdx
};
}
restoreState(newState2) {
this.idx = newState2.idx;
this.input = newState2.input;
this.groupIdx = newState2.groupIdx;
}
pattern(input) {
this.idx = 0;
this.input = input;
this.groupIdx = 0;
this.consumeChar("/");
const value = this.disjunction();
this.consumeChar("/");
const flags = {
type: "Flags",
loc: { begin: this.idx, end: input.length },
global: false,
ignoreCase: false,
multiLine: false,
unicode: false,
sticky: false
};
while (this.isRegExpFlag()) {
switch (this.popChar()) {
case "g":
addFlag(flags, "global");
break;
case "i":
addFlag(flags, "ignoreCase");
break;
case "m":
addFlag(flags, "multiLine");
break;
case "u":
addFlag(flags, "unicode");
break;
case "y":
addFlag(flags, "sticky");
break;
}
}
if (this.idx !== this.input.length) {
throw Error("Redundant input: " + this.input.substring(this.idx));
}
return {
type: "Pattern",
flags,
value,
loc: this.loc(0)
};
}
disjunction() {
const alts = [];
const begin = this.idx;
alts.push(this.alternative());
while (this.peekChar() === "|") {
this.consumeChar("|");
alts.push(this.alternative());
}
return { type: "Disjunction", value: alts, loc: this.loc(begin) };
}
alternative() {
const terms = [];
const begin = this.idx;
while (this.isTerm()) {
terms.push(this.term());
}
return { type: "Alternative", value: terms, loc: this.loc(begin) };
}
term() {
if (this.isAssertion()) {
return this.assertion();
} else {
return this.atom();
}
}
assertion() {
const begin = this.idx;
switch (this.popChar()) {
case "^":
return {
type: "StartAnchor",
loc: this.loc(begin)
};
case "$":
return { type: "EndAnchor", loc: this.loc(begin) };
// '\b' or '\B'
case "\\":
switch (this.popChar()) {
case "b":
return {
type: "WordBoundary",
loc: this.loc(begin)
};
case "B":
return {
type: "NonWordBoundary",
loc: this.loc(begin)
};
}
throw Error("Invalid Assertion Escape");
// '(?=' or '(?!'
case "(":
this.consumeChar("?");
let type;
switch (this.popChar()) {
case "=":
type = "Lookahead";
break;
case "!":
type = "NegativeLookahead";
break;
case "<": {
switch (this.popChar()) {
case "=":
type = "Lookbehind";
break;
case "!":
type = "NegativeLookbehind";
}
break;
}
}
ASSERT_EXISTS(type);
const disjunction = this.disjunction();
this.consumeChar(")");
return {
type,
value: disjunction,
loc: this.loc(begin)
};
}
return ASSERT_NEVER_REACH_HERE();
}
quantifier(isBacktracking = false) {
let range = void 0;
const begin = this.idx;
switch (this.popChar()) {
case "*":
range = {
atLeast: 0,
atMost: Infinity
};
break;
case "+":
range = {
atLeast: 1,
atMost: Infinity
};
break;
case "?":
range = {
atLeast: 0,
atMost: 1
};
break;
case "{":
const atLeast = this.integerIncludingZero();
switch (this.popChar()) {
case "}":
range = {
atLeast,
atMost: atLeast
};
break;
case ",":
let atMost;
if (this.isDigit()) {
atMost = this.integerIncludingZero();
range = {
atLeast,
atMost
};
} else {
range = {
atLeast,
atMost: Infinity
};
}
this.consumeChar("}");
break;
}
if (isBacktracking === true && range === void 0) {
return void 0;
}
ASSERT_EXISTS(range);
break;
}
if (isBacktracking === true && range === void 0) {
return void 0;
}
if (ASSERT_EXISTS(range)) {
if (this.peekChar(0) === "?") {
this.consumeChar("?");
range.greedy = false;
} else {
range.greedy = true;
}
range.type = "Quantifier";
range.loc = this.loc(begin);
return range;
}
}
atom() {
let atom2;
const begin = this.idx;
switch (this.peekChar()) {
case ".":
atom2 = this.dotAll();
break;
case "\\":
atom2 = this.atomEscape();
break;
case "[":
atom2 = this.characterClass();
break;
case "(":
atom2 = this.group();
break;
}
if (atom2 === void 0 && this.isPatternCharacter()) {
atom2 = this.patternCharacter();
}
if (ASSERT_EXISTS(atom2)) {
atom2.loc = this.loc(begin);
if (this.isQuantifier()) {
atom2.quantifier = this.quantifier();
}
return atom2;
}
return ASSERT_NEVER_REACH_HERE();
}
dotAll() {
this.consumeChar(".");
return {
type: "Set",
complement: true,
value: [cc("\n"), cc("\r"), cc("\u2028"), cc("\u2029")]
};
}
atomEscape() {
this.consumeChar("\\");
switch (this.peekChar()) {
case "1":
case "2":
case "3":
case "4":
case "5":
case "6":
case "7":
case "8":
case "9":
return this.decimalEscapeAtom();
case "d":
case "D":
case "s":
case "S":
case "w":
case "W":
return this.characterClassEscape();
case "f":
case "n":
case "r":
case "t":
case "v":
return this.controlEscapeAtom();
case "c":
return this.controlLetterEscapeAtom();
case "0":
return this.nulCharacterAtom();
case "x":
return this.hexEscapeSequenceAtom();
case "u":
return this.regExpUnicodeEscapeSequenceAtom();
default:
return this.identityEscapeAtom();
}
}
decimalEscapeAtom() {
const value = this.positiveInteger();
return { type: "GroupBackReference", value };
}
characterClassEscape() {
let set;
let complement = false;
switch (this.popChar()) {
case "d":
set = digitsCharCodes;
break;
case "D":
set = digitsCharCodes;
complement = true;
break;
case "s":
set = whitespaceCodes;
break;
case "S":
set = whitespaceCodes;
complement = true;
break;
case "w":
set = wordCharCodes;
break;
case "W":
set = wordCharCodes;
complement = true;
break;
}
if (ASSERT_EXISTS(set)) {
return { type: "Set", value: set, complement };
}
return ASSERT_NEVER_REACH_HERE();
}
controlEscapeAtom() {
let escapeCode;
switch (this.popChar()) {
case "f":
escapeCode = cc("\f");
break;
case "n":
escapeCode = cc("\n");
break;
case "r":
escapeCode = cc("\r");
break;
case "t":
escapeCode = cc(" ");
break;
case "v":
escapeCode = cc("\v");
break;
}
if (ASSERT_EXISTS(escapeCode)) {
return { type: "Character", value: escapeCode };
}
return ASSERT_NEVER_REACH_HERE();
}
controlLetterEscapeAtom() {
this.consumeChar("c");
const letter = this.popChar();
if (/[a-zA-Z]/.test(letter) === false) {
throw Error("Invalid ");
}
const letterCode = letter.toUpperCase().charCodeAt(0) - 64;
return { type: "Character", value: letterCode };
}
nulCharacterAtom() {
this.consumeChar("0");
return { type: "Character", value: cc("\0") };
}
hexEscapeSequenceAtom() {
this.consumeChar("x");
return this.parseHexDigits(2);
}
regExpUnicodeEscapeSequenceAtom() {
this.consumeChar("u");
return this.parseHexDigits(4);
}
identityEscapeAtom() {
const escapedChar = this.popChar();
return { type: "Character", value: cc(escapedChar) };
}
classPatternCharacterAtom() {
switch (this.peekChar()) {
// istanbul ignore next
case "\n":
// istanbul ignore next
case "\r":
// istanbul ignore next
case "\u2028":
// istanbul ignore next
case "\u2029":
// istanbul ignore next
case "\\":
// istanbul ignore next
case "]":
throw Error("TBD");
default:
const nextChar = this.popChar();
return { type: "Character", value: cc(nextChar) };
}
}
characterClass() {
const set = [];
let complement = false;
this.consumeChar("[");
if (this.peekChar(0) === "^") {
this.consumeChar("^");
complement = true;
}
while (this.isClassAtom()) {
const from = this.classAtom();
const isFromSingleChar = from.type === "Character";
if (isCharacter(from) && this.isRangeDash()) {
this.consumeChar("-");
const to = this.classAtom();
const isToSingleChar = to.type === "Character";
if (isCharacter(to)) {
if (to.value < from.value) {
throw Error("Range out of order in character class");
}
set.push({ from: from.value, to: to.value });
} else {
insertToSet(from.value, set);
set.push(cc("-"));
insertToSet(to.value, set);
}
} else {
insertToSet(from.value, set);
}
}
this.consumeChar("]");
return { type: "Set", complement, value: set };
}
classAtom() {
switch (this.peekChar()) {
// istanbul ignore next
case "]":
// istanbul ignore next
case "\n":
// istanbul ignore next
case "\r":
// istanbul ignore next
case "\u2028":
// istanbul ignore next
case "\u2029":
throw Error("TBD");
case "\\":
return this.classEscape();
default:
return this.classPatternCharacterAtom();
}
}
classEscape() {
this.consumeChar("\\");
switch (this.peekChar()) {
// Matches a backspace.
// (Not to be confused with \b word boundary outside characterClass)
case "b":
this.consumeChar("b");
return { type: "Character", value: cc("\b") };
case "d":
case "D":
case "s":
case "S":
case "w":
case "W":
return this.characterClassEscape();
case "f":
case "n":
case "r":
case "t":
case "v":
return this.controlEscapeAtom();
case "c":
return this.controlLetterEscapeAtom();
case "0":
return this.nulCharacterAtom();
case "x":
return this.hexEscapeSequenceAtom();
case "u":
return this.regExpUnicodeEscapeSequenceAtom();
default:
return this.identityEscapeAtom();
}
}
group() {
let capturing = true;
this.consumeChar("(");
switch (this.peekChar(0)) {
case "?":
this.consumeChar("?");
this.consumeChar(":");
capturing = false;
break;
default:
this.groupIdx++;
break;
}
const value = this.disjunction();
this.consumeChar(")");
const groupAst = {
type: "Group",
capturing,
value
};
if (capturing) {
groupAst["idx"] = this.groupIdx;
}
return groupAst;
}
positiveInteger() {
let number = this.popChar();
if (decimalPatternNoZero.test(number) === false) {
throw Error("Expecting a positive integer");
}
while (decimalPattern.test(this.peekChar(0))) {
number += this.popChar();
}
return parseInt(number, 10);
}
integerIncludingZero() {
let number = this.popChar();
if (decimalPattern.test(number) === false) {
throw Error("Expecting an integer");
}
while (decimalPattern.test(this.peekChar(0))) {
number += this.popChar();
}
return parseInt(number, 10);
}
patternCharacter() {
const nextChar = this.popChar();
switch (nextChar) {
// istanbul ignore next
case "\n":
// istanbul ignore next
case "\r":
// istanbul ignore next
case "\u2028":
// istanbul ignore next
case "\u2029":
// istanbul ignore next
case "^":
// istanbul ignore next
case "$":
// istanbul ignore next
case "\\":
// istanbul ignore next
case ".":
// istanbul ignore next
case "*":
// istanbul ignore next
case "+":
// istanbul ignore next
case "?":
// istanbul ignore next
case "(":
// istanbul ignore next
case ")":
// istanbul ignore next
case "[":
// istanbul ignore next
case "|":
throw Error("TBD");
default:
return { type: "Character", value: cc(nextChar) };
}
}
isRegExpFlag() {
switch (this.peekChar(0)) {
case "g":
case "i":
case "m":
case "u":
case "y":
return true;
default:
return false;
}
}
isRangeDash() {
return this.peekChar() === "-" && this.isClassAtom(1);
}
isDigit() {
return decimalPattern.test(this.peekChar(0));
}
isClassAtom(howMuch = 0) {
switch (this.peekChar(howMuch)) {
case "]":
case "\n":
case "\r":
case "\u2028":
case "\u2029":
return false;
default:
return true;
}
}
isTerm() {
return this.isAtom() || this.isAssertion();
}
isAtom() {
if (this.isPatternCharacter()) {
return true;
}
switch (this.peekChar(0)) {
case ".":
case "\\":
// atomEscape
case "[":
// characterClass
// TODO: isAtom must be called before isAssertion - disambiguate
case "(":
return true;
default:
return false;
}
}
isAssertion() {
switch (this.peekChar(0)) {
case "^":
case "$":
return true;
// '\b' or '\B'
case "\\":
switch (this.peekChar(1)) {
case "b":
case "B":
return true;
default:
return false;
}
// '(?=' or '(?!' or `(?<=` or `(?<!`
case "(":
return this.peekChar(1) === "?" && (this.peekChar(2) === "=" || this.peekChar(2) === "!" || this.peekChar(2) === "<" && (this.peekChar(3) === "=" || this.peekChar(3) === "!"));
default:
return false;
}
}
isQuantifier() {
const prevState = this.saveState();
try {
return this.quantifier(true) !== void 0;
} catch (e) {
return false;
} finally {
this.restoreState(prevState);
}
}
isPatternCharacter() {
switch (this.peekChar()) {
case "^":
case "$":
case "\\":
case ".":
case "*":
case "+":
case "?":
case "(":
case ")":
case "[":
case "|":
case "/":
case "\n":
case "\r":
case "\u2028":
case "\u2029":
return false;
default:
return true;
}
}
parseHexDigits(howMany) {
let hexString = "";
for (let i = 0; i < howMany; i++) {
const hexChar = this.popChar();
if (hexDigitPattern.test(hexChar) === false) {
throw Error("Expecting a HexDecimal digits");
}
hexString += hexChar;
}
const charCode = parseInt(hexString, 16);
return { type: "Character", value: charCode };
}
peekChar(howMuch = 0) {
return this.input[this.idx + howMuch];
}
popChar() {
const nextChar = this.peekChar(0);
this.consumeChar(void 0);
return nextChar;
}
consumeChar(char) {
if (char !== void 0 && this.input[this.idx] !== char) {
throw Error("Expected: '" + char + "' but found: '" + this.input[this.idx] + "' at offset: " + this.idx);
}
if (this.idx >= this.input.length) {
throw Error("Unexpected end of input");
}
this.idx++;
}
loc(begin) {
return { begin, end: this.idx };
}
};
var BaseRegExpVisitor = class {
static {
__name(this, "BaseRegExpVisitor");
}
static {
__name2(this, "BaseRegExpVisitor");
}
visitChildren(node) {
for (const key in node) {
const child = node[key];
if (node.hasOwnProperty(key)) {
if (child.type !== void 0) {
this.visit(child);
} else if (Array.isArray(child)) {
child.forEach((subChild) => {
this.visit(subChild);
}, this);
}
}
}
}
visit(node) {
switch (node.type) {
case "Pattern":
this.visitPattern(node);
break;
case "Flags":
this.visitFlags(node);
break;
case "Disjunction":
this.visitDisjunction(node);
break;
case "Alternative":
this.visitAlternative(node);
break;
case "StartAnchor":
this.visitStartAnchor(node);
break;
case "EndAnchor":
this.visitEndAnchor(node);
break;
case "WordBoundary":
this.visitWordBoundary(node);
break;
case "NonWordBoundary":
this.visitNonWordBoundary(node);
break;
case "Lookahead":
this.visitLookahead(node);
break;
case "NegativeLookahead":
this.visitNegativeLookahead(node);
break;
case "Lookbehind":
this.visitLookbehind(node);
break;
case "NegativeLookbehind":
this.visitNegativeLookbehind(node);
break;
case "Character":
this.visitCharacter(node);
break;
case "Set":
this.visitSet(node);
break;
case "Group":
this.visitGroup(node);
break;
case "GroupBackReference":
this.visitGroupBackReference(node);
break;
case "Quantifier":
this.visitQuantifier(node);
break;
}
this.visitChildren(node);
}
visitPattern(node) {
}
visitFlags(node) {
}
visitDisjunction(node) {
}
visitAlternative(node) {
}
// Assertion
visitStartAnchor(node) {
}
visitEndAnchor(node) {
}
visitWordBoundary(node) {
}
visitNonWordBoundary(node) {
}
visitLookahead(node) {
}
visitNegativeLookahead(node) {
}
visitLookbehind(node) {
}
visitNegativeLookbehind(node) {
}
// atoms
visitCharacter(node) {
}
visitSet(node) {
}
visitGroup(node) {
}
visitGroupBackReference(node) {
}
visitQuantifier(node) {
}
};
var NEWLINE_REGEXP = /\r?\n/gm;
var regexpParser = new RegExpParser();
var TerminalRegExpVisitor = class extends BaseRegExpVisitor {
static {
__name(this, "TerminalRegExpVisitor");
}
static {
__name2(this, "TerminalRegExpVisitor");
}
constructor() {
super(...arguments);
this.isStarting = true;
this.endRegexpStack = [];
this.multiline = false;
}
get endRegex() {
return this.endRegexpStack.join("");
}
reset(regex) {
this.multiline = false;
this.regex = regex;
this.startRegexp = "";
this.isStarting = true;
this.endRegexpStack = [];
}
visitGroup(node) {
if (node.quantifier) {
this.isStarting = false;
this.endRegexpStack = [];
}
}
visitCharacter(node) {
const char = String.fromCharCode(node.value);
if (!this.multiline && char === "\n") {
this.multiline = true;
}
if (node.quantifier) {
this.isStarting = false;
this.endRegexpStack = [];
} else {
const escapedChar = escapeRegExp(char);
this.endRegexpStack.push(escapedChar);
if (this.isStarting) {
this.startRegexp += escapedChar;
}
}
}
visitSet(node) {
if (!this.multiline) {
const set = this.regex.substring(node.loc.begin, node.loc.end);
const regex = new RegExp(set);
this.multiline = Boolean("\n".match(regex));
}
if (node.quantifier) {
this.isStarting = false;
this.endRegexpStack = [];
} else {
const set = this.regex.substring(node.loc.begin, node.loc.end);
this.endRegexpStack.push(set);
if (this.isStarting) {
this.startRegexp += set;
}
}
}
visitChildren(node) {
if (node.type === "Group") {
const group = node;
if (group.quantifier) {
return;
}
}
super.visitChildren(node);
}
};
var visitor = new TerminalRegExpVisitor();
function getTerminalParts(regexp) {
try {
if (typeof regexp !== "string") {
regexp = regexp.source;
}
regexp = `/${regexp}/`;
const pattern = regexpParser.pattern(regexp);
const parts = [];
for (const alternative of pattern.value.value) {
visitor.reset(regexp);
visitor.visit(alternative);
parts.push({
start: visitor.startRegexp,
end: visitor.endRegex
});
}
return parts;
} catch {
return [];
}
}
__name(getTerminalParts, "getTerminalParts");
__name2(getTerminalParts, "getTerminalParts");
function isMultilineComment(regexp) {
try {
if (typeof regexp === "string") {
regexp = new RegExp(regexp);
}
regexp = regexp.toString();
visitor.reset(regexp);
visitor.visit(regexpParser.pattern(regexp));
return visitor.multiline;
} catch {
return false;
}
}
__name(isMultilineComment, "isMultilineComment");
__name2(isMultilineComment, "isMultilineComment");
var whitespaceCharacters = "\f\n\r \v \xA0\u1680\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200A\u2028\u2029\u202F\u205F\u3000\uFEFF".split("");
function isWhitespace(value) {
const regexp = typeof value === "string" ? new RegExp(value) : value;
return whitespaceCharacters.some((ws) => regexp.test(ws));
}
__name(isWhitespace, "isWhitespace");
__name2(isWhitespace, "isWhitespace");
function escapeRegExp(value) {
return value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
}
__name(escapeRegExp, "escapeRegExp");
__name2(escapeRegExp, "escapeRegExp");
function partialMatches(regex, input) {
const partial = partialRegExp(regex);
const match = input.match(partial);
return !!match && match[0].length > 0;
}
__name(partialMatches, "partialMatches");
__name2(partialMatches, "partialMatches");
function partialRegExp(regex) {
if (typeof regex === "string") {
regex = new RegExp(regex);
}
const re = regex, source = regex.source;
let i = 0;
function process2() {
let result = "", tmp;
function appendRaw(nbChars) {
result += source.substr(i, nbChars);
i += nbChars;
}
__name(appendRaw, "appendRaw");
__name2(appendRaw, "appendRaw");
function appendOptional(nbChars) {
result += "(?:" + source.substr(i, nbChars) + "|$)";
i += nbChars;
}
__name(appendOptional, "appendOptional");
__name2(appendOptional, "appendOptional");
while (i < source.length) {
switch (source[i]) {
case "\\":
switch (source[i + 1]) {
case "c":
appendOptional(3);
break;
case "x":
appendOptional(4);
break;
case "u":
if (re.unicode) {
if (source[i + 2] === "{") {
appendOptional(source.indexOf("}", i) - i + 1);
} else {
appendOptional(6);
}
} else {
appendOptional(2);
}
break;
case "p":
case "P":
if (re.unicode) {
appendOptional(source.indexOf("}", i) - i + 1);
} else {
appendOptional(2);
}
break;
case "k":
appendOptional(source.indexOf(">", i) - i + 1);
break;
default:
appendOptional(2);
break;
}
break;
case "[":
tmp = /\[(?:\\.|.)*?\]/g;
tmp.lastIndex = i;
tmp = tmp.exec(source) || [];
appendOptional(tmp[0].length);
break;
case "|":
case "^":
case "$":
case "*":
case "+":
case "?":
appendRaw(1);
break;
case "{":
tmp = /\{\d+,?\d*\}/g;
tmp.lastIndex = i;
tmp = tmp.exec(source);
if (tmp) {
appendRaw(tmp[0].length);
} else {
appendOptional(1);
}
break;
case "(":
if (source[i + 1] === "?") {
switch (source[i + 2]) {
case ":":
result += "(?:";
i += 3;
result += process2() + "|$)";
break;
case "=":
result += "(?=";
i += 3;
result += process2() + ")";
break;
case "!":
tmp = i;
i += 3;
process2();
result += source.substr(tmp, i - tmp);
break;
case "<":
switch (source[i + 3]) {
case "=":
case "!":
tmp = i;
i += 4;
process2();
result += source.substr(tmp, i - tmp);
break;
default:
appendRaw(source.indexOf(">", i) - i + 1);
result += process2() + "|$)";
break;
}
break;
}
} else {
appendRaw(1);
result += process2() + "|$)";
}
break;
case ")":
++i;
return result;
default:
appendOptional(1);
break;
}
}
return result;
}
__name(process2, "process2");
__name2(process2, "process");
return new RegExp(process2(), regex.flags);
}
__name(partialRegExp, "partialRegExp");
__name2(partialRegExp, "partialRegExp");
function getEntryRule(grammar) {
return grammar.rules.find((e) => isParserRule(e) && e.entry);
}
__name(getEntryRule, "getEntryRule");
__name2(getEntryRule, "getEntryRule");
function getHiddenRules(grammar) {
return grammar.rules.filter((e) => isTerminalRule(e) && e.hidden);
}
__name(getHiddenRules, "getHiddenRules");
__name2(getHiddenRules, "getHiddenRules");
function getAllReachableRules(grammar, allTerminals) {
const ruleNames = /* @__PURE__ */ new Set();
const entryRule = getEntryRule(grammar);
if (!entryRule) {
return new Set(grammar.rules);
}
const topMostRules = [entryRule].concat(getHiddenRules(grammar));
for (const rule of topMostRules) {
ruleDfs(rule, ruleNames, allTerminals);
}
const rules = /* @__PURE__ */ new Set();
for (const rule of grammar.rules) {
if (ruleNames.has(rule.name) || isTerminalRule(rule) && rule.hidden) {
rules.add(rule);
}
}
return rules;
}
__name(getAllReachableRules, "getAllReachableRules");
__name2(getAllReachableRules, "getAllReachableRules");
function ruleDfs(rule, visitedSet, allTerminals) {
visitedSet.add(rule.name);
streamAllContents(rule).forEach((node) => {
if (isRuleCall(node) || allTerminals && isTerminalRuleCall(node)) {
const refRule = node.rule.ref;
if (refRule && !visitedSet.has(refRule.name)) {
ruleDfs(refRule, visitedSet, allTerminals);
}
}
});
}
__name(ruleDfs, "ruleDfs");
__name2(ruleDfs, "ruleDfs");
function getAllRulesUsedForCrossReferences(grammar) {
const result = /* @__PURE__ */ new Set();
streamAllContents(grammar).forEach((node) => {
if (isCrossReference(node)) {
if (isParserRule(node.type.ref)) {
result.add(node.type.ref);
}
if (isInferredType(node.type.ref) && isParserRule(node.type.ref.$container)) {
result.add(node.type.ref.$container);
}
}
});
return result;
}
__name(getAllRulesUsedForCrossReferences, "getAllRulesUsedForCrossReferences");
__name2(getAllRulesUsedForCrossReferences, "getAllRulesUsedForCrossReferences");
function getCrossReferenceTerminal(crossRef) {
if (crossRef.terminal) {
return crossRef.terminal;
} else if (crossRef.type.ref) {
const nameAssigment = findNameAssignment(crossRef.type.ref);
return nameAssigment?.terminal;
}
return void 0;
}
__name(getCrossReferenceTerminal, "getCrossReferenceTerminal");
__name2(getCrossReferenceTerminal, "getCrossReferenceTerminal");
function isCommentTerminal(terminalRule) {
return terminalRule.hidden && !isWhitespace(terminalRegex(terminalRule));
}
__name(isCommentTerminal, "isCommentTerminal");
__name2(isCommentTerminal, "isCommentTerminal");
function findNodesForProperty(node, property3) {
if (!node || !property3) {
return [];
}
return findNodesForPropertyInternal(node, property3, node.astNode, true);
}
__name(findNodesForProperty, "findNodesForProperty");
__name2(findNodesForProperty, "findNodesForProperty");
function findNodeForProperty(node, property3, index) {
if (!node || !property3) {
return void 0;
}
const nodes = findNodesForPropertyInternal(node, property3, node.astNode, true);
if (nodes.length === 0) {
return void 0;
}
if (index !== void 0) {
index = Math.max(0, Math.min(index, nodes.length - 1));
} else {
index = 0;
}
return nodes[index];
}
__name(findNodeForProperty, "findNodeForProperty");
__name2(findNodeForProperty, "findNodeForProperty");
function findNodesForPropertyInternal(node, property3, element, first2) {
if (!first2) {
const nodeFeature = getContainerOfType(node.grammarSource, isAssignment);
if (nodeFeature && nodeFeature.feature === property3) {
return [node];
}
}
if (isCompositeCstNode(node) && node.astNode === element) {
return node.content.flatMap((e) => findNodesForPropertyInternal(e, property3, element, false));
}
return [];
}
__name(findNodesForPropertyInternal, "findNodesForPropertyInternal");
__name2(findNodesForPropertyInternal, "findNodesForPropertyInternal");
function findNodesForKeyword(node, keyword) {
if (!node) {
return [];
}
return findNodesForKeywordInternal(node, keyword, node?.astNode);
}
__name(findNodesForKeyword, "findNodesForKeyword");
__name2(findNodesForKeyword, "findNodesForKeyword");
function findNodeForKeyword(node, keyword, index) {
if (!node) {
return void 0;
}
const nodes = findNodesForKeywordInternal(node, keyword, node?.astNode);
if (nodes.length === 0) {
return void 0;
}
if (index !== void 0) {
index = Math.max(0, Math.min(index, nodes.length - 1));
} else {
index = 0;
}
return nodes[index];
}
__name(findNodeForKeyword, "findNodeForKeyword");
__name2(findNodeForKeyword, "findNodeForKeyword");
function findNodesForKeywordInternal(node, keyword, element) {
if (node.astNode !== element) {
return [];
}
if (isKeyword(node.grammarSource) && node.grammarSource.value === keyword) {
return [node];
}
const treeIterator = streamCst(node).iterator();
let result;
const keywordNodes = [];
do {
result = treeIterator.next();
if (!result.done) {
const childNode = result.value;
if (childNode.astNode === element) {
if (isKeyword(childNode.grammarSource) && childNode.grammarSource.value === keyword) {
keywordNodes.push(childNode);
}
} else {
treeIterator.prune();
}
}
} while (!result.done);
return keywordNodes;
}
__name(findNodesForKeywordInternal, "findNodesForKeywordInternal");
__name2(findNodesForKeywordInternal, "findNodesForKeywordInternal");
function findAssignment(cstNode) {
const astNode = cstNode.astNode;
while (astNode === cstNode.container?.astNode) {
const assignment = getContainerOfType(cstNode.grammarSource, isAssignment);
if (assignment) {
return assignment;
}
cstNode = cstNode.container;
}
return void 0;
}
__name(findAssignment, "findAssignment");
__name2(findAssignment, "findAssignment");
function findNameAssignment(type) {
let startNode = type;
if (isInferredType(startNode)) {
if (isAction(startNode.$container)) {
startNode = startNode.$container.$container;
} else if (isAbstractParserRule(startNode.$container)) {
startNode = startNode.$container;
} else {
assertUnreachable(startNode.$container);
}
}
return findNameAssignmentInternal(type, startNode, /* @__PURE__ */ new Map());
}
__name(findNameAssignment, "findNameAssignment");
__name2(findNameAssignment, "findNameAssignment");
function findNameAssignmentInternal(type, startNode, cache) {
function go(node, refType) {
let childAssignment = void 0;
const parentAssignment = getContainerOfType(node, isAssignment);
if (!parentAssignment) {
childAssignment = findNameAssignmentInternal(refType, refType, cache);
}
cache.set(type, childAssignment);
return childAssignment;
}
__name(go, "go");
__name2(go, "go");
if (cache.has(type)) {
return cache.get(type);
}
cache.set(type, void 0);
for (const node of streamAllContents(startNode)) {
if (isAssignment(node) && node.feature.toLowerCase() === "name") {
cache.set(type, node);
return node;
} else if (isRuleCall(node) && isParserRule(node.rule.ref)) {
return go(node, node.rule.ref);
} else if (isSimpleType(node) && node.typeRef?.ref) {
return go(node, node.typeRef.ref);
}
}
return void 0;
}
__name(findNameAssignmentInternal, "findNameAssignmentInternal");
__name2(findNameAssignmentInternal, "findNameAssignmentInternal");
function getActionAtElement(element) {
const parent = element.$container;
if (isGroup(parent)) {
const elements = parent.elements;
const index = elements.indexOf(element);
for (let i = index - 1; i >= 0; i--) {
const item = elements[i];
if (isAction(item)) {
return item;
} else {
const action = streamAllContents(elements[i]).find(isAction);
if (action) {
return action;
}
}
}
}
if (isAbstractElement(parent)) {
return getActionAtElement(parent);
} else {
return void 0;
}
}
__name(getActionAtElement, "getActionAtElement");
__name2(getActionAtElement, "getActionAtElement");
function isOptionalCardinality(cardinality, element) {
return cardinality === "?" || cardinality === "*" || isGroup(element) && Boolean(element.guardCondition);
}
__name(isOptionalCardinality, "isOptionalCardinality");
__name2(isOptionalCardinality, "isOptionalCardinality");
function isArrayCardinality(cardinality) {
return cardinality === "*" || cardinality === "+";
}
__name(isArrayCardinality, "isArrayCardinality");
__name2(isArrayCardinality, "isArrayCardinality");
function isArrayOperator(operator) {
return operator === "+=";
}
__name(isArrayOperator, "isArrayOperator");
__name2(isArrayOperator, "isArrayOperator");
function isDataTypeRule(rule) {
return isDataTypeRuleInternal(rule, /* @__PURE__ */ new Set());
}
__name(isDataTypeRule, "isDataTypeRule");
__name2(isDataTypeRule, "isDataTypeRule");
function isDataTypeRuleInternal(rule, visited) {
if (visited.has(rule)) {
return true;
} else {
visited.add(rule);
}
for (const node of streamAllContents(rule)) {
if (isRuleCall(node)) {
if (!node.rule.ref) {
return false;
}
if (isParserRule(node.rule.ref) && !isDataTypeRuleInternal(node.rule.ref, visited)) {
return false;
}
if (isInfixRule(node.rule.ref)) {
return false;
}
} else if (isAssignment(node)) {
return false;
} else if (isAction(node)) {
return false;
}
}
return Boolean(rule.definition);
}
__name(isDataTypeRuleInternal, "isDataTypeRuleInternal");
__name2(isDataTypeRuleInternal, "isDataTypeRuleInternal");
function isDataType(type) {
return isDataTypeInternal(type.type, /* @__PURE__ */ new Set());
}
__name(isDataType, "isDataType");
__name2(isDataType, "isDataType");
function isDataTypeInternal(type, visited) {
if (visited.has(type)) {
return true;
} else {
visited.add(type);
}
if (isArrayType(type)) {
return false;
} else if (isReferenceType(type)) {
return false;
} else if (isUnionType(type)) {
return type.types.every((e) => isDataTypeInternal(e, visited));
} else if (isSimpleType(type)) {
if (type.primitiveType !== void 0) {
return true;
} else if (type.stringType !== void 0) {
return true;
} else if (type.typeRef !== void 0) {
const ref = type.typeRef.ref;
if (isType(ref)) {
return isDataTypeInternal(ref.type, visited);
} else {
return false;
}
} else {
return false;
}
} else {
return false;
}
}
__name(isDataTypeInternal, "isDataTypeInternal");
__name2(isDataTypeInternal, "isDataTypeInternal");
function getExplicitRuleType(rule) {
if (isTerminalRule(rule)) {
return void 0;
}
if (rule.inferredType) {
return rule.inferredType.name;
} else if (rule.dataType) {
return rule.dataType;
} else if (rule.returnType) {
const refType = rule.returnType.ref;
if (refType) {
return refType.name;
}
}
return void 0;
}
__name(getExplicitRuleType, "getExplicitRuleType");
__name2(getExplicitRuleType, "getExplicitRuleType");
function getTypeName(type) {
if (isAbstractParserRule(type)) {
return isParserRule(type) && isDataTypeRule(type) ? type.name : getExplicitRuleType(type) ?? type.name;
} else if (isInterface(type) || isType(type) || isReturnType(type)) {
return type.name;
} else if (isAction(type)) {
const actionType = getActionType(type);
if (actionType) {
return actionType;
}
} else if (isInferredType(type)) {
return type.name;
}
throw new Error("Cannot get name of Unknown Type");
}
__name(getTypeName, "getTypeName");
__name2(getTypeName, "getTypeName");
function getActionType(action) {
if (action.inferredType) {
return action.inferredType.name;
} else if (action.type?.ref) {
return getTypeName(action.type.ref);
}
return void 0;
}
__name(getActionType, "getActionType");
__name2(getActionType, "getActionType");
function getRuleTypeName(rule) {
if (isTerminalRule(rule)) {
return rule.type?.name ?? "string";
} else {
return isParserRule(rule) && isDataTypeRule(rule) ? rule.name : getExplicitRuleType(rule) ?? rule.name;
}
}
__name(getRuleTypeName, "getRuleTypeName");
__name2(getRuleTypeName, "getRuleTypeName");
function getRuleType(rule) {
if (isTerminalRule(rule)) {
return rule.type?.name ?? "string";
} else {
return getExplicitRuleType(rule) ?? rule.name;
}
}
__name(getRuleType, "getRuleType");
__name2(getRuleType, "getRuleType");
function terminalRegex(terminalRule) {
const flags = {
s: false,
i: false,
u: false
};
const source = abstractElementToRegex(terminalRule.definition, flags);
const flagText = Object.entries(flags).filter(([, value]) => value).map(([name]) => name).join("");
return new RegExp(source, flagText);
}
__name(terminalRegex, "terminalRegex");
__name2(terminalRegex, "terminalRegex");
var WILDCARD = /[\s\S]/.source;
function abstractElementToRegex(element, flags) {
if (isTerminalAlternatives(element)) {
return terminalAlternativesToRegex(element);
} else if (isTerminalGroup(element)) {
return terminalGroupToRegex(element);
} else if (isCharacterRange(element)) {
return characterRangeToRegex(element);
} else if (isTerminalRuleCall(element)) {
const rule = element.rule.ref;
if (!rule) {
throw new Error("Missing rule reference.");
}
return withCardinality(abstractElementToRegex(rule.definition), {
cardinality: element.cardinality,
lookahead: element.lookahead,
parenthesized: element.parenthesized
});
} else if (isNegatedToken(element)) {
return negateTokenToRegex(element);
} else if (isUntilToken(element)) {
return untilTokenToRegex(element);
} else if (isRegexToken(element)) {
const lastSlash = element.regex.lastIndexOf("/");
const source = element.regex.substring(1, lastSlash);
const regexFlags = element.regex.substring(lastSlash + 1);
if (flags) {
flags.i = regexFlags.includes("i");
flags.s = regexFlags.includes("s");
flags.u = regexFlags.includes("u");
}
return withCardinality(source, {
cardinality: element.cardinality,
lookahead: element.lookahead,
parenthesized: element.parenthesized,
wrap: false
});
} else if (isWildcard(element)) {
return withCardinality(WILDCARD, {
cardinality: element.cardinality,
lookahead: element.lookahead,
parenthesized: element.parenthesized
});
} else {
throw new Error(`Invalid terminal element: ${element?.$type}, ${element?.$cstNode?.text}`);
}
}
__name(abstractElementToRegex, "abstractElementToRegex");
__name2(abstractElementToRegex, "abstractElementToRegex");
function terminalAlternativesToRegex(alternatives) {
return withCardinality(alternatives.elements.map((e) => abstractElementToRegex(e)).join("|"), {
cardinality: alternatives.cardinality,
lookahead: alternatives.lookahead,
parenthesized: alternatives.parenthesized,
wrap: false
// wrapping is not required for top level alternatives, and nested alternatives are already parenthesized according to the grammar
});
}
__name(terminalAlternativesToRegex, "terminalAlternativesToRegex");
__name2(terminalAlternativesToRegex, "terminalAlternativesToRegex");
function terminalGroupToRegex(group) {
return withCardinality(group.elements.map((e) => abstractElementToRegex(e)).join(""), {
cardinality: group.cardinality,
lookahead: group.lookahead,
parenthesized: group.parenthesized,
wrap: false
// wrapping is not required for top level group, and nested group are already parenthesized according to the grammar
});
}
__name(terminalGroupToRegex, "terminalGroupToRegex");
__name2(terminalGroupToRegex, "terminalGroupToRegex");
function untilTokenToRegex(until) {
return withCardinality(`${WILDCARD}*?${abstractElementToRegex(until.terminal)}`, {
cardinality: until.cardinality,
lookahead: until.lookahead,
parenthesized: until.parenthesized
});
}
__name(untilTokenToRegex, "untilTokenToRegex");
__name2(untilTokenToRegex, "untilTokenToRegex");
function negateTokenToRegex(negate2) {
return withCardinality(`(?!${abstractElementToRegex(negate2.terminal)})${WILDCARD}*?`, {
cardinality: negate2.cardinality,
lookahead: negate2.lookahead,
parenthesized: negate2.parenthesized
});
}
__name(negateTokenToRegex, "negateTokenToRegex");
__name2(negateTokenToRegex, "negateTokenToRegex");
function characterRangeToRegex(range) {
if (range.right) {
return withCardinality(`[${keywordToRegex(range.left)}-${keywordToRegex(range.right)}]`, {
cardinality: range.cardinality,
lookahead: range.lookahead,
parenthesized: range.parenthesized,
wrap: false
});
}
return withCardinality(keywordToRegex(range.left), {
cardinality: range.cardinality,
lookahead: range.lookahead,
parenthesized: range.parenthesized,
wrap: false
});
}
__name(characterRangeToRegex, "characterRangeToRegex");
__name2(characterRangeToRegex, "characterRangeToRegex");
function keywordToRegex(keyword) {
return escapeRegExp(keyword.value);
}
__name(keywordToRegex, "keywordToRegex");
__name2(keywordToRegex, "keywordToRegex");
function withCardinality(regex, options) {
if (options.parenthesized || options.lookahead || options.wrap !== false) {
const groupConfig = options.lookahead ?? (options.parenthesized ? "" : "?:");
regex = `(${groupConfig}${regex})`;
}
if (options.cardinality) {
return `${regex}${options.cardinality}`;
}
return regex;
}
__name(withCardinality, "withCardinality");
__name2(withCardinality, "withCardinality");
function createGrammarConfig(services) {
const rules = [];
const grammar = services.Grammar;
for (const rule of grammar.rules) {
if (isTerminalRule(rule) && isCommentTerminal(rule) && isMultilineComment(terminalRegex(rule))) {
rules.push(rule.name);
}
}
return {
multilineCommentRules: rules,
nameRegexp: DefaultNameRegexp
};
}
__name(createGrammarConfig, "createGrammarConfig");
__name2(createGrammarConfig, "createGrammarConfig");
var freeGlobal = typeof global == "object" && global && global.Object === Object && global;
var freeGlobal_default = freeGlobal;
var freeSelf = typeof self == "object" && self && self.Object === Object && self;
var root = freeGlobal_default || freeSelf || Function("return this")();
var root_default = root;
var Symbol2 = root_default.Symbol;
var Symbol_default = Symbol2;
var objectProto = Object.prototype;
var hasOwnProperty = objectProto.hasOwnProperty;
var nativeObjectToString = objectProto.toString;
var symToStringTag = Symbol_default ? Symbol_default.toStringTag : void 0;
function getRawTag(value) {
var isOwn = hasOwnProperty.call(value, symToStringTag), tag = value[symToStringTag];
try {
value[symToStringTag] = void 0;
var unmasked = true;
} catch (e) {
}
var result = nativeObjectToString.call(value);
if (unmasked) {
if (isOwn) {
value[symToStringTag] = tag;
} else {
delete value[symToStringTag];
}
}
return result;
}
__name(getRawTag, "getRawTag");
__name2(getRawTag, "getRawTag");
var getRawTag_default = getRawTag;
var objectProto2 = Object.prototype;
var nativeObjectToString2 = objectProto2.toString;
function objectToString(value) {
return nativeObjectToString2.call(value);
}
__name(objectToString, "objectToString");
__name2(objectToString, "objectToString");
var objectToString_default = objectToString;
var nullTag = "[object Null]";
var undefinedTag = "[object Undefined]";
var symToStringTag2 = Symbol_default ? Symbol_default.toStringTag : void 0;
function baseGetTag(value) {
if (value == null) {
return value === void 0 ? undefinedTag : nullTag;
}
return symToStringTag2 && symToStringTag2 in Object(value) ? getRawTag_default(value) : objectToString_default(value);
}
__name(baseGetTag, "baseGetTag");
__name2(baseGetTag, "baseGetTag");
var baseGetTag_default = baseGetTag;
function isObjectLike(value) {
return value != null && typeof value == "object";
}
__name(isObjectLike, "isObjectLike");
__name2(isObjectLike, "isObjectLike");
var isObjectLike_default = isObjectLike;
var symbolTag = "[object Symbol]";
function isSymbol(value) {
return typeof value == "symbol" || isObjectLike_default(value) && baseGetTag_default(value) == symbolTag;
}
__name(isSymbol, "isSymbol");
__name2(isSymbol, "isSymbol");
var isSymbol_default = isSymbol;
function arrayMap(array, iteratee) {
var index = -1, length = array == null ? 0 : array.length, result = Array(length);
while (++index < length) {
result[index] = iteratee(array[index], index, array);
}
return result;
}
__name(arrayMap, "arrayMap");
__name2(arrayMap, "arrayMap");
var arrayMap_default = arrayMap;
var isArray = Array.isArray;
var isArray_default = isArray;
var INFINITY = 1 / 0;
var symbolProto = Symbol_default ? Symbol_default.prototype : void 0;
var symbolToString = symbolProto ? symbolProto.toString : void 0;
function baseToString(value) {
if (typeof value == "string") {
return value;
}
if (isArray_default(value)) {
return arrayMap_default(value, baseToString) + "";
}
if (isSymbol_default(value)) {
return symbolToString ? symbolToString.call(value) : "";
}
var result = value + "";
return result == "0" && 1 / value == -INFINITY ? "-0" : result;
}
__name(baseToString, "baseToString");
__name2(baseToString, "baseToString");
var baseToString_default = baseToString;
var reWhitespace = /\s/;
function trimmedEndIndex(string) {
var index = string.length;
while (index-- && reWhitespace.test(string.charAt(index))) {
}
return index;
}
__name(trimmedEndIndex, "trimmedEndIndex");
__name2(trimmedEndIndex, "trimmedEndIndex");
var trimmedEndIndex_default = trimmedEndIndex;
var reTrimStart = /^\s+/;
function baseTrim(string) {
return string ? string.slice(0, trimmedEndIndex_default(string) + 1).replace(reTrimStart, "") : string;
}
__name(baseTrim, "baseTrim");
__name2(baseTrim, "baseTrim");
var baseTrim_default = baseTrim;
function isObject(value) {
var type = typeof value;
return value != null && (type == "object" || type == "function");
}
__name(isObject, "isObject");
__name2(isObject, "isObject");
var isObject_default = isObject;
var NAN = 0 / 0;
var reIsBadHex = /^[-+]0x[0-9a-f]+$/i;
var reIsBinary = /^0b[01]+$/i;
var reIsOctal = /^0o[0-7]+$/i;
var freeParseInt = parseInt;
function toNumber(value) {
if (typeof value == "number") {
return value;
}
if (isSymbol_default(value)) {
return NAN;
}
if (isObject_default(value)) {
var other = typeof value.valueOf == "function" ? value.valueOf() : value;
value = isObject_default(other) ? other + "" : other;
}
if (typeof value != "string") {
return value === 0 ? value : +value;
}
value = baseTrim_default(value);
var isBinary = reIsBinary.test(value);
return isBinary || reIsOctal.test(value) ? freeParseInt(value.slice(2), isBinary ? 2 : 8) : reIsBadHex.test(value) ? NAN : +value;
}
__name(toNumber, "toNumber");
__name2(toNumber, "toNumber");
var toNumber_default = toNumber;
var INFINITY2 = 1 / 0;
var MAX_INTEGER = 17976931348623157e292;
function toFinite(value) {
if (!value) {
return value === 0 ? value : 0;
}
value = toNumber_default(value);
if (value === INFINITY2 || value === -INFINITY2) {
var sign = value < 0 ? -1 : 1;
return sign * MAX_INTEGER;
}
return value === value ? value : 0;
}
__name(toFinite, "toFinite");
__name2(toFinite, "toFinite");
var toFinite_default = toFinite;
function toInteger(value) {
var result = toFinite_default(value), remainder = result % 1;
return result === result ? remainder ? result - remainder : result : 0;
}
__name(toInteger, "toInteger");
__name2(toInteger, "toInteger");
var toInteger_default = toInteger;
function identity(value) {
return value;
}
__name(identity, "identity");
__name2(identity, "identity");
var identity_default = identity;
var asyncTag = "[object AsyncFunction]";
var funcTag = "[object Function]";
var genTag = "[object GeneratorFunction]";
var proxyTag = "[object Proxy]";
function isFunction(value) {
if (!isObject_default(value)) {
return false;
}
var tag = baseGetTag_default(value);
return tag == funcTag || tag == genTag || tag == asyncTag || tag == proxyTag;
}
__name(isFunction, "isFunction");
__name2(isFunction, "isFunction");
var isFunction_default = isFunction;
var coreJsData = root_default["__core-js_shared__"];
var coreJsData_default = coreJsData;
var maskSrcKey = (function() {
var uid = /[^.]+$/.exec(coreJsData_default && coreJsData_default.keys && coreJsData_default.keys.IE_PROTO || "");
return uid ? "Symbol(src)_1." + uid : "";
})();
function isMasked(func) {
return !!maskSrcKey && maskSrcKey in func;
}
__name(isMasked, "isMasked");
__name2(isMasked, "isMasked");
var isMasked_default = isMasked;
var funcProto = Function.prototype;
var funcToString = funcProto.toString;
function toSource(func) {
if (func != null) {
try {
return funcToString.call(func);
} catch (e) {
}
try {
return func + "";
} catch (e) {
}
}
return "";
}
__name(toSource, "toSource");
__name2(toSource, "toSource");
var toSource_default = toSource;
var reRegExpChar = /[\\^$.*+?()[\]{}|]/g;
var reIsHostCtor = /^\[object .+?Constructor\]$/;
var funcProto2 = Function.prototype;
var objectProto3 = Object.prototype;
var funcToString2 = funcProto2.toString;
var hasOwnProperty2 = objectProto3.hasOwnProperty;
var reIsNative = RegExp(
"^" + funcToString2.call(hasOwnProperty2).replace(reRegExpChar, "\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g, "$1.*?") + "$"
);
function baseIsNative(value) {
if (!isObject_default(value) || isMasked_default(value)) {
return false;
}
var pattern = isFunction_default(value) ? reIsNative : reIsHostCtor;
return pattern.test(toSource_default(value));
}
__name(baseIsNative, "baseIsNative");
__name2(baseIsNative, "baseIsNative");
var baseIsNative_default = baseIsNative;
function getValue(object, key) {
return object == null ? void 0 : object[key];
}
__name(getValue, "getValue");
__name2(getValue, "getValue");
var getValue_default = getValue;
function getNative(object, key) {
var value = getValue_default(object, key);
return baseIsNative_default(value) ? value : void 0;
}
__name(getNative, "getNative");
__name2(getNative, "getNative");
var getNative_default = getNative;
var WeakMap = getNative_default(root_default, "WeakMap");
var WeakMap_default = WeakMap;
var objectCreate = Object.create;
var baseCreate = /* @__PURE__ */ (function() {
function object() {
}
__name(object, "object");
__name2(object, "object");
return function(proto) {
if (!isObject_default(proto)) {
return {};
}
if (objectCreate) {
return objectCreate(proto);
}
object.prototype = proto;
var result = new object();
object.prototype = void 0;
return result;
};
})();
var baseCreate_default = baseCreate;
function apply(func, thisArg, args) {
switch (args.length) {
case 0:
return func.call(thisArg);
case 1:
return func.call(thisArg, args[0]);
case 2:
return func.call(thisArg, args[0], args[1]);
case 3:
return func.call(thisArg, args[0], args[1], args[2]);
}
return func.apply(thisArg, args);
}
__name(apply, "apply");
__name2(apply, "apply");
var apply_default = apply;
function noop() {
}
__name(noop, "noop");
__name2(noop, "noop");
var noop_default = noop;
function copyArray(source, array) {
var index = -1, length = source.length;
array || (array = Array(length));
while (++index < length) {
array[index] = source[index];
}
return array;
}
__name(copyArray, "copyArray");
__name2(copyArray, "copyArray");
var copyArray_default = copyArray;
var HOT_COUNT = 800;
var HOT_SPAN = 16;
var nativeNow = Date.now;
function shortOut(func) {
var count = 0, lastCalled = 0;
return function() {
var stamp = nativeNow(), remaining = HOT_SPAN - (stamp - lastCalled);
lastCalled = stamp;
if (remaining > 0) {
if (++count >= HOT_COUNT) {
return arguments[0];
}
} else {
count = 0;
}
return func.apply(void 0, arguments);
};
}
__name(shortOut, "shortOut");
__name2(shortOut, "shortOut");
var shortOut_default = shortOut;
function constant(value) {
return function() {
return value;
};
}
__name(constant, "constant");
__name2(constant, "constant");
var constant_default = constant;
var defineProperty = (function() {
try {
var func = getNative_default(Object, "defineProperty");
func({}, "", {});
return func;
} catch (e) {
}
})();
var defineProperty_default = defineProperty;
var baseSetToString = !defineProperty_default ? identity_default : function(func, string) {
return defineProperty_default(func, "toString", {
"configurable": true,
"enumerable": false,
"value": constant_default(string),
"writable": true
});
};
var baseSetToString_default = baseSetToString;
var setToString = shortOut_default(baseSetToString_default);
var setToString_default = setToString;
function arrayEach(array, iteratee) {
var index = -1, length = array == null ? 0 : array.length;
while (++index < length) {
if (iteratee(array[index], index, array) === false) {
break;
}
}
return array;
}
__name(arrayEach, "arrayEach");
__name2(arrayEach, "arrayEach");
var arrayEach_default = arrayEach;
function baseFindIndex(array, predicate, fromIndex, fromRight) {
var length = array.length, index = fromIndex + (fromRight ? 1 : -1);
while (fromRight ? index-- : ++index < length) {
if (predicate(array[index], index, array)) {
return index;
}
}
return -1;
}
__name(baseFindIndex, "baseFindIndex");
__name2(baseFindIndex, "baseFindIndex");
var baseFindIndex_default = baseFindIndex;
function baseIsNaN(value) {
return value !== value;
}
__name(baseIsNaN, "baseIsNaN");
__name2(baseIsNaN, "baseIsNaN");
var baseIsNaN_default = baseIsNaN;
function strictIndexOf(array, value, fromIndex) {
var index = fromIndex - 1, length = array.length;
while (++index < length) {
if (array[index] === value) {
return index;
}
}
return -1;
}
__name(strictIndexOf, "strictIndexOf");
__name2(strictIndexOf, "strictIndexOf");
var strictIndexOf_default = strictIndexOf;
function baseIndexOf(array, value, fromIndex) {
return value === value ? strictIndexOf_default(array, value, fromIndex) : baseFindIndex_default(array, baseIsNaN_default, fromIndex);
}
__name(baseIndexOf, "baseIndexOf");
__name2(baseIndexOf, "baseIndexOf");
var baseIndexOf_default = baseIndexOf;
function arrayIncludes(array, value) {
var length = array == null ? 0 : array.length;
return !!length && baseIndexOf_default(array, value, 0) > -1;
}
__name(arrayIncludes, "arrayIncludes");
__name2(arrayIncludes, "arrayIncludes");
var arrayIncludes_default = arrayIncludes;
var MAX_SAFE_INTEGER = 9007199254740991;
var reIsUint = /^(?:0|[1-9]\d*)$/;
function isIndex(value, length) {
var type = typeof value;
length = length == null ? MAX_SAFE_INTEGER : length;
return !!length && (type == "number" || type != "symbol" && reIsUint.test(value)) && (value > -1 && value % 1 == 0 && value < length);
}
__name(isIndex, "isIndex");
__name2(isIndex, "isIndex");
var isIndex_default = isIndex;
function baseAssignValue(object, key, value) {
if (key == "__proto__" && defineProperty_default) {
defineProperty_default(object, key, {
"configurable": true,
"enumerable": true,
"value": value,
"writable": true
});
} else {
object[key] = value;
}
}
__name(baseAssignValue, "baseAssignValue");
__name2(baseAssignValue, "baseAssignValue");
var baseAssignValue_default = baseAssignValue;
function eq(value, other) {
return value === other || value !== value && other !== other;
}
__name(eq, "eq");
__name2(eq, "eq");
var eq_default = eq;
var objectProto4 = Object.prototype;
var hasOwnProperty3 = objectProto4.hasOwnProperty;
function assignValue(object, key, value) {
var objValue = object[key];
if (!(hasOwnProperty3.call(object, key) && eq_default(objValue, value)) || value === void 0 && !(key in object)) {
baseAssignValue_default(object, key, value);
}
}
__name(assignValue, "assignValue");
__name2(assignValue, "assignValue");
var assignValue_default = assignValue;
function copyObject(source, props, object, customizer) {
var isNew = !object;
object || (object = {});
var index = -1, length = props.length;
while (++index < length) {
var key = props[index];
var newValue = customizer ? customizer(object[key], source[key], key, object, source) : void 0;
if (newValue === void 0) {
newValue = source[key];
}
if (isNew) {
baseAssignValue_default(object, key, newValue);
} else {
assignValue_default(object, key, newValue);
}
}
return object;
}
__name(copyObject, "copyObject");
__name2(copyObject, "copyObject");
var copyObject_default = copyObject;
var nativeMax = Math.max;
function overRest(func, start, transform) {
start = nativeMax(start === void 0 ? func.length - 1 : start, 0);
return function() {
var args = arguments, index = -1, length = nativeMax(args.length - start, 0), array = Array(length);
while (++index < length) {
array[index] = args[start + index];
}
index = -1;
var otherArgs = Array(start + 1);
while (++index < start) {
otherArgs[index] = args[index];
}
otherArgs[start] = transform(array);
return apply_default(func, this, otherArgs);
};
}
__name(overRest, "overRest");
__name2(overRest, "overRest");
var overRest_default = overRest;
function baseRest(func, start) {
return setToString_default(overRest_default(func, start, identity_default), func + "");
}
__name(baseRest, "baseRest");
__name2(baseRest, "baseRest");
var baseRest_default = baseRest;
var MAX_SAFE_INTEGER2 = 9007199254740991;
function isLength(value) {
return typeof value == "number" && value > -1 && value % 1 == 0 && value <= MAX_SAFE_INTEGER2;
}
__name(isLength, "isLength");
__name2(isLength, "isLength");
var isLength_default = isLength;
function isArrayLike(value) {
return value != null && isLength_default(value.length) && !isFunction_default(value);
}
__name(isArrayLike, "isArrayLike");
__name2(isArrayLike, "isArrayLike");
var isArrayLike_default = isArrayLike;
function isIterateeCall(value, index, object) {
if (!isObject_default(object)) {
return false;
}
var type = typeof index;
if (type == "number" ? isArrayLike_default(object) && isIndex_default(index, object.length) : type == "string" && index in object) {
return eq_default(object[index], value);
}
return false;
}
__name(isIterateeCall, "isIterateeCall");
__name2(isIterateeCall, "isIterateeCall");
var isIterateeCall_default = isIterateeCall;
function createAssigner(assigner) {
return baseRest_default(function(object, sources) {
var index = -1, length = sources.length, customizer = length > 1 ? sources[length - 1] : void 0, guard = length > 2 ? sources[2] : void 0;
customizer = assigner.length > 3 && typeof customizer == "function" ? (length--, customizer) : void 0;
if (guard && isIterateeCall_default(sources[0], sources[1], guard)) {
customizer = length < 3 ? void 0 : customizer;
length = 1;
}
object = Object(object);
while (++index < length) {
var source = sources[index];
if (source) {
assigner(object, source, index, customizer);
}
}
return object;
});
}
__name(createAssigner, "createAssigner");
__name2(createAssigner, "createAssigner");
var createAssigner_default = createAssigner;
var objectProto5 = Object.prototype;
function isPrototype(value) {
var Ctor = value && value.constructor, proto = typeof Ctor == "function" && Ctor.prototype || objectProto5;
return value === proto;
}
__name(isPrototype, "isPrototype");
__name2(isPrototype, "isPrototype");
var isPrototype_default = isPrototype;
function baseTimes(n, iteratee) {
var index = -1, result = Array(n);
while (++index < n) {
result[index] = iteratee(index);
}
return result;
}
__name(baseTimes, "baseTimes");
__name2(baseTimes, "baseTimes");
var baseTimes_default = baseTimes;
var argsTag = "[object Arguments]";
function baseIsArguments(value) {
return isObjectLike_default(value) && baseGetTag_default(value) == argsTag;
}
__name(baseIsArguments, "baseIsArguments");
__name2(baseIsArguments, "baseIsArguments");
var baseIsArguments_default = baseIsArguments;
var objectProto6 = Object.prototype;
var hasOwnProperty4 = objectProto6.hasOwnProperty;
var propertyIsEnumerable = objectProto6.propertyIsEnumerable;
var isArguments = baseIsArguments_default(/* @__PURE__ */ (function() {
return arguments;
})()) ? baseIsArguments_default : function(value) {
return isObjectLike_default(value) && hasOwnProperty4.call(value, "callee") && !propertyIsEnumerable.call(value, "callee");
};
var isArguments_default = isArguments;
function stubFalse() {
return false;
}
__name(stubFalse, "stubFalse");
__name2(stubFalse, "stubFalse");
var stubFalse_default = stubFalse;
var freeExports = typeof exports == "object" && exports && !exports.nodeType && exports;
var freeModule = freeExports && typeof module == "object" && module && !module.nodeType && module;
var moduleExports = freeModule && freeModule.exports === freeExports;
var Buffer2 = moduleExports ? root_default.Buffer : void 0;
var nativeIsBuffer = Buffer2 ? Buffer2.isBuffer : void 0;
var isBuffer = nativeIsBuffer || stubFalse_default;
var isBuffer_default = isBuffer;
var argsTag2 = "[object Arguments]";
var arrayTag = "[object Array]";
var boolTag = "[object Boolean]";
var dateTag = "[object Date]";
var errorTag = "[object Error]";
var funcTag2 = "[object Function]";
var mapTag = "[object Map]";
var numberTag = "[object Number]";
var objectTag = "[object Object]";
var regexpTag = "[object RegExp]";
var setTag = "[object Set]";
var stringTag = "[object String]";
var weakMapTag = "[object WeakMap]";
var arrayBufferTag = "[object ArrayBuffer]";
var dataViewTag = "[object DataView]";
var float32Tag = "[object Float32Array]";
var float64Tag = "[object Float64Array]";
var int8Tag = "[object Int8Array]";
var int16Tag = "[object Int16Array]";
var int32Tag = "[object Int32Array]";
var uint8Tag = "[object Uint8Array]";
var uint8ClampedTag = "[object Uint8ClampedArray]";
var uint16Tag = "[object Uint16Array]";
var uint32Tag = "[object Uint32Array]";
var typedArrayTags = {};
typedArrayTags[float32Tag] = typedArrayTags[float64Tag] = typedArrayTags[int8Tag] = typedArrayTags[int16Tag] = typedArrayTags[int32Tag] = typedArrayTags[uint8Tag] = typedArrayTags[uint8ClampedTag] = typedArrayTags[uint16Tag] = typedArrayTags[uint32Tag] = true;
typedArrayTags[argsTag2] = typedArrayTags[arrayTag] = typedArrayTags[arrayBufferTag] = typedArrayTags[boolTag] = typedArrayTags[dataViewTag] = typedArrayTags[dateTag] = typedArrayTags[errorTag] = typedArrayTags[funcTag2] = typedArrayTags[mapTag] = typedArrayTags[numberTag] = typedArrayTags[objectTag] = typedArrayTags[regexpTag] = typedArrayTags[setTag] = typedArrayTags[stringTag] = typedArrayTags[weakMapTag] = false;
function baseIsTypedArray(value) {
return isObjectLike_default(value) && isLength_default(value.length) && !!typedArrayTags[baseGetTag_default(value)];
}
__name(baseIsTypedArray, "baseIsTypedArray");
__name2(baseIsTypedArray, "baseIsTypedArray");
var baseIsTypedArray_default = baseIsTypedArray;
function baseUnary(func) {
return function(value) {
return func(value);
};
}
__name(baseUnary, "baseUnary");
__name2(baseUnary, "baseUnary");
var baseUnary_default = baseUnary;
var freeExports2 = typeof exports == "object" && exports && !exports.nodeType && exports;
var freeModule2 = freeExports2 && typeof module == "object" && module && !module.nodeType && module;
var moduleExports2 = freeModule2 && freeModule2.exports === freeExports2;
var freeProcess = moduleExports2 && freeGlobal_default.process;
var nodeUtil = (function() {
try {
var types = freeModule2 && freeModule2.require && freeModule2.require("util").types;
if (types) {
return types;
}
return freeProcess && freeProcess.binding && freeProcess.binding("util");
} catch (e) {
}
})();
var nodeUtil_default = nodeUtil;
var nodeIsTypedArray = nodeUtil_default && nodeUtil_default.isTypedArray;
var isTypedArray = nodeIsTypedArray ? baseUnary_default(nodeIsTypedArray) : baseIsTypedArray_default;
var isTypedArray_default = isTypedArray;
var objectProto7 = Object.prototype;
var hasOwnProperty5 = objectProto7.hasOwnProperty;
function arrayLikeKeys(value, inherited) {
var isArr = isArray_default(value), isArg = !isArr && isArguments_default(value), isBuff = !isArr && !isArg && isBuffer_default(value), isType2 = !isArr && !isArg && !isBuff && isTypedArray_default(value), skipIndexes = isArr || isArg || isBuff || isType2, result = skipIndexes ? baseTimes_default(value.length, String) : [], length = result.length;
for (var key in value) {
if ((inherited || hasOwnProperty5.call(value, key)) && !(skipIndexes && // Safari 9 has enumerable `arguments.length` in strict mode.
(key == "length" || // Node.js 0.10 has enumerable non-index properties on buffers.
isBuff && (key == "offset" || key == "parent") || // PhantomJS 2 has enumerable non-index properties on typed arrays.
isType2 && (key == "buffer" || key == "byteLength" || key == "byteOffset") || // Skip index properties.
isIndex_default(key, length)))) {
result.push(key);
}
}
return result;
}
__name(arrayLikeKeys, "arrayLikeKeys");
__name2(arrayLikeKeys, "arrayLikeKeys");
var arrayLikeKeys_default = arrayLikeKeys;
function overArg(func, transform) {
return function(arg) {
return func(transform(arg));
};
}
__name(overArg, "overArg");
__name2(overArg, "overArg");
var overArg_default = overArg;
var nativeKeys = overArg_default(Object.keys, Object);
var nativeKeys_default = nativeKeys;
var objectProto8 = Object.prototype;
var hasOwnProperty6 = objectProto8.hasOwnProperty;
function baseKeys(object) {
if (!isPrototype_default(object)) {
return nativeKeys_default(object);
}
var result = [];
for (var key in Object(object)) {
if (hasOwnProperty6.call(object, key) && key != "constructor") {
result.push(key);
}
}
return result;
}
__name(baseKeys, "baseKeys");
__name2(baseKeys, "baseKeys");
var baseKeys_default = baseKeys;
function keys(object) {
return isArrayLike_default(object) ? arrayLikeKeys_default(object) : baseKeys_default(object);
}
__name(keys, "keys");
__name2(keys, "keys");
var keys_default = keys;
var objectProto9 = Object.prototype;
var hasOwnProperty7 = objectProto9.hasOwnProperty;
var assign = createAssigner_default(function(object, source) {
if (isPrototype_default(source) || isArrayLike_default(source)) {
copyObject_default(source, keys_default(source), object);
return;
}
for (var key in source) {
if (hasOwnProperty7.call(source, key)) {
assignValue_default(object, key, source[key]);
}
}
});
var assign_default = assign;
function nativeKeysIn(object) {
var result = [];
if (object != null) {
for (var key in Object(object)) {
result.push(key);
}
}
return result;
}
__name(nativeKeysIn, "nativeKeysIn");
__name2(nativeKeysIn, "nativeKeysIn");
var nativeKeysIn_default = nativeKeysIn;
var objectProto10 = Object.prototype;
var hasOwnProperty8 = objectProto10.hasOwnProperty;
function baseKeysIn(object) {
if (!isObject_default(object)) {
return nativeKeysIn_default(object);
}
var isProto = isPrototype_default(object), result = [];
for (var key in object) {
if (!(key == "constructor" && (isProto || !hasOwnProperty8.call(object, key)))) {
result.push(key);
}
}
return result;
}
__name(baseKeysIn, "baseKeysIn");
__name2(baseKeysIn, "baseKeysIn");
var baseKeysIn_default = baseKeysIn;
function keysIn(object) {
return isArrayLike_default(object) ? arrayLikeKeys_default(object, true) : baseKeysIn_default(object);
}
__name(keysIn, "keysIn");
__name2(keysIn, "keysIn");
var keysIn_default = keysIn;
var reIsDeepProp = /\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\\]|\\.)*?\1)\]/;
var reIsPlainProp = /^\w*$/;
function isKey(value, object) {
if (isArray_default(value)) {
return false;
}
var type = typeof value;
if (type == "number" || type == "symbol" || type == "boolean" || value == null || isSymbol_default(value)) {
return true;
}
return reIsPlainProp.test(value) || !reIsDeepProp.test(value) || object != null && value in Object(object);
}
__name(isKey, "isKey");
__name2(isKey, "isKey");
var isKey_default = isKey;
var nativeCreate = getNative_default(Object, "create");
var nativeCreate_default = nativeCreate;
function hashClear() {
this.__data__ = nativeCreate_default ? nativeCreate_default(null) : {};
this.size = 0;
}
__name(hashClear, "hashClear");
__name2(hashClear, "hashClear");
var hashClear_default = hashClear;
function hashDelete(key) {
var result = this.has(key) && delete this.__data__[key];
this.size -= result ? 1 : 0;
return result;
}
__name(hashDelete, "hashDelete");
__name2(hashDelete, "hashDelete");
var hashDelete_default = hashDelete;
var HASH_UNDEFINED = "__lodash_hash_undefined__";
var objectProto11 = Object.prototype;
var hasOwnProperty9 = objectProto11.hasOwnProperty;
function hashGet(key) {
var data = this.__data__;
if (nativeCreate_default) {
var result = data[key];
return result === HASH_UNDEFINED ? void 0 : result;
}
return hasOwnProperty9.call(data, key) ? data[key] : void 0;
}
__name(hashGet, "hashGet");
__name2(hashGet, "hashGet");
var hashGet_default = hashGet;
var objectProto12 = Object.prototype;
var hasOwnProperty10 = objectProto12.hasOwnProperty;
function hashHas(key) {
var data = this.__data__;
return nativeCreate_default ? data[key] !== void 0 : hasOwnProperty10.call(data, key);
}
__name(hashHas, "hashHas");
__name2(hashHas, "hashHas");
var hashHas_default = hashHas;
var HASH_UNDEFINED2 = "__lodash_hash_undefined__";
function hashSet(key, value) {
var data = this.__data__;
this.size += this.has(key) ? 0 : 1;
data[key] = nativeCreate_default && value === void 0 ? HASH_UNDEFINED2 : value;
return this;
}
__name(hashSet, "hashSet");
__name2(hashSet, "hashSet");
var hashSet_default = hashSet;
function Hash(entries) {
var index = -1, length = entries == null ? 0 : entries.length;
this.clear();
while (++index < length) {
var entry = entries[index];
this.set(entry[0], entry[1]);
}
}
__name(Hash, "Hash");
__name2(Hash, "Hash");
Hash.prototype.clear = hashClear_default;
Hash.prototype["delete"] = hashDelete_default;
Hash.prototype.get = hashGet_default;
Hash.prototype.has = hashHas_default;
Hash.prototype.set = hashSet_default;
var Hash_default = Hash;
function listCacheClear() {
this.__data__ = [];
this.size = 0;
}
__name(listCacheClear, "listCacheClear");
__name2(listCacheClear, "listCacheClear");
var listCacheClear_default = listCacheClear;
function assocIndexOf(array, key) {
var length = array.length;
while (length--) {
if (eq_default(array[length][0], key)) {
return length;
}
}
return -1;
}
__name(assocIndexOf, "assocIndexOf");
__name2(assocIndexOf, "assocIndexOf");
var assocIndexOf_default = assocIndexOf;
var arrayProto = Array.prototype;
var splice = arrayProto.splice;
function listCacheDelete(key) {
var data = this.__data__, index = assocIndexOf_default(data, key);
if (index < 0) {
return false;
}
var lastIndex = data.length - 1;
if (index == lastIndex) {
data.pop();
} else {
splice.call(data, index, 1);
}
--this.size;
return true;
}
__name(listCacheDelete, "listCacheDelete");
__name2(listCacheDelete, "listCacheDelete");
var listCacheDelete_default = listCacheDelete;
function listCacheGet(key) {
var data = this.__data__, index = assocIndexOf_default(data, key);
return index < 0 ? void 0 : data[index][1];
}
__name(listCacheGet, "listCacheGet");
__name2(listCacheGet, "listCacheGet");
var listCacheGet_default = listCacheGet;
function listCacheHas(key) {
return assocIndexOf_default(this.__data__, key) > -1;
}
__name(listCacheHas, "listCacheHas");
__name2(listCacheHas, "listCacheHas");
var listCacheHas_default = listCacheHas;
function listCacheSet(key, value) {
var data = this.__data__, index = assocIndexOf_default(data, key);
if (index < 0) {
++this.size;
data.push([key, value]);
} else {
data[index][1] = value;
}
return this;
}
__name(listCacheSet, "listCacheSet");
__name2(listCacheSet, "listCacheSet");
var listCacheSet_default = listCacheSet;
function ListCache(entries) {
var index = -1, length = entries == null ? 0 : entries.length;
this.clear();
while (++index < length) {
var entry = entries[index];
this.set(entry[0], entry[1]);
}
}
__name(ListCache, "ListCache");
__name2(ListCache, "ListCache");
ListCache.prototype.clear = listCacheClear_default;
ListCache.prototype["delete"] = listCacheDelete_default;
ListCache.prototype.get = listCacheGet_default;
ListCache.prototype.has = listCacheHas_default;
ListCache.prototype.set = listCacheSet_default;
var ListCache_default = ListCache;
var Map2 = getNative_default(root_default, "Map");
var Map_default = Map2;
function mapCacheClear() {
this.size = 0;
this.__data__ = {
"hash": new Hash_default(),
"map": new (Map_default || ListCache_default)(),
"string": new Hash_default()
};
}
__name(mapCacheClear, "mapCacheClear");
__name2(mapCacheClear, "mapCacheClear");
var mapCacheClear_default = mapCacheClear;
function isKeyable(value) {
var type = typeof value;
return type == "string" || type == "number" || type == "symbol" || type == "boolean" ? value !== "__proto__" : value === null;
}
__name(isKeyable, "isKeyable");
__name2(isKeyable, "isKeyable");
var isKeyable_default = isKeyable;
function getMapData(map3, key) {
var data = map3.__data__;
return isKeyable_default(key) ? data[typeof key == "string" ? "string" : "hash"] : data.map;
}
__name(getMapData, "getMapData");
__name2(getMapData, "getMapData");
var getMapData_default = getMapData;
function mapCacheDelete(key) {
var result = getMapData_default(this, key)["delete"](key);
this.size -= result ? 1 : 0;
return result;
}
__name(mapCacheDelete, "mapCacheDelete");
__name2(mapCacheDelete, "mapCacheDelete");
var mapCacheDelete_default = mapCacheDelete;
function mapCacheGet(key) {
return getMapData_default(this, key).get(key);
}
__name(mapCacheGet, "mapCacheGet");
__name2(mapCacheGet, "mapCacheGet");
var mapCacheGet_default = mapCacheGet;
function mapCacheHas(key) {
return getMapData_default(this, key).has(key);
}
__name(mapCacheHas, "mapCacheHas");
__name2(mapCacheHas, "mapCacheHas");
var mapCacheHas_default = mapCacheHas;
function mapCacheSet(key, value) {
var data = getMapData_default(this, key), size = data.size;
data.set(key, value);
this.size += data.size == size ? 0 : 1;
return this;
}
__name(mapCacheSet, "mapCacheSet");
__name2(mapCacheSet, "mapCacheSet");
var mapCacheSet_default = mapCacheSet;
function MapCache(entries) {
var index = -1, length = entries == null ? 0 : entries.length;
this.clear();
while (++index < length) {
var entry = entries[index];
this.set(entry[0], entry[1]);
}
}
__name(MapCache, "MapCache");
__name2(MapCache, "MapCache");
MapCache.prototype.clear = mapCacheClear_default;
MapCache.prototype["delete"] = mapCacheDelete_default;
MapCache.prototype.get = mapCacheGet_default;
MapCache.prototype.has = mapCacheHas_default;
MapCache.prototype.set = mapCacheSet_default;
var MapCache_default = MapCache;
var FUNC_ERROR_TEXT = "Expected a function";
function memoize(func, resolver) {
if (typeof func != "function" || resolver != null && typeof resolver != "function") {
throw new TypeError(FUNC_ERROR_TEXT);
}
var memoized = /* @__PURE__ */ __name2(function() {
var args = arguments, key = resolver ? resolver.apply(this, args) : args[0], cache = memoized.cache;
if (cache.has(key)) {
return cache.get(key);
}
var result = func.apply(this, args);
memoized.cache = cache.set(key, result) || cache;
return result;
}, "memoized");
memoized.cache = new (memoize.Cache || MapCache_default)();
return memoized;
}
__name(memoize, "memoize");
__name2(memoize, "memoize");
memoize.Cache = MapCache_default;
var memoize_default = memoize;
var MAX_MEMOIZE_SIZE = 500;
function memoizeCapped(func) {
var result = memoize_default(func, function(key) {
if (cache.size === MAX_MEMOIZE_SIZE) {
cache.clear();
}
return key;
});
var cache = result.cache;
return result;
}
__name(memoizeCapped, "memoizeCapped");
__name2(memoizeCapped, "memoizeCapped");
var memoizeCapped_default = memoizeCapped;
var rePropName = /[^.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|$))/g;
var reEscapeChar = /\\(\\)?/g;
var stringToPath = memoizeCapped_default(function(string) {
var result = [];
if (string.charCodeAt(0) === 46) {
result.push("");
}
string.replace(rePropName, function(match, number, quote, subString) {
result.push(quote ? subString.replace(reEscapeChar, "$1") : number || match);
});
return result;
});
var stringToPath_default = stringToPath;
function toString2(value) {
return value == null ? "" : baseToString_default(value);
}
__name(toString2, "toString2");
__name2(toString2, "toString");
var toString_default = toString2;
function castPath(value, object) {
if (isArray_default(value)) {
return value;
}
return isKey_default(value, object) ? [value] : stringToPath_default(toString_default(value));
}
__name(castPath, "castPath");
__name2(castPath, "castPath");
var castPath_default = castPath;
var INFINITY3 = 1 / 0;
function toKey(value) {
if (typeof value == "string" || isSymbol_default(value)) {
return value;
}
var result = value + "";
return result == "0" && 1 / value == -INFINITY3 ? "-0" : result;
}
__name(toKey, "toKey");
__name2(toKey, "toKey");
var toKey_default = toKey;
function baseGet(object, path) {
path = castPath_default(path, object);
var index = 0, length = path.length;
while (object != null && index < length) {
object = object[toKey_default(path[index++])];
}
return index && index == length ? object : void 0;
}
__name(baseGet, "baseGet");
__name2(baseGet, "baseGet");
var baseGet_default = baseGet;
function get(object, path, defaultValue) {
var result = object == null ? void 0 : baseGet_default(object, path);
return result === void 0 ? defaultValue : result;
}
__name(get, "get");
__name2(get, "get");
var get_default = get;
function arrayPush(array, values2) {
var index = -1, length = values2.length, offset = array.length;
while (++index < length) {
array[offset + index] = values2[index];
}
return array;
}
__name(arrayPush, "arrayPush");
__name2(arrayPush, "arrayPush");
var arrayPush_default = arrayPush;
var spreadableSymbol = Symbol_default ? Symbol_default.isConcatSpreadable : void 0;
function isFlattenable(value) {
return isArray_default(value) || isArguments_default(value) || !!(spreadableSymbol && value && value[spreadableSymbol]);
}
__name(isFlattenable, "isFlattenable");
__name2(isFlattenable, "isFlattenable");
var isFlattenable_default = isFlattenable;
function baseFlatten(array, depth, predicate, isStrict, result) {
var index = -1, length = array.length;
predicate || (predicate = isFlattenable_default);
result || (result = []);
while (++index < length) {
var value = array[index];
if (depth > 0 && predicate(value)) {
if (depth > 1) {
baseFlatten(value, depth - 1, predicate, isStrict, result);
} else {
arrayPush_default(result, value);
}
} else if (!isStrict) {
result[result.length] = value;
}
}
return result;
}
__name(baseFlatten, "baseFlatten");
__name2(baseFlatten, "baseFlatten");
var baseFlatten_default = baseFlatten;
function flatten(array) {
var length = array == null ? 0 : array.length;
return length ? baseFlatten_default(array, 1) : [];
}
__name(flatten, "flatten");
__name2(flatten, "flatten");
var flatten_default = flatten;
var getPrototype = overArg_default(Object.getPrototypeOf, Object);
var getPrototype_default = getPrototype;
function baseSlice(array, start, end) {
var index = -1, length = array.length;
if (start < 0) {
start = -start > length ? 0 : length + start;
}
end = end > length ? length : end;
if (end < 0) {
end += length;
}
length = start > end ? 0 : end - start >>> 0;
start >>>= 0;
var result = Array(length);
while (++index < length) {
result[index] = array[index + start];
}
return result;
}
__name(baseSlice, "baseSlice");
__name2(baseSlice, "baseSlice");
var baseSlice_default = baseSlice;
function arrayReduce(array, iteratee, accumulator, initAccum) {
var index = -1, length = array == null ? 0 : array.length;
if (initAccum && length) {
accumulator = array[++index];
}
while (++index < length) {
accumulator = iteratee(accumulator, array[index], index, array);
}
return accumulator;
}
__name(arrayReduce, "arrayReduce");
__name2(arrayReduce, "arrayReduce");
var arrayReduce_default = arrayReduce;
function stackClear() {
this.__data__ = new ListCache_default();
this.size = 0;
}
__name(stackClear, "stackClear");
__name2(stackClear, "stackClear");
var stackClear_default = stackClear;
function stackDelete(key) {
var data = this.__data__, result = data["delete"](key);
this.size = data.size;
return result;
}
__name(stackDelete, "stackDelete");
__name2(stackDelete, "stackDelete");
var stackDelete_default = stackDelete;
function stackGet(key) {
return this.__data__.get(key);
}
__name(stackGet, "stackGet");
__name2(stackGet, "stackGet");
var stackGet_default = stackGet;
function stackHas(key) {
return this.__data__.has(key);
}
__name(stackHas, "stackHas");
__name2(stackHas, "stackHas");
var stackHas_default = stackHas;
var LARGE_ARRAY_SIZE = 200;
function stackSet(key, value) {
var data = this.__data__;
if (data instanceof ListCache_default) {
var pairs = data.__data__;
if (!Map_default || pairs.length < LARGE_ARRAY_SIZE - 1) {
pairs.push([key, value]);
this.size = ++data.size;
return this;
}
data = this.__data__ = new MapCache_default(pairs);
}
data.set(key, value);
this.size = data.size;
return this;
}
__name(stackSet, "stackSet");
__name2(stackSet, "stackSet");
var stackSet_default = stackSet;
function Stack(entries) {
var data = this.__data__ = new ListCache_default(entries);
this.size = data.size;
}
__name(Stack, "Stack");
__name2(Stack, "Stack");
Stack.prototype.clear = stackClear_default;
Stack.prototype["delete"] = stackDelete_default;
Stack.prototype.get = stackGet_default;
Stack.prototype.has = stackHas_default;
Stack.prototype.set = stackSet_default;
var Stack_default = Stack;
function baseAssign(object, source) {
return object && copyObject_default(source, keys_default(source), object);
}
__name(baseAssign, "baseAssign");
__name2(baseAssign, "baseAssign");
var baseAssign_default = baseAssign;
function baseAssignIn(object, source) {
return object && copyObject_default(source, keysIn_default(source), object);
}
__name(baseAssignIn, "baseAssignIn");
__name2(baseAssignIn, "baseAssignIn");
var baseAssignIn_default = baseAssignIn;
var freeExports3 = typeof exports == "object" && exports && !exports.nodeType && exports;
var freeModule3 = freeExports3 && typeof module == "object" && module && !module.nodeType && module;
var moduleExports3 = freeModule3 && freeModule3.exports === freeExports3;
var Buffer3 = moduleExports3 ? root_default.Buffer : void 0;
var allocUnsafe = Buffer3 ? Buffer3.allocUnsafe : void 0;
function cloneBuffer(buffer, isDeep) {
if (isDeep) {
return buffer.slice();
}
var length = buffer.length, result = allocUnsafe ? allocUnsafe(length) : new buffer.constructor(length);
buffer.copy(result);
return result;
}
__name(cloneBuffer, "cloneBuffer");
__name2(cloneBuffer, "cloneBuffer");
var cloneBuffer_default = cloneBuffer;
function arrayFilter(array, predicate) {
var index = -1, length = array == null ? 0 : array.length, resIndex = 0, result = [];
while (++index < length) {
var value = array[index];
if (predicate(value, index, array)) {
result[resIndex++] = value;
}
}
return result;
}
__name(arrayFilter, "arrayFilter");
__name2(arrayFilter, "arrayFilter");
var arrayFilter_default = arrayFilter;
function stubArray() {
return [];
}
__name(stubArray, "stubArray");
__name2(stubArray, "stubArray");
var stubArray_default = stubArray;
var objectProto13 = Object.prototype;
var propertyIsEnumerable2 = objectProto13.propertyIsEnumerable;
var nativeGetSymbols = Object.getOwnPropertySymbols;
var getSymbols = !nativeGetSymbols ? stubArray_default : function(object) {
if (object == null) {
return [];
}
object = Object(object);
return arrayFilter_default(nativeGetSymbols(object), function(symbol) {
return propertyIsEnumerable2.call(object, symbol);
});
};
var getSymbols_default = getSymbols;
function copySymbols(source, object) {
return copyObject_default(source, getSymbols_default(source), object);
}
__name(copySymbols, "copySymbols");
__name2(copySymbols, "copySymbols");
var copySymbols_default = copySymbols;
var nativeGetSymbols2 = Object.getOwnPropertySymbols;
var getSymbolsIn = !nativeGetSymbols2 ? stubArray_default : function(object) {
var result = [];
while (object) {
arrayPush_default(result, getSymbols_default(object));
object = getPrototype_default(object);
}
return result;
};
var getSymbolsIn_default = getSymbolsIn;
function copySymbolsIn(source, object) {
return copyObject_default(source, getSymbolsIn_default(source), object);
}
__name(copySymbolsIn, "copySymbolsIn");
__name2(copySymbolsIn, "copySymbolsIn");
var copySymbolsIn_default = copySymbolsIn;
function baseGetAllKeys(object, keysFunc, symbolsFunc) {
var result = keysFunc(object);
return isArray_default(object) ? result : arrayPush_default(result, symbolsFunc(object));
}
__name(baseGetAllKeys, "baseGetAllKeys");
__name2(baseGetAllKeys, "baseGetAllKeys");
var baseGetAllKeys_default = baseGetAllKeys;
function getAllKeys(object) {
return baseGetAllKeys_default(object, keys_default, getSymbols_default);
}
__name(getAllKeys, "getAllKeys");
__name2(getAllKeys, "getAllKeys");
var getAllKeys_default = getAllKeys;
function getAllKeysIn(object) {
return baseGetAllKeys_default(object, keysIn_default, getSymbolsIn_default);
}
__name(getAllKeysIn, "getAllKeysIn");
__name2(getAllKeysIn, "getAllKeysIn");
var getAllKeysIn_default = getAllKeysIn;
var DataView = getNative_default(root_default, "DataView");
var DataView_default = DataView;
var Promise2 = getNative_default(root_default, "Promise");
var Promise_default = Promise2;
var Set2 = getNative_default(root_default, "Set");
var Set_default = Set2;
var mapTag2 = "[object Map]";
var objectTag2 = "[object Object]";
var promiseTag = "[object Promise]";
var setTag2 = "[object Set]";
var weakMapTag2 = "[object WeakMap]";
var dataViewTag2 = "[object DataView]";
var dataViewCtorString = toSource_default(DataView_default);
var mapCtorString = toSource_default(Map_default);
var promiseCtorString = toSource_default(Promise_default);
var setCtorString = toSource_default(Set_default);
var weakMapCtorString = toSource_default(WeakMap_default);
var getTag = baseGetTag_default;
if (DataView_default && getTag(new DataView_default(new ArrayBuffer(1))) != dataViewTag2 || Map_default && getTag(new Map_default()) != mapTag2 || Promise_default && getTag(Promise_default.resolve()) != promiseTag || Set_default && getTag(new Set_default()) != setTag2 || WeakMap_default && getTag(new WeakMap_default()) != weakMapTag2) {
getTag = /* @__PURE__ */ __name2(function(value) {
var result = baseGetTag_default(value), Ctor = result == objectTag2 ? value.constructor : void 0, ctorString = Ctor ? toSource_default(Ctor) : "";
if (ctorString) {
switch (ctorString) {
case dataViewCtorString:
return dataViewTag2;
case mapCtorString:
return mapTag2;
case promiseCtorString:
return promiseTag;
case setCtorString:
return setTag2;
case weakMapCtorString:
return weakMapTag2;
}
}
return result;
}, "getTag");
}
var getTag_default = getTag;
var objectProto14 = Object.prototype;
var hasOwnProperty11 = objectProto14.hasOwnProperty;
function initCloneArray(array) {
var length = array.length, result = new array.constructor(length);
if (length && typeof array[0] == "string" && hasOwnProperty11.call(array, "index")) {
result.index = array.index;
result.input = array.input;
}
return result;
}
__name(initCloneArray, "initCloneArray");
__name2(initCloneArray, "initCloneArray");
var initCloneArray_default = initCloneArray;
var Uint8Array2 = root_default.Uint8Array;
var Uint8Array_default = Uint8Array2;
function cloneArrayBuffer(arrayBuffer) {
var result = new arrayBuffer.constructor(arrayBuffer.byteLength);
new Uint8Array_default(result).set(new Uint8Array_default(arrayBuffer));
return result;
}
__name(cloneArrayBuffer, "cloneArrayBuffer");
__name2(cloneArrayBuffer, "cloneArrayBuffer");
var cloneArrayBuffer_default = cloneArrayBuffer;
function cloneDataView(dataView, isDeep) {
var buffer = isDeep ? cloneArrayBuffer_default(dataView.buffer) : dataView.buffer;
return new dataView.constructor(buffer, dataView.byteOffset, dataView.byteLength);
}
__name(cloneDataView, "cloneDataView");
__name2(cloneDataView, "cloneDataView");
var cloneDataView_default = cloneDataView;
var reFlags = /\w*$/;
function cloneRegExp(regexp) {
var result = new regexp.constructor(regexp.source, reFlags.exec(regexp));
result.lastIndex = regexp.lastIndex;
return result;
}
__name(cloneRegExp, "cloneRegExp");
__name2(cloneRegExp, "cloneRegExp");
var cloneRegExp_default = cloneRegExp;
var symbolProto2 = Symbol_default ? Symbol_default.prototype : void 0;
var symbolValueOf = symbolProto2 ? symbolProto2.valueOf : void 0;
function cloneSymbol(symbol) {
return symbolValueOf ? Object(symbolValueOf.call(symbol)) : {};
}
__name(cloneSymbol, "cloneSymbol");
__name2(cloneSymbol, "cloneSymbol");
var cloneSymbol_default = cloneSymbol;
function cloneTypedArray(typedArray, isDeep) {
var buffer = isDeep ? cloneArrayBuffer_default(typedArray.buffer) : typedArray.buffer;
return new typedArray.constructor(buffer, typedArray.byteOffset, typedArray.length);
}
__name(cloneTypedArray, "cloneTypedArray");
__name2(cloneTypedArray, "cloneTypedArray");
var cloneTypedArray_default = cloneTypedArray;
var boolTag2 = "[object Boolean]";
var dateTag2 = "[object Date]";
var mapTag3 = "[object Map]";
var numberTag2 = "[object Number]";
var regexpTag2 = "[object RegExp]";
var setTag3 = "[object Set]";
var stringTag2 = "[object String]";
var symbolTag2 = "[object Symbol]";
var arrayBufferTag2 = "[object ArrayBuffer]";
var dataViewTag3 = "[object DataView]";
var float32Tag2 = "[object Float32Array]";
var float64Tag2 = "[object Float64Array]";
var int8Tag2 = "[object Int8Array]";
var int16Tag2 = "[object Int16Array]";
var int32Tag2 = "[object Int32Array]";
var uint8Tag2 = "[object Uint8Array]";
var uint8ClampedTag2 = "[object Uint8ClampedArray]";
var uint16Tag2 = "[object Uint16Array]";
var uint32Tag2 = "[object Uint32Array]";
function initCloneByTag(object, tag, isDeep) {
var Ctor = object.constructor;
switch (tag) {
case arrayBufferTag2:
return cloneArrayBuffer_default(object);
case boolTag2:
case dateTag2:
return new Ctor(+object);
case dataViewTag3:
return cloneDataView_default(object, isDeep);
case float32Tag2:
case float64Tag2:
case int8Tag2:
case int16Tag2:
case int32Tag2:
case uint8Tag2:
case uint8ClampedTag2:
case uint16Tag2:
case uint32Tag2:
return cloneTypedArray_default(object, isDeep);
case mapTag3:
return new Ctor();
case numberTag2:
case stringTag2:
return new Ctor(object);
case regexpTag2:
return cloneRegExp_default(object);
case setTag3:
return new Ctor();
case symbolTag2:
return cloneSymbol_default(object);
}
}
__name(initCloneByTag, "initCloneByTag");
__name2(initCloneByTag, "initCloneByTag");
var initCloneByTag_default = initCloneByTag;
function initCloneObject(object) {
return typeof object.constructor == "function" && !isPrototype_default(object) ? baseCreate_default(getPrototype_default(object)) : {};
}
__name(initCloneObject, "initCloneObject");
__name2(initCloneObject, "initCloneObject");
var initCloneObject_default = initCloneObject;
var mapTag4 = "[object Map]";
function baseIsMap(value) {
return isObjectLike_default(value) && getTag_default(value) == mapTag4;
}
__name(baseIsMap, "baseIsMap");
__name2(baseIsMap, "baseIsMap");
var baseIsMap_default = baseIsMap;
var nodeIsMap = nodeUtil_default && nodeUtil_default.isMap;
var isMap = nodeIsMap ? baseUnary_default(nodeIsMap) : baseIsMap_default;
var isMap_default = isMap;
var setTag4 = "[object Set]";
function baseIsSet(value) {
return isObjectLike_default(value) && getTag_default(value) == setTag4;
}
__name(baseIsSet, "baseIsSet");
__name2(baseIsSet, "baseIsSet");
var baseIsSet_default = baseIsSet;
var nodeIsSet = nodeUtil_default && nodeUtil_default.isSet;
var isSet = nodeIsSet ? baseUnary_default(nodeIsSet) : baseIsSet_default;
var isSet_default = isSet;
var CLONE_DEEP_FLAG = 1;
var CLONE_FLAT_FLAG = 2;
var CLONE_SYMBOLS_FLAG = 4;
var argsTag3 = "[object Arguments]";
var arrayTag2 = "[object Array]";
var boolTag3 = "[object Boolean]";
var dateTag3 = "[object Date]";
var errorTag2 = "[object Error]";
var funcTag3 = "[object Function]";
var genTag2 = "[object GeneratorFunction]";
var mapTag5 = "[object Map]";
var numberTag3 = "[object Number]";
var objectTag3 = "[object Object]";
var regexpTag3 = "[object RegExp]";
var setTag5 = "[object Set]";
var stringTag3 = "[object String]";
var symbolTag3 = "[object Symbol]";
var weakMapTag3 = "[object WeakMap]";
var arrayBufferTag3 = "[object ArrayBuffer]";
var dataViewTag4 = "[object DataView]";
var float32Tag3 = "[object Float32Array]";
var float64Tag3 = "[object Float64Array]";
var int8Tag3 = "[object Int8Array]";
var int16Tag3 = "[object Int16Array]";
var int32Tag3 = "[object Int32Array]";
var uint8Tag3 = "[object Uint8Array]";
var uint8ClampedTag3 = "[object Uint8ClampedArray]";
var uint16Tag3 = "[object Uint16Array]";
var uint32Tag3 = "[object Uint32Array]";
var cloneableTags = {};
cloneableTags[argsTag3] = cloneableTags[arrayTag2] = cloneableTags[arrayBufferTag3] = cloneableTags[dataViewTag4] = cloneableTags[boolTag3] = cloneableTags[dateTag3] = cloneableTags[float32Tag3] = cloneableTags[float64Tag3] = cloneableTags[int8Tag3] = cloneableTags[int16Tag3] = cloneableTags[int32Tag3] = cloneableTags[mapTag5] = cloneableTags[numberTag3] = cloneableTags[objectTag3] = cloneableTags[regexpTag3] = cloneableTags[setTag5] = cloneableTags[stringTag3] = cloneableTags[symbolTag3] = cloneableTags[uint8Tag3] = cloneableTags[uint8ClampedTag3] = cloneableTags[uint16Tag3] = cloneableTags[uint32Tag3] = true;
cloneableTags[errorTag2] = cloneableTags[funcTag3] = cloneableTags[weakMapTag3] = false;
function baseClone(value, bitmask, customizer, key, object, stack) {
var result, isDeep = bitmask & CLONE_DEEP_FLAG, isFlat = bitmask & CLONE_FLAT_FLAG, isFull = bitmask & CLONE_SYMBOLS_FLAG;
if (customizer) {
result = object ? customizer(value, key, object, stack) : customizer(value);
}
if (result !== void 0) {
return result;
}
if (!isObject_default(value)) {
return value;
}
var isArr = isArray_default(value);
if (isArr) {
result = initCloneArray_default(value);
if (!isDeep) {
return copyArray_default(value, result);
}
} else {
var tag = getTag_default(value), isFunc = tag == funcTag3 || tag == genTag2;
if (isBuffer_default(value)) {
return cloneBuffer_default(value, isDeep);
}
if (tag == objectTag3 || tag == argsTag3 || isFunc && !object) {
result = isFlat || isFunc ? {} : initCloneObject_default(value);
if (!isDeep) {
return isFlat ? copySymbolsIn_default(value, baseAssignIn_default(result, value)) : copySymbols_default(value, baseAssign_default(result, value));
}
} else {
if (!cloneableTags[tag]) {
return object ? value : {};
}
result = initCloneByTag_default(value, tag, isDeep);
}
}
stack || (stack = new Stack_default());
var stacked = stack.get(value);
if (stacked) {
return stacked;
}
stack.set(value, result);
if (isSet_default(value)) {
value.forEach(function(subValue) {
result.add(baseClone(subValue, bitmask, customizer, subValue, value, stack));
});
} else if (isMap_default(value)) {
value.forEach(function(subValue, key2) {
result.set(key2, baseClone(subValue, bitmask, customizer, key2, value, stack));
});
}
var keysFunc = isFull ? isFlat ? getAllKeysIn_default : getAllKeys_default : isFlat ? keysIn_default : keys_default;
var props = isArr ? void 0 : keysFunc(value);
arrayEach_default(props || value, function(subValue, key2) {
if (props) {
key2 = subValue;
subValue = value[key2];
}
assignValue_default(result, key2, baseClone(subValue, bitmask, customizer, key2, value, stack));
});
return result;
}
__name(baseClone, "baseClone");
__name2(baseClone, "baseClone");
var baseClone_default = baseClone;
var CLONE_SYMBOLS_FLAG2 = 4;
function clone(value) {
return baseClone_default(value, CLONE_SYMBOLS_FLAG2);
}
__name(clone, "clone");
__name2(clone, "clone");
var clone_default = clone;
function compact(array) {
var index = -1, length = array == null ? 0 : array.length, resIndex = 0, result = [];
while (++index < length) {
var value = array[index];
if (value) {
result[resIndex++] = value;
}
}
return result;
}
__name(compact, "compact");
__name2(compact, "compact");
var compact_default = compact;
var HASH_UNDEFINED3 = "__lodash_hash_undefined__";
function setCacheAdd(value) {
this.__data__.set(value, HASH_UNDEFINED3);
return this;
}
__name(setCacheAdd, "setCacheAdd");
__name2(setCacheAdd, "setCacheAdd");
var setCacheAdd_default = setCacheAdd;
function setCacheHas(value) {
return this.__data__.has(value);
}
__name(setCacheHas, "setCacheHas");
__name2(setCacheHas, "setCacheHas");
var setCacheHas_default = setCacheHas;
function SetCache(values2) {
var index = -1, length = values2 == null ? 0 : values2.length;
this.__data__ = new MapCache_default();
while (++index < length) {
this.add(values2[index]);
}
}
__name(SetCache, "SetCache");
__name2(SetCache, "SetCache");
SetCache.prototype.add = SetCache.prototype.push = setCacheAdd_default;
SetCache.prototype.has = setCacheHas_default;
var SetCache_default = SetCache;
function arraySome(array, predicate) {
var index = -1, length = array == null ? 0 : array.length;
while (++index < length) {
if (predicate(array[index], index, array)) {
return true;
}
}
return false;
}
__name(arraySome, "arraySome");
__name2(arraySome, "arraySome");
var arraySome_default = arraySome;
function cacheHas(cache, key) {
return cache.has(key);
}
__name(cacheHas, "cacheHas");
__name2(cacheHas, "cacheHas");
var cacheHas_default = cacheHas;
var COMPARE_PARTIAL_FLAG = 1;
var COMPARE_UNORDERED_FLAG = 2;
function equalArrays(array, other, bitmask, customizer, equalFunc, stack) {
var isPartial = bitmask & COMPARE_PARTIAL_FLAG, arrLength = array.length, othLength = other.length;
if (arrLength != othLength && !(isPartial && othLength > arrLength)) {
return false;
}
var arrStacked = stack.get(array);
var othStacked = stack.get(other);
if (arrStacked && othStacked) {
return arrStacked == other && othStacked == array;
}
var index = -1, result = true, seen = bitmask & COMPARE_UNORDERED_FLAG ? new SetCache_default() : void 0;
stack.set(array, other);
stack.set(other, array);
while (++index < arrLength) {
var arrValue = array[index], othValue = other[index];
if (customizer) {
var compared = isPartial ? customizer(othValue, arrValue, index, other, array, stack) : customizer(arrValue, othValue, index, array, other, stack);
}
if (compared !== void 0) {
if (compared) {
continue;
}
result = false;
break;
}
if (seen) {
if (!arraySome_default(other, function(othValue2, othIndex) {
if (!cacheHas_default(seen, othIndex) && (arrValue === othValue2 || equalFunc(arrValue, othValue2, bitmask, customizer, stack))) {
return seen.push(othIndex);
}
})) {
result = false;
break;
}
} else if (!(arrValue === othValue || equalFunc(arrValue, othValue, bitmask, customizer, stack))) {
result = false;
break;
}
}
stack["delete"](array);
stack["delete"](other);
return result;
}
__name(equalArrays, "equalArrays");
__name2(equalArrays, "equalArrays");
var equalArrays_default = equalArrays;
function mapToArray(map3) {
var index = -1, result = Array(map3.size);
map3.forEach(function(value, key) {
result[++index] = [key, value];
});
return result;
}
__name(mapToArray, "mapToArray");
__name2(mapToArray, "mapToArray");
var mapToArray_default = mapToArray;
function setToArray(set) {
var index = -1, result = Array(set.size);
set.forEach(function(value) {
result[++index] = value;
});
return result;
}
__name(setToArray, "setToArray");
__name2(setToArray, "setToArray");
var setToArray_default = setToArray;
var COMPARE_PARTIAL_FLAG2 = 1;
var COMPARE_UNORDERED_FLAG2 = 2;
var boolTag4 = "[object Boolean]";
var dateTag4 = "[object Date]";
var errorTag3 = "[object Error]";
var mapTag6 = "[object Map]";
var numberTag4 = "[object Number]";
var regexpTag4 = "[object RegExp]";
var setTag6 = "[object Set]";
var stringTag4 = "[object String]";
var symbolTag4 = "[object Symbol]";
var arrayBufferTag4 = "[object ArrayBuffer]";
var dataViewTag5 = "[object DataView]";
var symbolProto3 = Symbol_default ? Symbol_default.prototype : void 0;
var symbolValueOf2 = symbolProto3 ? symbolProto3.valueOf : void 0;
function equalByTag(object, other, tag, bitmask, customizer, equalFunc, stack) {
switch (tag) {
case dataViewTag5:
if (object.byteLength != other.byteLength || object.byteOffset != other.byteOffset) {
return false;
}
object = object.buffer;
other = other.buffer;
case arrayBufferTag4:
if (object.byteLength != other.byteLength || !equalFunc(new Uint8Array_default(object), new Uint8Array_default(other))) {
return false;
}
return true;
case boolTag4:
case dateTag4:
case numberTag4:
return eq_default(+object, +other);
case errorTag3:
return object.name == other.name && object.message == other.message;
case regexpTag4:
case stringTag4:
return object == other + "";
case mapTag6:
var convert = mapToArray_default;
case setTag6:
var isPartial = bitmask & COMPARE_PARTIAL_FLAG2;
convert || (convert = setToArray_default);
if (object.size != other.size && !isPartial) {
return false;
}
var stacked = stack.get(object);
if (stacked) {
return stacked == other;
}
bitmask |= COMPARE_UNORDERED_FLAG2;
stack.set(object, other);
var result = equalArrays_default(convert(object), convert(other), bitmask, customizer, equalFunc, stack);
stack["delete"](object);
return result;
case symbolTag4:
if (symbolValueOf2) {
return symbolValueOf2.call(object) == symbolValueOf2.call(other);
}
}
return false;
}
__name(equalByTag, "equalByTag");
__name2(equalByTag, "equalByTag");
var equalByTag_default = equalByTag;
var COMPARE_PARTIAL_FLAG3 = 1;
var objectProto15 = Object.prototype;
var hasOwnProperty12 = objectProto15.hasOwnProperty;
function equalObjects(object, other, bitmask, customizer, equalFunc, stack) {
var isPartial = bitmask & COMPARE_PARTIAL_FLAG3, objProps = getAllKeys_default(object), objLength = objProps.length, othProps = getAllKeys_default(other), othLength = othProps.length;
if (objLength != othLength && !isPartial) {
return false;
}
var index = objLength;
while (index--) {
var key = objProps[index];
if (!(isPartial ? key in other : hasOwnProperty12.call(other, key))) {
return false;
}
}
var objStacked = stack.get(object);
var othStacked = stack.get(other);
if (objStacked && othStacked) {
return objStacked == other && othStacked == object;
}
var result = true;
stack.set(object, other);
stack.set(other, object);
var skipCtor = isPartial;
while (++index < objLength) {
key = objProps[index];
var objValue = object[key], othValue = other[key];
if (customizer) {
var compared = isPartial ? customizer(othValue, objValue, key, other, object, stack) : customizer(objValue, othValue, key, object, other, stack);
}
if (!(compared === void 0 ? objValue === othValue || equalFunc(objValue, othValue, bitmask, customizer, stack) : compared)) {
result = false;
break;
}
skipCtor || (skipCtor = key == "constructor");
}
if (result && !skipCtor) {
var objCtor = object.constructor, othCtor = other.constructor;
if (objCtor != othCtor && ("constructor" in object && "constructor" in other) && !(typeof objCtor == "function" && objCtor instanceof objCtor && typeof othCtor == "function" && othCtor instanceof othCtor)) {
result = false;
}
}
stack["delete"](object);
stack["delete"](other);
return result;
}
__name(equalObjects, "equalObjects");
__name2(equalObjects, "equalObjects");
var equalObjects_default = equalObjects;
var COMPARE_PARTIAL_FLAG4 = 1;
var argsTag4 = "[object Arguments]";
var arrayTag3 = "[object Array]";
var objectTag4 = "[object Object]";
var objectProto16 = Object.prototype;
var hasOwnProperty13 = objectProto16.hasOwnProperty;
function baseIsEqualDeep(object, other, bitmask, customizer, equalFunc, stack) {
var objIsArr = isArray_default(object), othIsArr = isArray_default(other), objTag = objIsArr ? arrayTag3 : getTag_default(object), othTag = othIsArr ? arrayTag3 : getTag_default(other);
objTag = objTag == argsTag4 ? objectTag4 : objTag;
othTag = othTag == argsTag4 ? objectTag4 : othTag;
var objIsObj = objTag == objectTag4, othIsObj = othTag == objectTag4, isSameTag = objTag == othTag;
if (isSameTag && isBuffer_default(object)) {
if (!isBuffer_default(other)) {
return false;
}
objIsArr = true;
objIsObj = false;
}
if (isSameTag && !objIsObj) {
stack || (stack = new Stack_default());
return objIsArr || isTypedArray_default(object) ? equalArrays_default(object, other, bitmask, customizer, equalFunc, stack) : equalByTag_default(object, other, objTag, bitmask, customizer, equalFunc, stack);
}
if (!(bitmask & COMPARE_PARTIAL_FLAG4)) {
var objIsWrapped = objIsObj && hasOwnProperty13.call(object, "__wrapped__"), othIsWrapped = othIsObj && hasOwnProperty13.call(other, "__wrapped__");
if (objIsWrapped || othIsWrapped) {
var objUnwrapped = objIsWrapped ? object.value() : object, othUnwrapped = othIsWrapped ? other.value() : other;
stack || (stack = new Stack_default());
return equalFunc(objUnwrapped, othUnwrapped, bitmask, customizer, stack);
}
}
if (!isSameTag) {
return false;
}
stack || (stack = new Stack_default());
return equalObjects_default(object, other, bitmask, customizer, equalFunc, stack);
}
__name(baseIsEqualDeep, "baseIsEqualDeep");
__name2(baseIsEqualDeep, "baseIsEqualDeep");
var baseIsEqualDeep_default = baseIsEqualDeep;
function baseIsEqual(value, other, bitmask, customizer, stack) {
if (value === other) {
return true;
}
if (value == null || other == null || !isObjectLike_default(value) && !isObjectLike_default(other)) {
return value !== value && other !== other;
}
return baseIsEqualDeep_default(value, other, bitmask, customizer, baseIsEqual, stack);
}
__name(baseIsEqual, "baseIsEqual");
__name2(baseIsEqual, "baseIsEqual");
var baseIsEqual_default = baseIsEqual;
var COMPARE_PARTIAL_FLAG5 = 1;
var COMPARE_UNORDERED_FLAG3 = 2;
function baseIsMatch(object, source, matchData, customizer) {
var index = matchData.length, length = index, noCustomizer = !customizer;
if (object == null) {
return !length;
}
object = Object(object);
while (index--) {
var data = matchData[index];
if (noCustomizer && data[2] ? data[1] !== object[data[0]] : !(data[0] in object)) {
return false;
}
}
while (++index < length) {
data = matchData[index];
var key = data[0], objValue = object[key], srcValue = data[1];
if (noCustomizer && data[2]) {
if (objValue === void 0 && !(key in object)) {
return false;
}
} else {
var stack = new Stack_default();
if (customizer) {
var result = customizer(objValue, srcValue, key, object, source, stack);
}
if (!(result === void 0 ? baseIsEqual_default(srcValue, objValue, COMPARE_PARTIAL_FLAG5 | COMPARE_UNORDERED_FLAG3, customizer, stack) : result)) {
return false;
}
}
}
return true;
}
__name(baseIsMatch, "baseIsMatch");
__name2(baseIsMatch, "baseIsMatch");
var baseIsMatch_default = baseIsMatch;
function isStrictComparable(value) {
return value === value && !isObject_default(value);
}
__name(isStrictComparable, "isStrictComparable");
__name2(isStrictComparable, "isStrictComparable");
var isStrictComparable_default = isStrictComparable;
function getMatchData(object) {
var result = keys_default(object), length = result.length;
while (length--) {
var key = result[length], value = object[key];
result[length] = [key, value, isStrictComparable_default(value)];
}
return result;
}
__name(getMatchData, "getMatchData");
__name2(getMatchData, "getMatchData");
var getMatchData_default = getMatchData;
function matchesStrictComparable(key, srcValue) {
return function(object) {
if (object == null) {
return false;
}
return object[key] === srcValue && (srcValue !== void 0 || key in Object(object));
};
}
__name(matchesStrictComparable, "matchesStrictComparable");
__name2(matchesStrictComparable, "matchesStrictComparable");
var matchesStrictComparable_default = matchesStrictComparable;
function baseMatches(source) {
var matchData = getMatchData_default(source);
if (matchData.length == 1 && matchData[0][2]) {
return matchesStrictComparable_default(matchData[0][0], matchData[0][1]);
}
return function(object) {
return object === source || baseIsMatch_default(object, source, matchData);
};
}
__name(baseMatches, "baseMatches");
__name2(baseMatches, "baseMatches");
var baseMatches_default = baseMatches;
function baseHasIn(object, key) {
return object != null && key in Object(object);
}
__name(baseHasIn, "baseHasIn");
__name2(baseHasIn, "baseHasIn");
var baseHasIn_default = baseHasIn;
function hasPath(object, path, hasFunc) {
path = castPath_default(path, object);
var index = -1, length = path.length, result = false;
while (++index < length) {
var key = toKey_default(path[index]);
if (!(result = object != null && hasFunc(object, key))) {
break;
}
object = object[key];
}
if (result || ++index != length) {
return result;
}
length = object == null ? 0 : object.length;
return !!length && isLength_default(length) && isIndex_default(key, length) && (isArray_default(object) || isArguments_default(object));
}
__name(hasPath, "hasPath");
__name2(hasPath, "hasPath");
var hasPath_default = hasPath;
function hasIn(object, path) {
return object != null && hasPath_default(object, path, baseHasIn_default);
}
__name(hasIn, "hasIn");
__name2(hasIn, "hasIn");
var hasIn_default = hasIn;
var COMPARE_PARTIAL_FLAG6 = 1;
var COMPARE_UNORDERED_FLAG4 = 2;
function baseMatchesProperty(path, srcValue) {
if (isKey_default(path) && isStrictComparable_default(srcValue)) {
return matchesStrictComparable_default(toKey_default(path), srcValue);
}
return function(object) {
var objValue = get_default(object, path);
return objValue === void 0 && objValue === srcValue ? hasIn_default(object, path) : baseIsEqual_default(srcValue, objValue, COMPARE_PARTIAL_FLAG6 | COMPARE_UNORDERED_FLAG4);
};
}
__name(baseMatchesProperty, "baseMatchesProperty");
__name2(baseMatchesProperty, "baseMatchesProperty");
var baseMatchesProperty_default = baseMatchesProperty;
function baseProperty(key) {
return function(object) {
return object == null ? void 0 : object[key];
};
}
__name(baseProperty, "baseProperty");
__name2(baseProperty, "baseProperty");
var baseProperty_default = baseProperty;
function basePropertyDeep(path) {
return function(object) {
return baseGet_default(object, path);
};
}
__name(basePropertyDeep, "basePropertyDeep");
__name2(basePropertyDeep, "basePropertyDeep");
var basePropertyDeep_default = basePropertyDeep;
function property(path) {
return isKey_default(path) ? baseProperty_default(toKey_default(path)) : basePropertyDeep_default(path);
}
__name(property, "property");
__name2(property, "property");
var property_default = property;
function baseIteratee(value) {
if (typeof value == "function") {
return value;
}
if (value == null) {
return identity_default;
}
if (typeof value == "object") {
return isArray_default(value) ? baseMatchesProperty_default(value[0], value[1]) : baseMatches_default(value);
}
return property_default(value);
}
__name(baseIteratee, "baseIteratee");
__name2(baseIteratee, "baseIteratee");
var baseIteratee_default = baseIteratee;
function arrayAggregator(array, setter, iteratee, accumulator) {
var index = -1, length = array == null ? 0 : array.length;
while (++index < length) {
var value = array[index];
setter(accumulator, value, iteratee(value), array);
}
return accumulator;
}
__name(arrayAggregator, "arrayAggregator");
__name2(arrayAggregator, "arrayAggregator");
var arrayAggregator_default = arrayAggregator;
function createBaseFor(fromRight) {
return function(object, iteratee, keysFunc) {
var index = -1, iterable = Object(object), props = keysFunc(object), length = props.length;
while (length--) {
var key = props[fromRight ? length : ++index];
if (iteratee(iterable[key], key, iterable) === false) {
break;
}
}
return object;
};
}
__name(createBaseFor, "createBaseFor");
__name2(createBaseFor, "createBaseFor");
var createBaseFor_default = createBaseFor;
var baseFor = createBaseFor_default();
var baseFor_default = baseFor;
function baseForOwn(object, iteratee) {
return object && baseFor_default(object, iteratee, keys_default);
}
__name(baseForOwn, "baseForOwn");
__name2(baseForOwn, "baseForOwn");
var baseForOwn_default = baseForOwn;
function createBaseEach(eachFunc, fromRight) {
return function(collection, iteratee) {
if (collection == null) {
return collection;
}
if (!isArrayLike_default(collection)) {
return eachFunc(collection, iteratee);
}
var length = collection.length, index = fromRight ? length : -1, iterable = Object(collection);
while (fromRight ? index-- : ++index < length) {
if (iteratee(iterable[index], index, iterable) === false) {
break;
}
}
return collection;
};
}
__name(createBaseEach, "createBaseEach");
__name2(createBaseEach, "createBaseEach");
var createBaseEach_default = createBaseEach;
var baseEach = createBaseEach_default(baseForOwn_default);
var baseEach_default = baseEach;
function baseAggregator(collection, setter, iteratee, accumulator) {
baseEach_default(collection, function(value, key, collection2) {
setter(accumulator, value, iteratee(value), collection2);
});
return accumulator;
}
__name(baseAggregator, "baseAggregator");
__name2(baseAggregator, "baseAggregator");
var baseAggregator_default = baseAggregator;
function createAggregator(setter, initializer) {
return function(collection, iteratee) {
var func = isArray_default(collection) ? arrayAggregator_default : baseAggregator_default, accumulator = initializer ? initializer() : {};
return func(collection, setter, baseIteratee_default(iteratee, 2), accumulator);
};
}
__name(createAggregator, "createAggregator");
__name2(createAggregator, "createAggregator");
var createAggregator_default = createAggregator;
var objectProto17 = Object.prototype;
var hasOwnProperty14 = objectProto17.hasOwnProperty;
var defaults = baseRest_default(function(object, sources) {
object = Object(object);
var index = -1;
var length = sources.length;
var guard = length > 2 ? sources[2] : void 0;
if (guard && isIterateeCall_default(sources[0], sources[1], guard)) {
length = 1;
}
while (++index < length) {
var source = sources[index];
var props = keysIn_default(source);
var propsIndex = -1;
var propsLength = props.length;
while (++propsIndex < propsLength) {
var key = props[propsIndex];
var value = object[key];
if (value === void 0 || eq_default(value, objectProto17[key]) && !hasOwnProperty14.call(object, key)) {
object[key] = source[key];
}
}
}
return object;
});
var defaults_default = defaults;
function isArrayLikeObject(value) {
return isObjectLike_default(value) && isArrayLike_default(value);
}
__name(isArrayLikeObject, "isArrayLikeObject");
__name2(isArrayLikeObject, "isArrayLikeObject");
var isArrayLikeObject_default = isArrayLikeObject;
function arrayIncludesWith(array, value, comparator) {
var index = -1, length = array == null ? 0 : array.length;
while (++index < length) {
if (comparator(value, array[index])) {
return true;
}
}
return false;
}
__name(arrayIncludesWith, "arrayIncludesWith");
__name2(arrayIncludesWith, "arrayIncludesWith");
var arrayIncludesWith_default = arrayIncludesWith;
var LARGE_ARRAY_SIZE2 = 200;
function baseDifference(array, values2, iteratee, comparator) {
var index = -1, includes2 = arrayIncludes_default, isCommon = true, length = array.length, result = [], valuesLength = values2.length;
if (!length) {
return result;
}
if (iteratee) {
values2 = arrayMap_default(values2, baseUnary_default(iteratee));
}
if (comparator) {
includes2 = arrayIncludesWith_default;
isCommon = false;
} else if (values2.length >= LARGE_ARRAY_SIZE2) {
includes2 = cacheHas_default;
isCommon = false;
values2 = new SetCache_default(values2);
}
outer:
while (++index < length) {
var value = array[index], computed = iteratee == null ? value : iteratee(value);
value = comparator || value !== 0 ? value : 0;
if (isCommon && computed === computed) {
var valuesIndex = valuesLength;
while (valuesIndex--) {
if (values2[valuesIndex] === computed) {
continue outer;
}
}
result.push(value);
} else if (!includes2(values2, computed, comparator)) {
result.push(value);
}
}
return result;
}
__name(baseDifference, "baseDifference");
__name2(baseDifference, "baseDifference");
var baseDifference_default = baseDifference;
var difference = baseRest_default(function(array, values2) {
return isArrayLikeObject_default(array) ? baseDifference_default(array, baseFlatten_default(values2, 1, isArrayLikeObject_default, true)) : [];
});
var difference_default = difference;
function last(array) {
var length = array == null ? 0 : array.length;
return length ? array[length - 1] : void 0;
}
__name(last, "last");
__name2(last, "last");
var last_default = last;
function drop(array, n, guard) {
var length = array == null ? 0 : array.length;
if (!length) {
return [];
}
n = guard || n === void 0 ? 1 : toInteger_default(n);
return baseSlice_default(array, n < 0 ? 0 : n, length);
}
__name(drop, "drop");
__name2(drop, "drop");
var drop_default = drop;
function dropRight(array, n, guard) {
var length = array == null ? 0 : array.length;
if (!length) {
return [];
}
n = guard || n === void 0 ? 1 : toInteger_default(n);
n = length - n;
return baseSlice_default(array, 0, n < 0 ? 0 : n);
}
__name(dropRight, "dropRight");
__name2(dropRight, "dropRight");
var dropRight_default = dropRight;
function castFunction(value) {
return typeof value == "function" ? value : identity_default;
}
__name(castFunction, "castFunction");
__name2(castFunction, "castFunction");
var castFunction_default = castFunction;
function forEach(collection, iteratee) {
var func = isArray_default(collection) ? arrayEach_default : baseEach_default;
return func(collection, castFunction_default(iteratee));
}
__name(forEach, "forEach");
__name2(forEach, "forEach");
var forEach_default = forEach;
function arrayEvery(array, predicate) {
var index = -1, length = array == null ? 0 : array.length;
while (++index < length) {
if (!predicate(array[index], index, array)) {
return false;
}
}
return true;
}
__name(arrayEvery, "arrayEvery");
__name2(arrayEvery, "arrayEvery");
var arrayEvery_default = arrayEvery;
function baseEvery(collection, predicate) {
var result = true;
baseEach_default(collection, function(value, index, collection2) {
result = !!predicate(value, index, collection2);
return result;
});
return result;
}
__name(baseEvery, "baseEvery");
__name2(baseEvery, "baseEvery");
var baseEvery_default = baseEvery;
function every(collection, predicate, guard) {
var func = isArray_default(collection) ? arrayEvery_default : baseEvery_default;
if (guard && isIterateeCall_default(collection, predicate, guard)) {
predicate = void 0;
}
return func(collection, baseIteratee_default(predicate, 3));
}
__name(every, "every");
__name2(every, "every");
var every_default = every;
function baseFilter(collection, predicate) {
var result = [];
baseEach_default(collection, function(value, index, collection2) {
if (predicate(value, index, collection2)) {
result.push(value);
}
});
return result;
}
__name(baseFilter, "baseFilter");
__name2(baseFilter, "baseFilter");
var baseFilter_default = baseFilter;
function filter(collection, predicate) {
var func = isArray_default(collection) ? arrayFilter_default : baseFilter_default;
return func(collection, baseIteratee_default(predicate, 3));
}
__name(filter, "filter");
__name2(filter, "filter");
var filter_default = filter;
function createFind(findIndexFunc) {
return function(collection, predicate, fromIndex) {
var iterable = Object(collection);
if (!isArrayLike_default(collection)) {
var iteratee = baseIteratee_default(predicate, 3);
collection = keys_default(collection);
predicate = /* @__PURE__ */ __name2(function(key) {
return iteratee(iterable[key], key, iterable);
}, "predicate");
}
var index = findIndexFunc(collection, predicate, fromIndex);
return index > -1 ? iterable[iteratee ? collection[index] : index] : void 0;
};
}
__name(createFind, "createFind");
__name2(createFind, "createFind");
var createFind_default = createFind;
var nativeMax2 = Math.max;
function findIndex(array, predicate, fromIndex) {
var length = array == null ? 0 : array.length;
if (!length) {
return -1;
}
var index = fromIndex == null ? 0 : toInteger_default(fromIndex);
if (index < 0) {
index = nativeMax2(length + index, 0);
}
return baseFindIndex_default(array, baseIteratee_default(predicate, 3), index);
}
__name(findIndex, "findIndex");
__name2(findIndex, "findIndex");
var findIndex_default = findIndex;
var find = createFind_default(findIndex_default);
var find_default = find;
function head(array) {
return array && array.length ? array[0] : void 0;
}
__name(head, "head");
__name2(head, "head");
var head_default = head;
function baseMap(collection, iteratee) {
var index = -1, result = isArrayLike_default(collection) ? Array(collection.length) : [];
baseEach_default(collection, function(value, key, collection2) {
result[++index] = iteratee(value, key, collection2);
});
return result;
}
__name(baseMap, "baseMap");
__name2(baseMap, "baseMap");
var baseMap_default = baseMap;
function map(collection, iteratee) {
var func = isArray_default(collection) ? arrayMap_default : baseMap_default;
return func(collection, baseIteratee_default(iteratee, 3));
}
__name(map, "map");
__name2(map, "map");
var map_default = map;
function flatMap(collection, iteratee) {
return baseFlatten_default(map_default(collection, iteratee), 1);
}
__name(flatMap, "flatMap");
__name2(flatMap, "flatMap");
var flatMap_default = flatMap;
var objectProto18 = Object.prototype;
var hasOwnProperty15 = objectProto18.hasOwnProperty;
var groupBy = createAggregator_default(function(result, value, key) {
if (hasOwnProperty15.call(result, key)) {
result[key].push(value);
} else {
baseAssignValue_default(result, key, [value]);
}
});
var groupBy_default = groupBy;
var objectProto19 = Object.prototype;
var hasOwnProperty16 = objectProto19.hasOwnProperty;
function baseHas(object, key) {
return object != null && hasOwnProperty16.call(object, key);
}
__name(baseHas, "baseHas");
__name2(baseHas, "baseHas");
var baseHas_default = baseHas;
function has(object, path) {
return object != null && hasPath_default(object, path, baseHas_default);
}
__name(has, "has");
__name2(has, "has");
var has_default = has;
var stringTag5 = "[object String]";
function isString(value) {
return typeof value == "string" || !isArray_default(value) && isObjectLike_default(value) && baseGetTag_default(value) == stringTag5;
}
__name(isString, "isString");
__name2(isString, "isString");
var isString_default = isString;
function baseValues(object, props) {
return arrayMap_default(props, function(key) {
return object[key];
});
}
__name(baseValues, "baseValues");
__name2(baseValues, "baseValues");
var baseValues_default = baseValues;
function values(object) {
return object == null ? [] : baseValues_default(object, keys_default(object));
}
__name(values, "values");
__name2(values, "values");
var values_default = values;
var nativeMax3 = Math.max;
function includes(collection, value, fromIndex, guard) {
collection = isArrayLike_default(collection) ? collection : values_default(collection);
fromIndex = fromIndex && !guard ? toInteger_default(fromIndex) : 0;
var length = collection.length;
if (fromIndex < 0) {
fromIndex = nativeMax3(length + fromIndex, 0);
}
return isString_default(collection) ? fromIndex <= length && collection.indexOf(value, fromIndex) > -1 : !!length && baseIndexOf_default(collection, value, fromIndex) > -1;
}
__name(includes, "includes");
__name2(includes, "includes");
var includes_default = includes;
var nativeMax4 = Math.max;
function indexOf(array, value, fromIndex) {
var length = array == null ? 0 : array.length;
if (!length) {
return -1;
}
var index = fromIndex == null ? 0 : toInteger_default(fromIndex);
if (index < 0) {
index = nativeMax4(length + index, 0);
}
return baseIndexOf_default(array, value, index);
}
__name(indexOf, "indexOf");
__name2(indexOf, "indexOf");
var indexOf_default = indexOf;
var mapTag7 = "[object Map]";
var setTag7 = "[object Set]";
var objectProto20 = Object.prototype;
var hasOwnProperty17 = objectProto20.hasOwnProperty;
function isEmpty(value) {
if (value == null) {
return true;
}
if (isArrayLike_default(value) && (isArray_default(value) || typeof value == "string" || typeof value.splice == "function" || isBuffer_default(value) || isTypedArray_default(value) || isArguments_default(value))) {
return !value.length;
}
var tag = getTag_default(value);
if (tag == mapTag7 || tag == setTag7) {
return !value.size;
}
if (isPrototype_default(value)) {
return !baseKeys_default(value).length;
}
for (var key in value) {
if (hasOwnProperty17.call(value, key)) {
return false;
}
}
return true;
}
__name(isEmpty, "isEmpty");
__name2(isEmpty, "isEmpty");
var isEmpty_default = isEmpty;
var regexpTag5 = "[object RegExp]";
function baseIsRegExp(value) {
return isObjectLike_default(value) && baseGetTag_default(value) == regexpTag5;
}
__name(baseIsRegExp, "baseIsRegExp");
__name2(baseIsRegExp, "baseIsRegExp");
var baseIsRegExp_default = baseIsRegExp;
var nodeIsRegExp = nodeUtil_default && nodeUtil_default.isRegExp;
var isRegExp = nodeIsRegExp ? baseUnary_default(nodeIsRegExp) : baseIsRegExp_default;
var isRegExp_default = isRegExp;
function isUndefined(value) {
return value === void 0;
}
__name(isUndefined, "isUndefined");
__name2(isUndefined, "isUndefined");
var isUndefined_default = isUndefined;
var FUNC_ERROR_TEXT2 = "Expected a function";
function negate(predicate) {
if (typeof predicate != "function") {
throw new TypeError(FUNC_ERROR_TEXT2);
}
return function() {
var args = arguments;
switch (args.length) {
case 0:
return !predicate.call(this);
case 1:
return !predicate.call(this, args[0]);
case 2:
return !predicate.call(this, args[0], args[1]);
case 3:
return !predicate.call(this, args[0], args[1], args[2]);
}
return !predicate.apply(this, args);
};
}
__name(negate, "negate");
__name2(negate, "negate");
var negate_default = negate;
function baseSet(object, path, value, customizer) {
if (!isObject_default(object)) {
return object;
}
path = castPath_default(path, object);
var index = -1, length = path.length, lastIndex = length - 1, nested = object;
while (nested != null && ++index < length) {
var key = toKey_default(path[index]), newValue = value;
if (key === "__proto__" || key === "constructor" || key === "prototype") {
return object;
}
if (index != lastIndex) {
var objValue = nested[key];
newValue = customizer ? customizer(objValue, key, nested) : void 0;
if (newValue === void 0) {
newValue = isObject_default(objValue) ? objValue : isIndex_default(path[index + 1]) ? [] : {};
}
}
assignValue_default(nested, key, newValue);
nested = nested[key];
}
return object;
}
__name(baseSet, "baseSet");
__name2(baseSet, "baseSet");
var baseSet_default = baseSet;
function basePickBy(object, paths, predicate) {
var index = -1, length = paths.length, result = {};
while (++index < length) {
var path = paths[index], value = baseGet_default(object, path);
if (predicate(value, path)) {
baseSet_default(result, castPath_default(path, object), value);
}
}
return result;
}
__name(basePickBy, "basePickBy");
__name2(basePickBy, "basePickBy");
var basePickBy_default = basePickBy;
function pickBy(object, predicate) {
if (object == null) {
return {};
}
var props = arrayMap_default(getAllKeysIn_default(object), function(prop) {
return [prop];
});
predicate = baseIteratee_default(predicate);
return basePickBy_default(object, props, function(value, path) {
return predicate(value, path[0]);
});
}
__name(pickBy, "pickBy");
__name2(pickBy, "pickBy");
var pickBy_default = pickBy;
function baseReduce(collection, iteratee, accumulator, initAccum, eachFunc) {
eachFunc(collection, function(value, index, collection2) {
accumulator = initAccum ? (initAccum = false, value) : iteratee(accumulator, value, index, collection2);
});
return accumulator;
}
__name(baseReduce, "baseReduce");
__name2(baseReduce, "baseReduce");
var baseReduce_default = baseReduce;
function reduce(collection, iteratee, accumulator) {
var func = isArray_default(collection) ? arrayReduce_default : baseReduce_default, initAccum = arguments.length < 3;
return func(collection, baseIteratee_default(iteratee, 4), accumulator, initAccum, baseEach_default);
}
__name(reduce, "reduce");
__name2(reduce, "reduce");
var reduce_default = reduce;
function reject(collection, predicate) {
var func = isArray_default(collection) ? arrayFilter_default : baseFilter_default;
return func(collection, negate_default(baseIteratee_default(predicate, 3)));
}
__name(reject, "reject");
__name2(reject, "reject");
var reject_default = reject;
function baseSome(collection, predicate) {
var result;
baseEach_default(collection, function(value, index, collection2) {
result = predicate(value, index, collection2);
return !result;
});
return !!result;
}
__name(baseSome, "baseSome");
__name2(baseSome, "baseSome");
var baseSome_default = baseSome;
function some(collection, predicate, guard) {
var func = isArray_default(collection) ? arraySome_default : baseSome_default;
if (guard && isIterateeCall_default(collection, predicate, guard)) {
predicate = void 0;
}
return func(collection, baseIteratee_default(predicate, 3));
}
__name(some, "some");
__name2(some, "some");
var some_default = some;
var INFINITY4 = 1 / 0;
var createSet = !(Set_default && 1 / setToArray_default(new Set_default([, -0]))[1] == INFINITY4) ? noop_default : function(values2) {
return new Set_default(values2);
};
var createSet_default = createSet;
var LARGE_ARRAY_SIZE3 = 200;
function baseUniq(array, iteratee, comparator) {
var index = -1, includes2 = arrayIncludes_default, length = array.length, isCommon = true, result = [], seen = result;
if (comparator) {
isCommon = false;
includes2 = arrayIncludesWith_default;
} else if (length >= LARGE_ARRAY_SIZE3) {
var set = iteratee ? null : createSet_default(array);
if (set) {
return setToArray_default(set);
}
isCommon = false;
includes2 = cacheHas_default;
seen = new SetCache_default();
} else {
seen = iteratee ? [] : result;
}
outer:
while (++index < length) {
var value = array[index], computed = iteratee ? iteratee(value) : value;
value = comparator || value !== 0 ? value : 0;
if (isCommon && computed === computed) {
var seenIndex = seen.length;
while (seenIndex--) {
if (seen[seenIndex] === computed) {
continue outer;
}
}
if (iteratee) {
seen.push(computed);
}
result.push(value);
} else if (!includes2(seen, computed, comparator)) {
if (seen !== result) {
seen.push(computed);
}
result.push(value);
}
}
return result;
}
__name(baseUniq, "baseUniq");
__name2(baseUniq, "baseUniq");
var baseUniq_default = baseUniq;
function uniq(array) {
return array && array.length ? baseUniq_default(array) : [];
}
__name(uniq, "uniq");
__name2(uniq, "uniq");
var uniq_default = uniq;
function PRINT_ERROR(msg) {
if (console && console.error) {
console.error(`Error: ${msg}`);
}
}
__name(PRINT_ERROR, "PRINT_ERROR");
__name2(PRINT_ERROR, "PRINT_ERROR");
function PRINT_WARNING(msg) {
if (console && console.warn) {
console.warn(`Warning: ${msg}`);
}
}
__name(PRINT_WARNING, "PRINT_WARNING");
__name2(PRINT_WARNING, "PRINT_WARNING");
function timer(func) {
const start = (/* @__PURE__ */ new Date()).getTime();
const val = func();
const end = (/* @__PURE__ */ new Date()).getTime();
const total = end - start;
return { time: total, value: val };
}
__name(timer, "timer");
__name2(timer, "timer");
function toFastProperties(toBecomeFast) {
function FakeConstructor() {
}
__name(FakeConstructor, "FakeConstructor");
__name2(FakeConstructor, "FakeConstructor");
FakeConstructor.prototype = toBecomeFast;
const fakeInstance = new FakeConstructor();
function fakeAccess() {
return typeof fakeInstance.bar;
}
__name(fakeAccess, "fakeAccess");
__name2(fakeAccess, "fakeAccess");
fakeAccess();
fakeAccess();
if (1)
return toBecomeFast;
(0, eval)(toBecomeFast);
}
__name(toFastProperties, "toFastProperties");
__name2(toFastProperties, "toFastProperties");
function tokenLabel(tokType) {
if (hasTokenLabel(tokType)) {
return tokType.LABEL;
} else {
return tokType.name;
}
}
__name(tokenLabel, "tokenLabel");
__name2(tokenLabel, "tokenLabel");
function hasTokenLabel(obj) {
return isString_default(obj.LABEL) && obj.LABEL !== "";
}
__name(hasTokenLabel, "hasTokenLabel");
__name2(hasTokenLabel, "hasTokenLabel");
var AbstractProduction = class {
static {
__name(this, "AbstractProduction");
}
static {
__name2(this, "AbstractProduction");
}
get definition() {
return this._definition;
}
set definition(value) {
this._definition = value;
}
constructor(_definition) {
this._definition = _definition;
}
accept(visitor2) {
visitor2.visit(this);
forEach_default(this.definition, (prod) => {
prod.accept(visitor2);
});
}
};
var NonTerminal = class extends AbstractProduction {
static {
__name(this, "NonTerminal");
}
static {
__name2(this, "NonTerminal");
}
constructor(options) {
super([]);
this.idx = 1;
assign_default(this, pickBy_default(options, (v) => v !== void 0));
}
set definition(definition) {
}
get definition() {
if (this.referencedRule !== void 0) {
return this.referencedRule.definition;
}
return [];
}
accept(visitor2) {
visitor2.visit(this);
}
};
var Rule = class extends AbstractProduction {
static {
__name(this, "Rule");
}
static {
__name2(this, "Rule");
}
constructor(options) {
super(options.definition);
this.orgText = "";
assign_default(this, pickBy_default(options, (v) => v !== void 0));
}
};
var Alternative = class extends AbstractProduction {
static {
__name(this, "Alternative");
}
static {
__name2(this, "Alternative");
}
constructor(options) {
super(options.definition);
this.ignoreAmbiguities = false;
assign_default(this, pickBy_default(options, (v) => v !== void 0));
}
};
var Option = class extends AbstractProduction {
static {
__name(this, "Option");
}
static {
__name2(this, "Option");
}
constructor(options) {
super(options.definition);
this.idx = 1;
assign_default(this, pickBy_default(options, (v) => v !== void 0));
}
};
var RepetitionMandatory = class extends AbstractProduction {
static {
__name(this, "RepetitionMandatory");
}
static {
__name2(this, "RepetitionMandatory");
}
constructor(options) {
super(options.definition);
this.idx = 1;
assign_default(this, pickBy_default(options, (v) => v !== void 0));
}
};
var RepetitionMandatoryWithSeparator = class extends AbstractProduction {
static {
__name(this, "RepetitionMandatoryWithSeparator");
}
static {
__name2(this, "RepetitionMandatoryWithSeparator");
}
constructor(options) {
super(options.definition);
this.idx = 1;
assign_default(this, pickBy_default(options, (v) => v !== void 0));
}
};
var Repetition = class extends AbstractProduction {
static {
__name(this, "Repetition");
}
static {
__name2(this, "Repetition");
}
constructor(options) {
super(options.definition);
this.idx = 1;
assign_default(this, pickBy_default(options, (v) => v !== void 0));
}
};
var RepetitionWithSeparator = class extends AbstractProduction {
static {
__name(this, "RepetitionWithSeparator");
}
static {
__name2(this, "RepetitionWithSeparator");
}
constructor(options) {
super(options.definition);
this.idx = 1;
assign_default(this, pickBy_default(options, (v) => v !== void 0));
}
};
var Alternation = class extends AbstractProduction {
static {
__name(this, "Alternation");
}
static {
__name2(this, "Alternation");
}
get definition() {
return this._definition;
}
set definition(value) {
this._definition = value;
}
constructor(options) {
super(options.definition);
this.idx = 1;
this.ignoreAmbiguities = false;
this.hasPredicates = false;
assign_default(this, pickBy_default(options, (v) => v !== void 0));
}
};
var Terminal = class {
static {
__name(this, "Terminal");
}
static {
__name2(this, "Terminal");
}
constructor(options) {
this.idx = 1;
assign_default(this, pickBy_default(options, (v) => v !== void 0));
}
accept(visitor2) {
visitor2.visit(this);
}
};
function serializeGrammar(topRules) {
return map_default(topRules, serializeProduction);
}
__name(serializeGrammar, "serializeGrammar");
__name2(serializeGrammar, "serializeGrammar");
function serializeProduction(node) {
function convertDefinition(definition) {
return map_default(definition, serializeProduction);
}
__name(convertDefinition, "convertDefinition");
__name2(convertDefinition, "convertDefinition");
if (node instanceof NonTerminal) {
const serializedNonTerminal = {
type: "NonTerminal",
name: node.nonTerminalName,
idx: node.idx
};
if (isString_default(node.label)) {
serializedNonTerminal.label = node.label;
}
return serializedNonTerminal;
} else if (node instanceof Alternative) {
return {
type: "Alternative",
definition: convertDefinition(node.definition)
};
} else if (node instanceof Option) {
return {
type: "Option",
idx: node.idx,
definition: convertDefinition(node.definition)
};
} else if (node instanceof RepetitionMandatory) {
return {
type: "RepetitionMandatory",
idx: node.idx,
definition: convertDefinition(node.definition)
};
} else if (node instanceof RepetitionMandatoryWithSeparator) {
return {
type: "RepetitionMandatoryWithSeparator",
idx: node.idx,
separator: serializeProduction(new Terminal({ terminalType: node.separator })),
definition: convertDefinition(node.definition)
};
} else if (node instanceof RepetitionWithSeparator) {
return {
type: "RepetitionWithSeparator",
idx: node.idx,
separator: serializeProduction(new Terminal({ terminalType: node.separator })),
definition: convertDefinition(node.definition)
};
} else if (node instanceof Repetition) {
return {
type: "Repetition",
idx: node.idx,
definition: convertDefinition(node.definition)
};
} else if (node instanceof Alternation) {
return {
type: "Alternation",
idx: node.idx,
definition: convertDefinition(node.definition)
};
} else if (node instanceof Terminal) {
const serializedTerminal = {
type: "Terminal",
name: node.terminalType.name,
label: tokenLabel(node.terminalType),
idx: node.idx
};
if (isString_default(node.label)) {
serializedTerminal.terminalLabel = node.label;
}
const pattern = node.terminalType.PATTERN;
if (node.terminalType.PATTERN) {
serializedTerminal.pattern = isRegExp_default(pattern) ? pattern.source : pattern;
}
return serializedTerminal;
} else if (node instanceof Rule) {
return {
type: "Rule",
name: node.name,
orgText: node.orgText,
definition: convertDefinition(node.definition)
};
} else {
throw Error("non exhaustive match");
}
}
__name(serializeProduction, "serializeProduction");
__name2(serializeProduction, "serializeProduction");
var GAstVisitor = class {
static {
__name(this, "GAstVisitor");
}
static {
__name2(this, "GAstVisitor");
}
visit(node) {
const nodeAny = node;
switch (nodeAny.constructor) {
case NonTerminal:
return this.visitNonTerminal(nodeAny);
case Alternative:
return this.visitAlternative(nodeAny);
case Option:
return this.visitOption(nodeAny);
case RepetitionMandatory:
return this.visitRepetitionMandatory(nodeAny);
case RepetitionMandatoryWithSeparator:
return this.visitRepetitionMandatoryWithSeparator(nodeAny);
case RepetitionWithSeparator:
return this.visitRepetitionWithSeparator(nodeAny);
case Repetition:
return this.visitRepetition(nodeAny);
case Alternation:
return this.visitAlternation(nodeAny);
case Terminal:
return this.visitTerminal(nodeAny);
case Rule:
return this.visitRule(nodeAny);
/* c8 ignore next 2 */
default:
throw Error("non exhaustive match");
}
}
/* c8 ignore next */
visitNonTerminal(node) {
}
/* c8 ignore next */
visitAlternative(node) {
}
/* c8 ignore next */
visitOption(node) {
}
/* c8 ignore next */
visitRepetition(node) {
}
/* c8 ignore next */
visitRepetitionMandatory(node) {
}
/* c8 ignore next 3 */
visitRepetitionMandatoryWithSeparator(node) {
}
/* c8 ignore next */
visitRepetitionWithSeparator(node) {
}
/* c8 ignore next */
visitAlternation(node) {
}
/* c8 ignore next */
visitTerminal(node) {
}
/* c8 ignore next */
visitRule(node) {
}
};
function isSequenceProd(prod) {
return prod instanceof Alternative || prod instanceof Option || prod instanceof Repetition || prod instanceof RepetitionMandatory || prod instanceof RepetitionMandatoryWithSeparator || prod instanceof RepetitionWithSeparator || prod instanceof Terminal || prod instanceof Rule;
}
__name(isSequenceProd, "isSequenceProd");
__name2(isSequenceProd, "isSequenceProd");
function isOptionalProd(prod, alreadyVisited = []) {
const isDirectlyOptional = prod instanceof Option || prod instanceof Repetition || prod instanceof RepetitionWithSeparator;
if (isDirectlyOptional) {
return true;
}
if (prod instanceof Alternation) {
return some_default(prod.definition, (subProd) => {
return isOptionalProd(subProd, alreadyVisited);
});
} else if (prod instanceof NonTerminal && includes_default(alreadyVisited, prod)) {
return false;
} else if (prod instanceof AbstractProduction) {
if (prod instanceof NonTerminal) {
alreadyVisited.push(prod);
}
return every_default(prod.definition, (subProd) => {
return isOptionalProd(subProd, alreadyVisited);
});
} else {
return false;
}
}
__name(isOptionalProd, "isOptionalProd");
__name2(isOptionalProd, "isOptionalProd");
function isBranchingProd(prod) {
return prod instanceof Alternation;
}
__name(isBranchingProd, "isBranchingProd");
__name2(isBranchingProd, "isBranchingProd");
function getProductionDslName(prod) {
if (prod instanceof NonTerminal) {
return "SUBRULE";
} else if (prod instanceof Option) {
return "OPTION";
} else if (prod instanceof Alternation) {
return "OR";
} else if (prod instanceof RepetitionMandatory) {
return "AT_LEAST_ONE";
} else if (prod instanceof RepetitionMandatoryWithSeparator) {
return "AT_LEAST_ONE_SEP";
} else if (prod instanceof RepetitionWithSeparator) {
return "MANY_SEP";
} else if (prod instanceof Repetition) {
return "MANY";
} else if (prod instanceof Terminal) {
return "CONSUME";
} else {
throw Error("non exhaustive match");
}
}
__name(getProductionDslName, "getProductionDslName");
__name2(getProductionDslName, "getProductionDslName");
var RestWalker = class {
static {
__name(this, "RestWalker");
}
static {
__name2(this, "RestWalker");
}
walk(prod, prevRest = []) {
forEach_default(prod.definition, (subProd, index) => {
const currRest = drop_default(prod.definition, index + 1);
if (subProd instanceof NonTerminal) {
this.walkProdRef(subProd, currRest, prevRest);
} else if (subProd instanceof Terminal) {
this.walkTerminal(subProd, currRest, prevRest);
} else if (subProd instanceof Alternative) {
this.walkFlat(subProd, currRest, prevRest);
} else if (subProd instanceof Option) {
this.walkOption(subProd, currRest, prevRest);
} else if (subProd instanceof RepetitionMandatory) {
this.walkAtLeastOne(subProd, currRest, prevRest);
} else if (subProd instanceof RepetitionMandatoryWithSeparator) {
this.walkAtLeastOneSep(subProd, currRest, prevRest);
} else if (subProd instanceof RepetitionWithSeparator) {
this.walkManySep(subProd, currRest, prevRest);
} else if (subProd instanceof Repetition) {
this.walkMany(subProd, currRest, prevRest);
} else if (subProd instanceof Alternation) {
this.walkOr(subProd, currRest, prevRest);
} else {
throw Error("non exhaustive match");
}
});
}
walkTerminal(terminal, currRest, prevRest) {
}
walkProdRef(refProd, currRest, prevRest) {
}
walkFlat(flatProd, currRest, prevRest) {
const fullOrRest = currRest.concat(prevRest);
this.walk(flatProd, fullOrRest);
}
walkOption(optionProd, currRest, prevRest) {
const fullOrRest = currRest.concat(prevRest);
this.walk(optionProd, fullOrRest);
}
walkAtLeastOne(atLeastOneProd, currRest, prevRest) {
const fullAtLeastOneRest = [
new Option({ definition: atLeastOneProd.definition })
].concat(currRest, prevRest);
this.walk(atLeastOneProd, fullAtLeastOneRest);
}
walkAtLeastOneSep(atLeastOneSepProd, currRest, prevRest) {
const fullAtLeastOneSepRest = restForRepetitionWithSeparator(atLeastOneSepProd, currRest, prevRest);
this.walk(atLeastOneSepProd, fullAtLeastOneSepRest);
}
walkMany(manyProd, currRest, prevRest) {
const fullManyRest = [
new Option({ definition: manyProd.definition })
].concat(currRest, prevRest);
this.walk(manyProd, fullManyRest);
}
walkManySep(manySepProd, currRest, prevRest) {
const fullManySepRest = restForRepetitionWithSeparator(manySepProd, currRest, prevRest);
this.walk(manySepProd, fullManySepRest);
}
walkOr(orProd, currRest, prevRest) {
const fullOrRest = currRest.concat(prevRest);
forEach_default(orProd.definition, (alt) => {
const prodWrapper = new Alternative({ definition: [alt] });
this.walk(prodWrapper, fullOrRest);
});
}
};
function restForRepetitionWithSeparator(repSepProd, currRest, prevRest) {
const repSepRest = [
new Option({
definition: [
new Terminal({ terminalType: repSepProd.separator })
].concat(repSepProd.definition)
})
];
const fullRepSepRest = repSepRest.concat(currRest, prevRest);
return fullRepSepRest;
}
__name(restForRepetitionWithSeparator, "restForRepetitionWithSeparator");
__name2(restForRepetitionWithSeparator, "restForRepetitionWithSeparator");
function first(prod) {
if (prod instanceof NonTerminal) {
return first(prod.referencedRule);
} else if (prod instanceof Terminal) {
return firstForTerminal(prod);
} else if (isSequenceProd(prod)) {
return firstForSequence(prod);
} else if (isBranchingProd(prod)) {
return firstForBranching(prod);
} else {
throw Error("non exhaustive match");
}
}
__name(first, "first");
__name2(first, "first");
function firstForSequence(prod) {
let firstSet = [];
const seq = prod.definition;
let nextSubProdIdx = 0;
let hasInnerProdsRemaining = seq.length > nextSubProdIdx;
let currSubProd;
let isLastInnerProdOptional = true;
while (hasInnerProdsRemaining && isLastInnerProdOptional) {
currSubProd = seq[nextSubProdIdx];
isLastInnerProdOptional = isOptionalProd(currSubProd);
firstSet = firstSet.concat(first(currSubProd));
nextSubProdIdx = nextSubProdIdx + 1;
hasInnerProdsRemaining = seq.length > nextSubProdIdx;
}
return uniq_default(firstSet);
}
__name(firstForSequence, "firstForSequence");
__name2(firstForSequence, "firstForSequence");
function firstForBranching(prod) {
const allAlternativesFirsts = map_default(prod.definition, (innerProd) => {
return first(innerProd);
});
return uniq_default(flatten_default(allAlternativesFirsts));
}
__name(firstForBranching, "firstForBranching");
__name2(firstForBranching, "firstForBranching");
function firstForTerminal(terminal) {
return [terminal.terminalType];
}
__name(firstForTerminal, "firstForTerminal");
__name2(firstForTerminal, "firstForTerminal");
var IN = "_~IN~_";
var ResyncFollowsWalker = class extends RestWalker {
static {
__name(this, "ResyncFollowsWalker");
}
static {
__name2(this, "ResyncFollowsWalker");
}
constructor(topProd) {
super();
this.topProd = topProd;
this.follows = {};
}
startWalking() {
this.walk(this.topProd);
return this.follows;
}
walkTerminal(terminal, currRest, prevRest) {
}
walkProdRef(refProd, currRest, prevRest) {
const followName = buildBetweenProdsFollowPrefix(refProd.referencedRule, refProd.idx) + this.topProd.name;
const fullRest = currRest.concat(prevRest);
const restProd = new Alternative({ definition: fullRest });
const t_in_topProd_follows = first(restProd);
this.follows[followName] = t_in_topProd_follows;
}
};
function computeAllProdsFollows(topProductions) {
const reSyncFollows = {};
forEach_default(topProductions, (topProd) => {
const currRefsFollow = new ResyncFollowsWalker(topProd).startWalking();
assign_default(reSyncFollows, currRefsFollow);
});
return reSyncFollows;
}
__name(computeAllProdsFollows, "computeAllProdsFollows");
__name2(computeAllProdsFollows, "computeAllProdsFollows");
function buildBetweenProdsFollowPrefix(inner, occurenceInParent) {
return inner.name + occurenceInParent + IN;
}
__name(buildBetweenProdsFollowPrefix, "buildBetweenProdsFollowPrefix");
__name2(buildBetweenProdsFollowPrefix, "buildBetweenProdsFollowPrefix");
var regExpAstCache = {};
var regExpParser = new RegExpParser();
function getRegExpAst(regExp) {
const regExpStr = regExp.toString();
if (regExpAstCache.hasOwnProperty(regExpStr)) {
return regExpAstCache[regExpStr];
} else {
const regExpAst = regExpParser.pattern(regExpStr);
regExpAstCache[regExpStr] = regExpAst;
return regExpAst;
}
}
__name(getRegExpAst, "getRegExpAst");
__name2(getRegExpAst, "getRegExpAst");
function clearRegExpParserCache() {
regExpAstCache = {};
}
__name(clearRegExpParserCache, "clearRegExpParserCache");
__name2(clearRegExpParserCache, "clearRegExpParserCache");
var complementErrorMessage = "Complement Sets are not supported for first char optimization";
var failedOptimizationPrefixMsg = 'Unable to use "first char" lexer optimizations:\n';
function getOptimizedStartCodesIndices(regExp, ensureOptimizations = false) {
try {
const ast = getRegExpAst(regExp);
const firstChars = firstCharOptimizedIndices(ast.value, {}, ast.flags.ignoreCase);
return firstChars;
} catch (e) {
if (e.message === complementErrorMessage) {
if (ensureOptimizations) {
PRINT_WARNING(`${failedOptimizationPrefixMsg} Unable to optimize: < ${regExp.toString()} >
Complement Sets cannot be automatically optimized.
This will disable the lexer's first char optimizations.
See: https://chevrotain.io/docs/guide/resolving_lexer_errors.html#COMPLEMENT for details.`);
}
} else {
let msgSuffix = "";
if (ensureOptimizations) {
msgSuffix = "\n This will disable the lexer's first char optimizations.\n See: https://chevrotain.io/docs/guide/resolving_lexer_errors.html#REGEXP_PARSING for details.";
}
PRINT_ERROR(`${failedOptimizationPrefixMsg}
Failed parsing: < ${regExp.toString()} >
Using the @chevrotain/regexp-to-ast library
Please open an issue at: https://github.com/chevrotain/chevrotain/issues` + msgSuffix);
}
}
return [];
}
__name(getOptimizedStartCodesIndices, "getOptimizedStartCodesIndices");
__name2(getOptimizedStartCodesIndices, "getOptimizedStartCodesIndices");
function firstCharOptimizedIndices(ast, result, ignoreCase) {
switch (ast.type) {
case "Disjunction":
for (let i = 0; i < ast.value.length; i++) {
firstCharOptimizedIndices(ast.value[i], result, ignoreCase);
}
break;
case "Alternative":
const terms = ast.value;
for (let i = 0; i < terms.length; i++) {
const term = terms[i];
switch (term.type) {
case "EndAnchor":
// A group back reference cannot affect potential starting char.
// because if a back reference is the first production than automatically
// the group being referenced has had to come BEFORE so its codes have already been added
case "GroupBackReference":
// assertions do not affect potential starting codes
case "Lookahead":
case "NegativeLookahead":
case "Lookbehind":
case "NegativeLookbehind":
case "StartAnchor":
case "WordBoundary":
case "NonWordBoundary":
continue;
}
const atom2 = term;
switch (atom2.type) {
case "Character":
addOptimizedIdxToResult(atom2.value, result, ignoreCase);
break;
case "Set":
if (atom2.complement === true) {
throw Error(complementErrorMessage);
}
forEach_default(atom2.value, (code) => {
if (typeof code === "number") {
addOptimizedIdxToResult(code, result, ignoreCase);
} else {
const range = code;
if (ignoreCase === true) {
for (let rangeCode = range.from; rangeCode <= range.to; rangeCode++) {
addOptimizedIdxToResult(rangeCode, result, ignoreCase);
}
} else {
for (let rangeCode = range.from; rangeCode <= range.to && rangeCode < minOptimizationVal; rangeCode++) {
addOptimizedIdxToResult(rangeCode, result, ignoreCase);
}
if (range.to >= minOptimizationVal) {
const minUnOptVal = range.from >= minOptimizationVal ? range.from : minOptimizationVal;
const maxUnOptVal = range.to;
const minOptIdx = charCodeToOptimizedIndex(minUnOptVal);
const maxOptIdx = charCodeToOptimizedIndex(maxUnOptVal);
for (let currOptIdx = minOptIdx; currOptIdx <= maxOptIdx; currOptIdx++) {
result[currOptIdx] = currOptIdx;
}
}
}
}
});
break;
case "Group":
firstCharOptimizedIndices(atom2.value, result, ignoreCase);
break;
/* istanbul ignore next */
default:
throw Error("Non Exhaustive Match");
}
const isOptionalQuantifier = atom2.quantifier !== void 0 && atom2.quantifier.atLeast === 0;
if (
// A group may be optional due to empty contents /(?:)/
// or if everything inside it is optional /((a)?)/
atom2.type === "Group" && isWholeOptional(atom2) === false || // If this term is not a group it may only be optional if it has an optional quantifier
atom2.type !== "Group" && isOptionalQuantifier === false
) {
break;
}
}
break;
/* istanbul ignore next */
default:
throw Error("non exhaustive match!");
}
return values_default(result);
}
__name(firstCharOptimizedIndices, "firstCharOptimizedIndices");
__name2(firstCharOptimizedIndices, "firstCharOptimizedIndices");
function addOptimizedIdxToResult(code, result, ignoreCase) {
const optimizedCharIdx = charCodeToOptimizedIndex(code);
result[optimizedCharIdx] = optimizedCharIdx;
if (ignoreCase === true) {
handleIgnoreCase(code, result);
}
}
__name(addOptimizedIdxToResult, "addOptimizedIdxToResult");
__name2(addOptimizedIdxToResult, "addOptimizedIdxToResult");
function handleIgnoreCase(code, result) {
const char = String.fromCharCode(code);
const upperChar = char.toUpperCase();
if (upperChar !== char) {
const optimizedCharIdx = charCodeToOptimizedIndex(upperChar.charCodeAt(0));
result[optimizedCharIdx] = optimizedCharIdx;
} else {
const lowerChar = char.toLowerCase();
if (lowerChar !== char) {
const optimizedCharIdx = charCodeToOptimizedIndex(lowerChar.charCodeAt(0));
result[optimizedCharIdx] = optimizedCharIdx;
}
}
}
__name(handleIgnoreCase, "handleIgnoreCase");
__name2(handleIgnoreCase, "handleIgnoreCase");
function findCode(setNode, targetCharCodes) {
return find_default(setNode.value, (codeOrRange) => {
if (typeof codeOrRange === "number") {
return includes_default(targetCharCodes, codeOrRange);
} else {
const range = codeOrRange;
return find_default(targetCharCodes, (targetCode) => range.from <= targetCode && targetCode <= range.to) !== void 0;
}
});
}
__name(findCode, "findCode");
__name2(findCode, "findCode");
function isWholeOptional(ast) {
const quantifier = ast.quantifier;
if (quantifier && quantifier.atLeast === 0) {
return true;
}
if (!ast.value) {
return false;
}
return isArray_default(ast.value) ? every_default(ast.value, isWholeOptional) : isWholeOptional(ast.value);
}
__name(isWholeOptional, "isWholeOptional");
__name2(isWholeOptional, "isWholeOptional");
var CharCodeFinder = class extends BaseRegExpVisitor {
static {
__name(this, "CharCodeFinder");
}
static {
__name2(this, "CharCodeFinder");
}
constructor(targetCharCodes) {
super();
this.targetCharCodes = targetCharCodes;
this.found = false;
}
visitChildren(node) {
if (this.found === true) {
return;
}
switch (node.type) {
case "Lookahead":
this.visitLookahead(node);
return;
case "NegativeLookahead":
this.visitNegativeLookahead(node);
return;
case "Lookbehind":
this.visitLookbehind(node);
return;
case "NegativeLookbehind":
this.visitNegativeLookbehind(node);
return;
}
super.visitChildren(node);
}
visitCharacter(node) {
if (includes_default(this.targetCharCodes, node.value)) {
this.found = true;
}
}
visitSet(node) {
if (node.complement) {
if (findCode(node, this.targetCharCodes) === void 0) {
this.found = true;
}
} else {
if (findCode(node, this.targetCharCodes) !== void 0) {
this.found = true;
}
}
}
};
function canMatchCharCode(charCodes, pattern) {
if (pattern instanceof RegExp) {
const ast = getRegExpAst(pattern);
const charCodeFinder = new CharCodeFinder(charCodes);
charCodeFinder.visit(ast);
return charCodeFinder.found;
} else {
return find_default(pattern, (char) => {
return includes_default(charCodes, char.charCodeAt(0));
}) !== void 0;
}
}
__name(canMatchCharCode, "canMatchCharCode");
__name2(canMatchCharCode, "canMatchCharCode");
var PATTERN = "PATTERN";
var DEFAULT_MODE = "defaultMode";
var MODES = "modes";
function analyzeTokenTypes(tokenTypes, options) {
options = defaults_default(options, {
debug: false,
safeMode: false,
positionTracking: "full",
lineTerminatorCharacters: ["\r", "\n"],
tracer: /* @__PURE__ */ __name2((msg, action) => action(), "tracer")
});
const tracer = options.tracer;
tracer("initCharCodeToOptimizedIndexMap", () => {
initCharCodeToOptimizedIndexMap();
});
let onlyRelevantTypes;
tracer("Reject Lexer.NA", () => {
onlyRelevantTypes = reject_default(tokenTypes, (currType) => {
return currType[PATTERN] === Lexer.NA;
});
});
let hasCustom = false;
let allTransformedPatterns;
tracer("Transform Patterns", () => {
hasCustom = false;
allTransformedPatterns = map_default(onlyRelevantTypes, (currType) => {
const currPattern = currType[PATTERN];
if (isRegExp_default(currPattern)) {
const regExpSource = currPattern.source;
if (regExpSource.length === 1 && // only these regExp meta characters which can appear in a length one regExp
regExpSource !== "^" && regExpSource !== "$" && regExpSource !== "." && !currPattern.ignoreCase) {
return regExpSource;
} else if (regExpSource.length === 2 && regExpSource[0] === "\\" && // not a meta character
!includes_default([
"d",
"D",
"s",
"S",
"t",
"r",
"n",
"t",
"0",
"c",
"b",
"B",
"f",
"v",
"w",
"W"
], regExpSource[1])) {
return regExpSource[1];
} else {
return addStickyFlag(currPattern);
}
} else if (isFunction_default(currPattern)) {
hasCustom = true;
return { exec: currPattern };
} else if (typeof currPattern === "object") {
hasCustom = true;
return currPattern;
} else if (typeof currPattern === "string") {
if (currPattern.length === 1) {
return currPattern;
} else {
const escapedRegExpString = currPattern.replace(/[\\^$.*+?()[\]{}|]/g, "\\$&");
const wrappedRegExp = new RegExp(escapedRegExpString);
return addStickyFlag(wrappedRegExp);
}
} else {
throw Error("non exhaustive match");
}
});
});
let patternIdxToType;
let patternIdxToGroup;
let patternIdxToLongerAltIdxArr;
let patternIdxToPushMode;
let patternIdxToPopMode;
tracer("misc mapping", () => {
patternIdxToType = map_default(onlyRelevantTypes, (currType) => currType.tokenTypeIdx);
patternIdxToGroup = map_default(onlyRelevantTypes, (clazz) => {
const groupName = clazz.GROUP;
if (groupName === Lexer.SKIPPED) {
return void 0;
} else if (isString_default(groupName)) {
return groupName;
} else if (isUndefined_default(groupName)) {
return false;
} else {
throw Error("non exhaustive match");
}
});
patternIdxToLongerAltIdxArr = map_default(onlyRelevantTypes, (clazz) => {
const longerAltType = clazz.LONGER_ALT;
if (longerAltType) {
const longerAltIdxArr = isArray_default(longerAltType) ? map_default(longerAltType, (type) => indexOf_default(onlyRelevantTypes, type)) : [indexOf_default(onlyRelevantTypes, longerAltType)];
return longerAltIdxArr;
}
});
patternIdxToPushMode = map_default(onlyRelevantTypes, (clazz) => clazz.PUSH_MODE);
patternIdxToPopMode = map_default(onlyRelevantTypes, (clazz) => has_default(clazz, "POP_MODE"));
});
let patternIdxToCanLineTerminator;
tracer("Line Terminator Handling", () => {
const lineTerminatorCharCodes = getCharCodes(options.lineTerminatorCharacters);
patternIdxToCanLineTerminator = map_default(onlyRelevantTypes, (tokType) => false);
if (options.positionTracking !== "onlyOffset") {
patternIdxToCanLineTerminator = map_default(onlyRelevantTypes, (tokType) => {
if (has_default(tokType, "LINE_BREAKS")) {
return !!tokType.LINE_BREAKS;
} else {
return checkLineBreaksIssues(tokType, lineTerminatorCharCodes) === false && canMatchCharCode(lineTerminatorCharCodes, tokType.PATTERN);
}
});
}
});
let patternIdxToIsCustom;
let patternIdxToShort;
let emptyGroups;
let patternIdxToConfig;
tracer("Misc Mapping #2", () => {
patternIdxToIsCustom = map_default(onlyRelevantTypes, isCustomPattern);
patternIdxToShort = map_default(allTransformedPatterns, isShortPattern);
emptyGroups = reduce_default(onlyRelevantTypes, (acc, clazz) => {
const groupName = clazz.GROUP;
if (isString_default(groupName) && !(groupName === Lexer.SKIPPED)) {
acc[groupName] = [];
}
return acc;
}, {});
patternIdxToConfig = map_default(allTransformedPatterns, (x, idx) => {
return {
pattern: allTransformedPatterns[idx],
longerAlt: patternIdxToLongerAltIdxArr[idx],
canLineTerminator: patternIdxToCanLineTerminator[idx],
isCustom: patternIdxToIsCustom[idx],
short: patternIdxToShort[idx],
group: patternIdxToGroup[idx],
push: patternIdxToPushMode[idx],
pop: patternIdxToPopMode[idx],
tokenTypeIdx: patternIdxToType[idx],
tokenType: onlyRelevantTypes[idx]
};
});
});
let canBeOptimized = true;
let charCodeToPatternIdxToConfig = [];
if (!options.safeMode) {
tracer("First Char Optimization", () => {
charCodeToPatternIdxToConfig = reduce_default(onlyRelevantTypes, (result, currTokType, idx) => {
if (typeof currTokType.PATTERN === "string") {
const charCode = currTokType.PATTERN.charCodeAt(0);
const optimizedIdx = charCodeToOptimizedIndex(charCode);
addToMapOfArrays(result, optimizedIdx, patternIdxToConfig[idx]);
} else if (isArray_default(currTokType.START_CHARS_HINT)) {
let lastOptimizedIdx;
forEach_default(currTokType.START_CHARS_HINT, (charOrInt) => {
const charCode = typeof charOrInt === "string" ? charOrInt.charCodeAt(0) : charOrInt;
const currOptimizedIdx = charCodeToOptimizedIndex(charCode);
if (lastOptimizedIdx !== currOptimizedIdx) {
lastOptimizedIdx = currOptimizedIdx;
addToMapOfArrays(result, currOptimizedIdx, patternIdxToConfig[idx]);
}
});
} else if (isRegExp_default(currTokType.PATTERN)) {
if (currTokType.PATTERN.unicode) {
canBeOptimized = false;
if (options.ensureOptimizations) {
PRINT_ERROR(`${failedOptimizationPrefixMsg} Unable to analyze < ${currTokType.PATTERN.toString()} > pattern.
The regexp unicode flag is not currently supported by the regexp-to-ast library.
This will disable the lexer's first char optimizations.
For details See: https://chevrotain.io/docs/guide/resolving_lexer_errors.html#UNICODE_OPTIMIZE`);
}
} else {
const optimizedCodes = getOptimizedStartCodesIndices(currTokType.PATTERN, options.ensureOptimizations);
if (isEmpty_default(optimizedCodes)) {
canBeOptimized = false;
}
forEach_default(optimizedCodes, (code) => {
addToMapOfArrays(result, code, patternIdxToConfig[idx]);
});
}
} else {
if (options.ensureOptimizations) {
PRINT_ERROR(`${failedOptimizationPrefixMsg} TokenType: <${currTokType.name}> is using a custom token pattern without providing <start_chars_hint> parameter.
This will disable the lexer's first char optimizations.
For details See: https://chevrotain.io/docs/guide/resolving_lexer_errors.html#CUSTOM_OPTIMIZE`);
}
canBeOptimized = false;
}
return result;
}, []);
});
}
return {
emptyGroups,
patternIdxToConfig,
charCodeToPatternIdxToConfig,
hasCustom,
canBeOptimized
};
}
__name(analyzeTokenTypes, "analyzeTokenTypes");
__name2(analyzeTokenTypes, "analyzeTokenTypes");
function validatePatterns(tokenTypes, validModesNames) {
let errors = [];
const missingResult = findMissingPatterns(tokenTypes);
errors = errors.concat(missingResult.errors);
const invalidResult = findInvalidPatterns(missingResult.valid);
const validTokenTypes = invalidResult.valid;
errors = errors.concat(invalidResult.errors);
errors = errors.concat(validateRegExpPattern(validTokenTypes));
errors = errors.concat(findInvalidGroupType(validTokenTypes));
errors = errors.concat(findModesThatDoNotExist(validTokenTypes, validModesNames));
errors = errors.concat(findUnreachablePatterns(validTokenTypes));
return errors;
}
__name(validatePatterns, "validatePatterns");
__name2(validatePatterns, "validatePatterns");
function validateRegExpPattern(tokenTypes) {
let errors = [];
const withRegExpPatterns = filter_default(tokenTypes, (currTokType) => isRegExp_default(currTokType[PATTERN]));
errors = errors.concat(findEndOfInputAnchor(withRegExpPatterns));
errors = errors.concat(findStartOfInputAnchor(withRegExpPatterns));
errors = errors.concat(findUnsupportedFlags(withRegExpPatterns));
errors = errors.concat(findDuplicatePatterns(withRegExpPatterns));
errors = errors.concat(findEmptyMatchRegExps(withRegExpPatterns));
return errors;
}
__name(validateRegExpPattern, "validateRegExpPattern");
__name2(validateRegExpPattern, "validateRegExpPattern");
function findMissingPatterns(tokenTypes) {
const tokenTypesWithMissingPattern = filter_default(tokenTypes, (currType) => {
return !has_default(currType, PATTERN);
});
const errors = map_default(tokenTypesWithMissingPattern, (currType) => {
return {
message: "Token Type: ->" + currType.name + "<- missing static 'PATTERN' property",
type: LexerDefinitionErrorType.MISSING_PATTERN,
tokenTypes: [currType]
};
});
const valid = difference_default(tokenTypes, tokenTypesWithMissingPattern);
return { errors, valid };
}
__name(findMissingPatterns, "findMissingPatterns");
__name2(findMissingPatterns, "findMissingPatterns");
function findInvalidPatterns(tokenTypes) {
const tokenTypesWithInvalidPattern = filter_default(tokenTypes, (currType) => {
const pattern = currType[PATTERN];
return !isRegExp_default(pattern) && !isFunction_default(pattern) && !has_default(pattern, "exec") && !isString_default(pattern);
});
const errors = map_default(tokenTypesWithInvalidPattern, (currType) => {
return {
message: "Token Type: ->" + currType.name + "<- static 'PATTERN' can only be a RegExp, a Function matching the {CustomPatternMatcherFunc} type or an Object matching the {ICustomPattern} interface.",
type: LexerDefinitionErrorType.INVALID_PATTERN,
tokenTypes: [currType]
};
});
const valid = difference_default(tokenTypes, tokenTypesWithInvalidPattern);
return { errors, valid };
}
__name(findInvalidPatterns, "findInvalidPatterns");
__name2(findInvalidPatterns, "findInvalidPatterns");
var end_of_input = /[^\\][$]/;
function findEndOfInputAnchor(tokenTypes) {
class EndAnchorFinder extends BaseRegExpVisitor {
static {
__name(this, "EndAnchorFinder");
}
static {
__name2(this, "EndAnchorFinder");
}
constructor() {
super(...arguments);
this.found = false;
}
visitEndAnchor(node) {
this.found = true;
}
}
const invalidRegex = filter_default(tokenTypes, (currType) => {
const pattern = currType.PATTERN;
try {
const regexpAst = getRegExpAst(pattern);
const endAnchorVisitor = new EndAnchorFinder();
endAnchorVisitor.visit(regexpAst);
return endAnchorVisitor.found;
} catch (e) {
return end_of_input.test(pattern.source);
}
});
const errors = map_default(invalidRegex, (currType) => {
return {
message: "Unexpected RegExp Anchor Error:\n Token Type: ->" + currType.name + "<- static 'PATTERN' cannot contain end of input anchor '$'\n See chevrotain.io/docs/guide/resolving_lexer_errors.html#ANCHORS for details.",
type: LexerDefinitionErrorType.EOI_ANCHOR_FOUND,
tokenTypes: [currType]
};
});
return errors;
}
__name(findEndOfInputAnchor, "findEndOfInputAnchor");
__name2(findEndOfInputAnchor, "findEndOfInputAnchor");
function findEmptyMatchRegExps(tokenTypes) {
const matchesEmptyString = filter_default(tokenTypes, (currType) => {
const pattern = currType.PATTERN;
return pattern.test("");
});
const errors = map_default(matchesEmptyString, (currType) => {
return {
message: "Token Type: ->" + currType.name + "<- static 'PATTERN' must not match an empty string",
type: LexerDefinitionErrorType.EMPTY_MATCH_PATTERN,
tokenTypes: [currType]
};
});
return errors;
}
__name(findEmptyMatchRegExps, "findEmptyMatchRegExps");
__name2(findEmptyMatchRegExps, "findEmptyMatchRegExps");
var start_of_input = /[^\\[][\^]|^\^/;
function findStartOfInputAnchor(tokenTypes) {
class StartAnchorFinder extends BaseRegExpVisitor {
static {
__name(this, "StartAnchorFinder");
}
static {
__name2(this, "StartAnchorFinder");
}
constructor() {
super(...arguments);
this.found = false;
}
visitStartAnchor(node) {
this.found = true;
}
}
const invalidRegex = filter_default(tokenTypes, (currType) => {
const pattern = currType.PATTERN;
try {
const regexpAst = getRegExpAst(pattern);
const startAnchorVisitor = new StartAnchorFinder();
startAnchorVisitor.visit(regexpAst);
return startAnchorVisitor.found;
} catch (e) {
return start_of_input.test(pattern.source);
}
});
const errors = map_default(invalidRegex, (currType) => {
return {
message: "Unexpected RegExp Anchor Error:\n Token Type: ->" + currType.name + "<- static 'PATTERN' cannot contain start of input anchor '^'\n See https://chevrotain.io/docs/guide/resolving_lexer_errors.html#ANCHORS for details.",
type: LexerDefinitionErrorType.SOI_ANCHOR_FOUND,
tokenTypes: [currType]
};
});
return errors;
}
__name(findStartOfInputAnchor, "findStartOfInputAnchor");
__name2(findStartOfInputAnchor, "findStartOfInputAnchor");
function findUnsupportedFlags(tokenTypes) {
const invalidFlags = filter_default(tokenTypes, (currType) => {
const pattern = currType[PATTERN];
return pattern instanceof RegExp && (pattern.multiline || pattern.global);
});
const errors = map_default(invalidFlags, (currType) => {
return {
message: "Token Type: ->" + currType.name + "<- static 'PATTERN' may NOT contain global('g') or multiline('m')",
type: LexerDefinitionErrorType.UNSUPPORTED_FLAGS_FOUND,
tokenTypes: [currType]
};
});
return errors;
}
__name(findUnsupportedFlags, "findUnsupportedFlags");
__name2(findUnsupportedFlags, "findUnsupportedFlags");
function findDuplicatePatterns(tokenTypes) {
const found = [];
let identicalPatterns = map_default(tokenTypes, (outerType) => {
return reduce_default(tokenTypes, (result, innerType) => {
if (outerType.PATTERN.source === innerType.PATTERN.source && !includes_default(found, innerType) && innerType.PATTERN !== Lexer.NA) {
found.push(innerType);
result.push(innerType);
return result;
}
return result;
}, []);
});
identicalPatterns = compact_default(identicalPatterns);
const duplicatePatterns = filter_default(identicalPatterns, (currIdenticalSet) => {
return currIdenticalSet.length > 1;
});
const errors = map_default(duplicatePatterns, (setOfIdentical) => {
const tokenTypeNames = map_default(setOfIdentical, (currType) => {
return currType.name;
});
const dupPatternSrc = head_default(setOfIdentical).PATTERN;
return {
message: `The same RegExp pattern ->${dupPatternSrc}<-has been used in all of the following Token Types: ${tokenTypeNames.join(", ")} <-`,
type: LexerDefinitionErrorType.DUPLICATE_PATTERNS_FOUND,
tokenTypes: setOfIdentical
};
});
return errors;
}
__name(findDuplicatePatterns, "findDuplicatePatterns");
__name2(findDuplicatePatterns, "findDuplicatePatterns");
function findInvalidGroupType(tokenTypes) {
const invalidTypes = filter_default(tokenTypes, (clazz) => {
if (!has_default(clazz, "GROUP")) {
return false;
}
const group = clazz.GROUP;
return group !== Lexer.SKIPPED && group !== Lexer.NA && !isString_default(group);
});
const errors = map_default(invalidTypes, (currType) => {
return {
message: "Token Type: ->" + currType.name + "<- static 'GROUP' can only be Lexer.SKIPPED/Lexer.NA/A String",
type: LexerDefinitionErrorType.INVALID_GROUP_TYPE_FOUND,
tokenTypes: [currType]
};
});
return errors;
}
__name(findInvalidGroupType, "findInvalidGroupType");
__name2(findInvalidGroupType, "findInvalidGroupType");
function findModesThatDoNotExist(tokenTypes, validModes) {
const invalidModes = filter_default(tokenTypes, (clazz) => {
return clazz.PUSH_MODE !== void 0 && !includes_default(validModes, clazz.PUSH_MODE);
});
const errors = map_default(invalidModes, (tokType) => {
const msg = `Token Type: ->${tokType.name}<- static 'PUSH_MODE' value cannot refer to a Lexer Mode ->${tokType.PUSH_MODE}<-which does not exist`;
return {
message: msg,
type: LexerDefinitionErrorType.PUSH_MODE_DOES_NOT_EXIST,
tokenTypes: [tokType]
};
});
return errors;
}
__name(findModesThatDoNotExist, "findModesThatDoNotExist");
__name2(findModesThatDoNotExist, "findModesThatDoNotExist");
function findUnreachablePatterns(tokenTypes) {
const errors = [];
const canBeTested = reduce_default(tokenTypes, (result, tokType, idx) => {
const pattern = tokType.PATTERN;
if (pattern === Lexer.NA) {
return result;
}
if (isString_default(pattern)) {
result.push({ str: pattern, idx, tokenType: tokType });
} else if (isRegExp_default(pattern) && noMetaChar(pattern)) {
result.push({ str: pattern.source, idx, tokenType: tokType });
}
return result;
}, []);
forEach_default(tokenTypes, (aTokType, aIdx) => {
forEach_default(canBeTested, ({ str: bStr, idx: bIdx, tokenType: bTokType }) => {
if (aIdx < bIdx && tryToMatchStrToPattern(bStr, aTokType.PATTERN)) {
const msg = `Token: ->${bTokType.name}<- can never be matched.
Because it appears AFTER the Token Type ->${aTokType.name}<-in the lexer's definition.
See https://chevrotain.io/docs/guide/resolving_lexer_errors.html#UNREACHABLE`;
errors.push({
message: msg,
type: LexerDefinitionErrorType.UNREACHABLE_PATTERN,
tokenTypes: [aTokType, bTokType]
});
}
});
});
return errors;
}
__name(findUnreachablePatterns, "findUnreachablePatterns");
__name2(findUnreachablePatterns, "findUnreachablePatterns");
function tryToMatchStrToPattern(str, pattern) {
if (isRegExp_default(pattern)) {
if (usesLookAheadOrBehind(pattern)) {
return false;
}
const regExpArray = pattern.exec(str);
return regExpArray !== null && regExpArray.index === 0;
} else if (isFunction_default(pattern)) {
return pattern(str, 0, [], {});
} else if (has_default(pattern, "exec")) {
return pattern.exec(str, 0, [], {});
} else if (typeof pattern === "string") {
return pattern === str;
} else {
throw Error("non exhaustive match");
}
}
__name(tryToMatchStrToPattern, "tryToMatchStrToPattern");
__name2(tryToMatchStrToPattern, "tryToMatchStrToPattern");
function noMetaChar(regExp) {
const metaChars = [
".",
"\\",
"[",
"]",
"|",
"^",
"$",
"(",
")",
"?",
"*",
"+",
"{"
];
return find_default(metaChars, (char) => regExp.source.indexOf(char) !== -1) === void 0;
}
__name(noMetaChar, "noMetaChar");
__name2(noMetaChar, "noMetaChar");
function usesLookAheadOrBehind(regExp) {
return /(\(\?=)|(\(\?!)|(\(\?<=)|(\(\?<!)/.test(regExp.source);
}
__name(usesLookAheadOrBehind, "usesLookAheadOrBehind");
__name2(usesLookAheadOrBehind, "usesLookAheadOrBehind");
function addStickyFlag(pattern) {
const flags = pattern.ignoreCase ? "iy" : "y";
return new RegExp(`${pattern.source}`, flags);
}
__name(addStickyFlag, "addStickyFlag");
__name2(addStickyFlag, "addStickyFlag");
function performRuntimeChecks(lexerDefinition, trackLines, lineTerminatorCharacters) {
const errors = [];
if (!has_default(lexerDefinition, DEFAULT_MODE)) {
errors.push({
message: "A MultiMode Lexer cannot be initialized without a <" + DEFAULT_MODE + "> property in its definition\n",
type: LexerDefinitionErrorType.MULTI_MODE_LEXER_WITHOUT_DEFAULT_MODE
});
}
if (!has_default(lexerDefinition, MODES)) {
errors.push({
message: "A MultiMode Lexer cannot be initialized without a <" + MODES + "> property in its definition\n",
type: LexerDefinitionErrorType.MULTI_MODE_LEXER_WITHOUT_MODES_PROPERTY
});
}
if (has_default(lexerDefinition, MODES) && has_default(lexerDefinition, DEFAULT_MODE) && !has_default(lexerDefinition.modes, lexerDefinition.defaultMode)) {
errors.push({
message: `A MultiMode Lexer cannot be initialized with a ${DEFAULT_MODE}: <${lexerDefinition.defaultMode}>which does not exist
`,
type: LexerDefinitionErrorType.MULTI_MODE_LEXER_DEFAULT_MODE_VALUE_DOES_NOT_EXIST
});
}
if (has_default(lexerDefinition, MODES)) {
forEach_default(lexerDefinition.modes, (currModeValue, currModeName) => {
forEach_default(currModeValue, (currTokType, currIdx) => {
if (isUndefined_default(currTokType)) {
errors.push({
message: `A Lexer cannot be initialized using an undefined Token Type. Mode:<${currModeName}> at index: <${currIdx}>
`,
type: LexerDefinitionErrorType.LEXER_DEFINITION_CANNOT_CONTAIN_UNDEFINED
});
} else if (has_default(currTokType, "LONGER_ALT")) {
const longerAlt = isArray_default(currTokType.LONGER_ALT) ? currTokType.LONGER_ALT : [currTokType.LONGER_ALT];
forEach_default(longerAlt, (currLongerAlt) => {
if (!isUndefined_default(currLongerAlt) && !includes_default(currModeValue, currLongerAlt)) {
errors.push({
message: `A MultiMode Lexer cannot be initialized with a longer_alt <${currLongerAlt.name}> on token <${currTokType.name}> outside of mode <${currModeName}>
`,
type: LexerDefinitionErrorType.MULTI_MODE_LEXER_LONGER_ALT_NOT_IN_CURRENT_MODE
});
}
});
}
});
});
}
return errors;
}
__name(performRuntimeChecks, "performRuntimeChecks");
__name2(performRuntimeChecks, "performRuntimeChecks");
function performWarningRuntimeChecks(lexerDefinition, trackLines, lineTerminatorCharacters) {
const warnings = [];
let hasAnyLineBreak = false;
const allTokenTypes = compact_default(flatten_default(values_default(lexerDefinition.modes)));
const concreteTokenTypes = reject_default(allTokenTypes, (currType) => currType[PATTERN] === Lexer.NA);
const terminatorCharCodes = getCharCodes(lineTerminatorCharacters);
if (trackLines) {
forEach_default(concreteTokenTypes, (tokType) => {
const currIssue = checkLineBreaksIssues(tokType, terminatorCharCodes);
if (currIssue !== false) {
const message = buildLineBreakIssueMessage(tokType, currIssue);
const warningDescriptor = {
message,
type: currIssue.issue,
tokenType: tokType
};
warnings.push(warningDescriptor);
} else {
if (has_default(tokType, "LINE_BREAKS")) {
if (tokType.LINE_BREAKS === true) {
hasAnyLineBreak = true;
}
} else {
if (canMatchCharCode(terminatorCharCodes, tokType.PATTERN)) {
hasAnyLineBreak = true;
}
}
}
});
}
if (trackLines && !hasAnyLineBreak) {
warnings.push({
message: "Warning: No LINE_BREAKS Found.\n This Lexer has been defined to track line and column information,\n But none of the Token Types can be identified as matching a line terminator.\n See https://chevrotain.io/docs/guide/resolving_lexer_errors.html#LINE_BREAKS \n for details.",
type: LexerDefinitionErrorType.NO_LINE_BREAKS_FLAGS
});
}
return warnings;
}
__name(performWarningRuntimeChecks, "performWarningRuntimeChecks");
__name2(performWarningRuntimeChecks, "performWarningRuntimeChecks");
function cloneEmptyGroups(emptyGroups) {
const clonedResult = {};
const groupKeys = keys_default(emptyGroups);
forEach_default(groupKeys, (currKey) => {
const currGroupValue = emptyGroups[currKey];
if (isArray_default(currGroupValue)) {
clonedResult[currKey] = [];
} else {
throw Error("non exhaustive match");
}
});
return clonedResult;
}
__name(cloneEmptyGroups, "cloneEmptyGroups");
__name2(cloneEmptyGroups, "cloneEmptyGroups");
function isCustomPattern(tokenType) {
const pattern = tokenType.PATTERN;
if (isRegExp_default(pattern)) {
return false;
} else if (isFunction_default(pattern)) {
return true;
} else if (has_default(pattern, "exec")) {
return true;
} else if (isString_default(pattern)) {
return false;
} else {
throw Error("non exhaustive match");
}
}
__name(isCustomPattern, "isCustomPattern");
__name2(isCustomPattern, "isCustomPattern");
function isShortPattern(pattern) {
if (isString_default(pattern) && pattern.length === 1) {
return pattern.charCodeAt(0);
} else {
return false;
}
}
__name(isShortPattern, "isShortPattern");
__name2(isShortPattern, "isShortPattern");
var LineTerminatorOptimizedTester = {
// implements /\n|\r\n?/g.test
test: /* @__PURE__ */ __name2(function(text) {
const len = text.length;
for (let i = this.lastIndex; i < len; i++) {
const c = text.charCodeAt(i);
if (c === 10) {
this.lastIndex = i + 1;
return true;
} else if (c === 13) {
if (text.charCodeAt(i + 1) === 10) {
this.lastIndex = i + 2;
} else {
this.lastIndex = i + 1;
}
return true;
}
}
return false;
}, "test"),
lastIndex: 0
};
function checkLineBreaksIssues(tokType, lineTerminatorCharCodes) {
if (has_default(tokType, "LINE_BREAKS")) {
return false;
} else {
if (isRegExp_default(tokType.PATTERN)) {
try {
canMatchCharCode(lineTerminatorCharCodes, tokType.PATTERN);
} catch (e) {
return {
issue: LexerDefinitionErrorType.IDENTIFY_TERMINATOR,
errMsg: e.message
};
}
return false;
} else if (isString_default(tokType.PATTERN)) {
return false;
} else if (isCustomPattern(tokType)) {
return { issue: LexerDefinitionErrorType.CUSTOM_LINE_BREAK };
} else {
throw Error("non exhaustive match");
}
}
}
__name(checkLineBreaksIssues, "checkLineBreaksIssues");
__name2(checkLineBreaksIssues, "checkLineBreaksIssues");
function buildLineBreakIssueMessage(tokType, details) {
if (details.issue === LexerDefinitionErrorType.IDENTIFY_TERMINATOR) {
return `Warning: unable to identify line terminator usage in pattern.
The problem is in the <${tokType.name}> Token Type
Root cause: ${details.errMsg}.
For details See: https://chevrotain.io/docs/guide/resolving_lexer_errors.html#IDENTIFY_TERMINATOR`;
} else if (details.issue === LexerDefinitionErrorType.CUSTOM_LINE_BREAK) {
return `Warning: A Custom Token Pattern should specify the <line_breaks> option.
The problem is in the <${tokType.name}> Token Type
For details See: https://chevrotain.io/docs/guide/resolving_lexer_errors.html#CUSTOM_LINE_BREAK`;
} else {
throw Error("non exhaustive match");
}
}
__name(buildLineBreakIssueMessage, "buildLineBreakIssueMessage");
__name2(buildLineBreakIssueMessage, "buildLineBreakIssueMessage");
function getCharCodes(charsOrCodes) {
const charCodes = map_default(charsOrCodes, (numOrString) => {
if (isString_default(numOrString)) {
return numOrString.charCodeAt(0);
} else {
return numOrString;
}
});
return charCodes;
}
__name(getCharCodes, "getCharCodes");
__name2(getCharCodes, "getCharCodes");
function addToMapOfArrays(map3, key, value) {
if (map3[key] === void 0) {
map3[key] = [value];
} else {
map3[key].push(value);
}
}
__name(addToMapOfArrays, "addToMapOfArrays");
__name2(addToMapOfArrays, "addToMapOfArrays");
var minOptimizationVal = 256;
var charCodeToOptimizedIdxMap = [];
function charCodeToOptimizedIndex(charCode) {
return charCode < minOptimizationVal ? charCode : charCodeToOptimizedIdxMap[charCode];
}
__name(charCodeToOptimizedIndex, "charCodeToOptimizedIndex");
__name2(charCodeToOptimizedIndex, "charCodeToOptimizedIndex");
function initCharCodeToOptimizedIndexMap() {
if (isEmpty_default(charCodeToOptimizedIdxMap)) {
charCodeToOptimizedIdxMap = new Array(65536);
for (let i = 0; i < 65536; i++) {
charCodeToOptimizedIdxMap[i] = i > 255 ? 255 + ~~(i / 255) : i;
}
}
}
__name(initCharCodeToOptimizedIndexMap, "initCharCodeToOptimizedIndexMap");
__name2(initCharCodeToOptimizedIndexMap, "initCharCodeToOptimizedIndexMap");
function tokenStructuredMatcher(tokInstance, tokConstructor) {
const instanceType = tokInstance.tokenTypeIdx;
if (instanceType === tokConstructor.tokenTypeIdx) {
return true;
} else {
return tokConstructor.isParent === true && tokConstructor.categoryMatchesMap[instanceType] === true;
}
}
__name(tokenStructuredMatcher, "tokenStructuredMatcher");
__name2(tokenStructuredMatcher, "tokenStructuredMatcher");
function tokenStructuredMatcherNoCategories(token, tokType) {
return token.tokenTypeIdx === tokType.tokenTypeIdx;
}
__name(tokenStructuredMatcherNoCategories, "tokenStructuredMatcherNoCategories");
__name2(tokenStructuredMatcherNoCategories, "tokenStructuredMatcherNoCategories");
var tokenShortNameIdx = 1;
var tokenIdxToClass = {};
function augmentTokenTypes(tokenTypes) {
const tokenTypesAndParents = expandCategories(tokenTypes);
assignTokenDefaultProps(tokenTypesAndParents);
assignCategoriesMapProp(tokenTypesAndParents);
assignCategoriesTokensProp(tokenTypesAndParents);
forEach_default(tokenTypesAndParents, (tokType) => {
tokType.isParent = tokType.categoryMatches.length > 0;
});
}
__name(augmentTokenTypes, "augmentTokenTypes");
__name2(augmentTokenTypes, "augmentTokenTypes");
function expandCategories(tokenTypes) {
let result = clone_default(tokenTypes);
let categories = tokenTypes;
let searching = true;
while (searching) {
categories = compact_default(flatten_default(map_default(categories, (currTokType) => currTokType.CATEGORIES)));
const newCategories = difference_default(categories, result);
result = result.concat(newCategories);
if (isEmpty_default(newCategories)) {
searching = false;
} else {
categories = newCategories;
}
}
return result;
}
__name(expandCategories, "expandCategories");
__name2(expandCategories, "expandCategories");
function assignTokenDefaultProps(tokenTypes) {
forEach_default(tokenTypes, (currTokType) => {
if (!hasShortKeyProperty(currTokType)) {
tokenIdxToClass[tokenShortNameIdx] = currTokType;
currTokType.tokenTypeIdx = tokenShortNameIdx++;
}
if (hasCategoriesProperty(currTokType) && !isArray_default(currTokType.CATEGORIES)) {
currTokType.CATEGORIES = [currTokType.CATEGORIES];
}
if (!hasCategoriesProperty(currTokType)) {
currTokType.CATEGORIES = [];
}
if (!hasExtendingTokensTypesProperty(currTokType)) {
currTokType.categoryMatches = [];
}
if (!hasExtendingTokensTypesMapProperty(currTokType)) {
currTokType.categoryMatchesMap = {};
}
});
}
__name(assignTokenDefaultProps, "assignTokenDefaultProps");
__name2(assignTokenDefaultProps, "assignTokenDefaultProps");
function assignCategoriesTokensProp(tokenTypes) {
forEach_default(tokenTypes, (currTokType) => {
currTokType.categoryMatches = [];
forEach_default(currTokType.categoryMatchesMap, (val, key) => {
currTokType.categoryMatches.push(tokenIdxToClass[key].tokenTypeIdx);
});
});
}
__name(assignCategoriesTokensProp, "assignCategoriesTokensProp");
__name2(assignCategoriesTokensProp, "assignCategoriesTokensProp");
function assignCategoriesMapProp(tokenTypes) {
forEach_default(tokenTypes, (currTokType) => {
singleAssignCategoriesToksMap([], currTokType);
});
}
__name(assignCategoriesMapProp, "assignCategoriesMapProp");
__name2(assignCategoriesMapProp, "assignCategoriesMapProp");
function singleAssignCategoriesToksMap(path, nextNode) {
forEach_default(path, (pathNode) => {
nextNode.categoryMatchesMap[pathNode.tokenTypeIdx] = true;
});
forEach_default(nextNode.CATEGORIES, (nextCategory) => {
const newPath = path.concat(nextNode);
if (!includes_default(newPath, nextCategory)) {
singleAssignCategoriesToksMap(newPath, nextCategory);
}
});
}
__name(singleAssignCategoriesToksMap, "singleAssignCategoriesToksMap");
__name2(singleAssignCategoriesToksMap, "singleAssignCategoriesToksMap");
function hasShortKeyProperty(tokType) {
return has_default(tokType, "tokenTypeIdx");
}
__name(hasShortKeyProperty, "hasShortKeyProperty");
__name2(hasShortKeyProperty, "hasShortKeyProperty");
function hasCategoriesProperty(tokType) {
return has_default(tokType, "CATEGORIES");
}
__name(hasCategoriesProperty, "hasCategoriesProperty");
__name2(hasCategoriesProperty, "hasCategoriesProperty");
function hasExtendingTokensTypesProperty(tokType) {
return has_default(tokType, "categoryMatches");
}
__name(hasExtendingTokensTypesProperty, "hasExtendingTokensTypesProperty");
__name2(hasExtendingTokensTypesProperty, "hasExtendingTokensTypesProperty");
function hasExtendingTokensTypesMapProperty(tokType) {
return has_default(tokType, "categoryMatchesMap");
}
__name(hasExtendingTokensTypesMapProperty, "hasExtendingTokensTypesMapProperty");
__name2(hasExtendingTokensTypesMapProperty, "hasExtendingTokensTypesMapProperty");
function isTokenType(tokType) {
return has_default(tokType, "tokenTypeIdx");
}
__name(isTokenType, "isTokenType");
__name2(isTokenType, "isTokenType");
var defaultLexerErrorProvider = {
buildUnableToPopLexerModeMessage(token) {
return `Unable to pop Lexer Mode after encountering Token ->${token.image}<- The Mode Stack is empty`;
},
buildUnexpectedCharactersMessage(fullText, startOffset, length, line, column, mode) {
return `unexpected character: ->${fullText.charAt(startOffset)}<- at offset: ${startOffset}, skipped ${length} characters.`;
}
};
var LexerDefinitionErrorType;
(function(LexerDefinitionErrorType2) {
LexerDefinitionErrorType2[LexerDefinitionErrorType2["MISSING_PATTERN"] = 0] = "MISSING_PATTERN";
LexerDefinitionErrorType2[LexerDefinitionErrorType2["INVALID_PATTERN"] = 1] = "INVALID_PATTERN";
LexerDefinitionErrorType2[LexerDefinitionErrorType2["EOI_ANCHOR_FOUND"] = 2] = "EOI_ANCHOR_FOUND";
LexerDefinitionErrorType2[LexerDefinitionErrorType2["UNSUPPORTED_FLAGS_FOUND"] = 3] = "UNSUPPORTED_FLAGS_FOUND";
LexerDefinitionErrorType2[LexerDefinitionErrorType2["DUPLICATE_PATTERNS_FOUND"] = 4] = "DUPLICATE_PATTERNS_FOUND";
LexerDefinitionErrorType2[LexerDefinitionErrorType2["INVALID_GROUP_TYPE_FOUND"] = 5] = "INVALID_GROUP_TYPE_FOUND";
LexerDefinitionErrorType2[LexerDefinitionErrorType2["PUSH_MODE_DOES_NOT_EXIST"] = 6] = "PUSH_MODE_DOES_NOT_EXIST";
LexerDefinitionErrorType2[LexerDefinitionErrorType2["MULTI_MODE_LEXER_WITHOUT_DEFAULT_MODE"] = 7] = "MULTI_MODE_LEXER_WITHOUT_DEFAULT_MODE";
LexerDefinitionErrorType2[LexerDefinitionErrorType2["MULTI_MODE_LEXER_WITHOUT_MODES_PROPERTY"] = 8] = "MULTI_MODE_LEXER_WITHOUT_MODES_PROPERTY";
LexerDefinitionErrorType2[LexerDefinitionErrorType2["MULTI_MODE_LEXER_DEFAULT_MODE_VALUE_DOES_NOT_EXIST"] = 9] = "MULTI_MODE_LEXER_DEFAULT_MODE_VALUE_DOES_NOT_EXIST";
LexerDefinitionErrorType2[LexerDefinitionErrorType2["LEXER_DEFINITION_CANNOT_CONTAIN_UNDEFINED"] = 10] = "LEXER_DEFINITION_CANNOT_CONTAIN_UNDEFINED";
LexerDefinitionErrorType2[LexerDefinitionErrorType2["SOI_ANCHOR_FOUND"] = 11] = "SOI_ANCHOR_FOUND";
LexerDefinitionErrorType2[LexerDefinitionErrorType2["EMPTY_MATCH_PATTERN"] = 12] = "EMPTY_MATCH_PATTERN";
LexerDefinitionErrorType2[LexerDefinitionErrorType2["NO_LINE_BREAKS_FLAGS"] = 13] = "NO_LINE_BREAKS_FLAGS";
LexerDefinitionErrorType2[LexerDefinitionErrorType2["UNREACHABLE_PATTERN"] = 14] = "UNREACHABLE_PATTERN";
LexerDefinitionErrorType2[LexerDefinitionErrorType2["IDENTIFY_TERMINATOR"] = 15] = "IDENTIFY_TERMINATOR";
LexerDefinitionErrorType2[LexerDefinitionErrorType2["CUSTOM_LINE_BREAK"] = 16] = "CUSTOM_LINE_BREAK";
LexerDefinitionErrorType2[LexerDefinitionErrorType2["MULTI_MODE_LEXER_LONGER_ALT_NOT_IN_CURRENT_MODE"] = 17] = "MULTI_MODE_LEXER_LONGER_ALT_NOT_IN_CURRENT_MODE";
})(LexerDefinitionErrorType || (LexerDefinitionErrorType = {}));
var DEFAULT_LEXER_CONFIG = {
deferDefinitionErrorsHandling: false,
positionTracking: "full",
lineTerminatorsPattern: /\n|\r\n?/g,
lineTerminatorCharacters: ["\n", "\r"],
ensureOptimizations: false,
safeMode: false,
errorMessageProvider: defaultLexerErrorProvider,
traceInitPerf: false,
skipValidations: false,
recoveryEnabled: true
};
Object.freeze(DEFAULT_LEXER_CONFIG);
var Lexer = class {
static {
__name(this, "Lexer");
}
static {
__name2(this, "Lexer");
}
constructor(lexerDefinition, config = DEFAULT_LEXER_CONFIG) {
this.lexerDefinition = lexerDefinition;
this.lexerDefinitionErrors = [];
this.lexerDefinitionWarning = [];
this.patternIdxToConfig = {};
this.charCodeToPatternIdxToConfig = {};
this.modes = [];
this.emptyGroups = {};
this.trackStartLines = true;
this.trackEndLines = true;
this.hasCustom = false;
this.canModeBeOptimized = {};
this.TRACE_INIT = (phaseDesc, phaseImpl) => {
if (this.traceInitPerf === true) {
this.traceInitIndent++;
const indent = new Array(this.traceInitIndent + 1).join(" ");
if (this.traceInitIndent < this.traceInitMaxIdent) {
console.log(`${indent}--> <${phaseDesc}>`);
}
const { time, value } = timer(phaseImpl);
const traceMethod = time > 10 ? console.warn : console.log;
if (this.traceInitIndent < this.traceInitMaxIdent) {
traceMethod(`${indent}<-- <${phaseDesc}> time: ${time}ms`);
}
this.traceInitIndent--;
return value;
} else {
return phaseImpl();
}
};
if (typeof config === "boolean") {
throw Error("The second argument to the Lexer constructor is now an ILexerConfig Object.\na boolean 2nd argument is no longer supported");
}
this.config = assign_default({}, DEFAULT_LEXER_CONFIG, config);
const traceInitVal = this.config.traceInitPerf;
if (traceInitVal === true) {
this.traceInitMaxIdent = Infinity;
this.traceInitPerf = true;
} else if (typeof traceInitVal === "number") {
this.traceInitMaxIdent = traceInitVal;
this.traceInitPerf = true;
}
this.traceInitIndent = -1;
this.TRACE_INIT("Lexer Constructor", () => {
let actualDefinition;
let hasOnlySingleMode = true;
this.TRACE_INIT("Lexer Config handling", () => {
if (this.config.lineTerminatorsPattern === DEFAULT_LEXER_CONFIG.lineTerminatorsPattern) {
this.config.lineTerminatorsPattern = LineTerminatorOptimizedTester;
} else {
if (this.config.lineTerminatorCharacters === DEFAULT_LEXER_CONFIG.lineTerminatorCharacters) {
throw Error("Error: Missing <lineTerminatorCharacters> property on the Lexer config.\n For details See: https://chevrotain.io/docs/guide/resolving_lexer_errors.html#MISSING_LINE_TERM_CHARS");
}
}
if (config.safeMode && config.ensureOptimizations) {
throw Error('"safeMode" and "ensureOptimizations" flags are mutually exclusive.');
}
this.trackStartLines = /full|onlyStart/i.test(this.config.positionTracking);
this.trackEndLines = /full/i.test(this.config.positionTracking);
if (isArray_default(lexerDefinition)) {
actualDefinition = {
modes: { defaultMode: clone_default(lexerDefinition) },
defaultMode: DEFAULT_MODE
};
} else {
hasOnlySingleMode = false;
actualDefinition = clone_default(lexerDefinition);
}
});
if (this.config.skipValidations === false) {
this.TRACE_INIT("performRuntimeChecks", () => {
this.lexerDefinitionErrors = this.lexerDefinitionErrors.concat(performRuntimeChecks(actualDefinition, this.trackStartLines, this.config.lineTerminatorCharacters));
});
this.TRACE_INIT("performWarningRuntimeChecks", () => {
this.lexerDefinitionWarning = this.lexerDefinitionWarning.concat(performWarningRuntimeChecks(actualDefinition, this.trackStartLines, this.config.lineTerminatorCharacters));
});
}
actualDefinition.modes = actualDefinition.modes ? actualDefinition.modes : {};
forEach_default(actualDefinition.modes, (currModeValue, currModeName) => {
actualDefinition.modes[currModeName] = reject_default(currModeValue, (currTokType) => isUndefined_default(currTokType));
});
const allModeNames = keys_default(actualDefinition.modes);
forEach_default(actualDefinition.modes, (currModDef, currModName) => {
this.TRACE_INIT(`Mode: <${currModName}> processing`, () => {
this.modes.push(currModName);
if (this.config.skipValidations === false) {
this.TRACE_INIT(`validatePatterns`, () => {
this.lexerDefinitionErrors = this.lexerDefinitionErrors.concat(validatePatterns(currModDef, allModeNames));
});
}
if (isEmpty_default(this.lexerDefinitionErrors)) {
augmentTokenTypes(currModDef);
let currAnalyzeResult;
this.TRACE_INIT(`analyzeTokenTypes`, () => {
currAnalyzeResult = analyzeTokenTypes(currModDef, {
lineTerminatorCharacters: this.config.lineTerminatorCharacters,
positionTracking: config.positionTracking,
ensureOptimizations: config.ensureOptimizations,
safeMode: config.safeMode,
tracer: this.TRACE_INIT
});
});
this.patternIdxToConfig[currModName] = currAnalyzeResult.patternIdxToConfig;
this.charCodeToPatternIdxToConfig[currModName] = currAnalyzeResult.charCodeToPatternIdxToConfig;
this.emptyGroups = assign_default({}, this.emptyGroups, currAnalyzeResult.emptyGroups);
this.hasCustom = currAnalyzeResult.hasCustom || this.hasCustom;
this.canModeBeOptimized[currModName] = currAnalyzeResult.canBeOptimized;
}
});
});
this.defaultMode = actualDefinition.defaultMode;
if (!isEmpty_default(this.lexerDefinitionErrors) && !this.config.deferDefinitionErrorsHandling) {
const allErrMessages = map_default(this.lexerDefinitionErrors, (error) => {
return error.message;
});
const allErrMessagesString = allErrMessages.join("-----------------------\n");
throw new Error("Errors detected in definition of Lexer:\n" + allErrMessagesString);
}
forEach_default(this.lexerDefinitionWarning, (warningDescriptor) => {
PRINT_WARNING(warningDescriptor.message);
});
this.TRACE_INIT("Choosing sub-methods implementations", () => {
if (hasOnlySingleMode) {
this.handleModes = noop_default;
}
if (this.trackStartLines === false) {
this.computeNewColumn = identity_default;
}
if (this.trackEndLines === false) {
this.updateTokenEndLineColumnLocation = noop_default;
}
if (/full/i.test(this.config.positionTracking)) {
this.createTokenInstance = this.createFullToken;
} else if (/onlyStart/i.test(this.config.positionTracking)) {
this.createTokenInstance = this.createStartOnlyToken;
} else if (/onlyOffset/i.test(this.config.positionTracking)) {
this.createTokenInstance = this.createOffsetOnlyToken;
} else {
throw Error(`Invalid <positionTracking> config option: "${this.config.positionTracking}"`);
}
if (this.hasCustom) {
this.addToken = this.addTokenUsingPush;
this.handlePayload = this.handlePayloadWithCustom;
} else {
this.addToken = this.addTokenUsingMemberAccess;
this.handlePayload = this.handlePayloadNoCustom;
}
});
this.TRACE_INIT("Failed Optimization Warnings", () => {
const unOptimizedModes = reduce_default(this.canModeBeOptimized, (cannotBeOptimized, canBeOptimized, modeName) => {
if (canBeOptimized === false) {
cannotBeOptimized.push(modeName);
}
return cannotBeOptimized;
}, []);
if (config.ensureOptimizations && !isEmpty_default(unOptimizedModes)) {
throw Error(`Lexer Modes: < ${unOptimizedModes.join(", ")} > cannot be optimized.
Disable the "ensureOptimizations" lexer config flag to silently ignore this and run the lexer in an un-optimized mode.
Or inspect the console log for details on how to resolve these issues.`);
}
});
this.TRACE_INIT("clearRegExpParserCache", () => {
clearRegExpParserCache();
});
this.TRACE_INIT("toFastProperties", () => {
toFastProperties(this);
});
});
}
tokenize(text, initialMode = this.defaultMode) {
if (!isEmpty_default(this.lexerDefinitionErrors)) {
const allErrMessages = map_default(this.lexerDefinitionErrors, (error) => {
return error.message;
});
const allErrMessagesString = allErrMessages.join("-----------------------\n");
throw new Error("Unable to Tokenize because Errors detected in definition of Lexer:\n" + allErrMessagesString);
}
return this.tokenizeInternal(text, initialMode);
}
// There is quite a bit of duplication between this and "tokenizeInternalLazy"
// This is intentional due to performance considerations.
// this method also used quite a bit of `!` none null assertions because it is too optimized
// for `tsc` to always understand it is "safe"
tokenizeInternal(text, initialMode) {
let i, j, k, matchAltImage, longerAlt, matchedImage, payload, altPayload, imageLength, group, tokType, newToken, errLength, msg, match;
const orgText = text;
const orgLength = orgText.length;
let offset = 0;
let matchedTokensIndex = 0;
const guessedNumberOfTokens = this.hasCustom ? 0 : Math.floor(text.length / 10);
const matchedTokens = new Array(guessedNumberOfTokens);
const errors = [];
let line = this.trackStartLines ? 1 : void 0;
let column = this.trackStartLines ? 1 : void 0;
const groups = cloneEmptyGroups(this.emptyGroups);
const trackLines = this.trackStartLines;
const lineTerminatorPattern = this.config.lineTerminatorsPattern;
let currModePatternsLength = 0;
let patternIdxToConfig = [];
let currCharCodeToPatternIdxToConfig = [];
const modeStack = [];
const emptyArray = [];
Object.freeze(emptyArray);
let isOptimizedMode = false;
const pop_mode = /* @__PURE__ */ __name2((popToken) => {
if (modeStack.length === 1 && // if we have both a POP_MODE and a PUSH_MODE this is in-fact a "transition"
// So no error should occur.
popToken.tokenType.PUSH_MODE === void 0) {
const msg2 = this.config.errorMessageProvider.buildUnableToPopLexerModeMessage(popToken);
errors.push({
offset: popToken.startOffset,
line: popToken.startLine,
column: popToken.startColumn,
length: popToken.image.length,
message: msg2
});
} else {
modeStack.pop();
const newMode = last_default(modeStack);
patternIdxToConfig = this.patternIdxToConfig[newMode];
currCharCodeToPatternIdxToConfig = this.charCodeToPatternIdxToConfig[newMode];
currModePatternsLength = patternIdxToConfig.length;
const modeCanBeOptimized = this.canModeBeOptimized[newMode] && this.config.safeMode === false;
if (currCharCodeToPatternIdxToConfig && modeCanBeOptimized) {
isOptimizedMode = true;
} else {
isOptimizedMode = false;
}
}
}, "pop_mode");
function push_mode(newMode) {
modeStack.push(newMode);
currCharCodeToPatternIdxToConfig = this.charCodeToPatternIdxToConfig[newMode];
patternIdxToConfig = this.patternIdxToConfig[newMode];
currModePatternsLength = patternIdxToConfig.length;
currModePatternsLength = patternIdxToConfig.length;
const modeCanBeOptimized = this.canModeBeOptimized[newMode] && this.config.safeMode === false;
if (currCharCodeToPatternIdxToConfig && modeCanBeOptimized) {
isOptimizedMode = true;
} else {
isOptimizedMode = false;
}
}
__name(push_mode, "push_mode");
__name2(push_mode, "push_mode");
push_mode.call(this, initialMode);
let currConfig;
const recoveryEnabled = this.config.recoveryEnabled;
while (offset < orgLength) {
matchedImage = null;
imageLength = -1;
const nextCharCode = orgText.charCodeAt(offset);
let chosenPatternIdxToConfig;
if (isOptimizedMode) {
const optimizedCharIdx = charCodeToOptimizedIndex(nextCharCode);
const possiblePatterns = currCharCodeToPatternIdxToConfig[optimizedCharIdx];
chosenPatternIdxToConfig = possiblePatterns !== void 0 ? possiblePatterns : emptyArray;
} else {
chosenPatternIdxToConfig = patternIdxToConfig;
}
const chosenPatternsLength = chosenPatternIdxToConfig.length;
for (i = 0; i < chosenPatternsLength; i++) {
currConfig = chosenPatternIdxToConfig[i];
const currPattern = currConfig.pattern;
payload = null;
const singleCharCode = currConfig.short;
if (singleCharCode !== false) {
if (nextCharCode === singleCharCode) {
imageLength = 1;
matchedImage = currPattern;
}
} else if (currConfig.isCustom === true) {
match = currPattern.exec(orgText, offset, matchedTokens, groups);
if (match !== null) {
matchedImage = match[0];
imageLength = matchedImage.length;
if (match.payload !== void 0) {
payload = match.payload;
}
} else {
matchedImage = null;
}
} else {
currPattern.lastIndex = offset;
imageLength = this.matchLength(currPattern, text, offset);
}
if (imageLength !== -1) {
longerAlt = currConfig.longerAlt;
if (longerAlt !== void 0) {
matchedImage = text.substring(offset, offset + imageLength);
const longerAltLength = longerAlt.length;
for (k = 0; k < longerAltLength; k++) {
const longerAltConfig = patternIdxToConfig[longerAlt[k]];
const longerAltPattern = longerAltConfig.pattern;
altPayload = null;
if (longerAltConfig.isCustom === true) {
match = longerAltPattern.exec(orgText, offset, matchedTokens, groups);
if (match !== null) {
matchAltImage = match[0];
if (match.payload !== void 0) {
altPayload = match.payload;
}
} else {
matchAltImage = null;
}
} else {
longerAltPattern.lastIndex = offset;
matchAltImage = this.match(longerAltPattern, text, offset);
}
if (matchAltImage && matchAltImage.length > matchedImage.length) {
matchedImage = matchAltImage;
imageLength = matchAltImage.length;
payload = altPayload;
currConfig = longerAltConfig;
break;
}
}
}
break;
}
}
if (imageLength !== -1) {
group = currConfig.group;
if (group !== void 0) {
matchedImage = matchedImage !== null ? matchedImage : text.substring(offset, offset + imageLength);
tokType = currConfig.tokenTypeIdx;
newToken = this.createTokenInstance(matchedImage, offset, tokType, currConfig.tokenType, line, column, imageLength);
this.handlePayload(newToken, payload);
if (group === false) {
matchedTokensIndex = this.addToken(matchedTokens, matchedTokensIndex, newToken);
} else {
groups[group].push(newToken);
}
}
if (trackLines === true && currConfig.canLineTerminator === true) {
let numOfLTsInMatch = 0;
let foundTerminator;
let lastLTEndOffset;
lineTerminatorPattern.lastIndex = 0;
do {
matchedImage = matchedImage !== null ? matchedImage : text.substring(offset, offset + imageLength);
foundTerminator = lineTerminatorPattern.test(matchedImage);
if (foundTerminator === true) {
lastLTEndOffset = lineTerminatorPattern.lastIndex - 1;
numOfLTsInMatch++;
}
} while (foundTerminator === true);
if (numOfLTsInMatch !== 0) {
line = line + numOfLTsInMatch;
column = imageLength - lastLTEndOffset;
this.updateTokenEndLineColumnLocation(newToken, group, lastLTEndOffset, numOfLTsInMatch, line, column, imageLength);
} else {
column = this.computeNewColumn(column, imageLength);
}
} else {
column = this.computeNewColumn(column, imageLength);
}
offset = offset + imageLength;
this.handleModes(currConfig, pop_mode, push_mode, newToken);
} else {
const errorStartOffset = offset;
const errorLine = line;
const errorColumn = column;
let foundResyncPoint = recoveryEnabled === false;
while (foundResyncPoint === false && offset < orgLength) {
offset++;
for (j = 0; j < currModePatternsLength; j++) {
const currConfig2 = patternIdxToConfig[j];
const currPattern = currConfig2.pattern;
const singleCharCode = currConfig2.short;
if (singleCharCode !== false) {
if (orgText.charCodeAt(offset) === singleCharCode) {
foundResyncPoint = true;
}
} else if (currConfig2.isCustom === true) {
foundResyncPoint = currPattern.exec(orgText, offset, matchedTokens, groups) !== null;
} else {
currPattern.lastIndex = offset;
foundResyncPoint = currPattern.exec(text) !== null;
}
if (foundResyncPoint === true) {
break;
}
}
}
errLength = offset - errorStartOffset;
column = this.computeNewColumn(column, errLength);
msg = this.config.errorMessageProvider.buildUnexpectedCharactersMessage(orgText, errorStartOffset, errLength, errorLine, errorColumn, last_default(modeStack));
errors.push({
offset: errorStartOffset,
line: errorLine,
column: errorColumn,
length: errLength,
message: msg
});
if (recoveryEnabled === false) {
break;
}
}
}
if (!this.hasCustom) {
matchedTokens.length = matchedTokensIndex;
}
return {
tokens: matchedTokens,
groups,
errors
};
}
handleModes(config, pop_mode, push_mode, newToken) {
if (config.pop === true) {
const pushMode = config.push;
pop_mode(newToken);
if (pushMode !== void 0) {
push_mode.call(this, pushMode);
}
} else if (config.push !== void 0) {
push_mode.call(this, config.push);
}
}
// TODO: decrease this under 600 characters? inspect stripping comments option in TSC compiler
updateTokenEndLineColumnLocation(newToken, group, lastLTIdx, numOfLTsInMatch, line, column, imageLength) {
let lastCharIsLT, fixForEndingInLT;
if (group !== void 0) {
lastCharIsLT = lastLTIdx === imageLength - 1;
fixForEndingInLT = lastCharIsLT ? -1 : 0;
if (!(numOfLTsInMatch === 1 && lastCharIsLT === true)) {
newToken.endLine = line + fixForEndingInLT;
newToken.endColumn = column - 1 + -fixForEndingInLT;
}
}
}
computeNewColumn(oldColumn, imageLength) {
return oldColumn + imageLength;
}
createOffsetOnlyToken(image, startOffset, tokenTypeIdx, tokenType) {
return {
image,
startOffset,
tokenTypeIdx,
tokenType
};
}
createStartOnlyToken(image, startOffset, tokenTypeIdx, tokenType, startLine, startColumn) {
return {
image,
startOffset,
startLine,
startColumn,
tokenTypeIdx,
tokenType
};
}
createFullToken(image, startOffset, tokenTypeIdx, tokenType, startLine, startColumn, imageLength) {
return {
image,
startOffset,
endOffset: startOffset + imageLength - 1,
startLine,
endLine: startLine,
startColumn,
endColumn: startColumn + imageLength - 1,
tokenTypeIdx,
tokenType
};
}
addTokenUsingPush(tokenVector, index, tokenToAdd) {
tokenVector.push(tokenToAdd);
return index;
}
addTokenUsingMemberAccess(tokenVector, index, tokenToAdd) {
tokenVector[index] = tokenToAdd;
index++;
return index;
}
handlePayloadNoCustom(token, payload) {
}
handlePayloadWithCustom(token, payload) {
if (payload !== null) {
token.payload = payload;
}
}
match(pattern, text, offset) {
const found = pattern.test(text);
if (found === true) {
return text.substring(offset, pattern.lastIndex);
}
return null;
}
matchLength(pattern, text, offset) {
const found = pattern.test(text);
if (found === true) {
return pattern.lastIndex - offset;
}
return -1;
}
};
Lexer.SKIPPED = "This marks a skipped Token pattern, this means each token identified by it will be consumed and then thrown into oblivion, this can be used to for example to completely ignore whitespace.";
Lexer.NA = /NOT_APPLICABLE/;
function tokenLabel2(tokType) {
if (hasTokenLabel2(tokType)) {
return tokType.LABEL;
} else {
return tokType.name;
}
}
__name(tokenLabel2, "tokenLabel2");
__name2(tokenLabel2, "tokenLabel");
function hasTokenLabel2(obj) {
return isString_default(obj.LABEL) && obj.LABEL !== "";
}
__name(hasTokenLabel2, "hasTokenLabel2");
__name2(hasTokenLabel2, "hasTokenLabel");
var PARENT = "parent";
var CATEGORIES = "categories";
var LABEL = "label";
var GROUP = "group";
var PUSH_MODE = "push_mode";
var POP_MODE = "pop_mode";
var LONGER_ALT = "longer_alt";
var LINE_BREAKS = "line_breaks";
var START_CHARS_HINT = "start_chars_hint";
function createToken(config) {
return createTokenInternal(config);
}
__name(createToken, "createToken");
__name2(createToken, "createToken");
function createTokenInternal(config) {
const pattern = config.pattern;
const tokenType = {};
tokenType.name = config.name;
if (!isUndefined_default(pattern)) {
tokenType.PATTERN = pattern;
}
if (has_default(config, PARENT)) {
throw "The parent property is no longer supported.\nSee: https://github.com/chevrotain/chevrotain/issues/564#issuecomment-349062346 for details.";
}
if (has_default(config, CATEGORIES)) {
tokenType.CATEGORIES = config[CATEGORIES];
}
augmentTokenTypes([tokenType]);
if (has_default(config, LABEL)) {
tokenType.LABEL = config[LABEL];
}
if (has_default(config, GROUP)) {
tokenType.GROUP = config[GROUP];
}
if (has_default(config, POP_MODE)) {
tokenType.POP_MODE = config[POP_MODE];
}
if (has_default(config, PUSH_MODE)) {
tokenType.PUSH_MODE = config[PUSH_MODE];
}
if (has_default(config, LONGER_ALT)) {
tokenType.LONGER_ALT = config[LONGER_ALT];
}
if (has_default(config, LINE_BREAKS)) {
tokenType.LINE_BREAKS = config[LINE_BREAKS];
}
if (has_default(config, START_CHARS_HINT)) {
tokenType.START_CHARS_HINT = config[START_CHARS_HINT];
}
return tokenType;
}
__name(createTokenInternal, "createTokenInternal");
__name2(createTokenInternal, "createTokenInternal");
var EOF = createToken({ name: "EOF", pattern: Lexer.NA });
augmentTokenTypes([EOF]);
function createTokenInstance(tokType, image, startOffset, endOffset, startLine, endLine, startColumn, endColumn) {
return {
image,
startOffset,
endOffset,
startLine,
endLine,
startColumn,
endColumn,
tokenTypeIdx: tokType.tokenTypeIdx,
tokenType: tokType
};
}
__name(createTokenInstance, "createTokenInstance");
__name2(createTokenInstance, "createTokenInstance");
function tokenMatcher(token, tokType) {
return tokenStructuredMatcher(token, tokType);
}
__name(tokenMatcher, "tokenMatcher");
__name2(tokenMatcher, "tokenMatcher");
var defaultParserErrorProvider = {
buildMismatchTokenMessage({ expected, actual, previous, ruleName }) {
const hasLabel = hasTokenLabel2(expected);
const expectedMsg = hasLabel ? `--> ${tokenLabel2(expected)} <--` : `token of type --> ${expected.name} <--`;
const msg = `Expecting ${expectedMsg} but found --> '${actual.image}' <--`;
return msg;
},
buildNotAllInputParsedMessage({ firstRedundant, ruleName }) {
return "Redundant input, expecting EOF but found: " + firstRedundant.image;
},
buildNoViableAltMessage({ expectedPathsPerAlt, actual, previous, customUserDescription, ruleName }) {
const errPrefix = "Expecting: ";
const actualText = head_default(actual).image;
const errSuffix = "\nbut found: '" + actualText + "'";
if (customUserDescription) {
return errPrefix + customUserDescription + errSuffix;
} else {
const allLookAheadPaths = reduce_default(expectedPathsPerAlt, (result, currAltPaths) => result.concat(currAltPaths), []);
const nextValidTokenSequences = map_default(allLookAheadPaths, (currPath) => `[${map_default(currPath, (currTokenType) => tokenLabel2(currTokenType)).join(", ")}]`);
const nextValidSequenceItems = map_default(nextValidTokenSequences, (itemMsg, idx) => ` ${idx + 1}. ${itemMsg}`);
const calculatedDescription = `one of these possible Token sequences:
${nextValidSequenceItems.join("\n")}`;
return errPrefix + calculatedDescription + errSuffix;
}
},
buildEarlyExitMessage({ expectedIterationPaths, actual, customUserDescription, ruleName }) {
const errPrefix = "Expecting: ";
const actualText = head_default(actual).image;
const errSuffix = "\nbut found: '" + actualText + "'";
if (customUserDescription) {
return errPrefix + customUserDescription + errSuffix;
} else {
const nextValidTokenSequences = map_default(expectedIterationPaths, (currPath) => `[${map_default(currPath, (currTokenType) => tokenLabel2(currTokenType)).join(",")}]`);
const calculatedDescription = `expecting at least one iteration which starts with one of these possible Token sequences::
<${nextValidTokenSequences.join(" ,")}>`;
return errPrefix + calculatedDescription + errSuffix;
}
}
};
Object.freeze(defaultParserErrorProvider);
var defaultGrammarResolverErrorProvider = {
buildRuleNotFoundError(topLevelRule, undefinedRule) {
const msg = "Invalid grammar, reference to a rule which is not defined: ->" + undefinedRule.nonTerminalName + "<-\ninside top level rule: ->" + topLevelRule.name + "<-";
return msg;
}
};
var defaultGrammarValidatorErrorProvider = {
buildDuplicateFoundError(topLevelRule, duplicateProds) {
function getExtraProductionArgument2(prod) {
if (prod instanceof Terminal) {
return prod.terminalType.name;
} else if (prod instanceof NonTerminal) {
return prod.nonTerminalName;
} else {
return "";
}
}
__name(getExtraProductionArgument2, "getExtraProductionArgument2");
__name2(getExtraProductionArgument2, "getExtraProductionArgument");
const topLevelName = topLevelRule.name;
const duplicateProd = head_default(duplicateProds);
const index = duplicateProd.idx;
const dslName = getProductionDslName(duplicateProd);
const extraArgument = getExtraProductionArgument2(duplicateProd);
const hasExplicitIndex = index > 0;
let msg = `->${dslName}${hasExplicitIndex ? index : ""}<- ${extraArgument ? `with argument: ->${extraArgument}<-` : ""}
appears more than once (${duplicateProds.length} times) in the top level rule: ->${topLevelName}<-.
For further details see: https://chevrotain.io/docs/FAQ.html#NUMERICAL_SUFFIXES
`;
msg = msg.replace(/[ \t]+/g, " ");
msg = msg.replace(/\s\s+/g, "\n");
return msg;
},
buildNamespaceConflictError(rule) {
const errMsg = `Namespace conflict found in grammar.
The grammar has both a Terminal(Token) and a Non-Terminal(Rule) named: <${rule.name}>.
To resolve this make sure each Terminal and Non-Terminal names are unique
This is easy to accomplish by using the convention that Terminal names start with an uppercase letter
and Non-Terminal names start with a lower case letter.`;
return errMsg;
},
buildAlternationPrefixAmbiguityError(options) {
const pathMsg = map_default(options.prefixPath, (currTok) => tokenLabel2(currTok)).join(", ");
const occurrence = options.alternation.idx === 0 ? "" : options.alternation.idx;
const errMsg = `Ambiguous alternatives: <${options.ambiguityIndices.join(" ,")}> due to common lookahead prefix
in <OR${occurrence}> inside <${options.topLevelRule.name}> Rule,
<${pathMsg}> may appears as a prefix path in all these alternatives.
See: https://chevrotain.io/docs/guide/resolving_grammar_errors.html#COMMON_PREFIX
For Further details.`;
return errMsg;
},
buildAlternationAmbiguityError(options) {
const occurrence = options.alternation.idx === 0 ? "" : options.alternation.idx;
const isEmptyPath = options.prefixPath.length === 0;
let currMessage = `Ambiguous Alternatives Detected: <${options.ambiguityIndices.join(" ,")}> in <OR${occurrence}> inside <${options.topLevelRule.name}> Rule,
`;
if (isEmptyPath) {
currMessage += `These alternatives are all empty (match no tokens), making them indistinguishable.
Only the last alternative may be empty.
`;
} else {
const pathMsg = map_default(options.prefixPath, (currtok) => tokenLabel2(currtok)).join(", ");
currMessage += `<${pathMsg}> may appears as a prefix path in all these alternatives.
`;
}
currMessage += `See: https://chevrotain.io/docs/guide/resolving_grammar_errors.html#AMBIGUOUS_ALTERNATIVES
For Further details.`;
return currMessage;
},
buildEmptyRepetitionError(options) {
let dslName = getProductionDslName(options.repetition);
if (options.repetition.idx !== 0) {
dslName += options.repetition.idx;
}
const errMsg = `The repetition <${dslName}> within Rule <${options.topLevelRule.name}> can never consume any tokens.
This could lead to an infinite loop.`;
return errMsg;
},
// TODO: remove - `errors_public` from nyc.config.js exclude
// once this method is fully removed from this file
buildTokenNameError(options) {
return "deprecated";
},
buildEmptyAlternationError(options) {
const errMsg = `Ambiguous empty alternative: <${options.emptyChoiceIdx + 1}> in <OR${options.alternation.idx}> inside <${options.topLevelRule.name}> Rule.
Only the last alternative may be an empty alternative.`;
return errMsg;
},
buildTooManyAlternativesError(options) {
const errMsg = `An Alternation cannot have more than 256 alternatives:
<OR${options.alternation.idx}> inside <${options.topLevelRule.name}> Rule.
has ${options.alternation.definition.length + 1} alternatives.`;
return errMsg;
},
buildLeftRecursionError(options) {
const ruleName = options.topLevelRule.name;
const pathNames = map_default(options.leftRecursionPath, (currRule) => currRule.name);
const leftRecursivePath = `${ruleName} --> ${pathNames.concat([ruleName]).join(" --> ")}`;
const errMsg = `Left Recursion found in grammar.
rule: <${ruleName}> can be invoked from itself (directly or indirectly)
without consuming any Tokens. The grammar path that causes this is:
${leftRecursivePath}
To fix this refactor your grammar to remove the left recursion.
see: https://en.wikipedia.org/wiki/LL_parser#Left_factoring.`;
return errMsg;
},
// TODO: remove - `errors_public` from nyc.config.js exclude
// once this method is fully removed from this file
buildInvalidRuleNameError(options) {
return "deprecated";
},
buildDuplicateRuleNameError(options) {
let ruleName;
if (options.topLevelRule instanceof Rule) {
ruleName = options.topLevelRule.name;
} else {
ruleName = options.topLevelRule;
}
const errMsg = `Duplicate definition, rule: ->${ruleName}<- is already defined in the grammar: ->${options.grammarName}<-`;
return errMsg;
}
};
function resolveGrammar(topLevels, errMsgProvider) {
const refResolver = new GastRefResolverVisitor(topLevels, errMsgProvider);
refResolver.resolveRefs();
return refResolver.errors;
}
__name(resolveGrammar, "resolveGrammar");
__name2(resolveGrammar, "resolveGrammar");
var GastRefResolverVisitor = class extends GAstVisitor {
static {
__name(this, "GastRefResolverVisitor");
}
static {
__name2(this, "GastRefResolverVisitor");
}
constructor(nameToTopRule, errMsgProvider) {
super();
this.nameToTopRule = nameToTopRule;
this.errMsgProvider = errMsgProvider;
this.errors = [];
}
resolveRefs() {
forEach_default(values_default(this.nameToTopRule), (prod) => {
this.currTopLevel = prod;
prod.accept(this);
});
}
visitNonTerminal(node) {
const ref = this.nameToTopRule[node.nonTerminalName];
if (!ref) {
const msg = this.errMsgProvider.buildRuleNotFoundError(this.currTopLevel, node);
this.errors.push({
message: msg,
type: ParserDefinitionErrorType.UNRESOLVED_SUBRULE_REF,
ruleName: this.currTopLevel.name,
unresolvedRefName: node.nonTerminalName
});
} else {
node.referencedRule = ref;
}
}
};
var AbstractNextPossibleTokensWalker = class extends RestWalker {
static {
__name(this, "AbstractNextPossibleTokensWalker");
}
static {
__name2(this, "AbstractNextPossibleTokensWalker");
}
constructor(topProd, path) {
super();
this.topProd = topProd;
this.path = path;
this.possibleTokTypes = [];
this.nextProductionName = "";
this.nextProductionOccurrence = 0;
this.found = false;
this.isAtEndOfPath = false;
}
startWalking() {
this.found = false;
if (this.path.ruleStack[0] !== this.topProd.name) {
throw Error("The path does not start with the walker's top Rule!");
}
this.ruleStack = clone_default(this.path.ruleStack).reverse();
this.occurrenceStack = clone_default(this.path.occurrenceStack).reverse();
this.ruleStack.pop();
this.occurrenceStack.pop();
this.updateExpectedNext();
this.walk(this.topProd);
return this.possibleTokTypes;
}
walk(prod, prevRest = []) {
if (!this.found) {
super.walk(prod, prevRest);
}
}
walkProdRef(refProd, currRest, prevRest) {
if (refProd.referencedRule.name === this.nextProductionName && refProd.idx === this.nextProductionOccurrence) {
const fullRest = currRest.concat(prevRest);
this.updateExpectedNext();
this.walk(refProd.referencedRule, fullRest);
}
}
updateExpectedNext() {
if (isEmpty_default(this.ruleStack)) {
this.nextProductionName = "";
this.nextProductionOccurrence = 0;
this.isAtEndOfPath = true;
} else {
this.nextProductionName = this.ruleStack.pop();
this.nextProductionOccurrence = this.occurrenceStack.pop();
}
}
};
var NextAfterTokenWalker = class extends AbstractNextPossibleTokensWalker {
static {
__name(this, "NextAfterTokenWalker");
}
static {
__name2(this, "NextAfterTokenWalker");
}
constructor(topProd, path) {
super(topProd, path);
this.path = path;
this.nextTerminalName = "";
this.nextTerminalOccurrence = 0;
this.nextTerminalName = this.path.lastTok.name;
this.nextTerminalOccurrence = this.path.lastTokOccurrence;
}
walkTerminal(terminal, currRest, prevRest) {
if (this.isAtEndOfPath && terminal.terminalType.name === this.nextTerminalName && terminal.idx === this.nextTerminalOccurrence && !this.found) {
const fullRest = currRest.concat(prevRest);
const restProd = new Alternative({ definition: fullRest });
this.possibleTokTypes = first(restProd);
this.found = true;
}
}
};
var AbstractNextTerminalAfterProductionWalker = class extends RestWalker {
static {
__name(this, "AbstractNextTerminalAfterProductionWalker");
}
static {
__name2(this, "AbstractNextTerminalAfterProductionWalker");
}
constructor(topRule, occurrence) {
super();
this.topRule = topRule;
this.occurrence = occurrence;
this.result = {
token: void 0,
occurrence: void 0,
isEndOfRule: void 0
};
}
startWalking() {
this.walk(this.topRule);
return this.result;
}
};
var NextTerminalAfterManyWalker = class extends AbstractNextTerminalAfterProductionWalker {
static {
__name(this, "NextTerminalAfterManyWalker");
}
static {
__name2(this, "NextTerminalAfterManyWalker");
}
walkMany(manyProd, currRest, prevRest) {
if (manyProd.idx === this.occurrence) {
const firstAfterMany = head_default(currRest.concat(prevRest));
this.result.isEndOfRule = firstAfterMany === void 0;
if (firstAfterMany instanceof Terminal) {
this.result.token = firstAfterMany.terminalType;
this.result.occurrence = firstAfterMany.idx;
}
} else {
super.walkMany(manyProd, currRest, prevRest);
}
}
};
var NextTerminalAfterManySepWalker = class extends AbstractNextTerminalAfterProductionWalker {
static {
__name(this, "NextTerminalAfterManySepWalker");
}
static {
__name2(this, "NextTerminalAfterManySepWalker");
}
walkManySep(manySepProd, currRest, prevRest) {
if (manySepProd.idx === this.occurrence) {
const firstAfterManySep = head_default(currRest.concat(prevRest));
this.result.isEndOfRule = firstAfterManySep === void 0;
if (firstAfterManySep instanceof Terminal) {
this.result.token = firstAfterManySep.terminalType;
this.result.occurrence = firstAfterManySep.idx;
}
} else {
super.walkManySep(manySepProd, currRest, prevRest);
}
}
};
var NextTerminalAfterAtLeastOneWalker = class extends AbstractNextTerminalAfterProductionWalker {
static {
__name(this, "NextTerminalAfterAtLeastOneWalker");
}
static {
__name2(this, "NextTerminalAfterAtLeastOneWalker");
}
walkAtLeastOne(atLeastOneProd, currRest, prevRest) {
if (atLeastOneProd.idx === this.occurrence) {
const firstAfterAtLeastOne = head_default(currRest.concat(prevRest));
this.result.isEndOfRule = firstAfterAtLeastOne === void 0;
if (firstAfterAtLeastOne instanceof Terminal) {
this.result.token = firstAfterAtLeastOne.terminalType;
this.result.occurrence = firstAfterAtLeastOne.idx;
}
} else {
super.walkAtLeastOne(atLeastOneProd, currRest, prevRest);
}
}
};
var NextTerminalAfterAtLeastOneSepWalker = class extends AbstractNextTerminalAfterProductionWalker {
static {
__name(this, "NextTerminalAfterAtLeastOneSepWalker");
}
static {
__name2(this, "NextTerminalAfterAtLeastOneSepWalker");
}
walkAtLeastOneSep(atleastOneSepProd, currRest, prevRest) {
if (atleastOneSepProd.idx === this.occurrence) {
const firstAfterfirstAfterAtLeastOneSep = head_default(currRest.concat(prevRest));
this.result.isEndOfRule = firstAfterfirstAfterAtLeastOneSep === void 0;
if (firstAfterfirstAfterAtLeastOneSep instanceof Terminal) {
this.result.token = firstAfterfirstAfterAtLeastOneSep.terminalType;
this.result.occurrence = firstAfterfirstAfterAtLeastOneSep.idx;
}
} else {
super.walkAtLeastOneSep(atleastOneSepProd, currRest, prevRest);
}
}
};
function possiblePathsFrom(targetDef, maxLength, currPath = []) {
currPath = clone_default(currPath);
let result = [];
let i = 0;
function remainingPathWith(nextDef) {
return nextDef.concat(drop_default(targetDef, i + 1));
}
__name(remainingPathWith, "remainingPathWith");
__name2(remainingPathWith, "remainingPathWith");
function getAlternativesForProd(definition) {
const alternatives = possiblePathsFrom(remainingPathWith(definition), maxLength, currPath);
return result.concat(alternatives);
}
__name(getAlternativesForProd, "getAlternativesForProd");
__name2(getAlternativesForProd, "getAlternativesForProd");
while (currPath.length < maxLength && i < targetDef.length) {
const prod = targetDef[i];
if (prod instanceof Alternative) {
return getAlternativesForProd(prod.definition);
} else if (prod instanceof NonTerminal) {
return getAlternativesForProd(prod.definition);
} else if (prod instanceof Option) {
result = getAlternativesForProd(prod.definition);
} else if (prod instanceof RepetitionMandatory) {
const newDef = prod.definition.concat([
new Repetition({
definition: prod.definition
})
]);
return getAlternativesForProd(newDef);
} else if (prod instanceof RepetitionMandatoryWithSeparator) {
const newDef = [
new Alternative({ definition: prod.definition }),
new Repetition({
definition: [new Terminal({ terminalType: prod.separator })].concat(prod.definition)
})
];
return getAlternativesForProd(newDef);
} else if (prod instanceof RepetitionWithSeparator) {
const newDef = prod.definition.concat([
new Repetition({
definition: [new Terminal({ terminalType: prod.separator })].concat(prod.definition)
})
]);
result = getAlternativesForProd(newDef);
} else if (prod instanceof Repetition) {
const newDef = prod.definition.concat([
new Repetition({
definition: prod.definition
})
]);
result = getAlternativesForProd(newDef);
} else if (prod instanceof Alternation) {
forEach_default(prod.definition, (currAlt) => {
if (isEmpty_default(currAlt.definition) === false) {
result = getAlternativesForProd(currAlt.definition);
}
});
return result;
} else if (prod instanceof Terminal) {
currPath.push(prod.terminalType);
} else {
throw Error("non exhaustive match");
}
i++;
}
result.push({
partialPath: currPath,
suffixDef: drop_default(targetDef, i)
});
return result;
}
__name(possiblePathsFrom, "possiblePathsFrom");
__name2(possiblePathsFrom, "possiblePathsFrom");
function nextPossibleTokensAfter(initialDef, tokenVector, tokMatcher, maxLookAhead) {
const EXIT_NON_TERMINAL = "EXIT_NONE_TERMINAL";
const EXIT_NON_TERMINAL_ARR = [EXIT_NON_TERMINAL];
const EXIT_ALTERNATIVE = "EXIT_ALTERNATIVE";
let foundCompletePath = false;
const tokenVectorLength = tokenVector.length;
const minimalAlternativesIndex = tokenVectorLength - maxLookAhead - 1;
const result = [];
const possiblePaths = [];
possiblePaths.push({
idx: -1,
def: initialDef,
ruleStack: [],
occurrenceStack: []
});
while (!isEmpty_default(possiblePaths)) {
const currPath = possiblePaths.pop();
if (currPath === EXIT_ALTERNATIVE) {
if (foundCompletePath && last_default(possiblePaths).idx <= minimalAlternativesIndex) {
possiblePaths.pop();
}
continue;
}
const currDef = currPath.def;
const currIdx = currPath.idx;
const currRuleStack = currPath.ruleStack;
const currOccurrenceStack = currPath.occurrenceStack;
if (isEmpty_default(currDef)) {
continue;
}
const prod = currDef[0];
if (prod === EXIT_NON_TERMINAL) {
const nextPath = {
idx: currIdx,
def: drop_default(currDef),
ruleStack: dropRight_default(currRuleStack),
occurrenceStack: dropRight_default(currOccurrenceStack)
};
possiblePaths.push(nextPath);
} else if (prod instanceof Terminal) {
if (currIdx < tokenVectorLength - 1) {
const nextIdx = currIdx + 1;
const actualToken = tokenVector[nextIdx];
if (tokMatcher(actualToken, prod.terminalType)) {
const nextPath = {
idx: nextIdx,
def: drop_default(currDef),
ruleStack: currRuleStack,
occurrenceStack: currOccurrenceStack
};
possiblePaths.push(nextPath);
}
} else if (currIdx === tokenVectorLength - 1) {
result.push({
nextTokenType: prod.terminalType,
nextTokenOccurrence: prod.idx,
ruleStack: currRuleStack,
occurrenceStack: currOccurrenceStack
});
foundCompletePath = true;
} else {
throw Error("non exhaustive match");
}
} else if (prod instanceof NonTerminal) {
const newRuleStack = clone_default(currRuleStack);
newRuleStack.push(prod.nonTerminalName);
const newOccurrenceStack = clone_default(currOccurrenceStack);
newOccurrenceStack.push(prod.idx);
const nextPath = {
idx: currIdx,
def: prod.definition.concat(EXIT_NON_TERMINAL_ARR, drop_default(currDef)),
ruleStack: newRuleStack,
occurrenceStack: newOccurrenceStack
};
possiblePaths.push(nextPath);
} else if (prod instanceof Option) {
const nextPathWithout = {
idx: currIdx,
def: drop_default(currDef),
ruleStack: currRuleStack,
occurrenceStack: currOccurrenceStack
};
possiblePaths.push(nextPathWithout);
possiblePaths.push(EXIT_ALTERNATIVE);
const nextPathWith = {
idx: currIdx,
def: prod.definition.concat(drop_default(currDef)),
ruleStack: currRuleStack,
occurrenceStack: currOccurrenceStack
};
possiblePaths.push(nextPathWith);
} else if (prod instanceof RepetitionMandatory) {
const secondIteration = new Repetition({
definition: prod.definition,
idx: prod.idx
});
const nextDef = prod.definition.concat([secondIteration], drop_default(currDef));
const nextPath = {
idx: currIdx,
def: nextDef,
ruleStack: currRuleStack,
occurrenceStack: currOccurrenceStack
};
possiblePaths.push(nextPath);
} else if (prod instanceof RepetitionMandatoryWithSeparator) {
const separatorGast = new Terminal({
terminalType: prod.separator
});
const secondIteration = new Repetition({
definition: [separatorGast].concat(prod.definition),
idx: prod.idx
});
const nextDef = prod.definition.concat([secondIteration], drop_default(currDef));
const nextPath = {
idx: currIdx,
def: nextDef,
ruleStack: currRuleStack,
occurrenceStack: currOccurrenceStack
};
possiblePaths.push(nextPath);
} else if (prod instanceof RepetitionWithSeparator) {
const nextPathWithout = {
idx: currIdx,
def: drop_default(currDef),
ruleStack: currRuleStack,
occurrenceStack: currOccurrenceStack
};
possiblePaths.push(nextPathWithout);
possiblePaths.push(EXIT_ALTERNATIVE);
const separatorGast = new Terminal({
terminalType: prod.separator
});
const nthRepetition = new Repetition({
definition: [separatorGast].concat(prod.definition),
idx: prod.idx
});
const nextDef = prod.definition.concat([nthRepetition], drop_default(currDef));
const nextPathWith = {
idx: currIdx,
def: nextDef,
ruleStack: currRuleStack,
occurrenceStack: currOccurrenceStack
};
possiblePaths.push(nextPathWith);
} else if (prod instanceof Repetition) {
const nextPathWithout = {
idx: currIdx,
def: drop_default(currDef),
ruleStack: currRuleStack,
occurrenceStack: currOccurrenceStack
};
possiblePaths.push(nextPathWithout);
possiblePaths.push(EXIT_ALTERNATIVE);
const nthRepetition = new Repetition({
definition: prod.definition,
idx: prod.idx
});
const nextDef = prod.definition.concat([nthRepetition], drop_default(currDef));
const nextPathWith = {
idx: currIdx,
def: nextDef,
ruleStack: currRuleStack,
occurrenceStack: currOccurrenceStack
};
possiblePaths.push(nextPathWith);
} else if (prod instanceof Alternation) {
for (let i = prod.definition.length - 1; i >= 0; i--) {
const currAlt = prod.definition[i];
const currAltPath = {
idx: currIdx,
def: currAlt.definition.concat(drop_default(currDef)),
ruleStack: currRuleStack,
occurrenceStack: currOccurrenceStack
};
possiblePaths.push(currAltPath);
possiblePaths.push(EXIT_ALTERNATIVE);
}
} else if (prod instanceof Alternative) {
possiblePaths.push({
idx: currIdx,
def: prod.definition.concat(drop_default(currDef)),
ruleStack: currRuleStack,
occurrenceStack: currOccurrenceStack
});
} else if (prod instanceof Rule) {
possiblePaths.push(expandTopLevelRule(prod, currIdx, currRuleStack, currOccurrenceStack));
} else {
throw Error("non exhaustive match");
}
}
return result;
}
__name(nextPossibleTokensAfter, "nextPossibleTokensAfter");
__name2(nextPossibleTokensAfter, "nextPossibleTokensAfter");
function expandTopLevelRule(topRule, currIdx, currRuleStack, currOccurrenceStack) {
const newRuleStack = clone_default(currRuleStack);
newRuleStack.push(topRule.name);
const newCurrOccurrenceStack = clone_default(currOccurrenceStack);
newCurrOccurrenceStack.push(1);
return {
idx: currIdx,
def: topRule.definition,
ruleStack: newRuleStack,
occurrenceStack: newCurrOccurrenceStack
};
}
__name(expandTopLevelRule, "expandTopLevelRule");
__name2(expandTopLevelRule, "expandTopLevelRule");
var PROD_TYPE;
(function(PROD_TYPE2) {
PROD_TYPE2[PROD_TYPE2["OPTION"] = 0] = "OPTION";
PROD_TYPE2[PROD_TYPE2["REPETITION"] = 1] = "REPETITION";
PROD_TYPE2[PROD_TYPE2["REPETITION_MANDATORY"] = 2] = "REPETITION_MANDATORY";
PROD_TYPE2[PROD_TYPE2["REPETITION_MANDATORY_WITH_SEPARATOR"] = 3] = "REPETITION_MANDATORY_WITH_SEPARATOR";
PROD_TYPE2[PROD_TYPE2["REPETITION_WITH_SEPARATOR"] = 4] = "REPETITION_WITH_SEPARATOR";
PROD_TYPE2[PROD_TYPE2["ALTERNATION"] = 5] = "ALTERNATION";
})(PROD_TYPE || (PROD_TYPE = {}));
function getProdType(prod) {
if (prod instanceof Option || prod === "Option") {
return PROD_TYPE.OPTION;
} else if (prod instanceof Repetition || prod === "Repetition") {
return PROD_TYPE.REPETITION;
} else if (prod instanceof RepetitionMandatory || prod === "RepetitionMandatory") {
return PROD_TYPE.REPETITION_MANDATORY;
} else if (prod instanceof RepetitionMandatoryWithSeparator || prod === "RepetitionMandatoryWithSeparator") {
return PROD_TYPE.REPETITION_MANDATORY_WITH_SEPARATOR;
} else if (prod instanceof RepetitionWithSeparator || prod === "RepetitionWithSeparator") {
return PROD_TYPE.REPETITION_WITH_SEPARATOR;
} else if (prod instanceof Alternation || prod === "Alternation") {
return PROD_TYPE.ALTERNATION;
} else {
throw Error("non exhaustive match");
}
}
__name(getProdType, "getProdType");
__name2(getProdType, "getProdType");
function getLookaheadPaths(options) {
const { occurrence, rule, prodType, maxLookahead } = options;
const type = getProdType(prodType);
if (type === PROD_TYPE.ALTERNATION) {
return getLookaheadPathsForOr(occurrence, rule, maxLookahead);
} else {
return getLookaheadPathsForOptionalProd(occurrence, rule, type, maxLookahead);
}
}
__name(getLookaheadPaths, "getLookaheadPaths");
__name2(getLookaheadPaths, "getLookaheadPaths");
function buildLookaheadFuncForOr(occurrence, ruleGrammar, maxLookahead, hasPredicates, dynamicTokensEnabled, laFuncBuilder) {
const lookAheadPaths = getLookaheadPathsForOr(occurrence, ruleGrammar, maxLookahead);
const tokenMatcher2 = areTokenCategoriesNotUsed(lookAheadPaths) ? tokenStructuredMatcherNoCategories : tokenStructuredMatcher;
return laFuncBuilder(lookAheadPaths, hasPredicates, tokenMatcher2, dynamicTokensEnabled);
}
__name(buildLookaheadFuncForOr, "buildLookaheadFuncForOr");
__name2(buildLookaheadFuncForOr, "buildLookaheadFuncForOr");
function buildLookaheadFuncForOptionalProd(occurrence, ruleGrammar, k, dynamicTokensEnabled, prodType, lookaheadBuilder) {
const lookAheadPaths = getLookaheadPathsForOptionalProd(occurrence, ruleGrammar, prodType, k);
const tokenMatcher2 = areTokenCategoriesNotUsed(lookAheadPaths) ? tokenStructuredMatcherNoCategories : tokenStructuredMatcher;
return lookaheadBuilder(lookAheadPaths[0], tokenMatcher2, dynamicTokensEnabled);
}
__name(buildLookaheadFuncForOptionalProd, "buildLookaheadFuncForOptionalProd");
__name2(buildLookaheadFuncForOptionalProd, "buildLookaheadFuncForOptionalProd");
function buildAlternativesLookAheadFunc(alts, hasPredicates, tokenMatcher2, dynamicTokensEnabled) {
const numOfAlts = alts.length;
const areAllOneTokenLookahead = every_default(alts, (currAlt) => {
return every_default(currAlt, (currPath) => {
return currPath.length === 1;
});
});
if (hasPredicates) {
return function(orAlts) {
const predicates = map_default(orAlts, (currAlt) => currAlt.GATE);
for (let t = 0; t < numOfAlts; t++) {
const currAlt = alts[t];
const currNumOfPaths = currAlt.length;
const currPredicate = predicates[t];
if (currPredicate !== void 0 && currPredicate.call(this) === false) {
continue;
}
nextPath: for (let j = 0; j < currNumOfPaths; j++) {
const currPath = currAlt[j];
const currPathLength = currPath.length;
for (let i = 0; i < currPathLength; i++) {
const nextToken = this.LA(i + 1);
if (tokenMatcher2(nextToken, currPath[i]) === false) {
continue nextPath;
}
}
return t;
}
}
return void 0;
};
} else if (areAllOneTokenLookahead && !dynamicTokensEnabled) {
const singleTokenAlts = map_default(alts, (currAlt) => {
return flatten_default(currAlt);
});
const choiceToAlt = reduce_default(singleTokenAlts, (result, currAlt, idx) => {
forEach_default(currAlt, (currTokType) => {
if (!has_default(result, currTokType.tokenTypeIdx)) {
result[currTokType.tokenTypeIdx] = idx;
}
forEach_default(currTokType.categoryMatches, (currExtendingType) => {
if (!has_default(result, currExtendingType)) {
result[currExtendingType] = idx;
}
});
});
return result;
}, {});
return function() {
const nextToken = this.LA(1);
return choiceToAlt[nextToken.tokenTypeIdx];
};
} else {
return function() {
for (let t = 0; t < numOfAlts; t++) {
const currAlt = alts[t];
const currNumOfPaths = currAlt.length;
nextPath: for (let j = 0; j < currNumOfPaths; j++) {
const currPath = currAlt[j];
const currPathLength = currPath.length;
for (let i = 0; i < currPathLength; i++) {
const nextToken = this.LA(i + 1);
if (tokenMatcher2(nextToken, currPath[i]) === false) {
continue nextPath;
}
}
return t;
}
}
return void 0;
};
}
}
__name(buildAlternativesLookAheadFunc, "buildAlternativesLookAheadFunc");
__name2(buildAlternativesLookAheadFunc, "buildAlternativesLookAheadFunc");
function buildSingleAlternativeLookaheadFunction(alt, tokenMatcher2, dynamicTokensEnabled) {
const areAllOneTokenLookahead = every_default(alt, (currPath) => {
return currPath.length === 1;
});
const numOfPaths = alt.length;
if (areAllOneTokenLookahead && !dynamicTokensEnabled) {
const singleTokensTypes = flatten_default(alt);
if (singleTokensTypes.length === 1 && isEmpty_default(singleTokensTypes[0].categoryMatches)) {
const expectedTokenType = singleTokensTypes[0];
const expectedTokenUniqueKey = expectedTokenType.tokenTypeIdx;
return function() {
return this.LA(1).tokenTypeIdx === expectedTokenUniqueKey;
};
} else {
const choiceToAlt = reduce_default(singleTokensTypes, (result, currTokType, idx) => {
result[currTokType.tokenTypeIdx] = true;
forEach_default(currTokType.categoryMatches, (currExtendingType) => {
result[currExtendingType] = true;
});
return result;
}, []);
return function() {
const nextToken = this.LA(1);
return choiceToAlt[nextToken.tokenTypeIdx] === true;
};
}
} else {
return function() {
nextPath: for (let j = 0; j < numOfPaths; j++) {
const currPath = alt[j];
const currPathLength = currPath.length;
for (let i = 0; i < currPathLength; i++) {
const nextToken = this.LA(i + 1);
if (tokenMatcher2(nextToken, currPath[i]) === false) {
continue nextPath;
}
}
return true;
}
return false;
};
}
}
__name(buildSingleAlternativeLookaheadFunction, "buildSingleAlternativeLookaheadFunction");
__name2(buildSingleAlternativeLookaheadFunction, "buildSingleAlternativeLookaheadFunction");
var RestDefinitionFinderWalker = class extends RestWalker {
static {
__name(this, "RestDefinitionFinderWalker");
}
static {
__name2(this, "RestDefinitionFinderWalker");
}
constructor(topProd, targetOccurrence, targetProdType) {
super();
this.topProd = topProd;
this.targetOccurrence = targetOccurrence;
this.targetProdType = targetProdType;
}
startWalking() {
this.walk(this.topProd);
return this.restDef;
}
checkIsTarget(node, expectedProdType, currRest, prevRest) {
if (node.idx === this.targetOccurrence && this.targetProdType === expectedProdType) {
this.restDef = currRest.concat(prevRest);
return true;
}
return false;
}
walkOption(optionProd, currRest, prevRest) {
if (!this.checkIsTarget(optionProd, PROD_TYPE.OPTION, currRest, prevRest)) {
super.walkOption(optionProd, currRest, prevRest);
}
}
walkAtLeastOne(atLeastOneProd, currRest, prevRest) {
if (!this.checkIsTarget(atLeastOneProd, PROD_TYPE.REPETITION_MANDATORY, currRest, prevRest)) {
super.walkOption(atLeastOneProd, currRest, prevRest);
}
}
walkAtLeastOneSep(atLeastOneSepProd, currRest, prevRest) {
if (!this.checkIsTarget(atLeastOneSepProd, PROD_TYPE.REPETITION_MANDATORY_WITH_SEPARATOR, currRest, prevRest)) {
super.walkOption(atLeastOneSepProd, currRest, prevRest);
}
}
walkMany(manyProd, currRest, prevRest) {
if (!this.checkIsTarget(manyProd, PROD_TYPE.REPETITION, currRest, prevRest)) {
super.walkOption(manyProd, currRest, prevRest);
}
}
walkManySep(manySepProd, currRest, prevRest) {
if (!this.checkIsTarget(manySepProd, PROD_TYPE.REPETITION_WITH_SEPARATOR, currRest, prevRest)) {
super.walkOption(manySepProd, currRest, prevRest);
}
}
};
var InsideDefinitionFinderVisitor = class extends GAstVisitor {
static {
__name(this, "InsideDefinitionFinderVisitor");
}
static {
__name2(this, "InsideDefinitionFinderVisitor");
}
constructor(targetOccurrence, targetProdType, targetRef) {
super();
this.targetOccurrence = targetOccurrence;
this.targetProdType = targetProdType;
this.targetRef = targetRef;
this.result = [];
}
checkIsTarget(node, expectedProdName) {
if (node.idx === this.targetOccurrence && this.targetProdType === expectedProdName && (this.targetRef === void 0 || node === this.targetRef)) {
this.result = node.definition;
}
}
visitOption(node) {
this.checkIsTarget(node, PROD_TYPE.OPTION);
}
visitRepetition(node) {
this.checkIsTarget(node, PROD_TYPE.REPETITION);
}
visitRepetitionMandatory(node) {
this.checkIsTarget(node, PROD_TYPE.REPETITION_MANDATORY);
}
visitRepetitionMandatoryWithSeparator(node) {
this.checkIsTarget(node, PROD_TYPE.REPETITION_MANDATORY_WITH_SEPARATOR);
}
visitRepetitionWithSeparator(node) {
this.checkIsTarget(node, PROD_TYPE.REPETITION_WITH_SEPARATOR);
}
visitAlternation(node) {
this.checkIsTarget(node, PROD_TYPE.ALTERNATION);
}
};
function initializeArrayOfArrays(size) {
const result = new Array(size);
for (let i = 0; i < size; i++) {
result[i] = [];
}
return result;
}
__name(initializeArrayOfArrays, "initializeArrayOfArrays");
__name2(initializeArrayOfArrays, "initializeArrayOfArrays");
function pathToHashKeys(path) {
let keys3 = [""];
for (let i = 0; i < path.length; i++) {
const tokType = path[i];
const longerKeys = [];
for (let j = 0; j < keys3.length; j++) {
const currShorterKey = keys3[j];
longerKeys.push(currShorterKey + "_" + tokType.tokenTypeIdx);
for (let t = 0; t < tokType.categoryMatches.length; t++) {
const categoriesKeySuffix = "_" + tokType.categoryMatches[t];
longerKeys.push(currShorterKey + categoriesKeySuffix);
}
}
keys3 = longerKeys;
}
return keys3;
}
__name(pathToHashKeys, "pathToHashKeys");
__name2(pathToHashKeys, "pathToHashKeys");
function isUniquePrefixHash(altKnownPathsKeys, searchPathKeys, idx) {
for (let currAltIdx = 0; currAltIdx < altKnownPathsKeys.length; currAltIdx++) {
if (currAltIdx === idx) {
continue;
}
const otherAltKnownPathsKeys = altKnownPathsKeys[currAltIdx];
for (let searchIdx = 0; searchIdx < searchPathKeys.length; searchIdx++) {
const searchKey = searchPathKeys[searchIdx];
if (otherAltKnownPathsKeys[searchKey] === true) {
return false;
}
}
}
return true;
}
__name(isUniquePrefixHash, "isUniquePrefixHash");
__name2(isUniquePrefixHash, "isUniquePrefixHash");
function lookAheadSequenceFromAlternatives(altsDefs, k) {
const partialAlts = map_default(altsDefs, (currAlt) => possiblePathsFrom([currAlt], 1));
const finalResult = initializeArrayOfArrays(partialAlts.length);
const altsHashes = map_default(partialAlts, (currAltPaths) => {
const dict = {};
forEach_default(currAltPaths, (item) => {
const keys3 = pathToHashKeys(item.partialPath);
forEach_default(keys3, (currKey) => {
dict[currKey] = true;
});
});
return dict;
});
let newData = partialAlts;
for (let pathLength = 1; pathLength <= k; pathLength++) {
const currDataset = newData;
newData = initializeArrayOfArrays(currDataset.length);
for (let altIdx = 0; altIdx < currDataset.length; altIdx++) {
const currAltPathsAndSuffixes = currDataset[altIdx];
for (let currPathIdx = 0; currPathIdx < currAltPathsAndSuffixes.length; currPathIdx++) {
const currPathPrefix = currAltPathsAndSuffixes[currPathIdx].partialPath;
const suffixDef = currAltPathsAndSuffixes[currPathIdx].suffixDef;
const prefixKeys = pathToHashKeys(currPathPrefix);
const isUnique = isUniquePrefixHash(altsHashes, prefixKeys, altIdx);
if (isUnique || isEmpty_default(suffixDef) || currPathPrefix.length === k) {
const currAltResult = finalResult[altIdx];
if (containsPath(currAltResult, currPathPrefix) === false) {
currAltResult.push(currPathPrefix);
for (let j = 0; j < prefixKeys.length; j++) {
const currKey = prefixKeys[j];
altsHashes[altIdx][currKey] = true;
}
}
} else {
const newPartialPathsAndSuffixes = possiblePathsFrom(suffixDef, pathLength + 1, currPathPrefix);
newData[altIdx] = newData[altIdx].concat(newPartialPathsAndSuffixes);
forEach_default(newPartialPathsAndSuffixes, (item) => {
const prefixKeys2 = pathToHashKeys(item.partialPath);
forEach_default(prefixKeys2, (key) => {
altsHashes[altIdx][key] = true;
});
});
}
}
}
}
return finalResult;
}
__name(lookAheadSequenceFromAlternatives, "lookAheadSequenceFromAlternatives");
__name2(lookAheadSequenceFromAlternatives, "lookAheadSequenceFromAlternatives");
function getLookaheadPathsForOr(occurrence, ruleGrammar, k, orProd) {
const visitor2 = new InsideDefinitionFinderVisitor(occurrence, PROD_TYPE.ALTERNATION, orProd);
ruleGrammar.accept(visitor2);
return lookAheadSequenceFromAlternatives(visitor2.result, k);
}
__name(getLookaheadPathsForOr, "getLookaheadPathsForOr");
__name2(getLookaheadPathsForOr, "getLookaheadPathsForOr");
function getLookaheadPathsForOptionalProd(occurrence, ruleGrammar, prodType, k) {
const insideDefVisitor = new InsideDefinitionFinderVisitor(occurrence, prodType);
ruleGrammar.accept(insideDefVisitor);
const insideDef = insideDefVisitor.result;
const afterDefWalker = new RestDefinitionFinderWalker(ruleGrammar, occurrence, prodType);
const afterDef = afterDefWalker.startWalking();
const insideFlat = new Alternative({ definition: insideDef });
const afterFlat = new Alternative({ definition: afterDef });
return lookAheadSequenceFromAlternatives([insideFlat, afterFlat], k);
}
__name(getLookaheadPathsForOptionalProd, "getLookaheadPathsForOptionalProd");
__name2(getLookaheadPathsForOptionalProd, "getLookaheadPathsForOptionalProd");
function containsPath(alternative, searchPath) {
compareOtherPath: for (let i = 0; i < alternative.length; i++) {
const otherPath = alternative[i];
if (otherPath.length !== searchPath.length) {
continue;
}
for (let j = 0; j < otherPath.length; j++) {
const searchTok = searchPath[j];
const otherTok = otherPath[j];
const matchingTokens = searchTok === otherTok || otherTok.categoryMatchesMap[searchTok.tokenTypeIdx] !== void 0;
if (matchingTokens === false) {
continue compareOtherPath;
}
}
return true;
}
return false;
}
__name(containsPath, "containsPath");
__name2(containsPath, "containsPath");
function isStrictPrefixOfPath(prefix, other) {
return prefix.length < other.length && every_default(prefix, (tokType, idx) => {
const otherTokType = other[idx];
return tokType === otherTokType || otherTokType.categoryMatchesMap[tokType.tokenTypeIdx];
});
}
__name(isStrictPrefixOfPath, "isStrictPrefixOfPath");
__name2(isStrictPrefixOfPath, "isStrictPrefixOfPath");
function areTokenCategoriesNotUsed(lookAheadPaths) {
return every_default(lookAheadPaths, (singleAltPaths) => every_default(singleAltPaths, (singlePath) => every_default(singlePath, (token) => isEmpty_default(token.categoryMatches))));
}
__name(areTokenCategoriesNotUsed, "areTokenCategoriesNotUsed");
__name2(areTokenCategoriesNotUsed, "areTokenCategoriesNotUsed");
function validateLookahead(options) {
const lookaheadValidationErrorMessages = options.lookaheadStrategy.validate({
rules: options.rules,
tokenTypes: options.tokenTypes,
grammarName: options.grammarName
});
return map_default(lookaheadValidationErrorMessages, (errorMessage) => Object.assign({ type: ParserDefinitionErrorType.CUSTOM_LOOKAHEAD_VALIDATION }, errorMessage));
}
__name(validateLookahead, "validateLookahead");
__name2(validateLookahead, "validateLookahead");
function validateGrammar(topLevels, tokenTypes, errMsgProvider, grammarName) {
const duplicateErrors = flatMap_default(topLevels, (currTopLevel) => validateDuplicateProductions(currTopLevel, errMsgProvider));
const termsNamespaceConflictErrors = checkTerminalAndNoneTerminalsNameSpace(topLevels, tokenTypes, errMsgProvider);
const tooManyAltsErrors = flatMap_default(topLevels, (curRule) => validateTooManyAlts(curRule, errMsgProvider));
const duplicateRulesError = flatMap_default(topLevels, (curRule) => validateRuleDoesNotAlreadyExist(curRule, topLevels, grammarName, errMsgProvider));
return duplicateErrors.concat(termsNamespaceConflictErrors, tooManyAltsErrors, duplicateRulesError);
}
__name(validateGrammar, "validateGrammar");
__name2(validateGrammar, "validateGrammar");
function validateDuplicateProductions(topLevelRule, errMsgProvider) {
const collectorVisitor2 = new OccurrenceValidationCollector();
topLevelRule.accept(collectorVisitor2);
const allRuleProductions = collectorVisitor2.allProductions;
const productionGroups = groupBy_default(allRuleProductions, identifyProductionForDuplicates);
const duplicates = pickBy_default(productionGroups, (currGroup) => {
return currGroup.length > 1;
});
const errors = map_default(values_default(duplicates), (currDuplicates) => {
const firstProd = head_default(currDuplicates);
const msg = errMsgProvider.buildDuplicateFoundError(topLevelRule, currDuplicates);
const dslName = getProductionDslName(firstProd);
const defError = {
message: msg,
type: ParserDefinitionErrorType.DUPLICATE_PRODUCTIONS,
ruleName: topLevelRule.name,
dslName,
occurrence: firstProd.idx
};
const param = getExtraProductionArgument(firstProd);
if (param) {
defError.parameter = param;
}
return defError;
});
return errors;
}
__name(validateDuplicateProductions, "validateDuplicateProductions");
__name2(validateDuplicateProductions, "validateDuplicateProductions");
function identifyProductionForDuplicates(prod) {
return `${getProductionDslName(prod)}_#_${prod.idx}_#_${getExtraProductionArgument(prod)}`;
}
__name(identifyProductionForDuplicates, "identifyProductionForDuplicates");
__name2(identifyProductionForDuplicates, "identifyProductionForDuplicates");
function getExtraProductionArgument(prod) {
if (prod instanceof Terminal) {
return prod.terminalType.name;
} else if (prod instanceof NonTerminal) {
return prod.nonTerminalName;
} else {
return "";
}
}
__name(getExtraProductionArgument, "getExtraProductionArgument");
__name2(getExtraProductionArgument, "getExtraProductionArgument");
var OccurrenceValidationCollector = class extends GAstVisitor {
static {
__name(this, "OccurrenceValidationCollector");
}
static {
__name2(this, "OccurrenceValidationCollector");
}
constructor() {
super(...arguments);
this.allProductions = [];
}
visitNonTerminal(subrule) {
this.allProductions.push(subrule);
}
visitOption(option2) {
this.allProductions.push(option2);
}
visitRepetitionWithSeparator(manySep) {
this.allProductions.push(manySep);
}
visitRepetitionMandatory(atLeastOne) {
this.allProductions.push(atLeastOne);
}
visitRepetitionMandatoryWithSeparator(atLeastOneSep) {
this.allProductions.push(atLeastOneSep);
}
visitRepetition(many) {
this.allProductions.push(many);
}
visitAlternation(or) {
this.allProductions.push(or);
}
visitTerminal(terminal) {
this.allProductions.push(terminal);
}
};
function validateRuleDoesNotAlreadyExist(rule, allRules, className, errMsgProvider) {
const errors = [];
const occurrences = reduce_default(allRules, (result, curRule) => {
if (curRule.name === rule.name) {
return result + 1;
}
return result;
}, 0);
if (occurrences > 1) {
const errMsg = errMsgProvider.buildDuplicateRuleNameError({
topLevelRule: rule,
grammarName: className
});
errors.push({
message: errMsg,
type: ParserDefinitionErrorType.DUPLICATE_RULE_NAME,
ruleName: rule.name
});
}
return errors;
}
__name(validateRuleDoesNotAlreadyExist, "validateRuleDoesNotAlreadyExist");
__name2(validateRuleDoesNotAlreadyExist, "validateRuleDoesNotAlreadyExist");
function validateRuleIsOverridden(ruleName, definedRulesNames, className) {
const errors = [];
let errMsg;
if (!includes_default(definedRulesNames, ruleName)) {
errMsg = `Invalid rule override, rule: ->${ruleName}<- cannot be overridden in the grammar: ->${className}<-as it is not defined in any of the super grammars `;
errors.push({
message: errMsg,
type: ParserDefinitionErrorType.INVALID_RULE_OVERRIDE,
ruleName
});
}
return errors;
}
__name(validateRuleIsOverridden, "validateRuleIsOverridden");
__name2(validateRuleIsOverridden, "validateRuleIsOverridden");
function validateNoLeftRecursion(topRule, currRule, errMsgProvider, path = []) {
const errors = [];
const nextNonTerminals = getFirstNoneTerminal(currRule.definition);
if (isEmpty_default(nextNonTerminals)) {
return [];
} else {
const ruleName = topRule.name;
const foundLeftRecursion = includes_default(nextNonTerminals, topRule);
if (foundLeftRecursion) {
errors.push({
message: errMsgProvider.buildLeftRecursionError({
topLevelRule: topRule,
leftRecursionPath: path
}),
type: ParserDefinitionErrorType.LEFT_RECURSION,
ruleName
});
}
const validNextSteps = difference_default(nextNonTerminals, path.concat([topRule]));
const errorsFromNextSteps = flatMap_default(validNextSteps, (currRefRule) => {
const newPath = clone_default(path);
newPath.push(currRefRule);
return validateNoLeftRecursion(topRule, currRefRule, errMsgProvider, newPath);
});
return errors.concat(errorsFromNextSteps);
}
}
__name(validateNoLeftRecursion, "validateNoLeftRecursion");
__name2(validateNoLeftRecursion, "validateNoLeftRecursion");
function getFirstNoneTerminal(definition) {
let result = [];
if (isEmpty_default(definition)) {
return result;
}
const firstProd = head_default(definition);
if (firstProd instanceof NonTerminal) {
result.push(firstProd.referencedRule);
} else if (firstProd instanceof Alternative || firstProd instanceof Option || firstProd instanceof RepetitionMandatory || firstProd instanceof RepetitionMandatoryWithSeparator || firstProd instanceof RepetitionWithSeparator || firstProd instanceof Repetition) {
result = result.concat(getFirstNoneTerminal(firstProd.definition));
} else if (firstProd instanceof Alternation) {
result = flatten_default(map_default(firstProd.definition, (currSubDef) => getFirstNoneTerminal(currSubDef.definition)));
} else if (firstProd instanceof Terminal) {
} else {
throw Error("non exhaustive match");
}
const isFirstOptional = isOptionalProd(firstProd);
const hasMore = definition.length > 1;
if (isFirstOptional && hasMore) {
const rest = drop_default(definition);
return result.concat(getFirstNoneTerminal(rest));
} else {
return result;
}
}
__name(getFirstNoneTerminal, "getFirstNoneTerminal");
__name2(getFirstNoneTerminal, "getFirstNoneTerminal");
var OrCollector = class extends GAstVisitor {
static {
__name(this, "OrCollector");
}
static {
__name2(this, "OrCollector");
}
constructor() {
super(...arguments);
this.alternations = [];
}
visitAlternation(node) {
this.alternations.push(node);
}
};
function validateEmptyOrAlternative(topLevelRule, errMsgProvider) {
const orCollector = new OrCollector();
topLevelRule.accept(orCollector);
const ors = orCollector.alternations;
const errors = flatMap_default(ors, (currOr) => {
const exceptLast = dropRight_default(currOr.definition);
return flatMap_default(exceptLast, (currAlternative, currAltIdx) => {
const possibleFirstInAlt = nextPossibleTokensAfter([currAlternative], [], tokenStructuredMatcher, 1);
if (isEmpty_default(possibleFirstInAlt)) {
return [
{
message: errMsgProvider.buildEmptyAlternationError({
topLevelRule,
alternation: currOr,
emptyChoiceIdx: currAltIdx
}),
type: ParserDefinitionErrorType.NONE_LAST_EMPTY_ALT,
ruleName: topLevelRule.name,
occurrence: currOr.idx,
alternative: currAltIdx + 1
}
];
} else {
return [];
}
});
});
return errors;
}
__name(validateEmptyOrAlternative, "validateEmptyOrAlternative");
__name2(validateEmptyOrAlternative, "validateEmptyOrAlternative");
function validateAmbiguousAlternationAlternatives(topLevelRule, globalMaxLookahead, errMsgProvider) {
const orCollector = new OrCollector();
topLevelRule.accept(orCollector);
let ors = orCollector.alternations;
ors = reject_default(ors, (currOr) => currOr.ignoreAmbiguities === true);
const errors = flatMap_default(ors, (currOr) => {
const currOccurrence = currOr.idx;
const actualMaxLookahead = currOr.maxLookahead || globalMaxLookahead;
const alternatives = getLookaheadPathsForOr(currOccurrence, topLevelRule, actualMaxLookahead, currOr);
const altsAmbiguityErrors = checkAlternativesAmbiguities(alternatives, currOr, topLevelRule, errMsgProvider);
const altsPrefixAmbiguityErrors = checkPrefixAlternativesAmbiguities(alternatives, currOr, topLevelRule, errMsgProvider);
return altsAmbiguityErrors.concat(altsPrefixAmbiguityErrors);
});
return errors;
}
__name(validateAmbiguousAlternationAlternatives, "validateAmbiguousAlternationAlternatives");
__name2(validateAmbiguousAlternationAlternatives, "validateAmbiguousAlternationAlternatives");
var RepetitionCollector = class extends GAstVisitor {
static {
__name(this, "RepetitionCollector");
}
static {
__name2(this, "RepetitionCollector");
}
constructor() {
super(...arguments);
this.allProductions = [];
}
visitRepetitionWithSeparator(manySep) {
this.allProductions.push(manySep);
}
visitRepetitionMandatory(atLeastOne) {
this.allProductions.push(atLeastOne);
}
visitRepetitionMandatoryWithSeparator(atLeastOneSep) {
this.allProductions.push(atLeastOneSep);
}
visitRepetition(many) {
this.allProductions.push(many);
}
};
function validateTooManyAlts(topLevelRule, errMsgProvider) {
const orCollector = new OrCollector();
topLevelRule.accept(orCollector);
const ors = orCollector.alternations;
const errors = flatMap_default(ors, (currOr) => {
if (currOr.definition.length > 255) {
return [
{
message: errMsgProvider.buildTooManyAlternativesError({
topLevelRule,
alternation: currOr
}),
type: ParserDefinitionErrorType.TOO_MANY_ALTS,
ruleName: topLevelRule.name,
occurrence: currOr.idx
}
];
} else {
return [];
}
});
return errors;
}
__name(validateTooManyAlts, "validateTooManyAlts");
__name2(validateTooManyAlts, "validateTooManyAlts");
function validateSomeNonEmptyLookaheadPath(topLevelRules, maxLookahead, errMsgProvider) {
const errors = [];
forEach_default(topLevelRules, (currTopRule) => {
const collectorVisitor2 = new RepetitionCollector();
currTopRule.accept(collectorVisitor2);
const allRuleProductions = collectorVisitor2.allProductions;
forEach_default(allRuleProductions, (currProd) => {
const prodType = getProdType(currProd);
const actualMaxLookahead = currProd.maxLookahead || maxLookahead;
const currOccurrence = currProd.idx;
const paths = getLookaheadPathsForOptionalProd(currOccurrence, currTopRule, prodType, actualMaxLookahead);
const pathsInsideProduction = paths[0];
if (isEmpty_default(flatten_default(pathsInsideProduction))) {
const errMsg = errMsgProvider.buildEmptyRepetitionError({
topLevelRule: currTopRule,
repetition: currProd
});
errors.push({
message: errMsg,
type: ParserDefinitionErrorType.NO_NON_EMPTY_LOOKAHEAD,
ruleName: currTopRule.name
});
}
});
});
return errors;
}
__name(validateSomeNonEmptyLookaheadPath, "validateSomeNonEmptyLookaheadPath");
__name2(validateSomeNonEmptyLookaheadPath, "validateSomeNonEmptyLookaheadPath");
function checkAlternativesAmbiguities(alternatives, alternation2, rule, errMsgProvider) {
const foundAmbiguousPaths = [];
const identicalAmbiguities = reduce_default(alternatives, (result, currAlt, currAltIdx) => {
if (alternation2.definition[currAltIdx].ignoreAmbiguities === true) {
return result;
}
forEach_default(currAlt, (currPath) => {
const altsCurrPathAppearsIn = [currAltIdx];
forEach_default(alternatives, (currOtherAlt, currOtherAltIdx) => {
if (currAltIdx !== currOtherAltIdx && containsPath(currOtherAlt, currPath) && // ignore (skip) ambiguities with this "other" alternative
alternation2.definition[currOtherAltIdx].ignoreAmbiguities !== true) {
altsCurrPathAppearsIn.push(currOtherAltIdx);
}
});
if (altsCurrPathAppearsIn.length > 1 && !containsPath(foundAmbiguousPaths, currPath)) {
foundAmbiguousPaths.push(currPath);
result.push({
alts: altsCurrPathAppearsIn,
path: currPath
});
}
});
return result;
}, []);
const currErrors = map_default(identicalAmbiguities, (currAmbDescriptor) => {
const ambgIndices = map_default(currAmbDescriptor.alts, (currAltIdx) => currAltIdx + 1);
const currMessage = errMsgProvider.buildAlternationAmbiguityError({
topLevelRule: rule,
alternation: alternation2,
ambiguityIndices: ambgIndices,
prefixPath: currAmbDescriptor.path
});
return {
message: currMessage,
type: ParserDefinitionErrorType.AMBIGUOUS_ALTS,
ruleName: rule.name,
occurrence: alternation2.idx,
alternatives: currAmbDescriptor.alts
};
});
return currErrors;
}
__name(checkAlternativesAmbiguities, "checkAlternativesAmbiguities");
__name2(checkAlternativesAmbiguities, "checkAlternativesAmbiguities");
function checkPrefixAlternativesAmbiguities(alternatives, alternation2, rule, errMsgProvider) {
const pathsAndIndices = reduce_default(alternatives, (result, currAlt, idx) => {
const currPathsAndIdx = map_default(currAlt, (currPath) => {
return { idx, path: currPath };
});
return result.concat(currPathsAndIdx);
}, []);
const errors = compact_default(flatMap_default(pathsAndIndices, (currPathAndIdx) => {
const alternativeGast = alternation2.definition[currPathAndIdx.idx];
if (alternativeGast.ignoreAmbiguities === true) {
return [];
}
const targetIdx = currPathAndIdx.idx;
const targetPath = currPathAndIdx.path;
const prefixAmbiguitiesPathsAndIndices = filter_default(pathsAndIndices, (searchPathAndIdx) => {
return (
// ignore (skip) ambiguities with this "other" alternative
alternation2.definition[searchPathAndIdx.idx].ignoreAmbiguities !== true && searchPathAndIdx.idx < targetIdx && // checking for strict prefix because identical lookaheads
// will be be detected using a different validation.
isStrictPrefixOfPath(searchPathAndIdx.path, targetPath)
);
});
const currPathPrefixErrors = map_default(prefixAmbiguitiesPathsAndIndices, (currAmbPathAndIdx) => {
const ambgIndices = [currAmbPathAndIdx.idx + 1, targetIdx + 1];
const occurrence = alternation2.idx === 0 ? "" : alternation2.idx;
const message = errMsgProvider.buildAlternationPrefixAmbiguityError({
topLevelRule: rule,
alternation: alternation2,
ambiguityIndices: ambgIndices,
prefixPath: currAmbPathAndIdx.path
});
return {
message,
type: ParserDefinitionErrorType.AMBIGUOUS_PREFIX_ALTS,
ruleName: rule.name,
occurrence,
alternatives: ambgIndices
};
});
return currPathPrefixErrors;
}));
return errors;
}
__name(checkPrefixAlternativesAmbiguities, "checkPrefixAlternativesAmbiguities");
__name2(checkPrefixAlternativesAmbiguities, "checkPrefixAlternativesAmbiguities");
function checkTerminalAndNoneTerminalsNameSpace(topLevels, tokenTypes, errMsgProvider) {
const errors = [];
const tokenNames = map_default(tokenTypes, (currToken) => currToken.name);
forEach_default(topLevels, (currRule) => {
const currRuleName = currRule.name;
if (includes_default(tokenNames, currRuleName)) {
const errMsg = errMsgProvider.buildNamespaceConflictError(currRule);
errors.push({
message: errMsg,
type: ParserDefinitionErrorType.CONFLICT_TOKENS_RULES_NAMESPACE,
ruleName: currRuleName
});
}
});
return errors;
}
__name(checkTerminalAndNoneTerminalsNameSpace, "checkTerminalAndNoneTerminalsNameSpace");
__name2(checkTerminalAndNoneTerminalsNameSpace, "checkTerminalAndNoneTerminalsNameSpace");
function resolveGrammar2(options) {
const actualOptions = defaults_default(options, {
errMsgProvider: defaultGrammarResolverErrorProvider
});
const topRulesTable = {};
forEach_default(options.rules, (rule) => {
topRulesTable[rule.name] = rule;
});
return resolveGrammar(topRulesTable, actualOptions.errMsgProvider);
}
__name(resolveGrammar2, "resolveGrammar2");
__name2(resolveGrammar2, "resolveGrammar");
function validateGrammar2(options) {
options = defaults_default(options, {
errMsgProvider: defaultGrammarValidatorErrorProvider
});
return validateGrammar(options.rules, options.tokenTypes, options.errMsgProvider, options.grammarName);
}
__name(validateGrammar2, "validateGrammar2");
__name2(validateGrammar2, "validateGrammar");
var MISMATCHED_TOKEN_EXCEPTION = "MismatchedTokenException";
var NO_VIABLE_ALT_EXCEPTION = "NoViableAltException";
var EARLY_EXIT_EXCEPTION = "EarlyExitException";
var NOT_ALL_INPUT_PARSED_EXCEPTION = "NotAllInputParsedException";
var RECOGNITION_EXCEPTION_NAMES = [
MISMATCHED_TOKEN_EXCEPTION,
NO_VIABLE_ALT_EXCEPTION,
EARLY_EXIT_EXCEPTION,
NOT_ALL_INPUT_PARSED_EXCEPTION
];
Object.freeze(RECOGNITION_EXCEPTION_NAMES);
function isRecognitionException(error) {
return includes_default(RECOGNITION_EXCEPTION_NAMES, error.name);
}
__name(isRecognitionException, "isRecognitionException");
__name2(isRecognitionException, "isRecognitionException");
var RecognitionException = class extends Error {
static {
__name(this, "RecognitionException");
}
static {
__name2(this, "RecognitionException");
}
constructor(message, token) {
super(message);
this.token = token;
this.resyncedTokens = [];
Object.setPrototypeOf(this, new.target.prototype);
if (Error.captureStackTrace) {
Error.captureStackTrace(this, this.constructor);
}
}
};
var MismatchedTokenException = class extends RecognitionException {
static {
__name(this, "MismatchedTokenException");
}
static {
__name2(this, "MismatchedTokenException");
}
constructor(message, token, previousToken) {
super(message, token);
this.previousToken = previousToken;
this.name = MISMATCHED_TOKEN_EXCEPTION;
}
};
var NoViableAltException = class extends RecognitionException {
static {
__name(this, "NoViableAltException");
}
static {
__name2(this, "NoViableAltException");
}
constructor(message, token, previousToken) {
super(message, token);
this.previousToken = previousToken;
this.name = NO_VIABLE_ALT_EXCEPTION;
}
};
var NotAllInputParsedException = class extends RecognitionException {
static {
__name(this, "NotAllInputParsedException");
}
static {
__name2(this, "NotAllInputParsedException");
}
constructor(message, token) {
super(message, token);
this.name = NOT_ALL_INPUT_PARSED_EXCEPTION;
}
};
var EarlyExitException = class extends RecognitionException {
static {
__name(this, "EarlyExitException");
}
static {
__name2(this, "EarlyExitException");
}
constructor(message, token, previousToken) {
super(message, token);
this.previousToken = previousToken;
this.name = EARLY_EXIT_EXCEPTION;
}
};
var EOF_FOLLOW_KEY = {};
var IN_RULE_RECOVERY_EXCEPTION = "InRuleRecoveryException";
var InRuleRecoveryException = class extends Error {
static {
__name(this, "InRuleRecoveryException");
}
static {
__name2(this, "InRuleRecoveryException");
}
constructor(message) {
super(message);
this.name = IN_RULE_RECOVERY_EXCEPTION;
}
};
var Recoverable = class {
static {
__name(this, "Recoverable");
}
static {
__name2(this, "Recoverable");
}
initRecoverable(config) {
this.firstAfterRepMap = {};
this.resyncFollows = {};
this.recoveryEnabled = has_default(config, "recoveryEnabled") ? config.recoveryEnabled : DEFAULT_PARSER_CONFIG.recoveryEnabled;
if (this.recoveryEnabled) {
this.attemptInRepetitionRecovery = attemptInRepetitionRecovery;
}
}
getTokenToInsert(tokType) {
const tokToInsert = createTokenInstance(tokType, "", NaN, NaN, NaN, NaN, NaN, NaN);
tokToInsert.isInsertedInRecovery = true;
return tokToInsert;
}
canTokenTypeBeInsertedInRecovery(tokType) {
return true;
}
canTokenTypeBeDeletedInRecovery(tokType) {
return true;
}
tryInRepetitionRecovery(grammarRule, grammarRuleArgs, lookAheadFunc, expectedTokType) {
const reSyncTokType = this.findReSyncTokenType();
const savedLexerState = this.exportLexerState();
const resyncedTokens = [];
let passedResyncPoint = false;
const nextTokenWithoutResync = this.LA(1);
let currToken = this.LA(1);
const generateErrorMessage = /* @__PURE__ */ __name2(() => {
const previousToken = this.LA(0);
const msg = this.errorMessageProvider.buildMismatchTokenMessage({
expected: expectedTokType,
actual: nextTokenWithoutResync,
previous: previousToken,
ruleName: this.getCurrRuleFullName()
});
const error = new MismatchedTokenException(msg, nextTokenWithoutResync, this.LA(0));
error.resyncedTokens = dropRight_default(resyncedTokens);
this.SAVE_ERROR(error);
}, "generateErrorMessage");
while (!passedResyncPoint) {
if (this.tokenMatcher(currToken, expectedTokType)) {
generateErrorMessage();
return;
} else if (lookAheadFunc.call(this)) {
generateErrorMessage();
grammarRule.apply(this, grammarRuleArgs);
return;
} else if (this.tokenMatcher(currToken, reSyncTokType)) {
passedResyncPoint = true;
} else {
currToken = this.SKIP_TOKEN();
this.addToResyncTokens(currToken, resyncedTokens);
}
}
this.importLexerState(savedLexerState);
}
shouldInRepetitionRecoveryBeTried(expectTokAfterLastMatch, nextTokIdx, notStuck) {
if (notStuck === false) {
return false;
}
if (this.tokenMatcher(this.LA(1), expectTokAfterLastMatch)) {
return false;
}
if (this.isBackTracking()) {
return false;
}
if (this.canPerformInRuleRecovery(expectTokAfterLastMatch, this.getFollowsForInRuleRecovery(expectTokAfterLastMatch, nextTokIdx))) {
return false;
}
return true;
}
// Error Recovery functionality
getFollowsForInRuleRecovery(tokType, tokIdxInRule) {
const grammarPath = this.getCurrentGrammarPath(tokType, tokIdxInRule);
const follows = this.getNextPossibleTokenTypes(grammarPath);
return follows;
}
tryInRuleRecovery(expectedTokType, follows) {
if (this.canRecoverWithSingleTokenInsertion(expectedTokType, follows)) {
const tokToInsert = this.getTokenToInsert(expectedTokType);
return tokToInsert;
}
if (this.canRecoverWithSingleTokenDeletion(expectedTokType)) {
const nextTok = this.SKIP_TOKEN();
this.consumeToken();
return nextTok;
}
throw new InRuleRecoveryException("sad sad panda");
}
canPerformInRuleRecovery(expectedToken, follows) {
return this.canRecoverWithSingleTokenInsertion(expectedToken, follows) || this.canRecoverWithSingleTokenDeletion(expectedToken);
}
canRecoverWithSingleTokenInsertion(expectedTokType, follows) {
if (!this.canTokenTypeBeInsertedInRecovery(expectedTokType)) {
return false;
}
if (isEmpty_default(follows)) {
return false;
}
const mismatchedTok = this.LA(1);
const isMisMatchedTokInFollows = find_default(follows, (possibleFollowsTokType) => {
return this.tokenMatcher(mismatchedTok, possibleFollowsTokType);
}) !== void 0;
return isMisMatchedTokInFollows;
}
canRecoverWithSingleTokenDeletion(expectedTokType) {
if (!this.canTokenTypeBeDeletedInRecovery(expectedTokType)) {
return false;
}
const isNextTokenWhatIsExpected = this.tokenMatcher(this.LA(2), expectedTokType);
return isNextTokenWhatIsExpected;
}
isInCurrentRuleReSyncSet(tokenTypeIdx) {
const followKey = this.getCurrFollowKey();
const currentRuleReSyncSet = this.getFollowSetFromFollowKey(followKey);
return includes_default(currentRuleReSyncSet, tokenTypeIdx);
}
findReSyncTokenType() {
const allPossibleReSyncTokTypes = this.flattenFollowSet();
let nextToken = this.LA(1);
let k = 2;
while (true) {
const foundMatch = find_default(allPossibleReSyncTokTypes, (resyncTokType) => {
const canMatch = tokenMatcher(nextToken, resyncTokType);
return canMatch;
});
if (foundMatch !== void 0) {
return foundMatch;
}
nextToken = this.LA(k);
k++;
}
}
getCurrFollowKey() {
if (this.RULE_STACK.length === 1) {
return EOF_FOLLOW_KEY;
}
const currRuleShortName = this.getLastExplicitRuleShortName();
const currRuleIdx = this.getLastExplicitRuleOccurrenceIndex();
const prevRuleShortName = this.getPreviousExplicitRuleShortName();
return {
ruleName: this.shortRuleNameToFullName(currRuleShortName),
idxInCallingRule: currRuleIdx,
inRule: this.shortRuleNameToFullName(prevRuleShortName)
};
}
buildFullFollowKeyStack() {
const explicitRuleStack = this.RULE_STACK;
const explicitOccurrenceStack = this.RULE_OCCURRENCE_STACK;
return map_default(explicitRuleStack, (ruleName, idx) => {
if (idx === 0) {
return EOF_FOLLOW_KEY;
}
return {
ruleName: this.shortRuleNameToFullName(ruleName),
idxInCallingRule: explicitOccurrenceStack[idx],
inRule: this.shortRuleNameToFullName(explicitRuleStack[idx - 1])
};
});
}
flattenFollowSet() {
const followStack = map_default(this.buildFullFollowKeyStack(), (currKey) => {
return this.getFollowSetFromFollowKey(currKey);
});
return flatten_default(followStack);
}
getFollowSetFromFollowKey(followKey) {
if (followKey === EOF_FOLLOW_KEY) {
return [EOF];
}
const followName = followKey.ruleName + followKey.idxInCallingRule + IN + followKey.inRule;
return this.resyncFollows[followName];
}
// It does not make any sense to include a virtual EOF token in the list of resynced tokens
// as EOF does not really exist and thus does not contain any useful information (line/column numbers)
addToResyncTokens(token, resyncTokens) {
if (!this.tokenMatcher(token, EOF)) {
resyncTokens.push(token);
}
return resyncTokens;
}
reSyncTo(tokType) {
const resyncedTokens = [];
let nextTok = this.LA(1);
while (this.tokenMatcher(nextTok, tokType) === false) {
nextTok = this.SKIP_TOKEN();
this.addToResyncTokens(nextTok, resyncedTokens);
}
return dropRight_default(resyncedTokens);
}
attemptInRepetitionRecovery(prodFunc, args, lookaheadFunc, dslMethodIdx, prodOccurrence, nextToksWalker, notStuck) {
}
getCurrentGrammarPath(tokType, tokIdxInRule) {
const pathRuleStack = this.getHumanReadableRuleStack();
const pathOccurrenceStack = clone_default(this.RULE_OCCURRENCE_STACK);
const grammarPath = {
ruleStack: pathRuleStack,
occurrenceStack: pathOccurrenceStack,
lastTok: tokType,
lastTokOccurrence: tokIdxInRule
};
return grammarPath;
}
getHumanReadableRuleStack() {
return map_default(this.RULE_STACK, (currShortName) => this.shortRuleNameToFullName(currShortName));
}
};
function attemptInRepetitionRecovery(prodFunc, args, lookaheadFunc, dslMethodIdx, prodOccurrence, nextToksWalker, notStuck) {
const key = this.getKeyForAutomaticLookahead(dslMethodIdx, prodOccurrence);
let firstAfterRepInfo = this.firstAfterRepMap[key];
if (firstAfterRepInfo === void 0) {
const currRuleName = this.getCurrRuleFullName();
const ruleGrammar = this.getGAstProductions()[currRuleName];
const walker = new nextToksWalker(ruleGrammar, prodOccurrence);
firstAfterRepInfo = walker.startWalking();
this.firstAfterRepMap[key] = firstAfterRepInfo;
}
let expectTokAfterLastMatch = firstAfterRepInfo.token;
let nextTokIdx = firstAfterRepInfo.occurrence;
const isEndOfRule = firstAfterRepInfo.isEndOfRule;
if (this.RULE_STACK.length === 1 && isEndOfRule && expectTokAfterLastMatch === void 0) {
expectTokAfterLastMatch = EOF;
nextTokIdx = 1;
}
if (expectTokAfterLastMatch === void 0 || nextTokIdx === void 0) {
return;
}
if (this.shouldInRepetitionRecoveryBeTried(expectTokAfterLastMatch, nextTokIdx, notStuck)) {
this.tryInRepetitionRecovery(prodFunc, args, lookaheadFunc, expectTokAfterLastMatch);
}
}
__name(attemptInRepetitionRecovery, "attemptInRepetitionRecovery");
__name2(attemptInRepetitionRecovery, "attemptInRepetitionRecovery");
var BITS_FOR_METHOD_TYPE = 4;
var BITS_FOR_OCCURRENCE_IDX = 8;
var BITS_FOR_ALT_IDX = 8;
var OR_IDX = 1 << BITS_FOR_OCCURRENCE_IDX;
var OPTION_IDX = 2 << BITS_FOR_OCCURRENCE_IDX;
var MANY_IDX = 3 << BITS_FOR_OCCURRENCE_IDX;
var AT_LEAST_ONE_IDX = 4 << BITS_FOR_OCCURRENCE_IDX;
var MANY_SEP_IDX = 5 << BITS_FOR_OCCURRENCE_IDX;
var AT_LEAST_ONE_SEP_IDX = 6 << BITS_FOR_OCCURRENCE_IDX;
function getKeyForAutomaticLookahead(ruleIdx, dslMethodIdx, occurrence) {
return occurrence | dslMethodIdx | ruleIdx;
}
__name(getKeyForAutomaticLookahead, "getKeyForAutomaticLookahead");
__name2(getKeyForAutomaticLookahead, "getKeyForAutomaticLookahead");
var BITS_START_FOR_ALT_IDX = 32 - BITS_FOR_ALT_IDX;
var LLkLookaheadStrategy = class {
static {
__name(this, "LLkLookaheadStrategy");
}
static {
__name2(this, "LLkLookaheadStrategy");
}
constructor(options) {
var _a;
this.maxLookahead = (_a = options === null || options === void 0 ? void 0 : options.maxLookahead) !== null && _a !== void 0 ? _a : DEFAULT_PARSER_CONFIG.maxLookahead;
}
validate(options) {
const leftRecursionErrors = this.validateNoLeftRecursion(options.rules);
if (isEmpty_default(leftRecursionErrors)) {
const emptyAltErrors = this.validateEmptyOrAlternatives(options.rules);
const ambiguousAltsErrors = this.validateAmbiguousAlternationAlternatives(options.rules, this.maxLookahead);
const emptyRepetitionErrors = this.validateSomeNonEmptyLookaheadPath(options.rules, this.maxLookahead);
const allErrors = [
...leftRecursionErrors,
...emptyAltErrors,
...ambiguousAltsErrors,
...emptyRepetitionErrors
];
return allErrors;
}
return leftRecursionErrors;
}
validateNoLeftRecursion(rules) {
return flatMap_default(rules, (currTopRule) => validateNoLeftRecursion(currTopRule, currTopRule, defaultGrammarValidatorErrorProvider));
}
validateEmptyOrAlternatives(rules) {
return flatMap_default(rules, (currTopRule) => validateEmptyOrAlternative(currTopRule, defaultGrammarValidatorErrorProvider));
}
validateAmbiguousAlternationAlternatives(rules, maxLookahead) {
return flatMap_default(rules, (currTopRule) => validateAmbiguousAlternationAlternatives(currTopRule, maxLookahead, defaultGrammarValidatorErrorProvider));
}
validateSomeNonEmptyLookaheadPath(rules, maxLookahead) {
return validateSomeNonEmptyLookaheadPath(rules, maxLookahead, defaultGrammarValidatorErrorProvider);
}
buildLookaheadForAlternation(options) {
return buildLookaheadFuncForOr(options.prodOccurrence, options.rule, options.maxLookahead, options.hasPredicates, options.dynamicTokensEnabled, buildAlternativesLookAheadFunc);
}
buildLookaheadForOptional(options) {
return buildLookaheadFuncForOptionalProd(options.prodOccurrence, options.rule, options.maxLookahead, options.dynamicTokensEnabled, getProdType(options.prodType), buildSingleAlternativeLookaheadFunction);
}
};
var LooksAhead = class {
static {
__name(this, "LooksAhead");
}
static {
__name2(this, "LooksAhead");
}
initLooksAhead(config) {
this.dynamicTokensEnabled = has_default(config, "dynamicTokensEnabled") ? config.dynamicTokensEnabled : DEFAULT_PARSER_CONFIG.dynamicTokensEnabled;
this.maxLookahead = has_default(config, "maxLookahead") ? config.maxLookahead : DEFAULT_PARSER_CONFIG.maxLookahead;
this.lookaheadStrategy = has_default(config, "lookaheadStrategy") ? config.lookaheadStrategy : new LLkLookaheadStrategy({ maxLookahead: this.maxLookahead });
this.lookAheadFuncsCache = /* @__PURE__ */ new Map();
}
preComputeLookaheadFunctions(rules) {
forEach_default(rules, (currRule) => {
this.TRACE_INIT(`${currRule.name} Rule Lookahead`, () => {
const { alternation: alternation2, repetition: repetition2, option: option2, repetitionMandatory: repetitionMandatory2, repetitionMandatoryWithSeparator, repetitionWithSeparator } = collectMethods(currRule);
forEach_default(alternation2, (currProd) => {
const prodIdx = currProd.idx === 0 ? "" : currProd.idx;
this.TRACE_INIT(`${getProductionDslName(currProd)}${prodIdx}`, () => {
const laFunc = this.lookaheadStrategy.buildLookaheadForAlternation({
prodOccurrence: currProd.idx,
rule: currRule,
maxLookahead: currProd.maxLookahead || this.maxLookahead,
hasPredicates: currProd.hasPredicates,
dynamicTokensEnabled: this.dynamicTokensEnabled
});
const key = getKeyForAutomaticLookahead(this.fullRuleNameToShort[currRule.name], OR_IDX, currProd.idx);
this.setLaFuncCache(key, laFunc);
});
});
forEach_default(repetition2, (currProd) => {
this.computeLookaheadFunc(currRule, currProd.idx, MANY_IDX, "Repetition", currProd.maxLookahead, getProductionDslName(currProd));
});
forEach_default(option2, (currProd) => {
this.computeLookaheadFunc(currRule, currProd.idx, OPTION_IDX, "Option", currProd.maxLookahead, getProductionDslName(currProd));
});
forEach_default(repetitionMandatory2, (currProd) => {
this.computeLookaheadFunc(currRule, currProd.idx, AT_LEAST_ONE_IDX, "RepetitionMandatory", currProd.maxLookahead, getProductionDslName(currProd));
});
forEach_default(repetitionMandatoryWithSeparator, (currProd) => {
this.computeLookaheadFunc(currRule, currProd.idx, AT_LEAST_ONE_SEP_IDX, "RepetitionMandatoryWithSeparator", currProd.maxLookahead, getProductionDslName(currProd));
});
forEach_default(repetitionWithSeparator, (currProd) => {
this.computeLookaheadFunc(currRule, currProd.idx, MANY_SEP_IDX, "RepetitionWithSeparator", currProd.maxLookahead, getProductionDslName(currProd));
});
});
});
}
computeLookaheadFunc(rule, prodOccurrence, prodKey, prodType, prodMaxLookahead, dslMethodName) {
this.TRACE_INIT(`${dslMethodName}${prodOccurrence === 0 ? "" : prodOccurrence}`, () => {
const laFunc = this.lookaheadStrategy.buildLookaheadForOptional({
prodOccurrence,
rule,
maxLookahead: prodMaxLookahead || this.maxLookahead,
dynamicTokensEnabled: this.dynamicTokensEnabled,
prodType
});
const key = getKeyForAutomaticLookahead(this.fullRuleNameToShort[rule.name], prodKey, prodOccurrence);
this.setLaFuncCache(key, laFunc);
});
}
// this actually returns a number, but it is always used as a string (object prop key)
getKeyForAutomaticLookahead(dslMethodIdx, occurrence) {
const currRuleShortName = this.getLastExplicitRuleShortName();
return getKeyForAutomaticLookahead(currRuleShortName, dslMethodIdx, occurrence);
}
getLaFuncFromCache(key) {
return this.lookAheadFuncsCache.get(key);
}
/* istanbul ignore next */
setLaFuncCache(key, value) {
this.lookAheadFuncsCache.set(key, value);
}
};
var DslMethodsCollectorVisitor = class extends GAstVisitor {
static {
__name(this, "DslMethodsCollectorVisitor");
}
static {
__name2(this, "DslMethodsCollectorVisitor");
}
constructor() {
super(...arguments);
this.dslMethods = {
option: [],
alternation: [],
repetition: [],
repetitionWithSeparator: [],
repetitionMandatory: [],
repetitionMandatoryWithSeparator: []
};
}
reset() {
this.dslMethods = {
option: [],
alternation: [],
repetition: [],
repetitionWithSeparator: [],
repetitionMandatory: [],
repetitionMandatoryWithSeparator: []
};
}
visitOption(option2) {
this.dslMethods.option.push(option2);
}
visitRepetitionWithSeparator(manySep) {
this.dslMethods.repetitionWithSeparator.push(manySep);
}
visitRepetitionMandatory(atLeastOne) {
this.dslMethods.repetitionMandatory.push(atLeastOne);
}
visitRepetitionMandatoryWithSeparator(atLeastOneSep) {
this.dslMethods.repetitionMandatoryWithSeparator.push(atLeastOneSep);
}
visitRepetition(many) {
this.dslMethods.repetition.push(many);
}
visitAlternation(or) {
this.dslMethods.alternation.push(or);
}
};
var collectorVisitor = new DslMethodsCollectorVisitor();
function collectMethods(rule) {
collectorVisitor.reset();
rule.accept(collectorVisitor);
const dslMethods = collectorVisitor.dslMethods;
collectorVisitor.reset();
return dslMethods;
}
__name(collectMethods, "collectMethods");
__name2(collectMethods, "collectMethods");
function setNodeLocationOnlyOffset(currNodeLocation, newLocationInfo) {
if (isNaN(currNodeLocation.startOffset) === true) {
currNodeLocation.startOffset = newLocationInfo.startOffset;
currNodeLocation.endOffset = newLocationInfo.endOffset;
} else if (currNodeLocation.endOffset < newLocationInfo.endOffset === true) {
currNodeLocation.endOffset = newLocationInfo.endOffset;
}
}
__name(setNodeLocationOnlyOffset, "setNodeLocationOnlyOffset");
__name2(setNodeLocationOnlyOffset, "setNodeLocationOnlyOffset");
function setNodeLocationFull(currNodeLocation, newLocationInfo) {
if (isNaN(currNodeLocation.startOffset) === true) {
currNodeLocation.startOffset = newLocationInfo.startOffset;
currNodeLocation.startColumn = newLocationInfo.startColumn;
currNodeLocation.startLine = newLocationInfo.startLine;
currNodeLocation.endOffset = newLocationInfo.endOffset;
currNodeLocation.endColumn = newLocationInfo.endColumn;
currNodeLocation.endLine = newLocationInfo.endLine;
} else if (currNodeLocation.endOffset < newLocationInfo.endOffset === true) {
currNodeLocation.endOffset = newLocationInfo.endOffset;
currNodeLocation.endColumn = newLocationInfo.endColumn;
currNodeLocation.endLine = newLocationInfo.endLine;
}
}
__name(setNodeLocationFull, "setNodeLocationFull");
__name2(setNodeLocationFull, "setNodeLocationFull");
function addTerminalToCst(node, token, tokenTypeName) {
if (node.children[tokenTypeName] === void 0) {
node.children[tokenTypeName] = [token];
} else {
node.children[tokenTypeName].push(token);
}
}
__name(addTerminalToCst, "addTerminalToCst");
__name2(addTerminalToCst, "addTerminalToCst");
function addNoneTerminalToCst(node, ruleName, ruleResult) {
if (node.children[ruleName] === void 0) {
node.children[ruleName] = [ruleResult];
} else {
node.children[ruleName].push(ruleResult);
}
}
__name(addNoneTerminalToCst, "addNoneTerminalToCst");
__name2(addNoneTerminalToCst, "addNoneTerminalToCst");
var NAME = "name";
function defineNameProp(obj, nameValue) {
Object.defineProperty(obj, NAME, {
enumerable: false,
configurable: true,
writable: false,
value: nameValue
});
}
__name(defineNameProp, "defineNameProp");
__name2(defineNameProp, "defineNameProp");
function defaultVisit(ctx, param) {
const childrenNames = keys_default(ctx);
const childrenNamesLength = childrenNames.length;
for (let i = 0; i < childrenNamesLength; i++) {
const currChildName = childrenNames[i];
const currChildArray = ctx[currChildName];
const currChildArrayLength = currChildArray.length;
for (let j = 0; j < currChildArrayLength; j++) {
const currChild = currChildArray[j];
if (currChild.tokenTypeIdx === void 0) {
this[currChild.name](currChild.children, param);
}
}
}
}
__name(defaultVisit, "defaultVisit");
__name2(defaultVisit, "defaultVisit");
function createBaseSemanticVisitorConstructor(grammarName, ruleNames) {
const derivedConstructor = /* @__PURE__ */ __name2(function() {
}, "derivedConstructor");
defineNameProp(derivedConstructor, grammarName + "BaseSemantics");
const semanticProto = {
visit: /* @__PURE__ */ __name2(function(cstNode, param) {
if (isArray_default(cstNode)) {
cstNode = cstNode[0];
}
if (isUndefined_default(cstNode)) {
return void 0;
}
return this[cstNode.name](cstNode.children, param);
}, "visit"),
validateVisitor: /* @__PURE__ */ __name2(function() {
const semanticDefinitionErrors = validateVisitor(this, ruleNames);
if (!isEmpty_default(semanticDefinitionErrors)) {
const errorMessages = map_default(semanticDefinitionErrors, (currDefError) => currDefError.msg);
throw Error(`Errors Detected in CST Visitor <${this.constructor.name}>:
${errorMessages.join("\n\n").replace(/\n/g, "\n ")}`);
}
}, "validateVisitor")
};
derivedConstructor.prototype = semanticProto;
derivedConstructor.prototype.constructor = derivedConstructor;
derivedConstructor._RULE_NAMES = ruleNames;
return derivedConstructor;
}
__name(createBaseSemanticVisitorConstructor, "createBaseSemanticVisitorConstructor");
__name2(createBaseSemanticVisitorConstructor, "createBaseSemanticVisitorConstructor");
function createBaseVisitorConstructorWithDefaults(grammarName, ruleNames, baseConstructor) {
const derivedConstructor = /* @__PURE__ */ __name2(function() {
}, "derivedConstructor");
defineNameProp(derivedConstructor, grammarName + "BaseSemanticsWithDefaults");
const withDefaultsProto = Object.create(baseConstructor.prototype);
forEach_default(ruleNames, (ruleName) => {
withDefaultsProto[ruleName] = defaultVisit;
});
derivedConstructor.prototype = withDefaultsProto;
derivedConstructor.prototype.constructor = derivedConstructor;
return derivedConstructor;
}
__name(createBaseVisitorConstructorWithDefaults, "createBaseVisitorConstructorWithDefaults");
__name2(createBaseVisitorConstructorWithDefaults, "createBaseVisitorConstructorWithDefaults");
var CstVisitorDefinitionError;
(function(CstVisitorDefinitionError2) {
CstVisitorDefinitionError2[CstVisitorDefinitionError2["REDUNDANT_METHOD"] = 0] = "REDUNDANT_METHOD";
CstVisitorDefinitionError2[CstVisitorDefinitionError2["MISSING_METHOD"] = 1] = "MISSING_METHOD";
})(CstVisitorDefinitionError || (CstVisitorDefinitionError = {}));
function validateVisitor(visitorInstance, ruleNames) {
const missingErrors = validateMissingCstMethods(visitorInstance, ruleNames);
return missingErrors;
}
__name(validateVisitor, "validateVisitor");
__name2(validateVisitor, "validateVisitor");
function validateMissingCstMethods(visitorInstance, ruleNames) {
const missingRuleNames = filter_default(ruleNames, (currRuleName) => {
return isFunction_default(visitorInstance[currRuleName]) === false;
});
const errors = map_default(missingRuleNames, (currRuleName) => {
return {
msg: `Missing visitor method: <${currRuleName}> on ${visitorInstance.constructor.name} CST Visitor.`,
type: CstVisitorDefinitionError.MISSING_METHOD,
methodName: currRuleName
};
});
return compact_default(errors);
}
__name(validateMissingCstMethods, "validateMissingCstMethods");
__name2(validateMissingCstMethods, "validateMissingCstMethods");
var TreeBuilder = class {
static {
__name(this, "TreeBuilder");
}
static {
__name2(this, "TreeBuilder");
}
initTreeBuilder(config) {
this.CST_STACK = [];
this.outputCst = config.outputCst;
this.nodeLocationTracking = has_default(config, "nodeLocationTracking") ? config.nodeLocationTracking : DEFAULT_PARSER_CONFIG.nodeLocationTracking;
if (!this.outputCst) {
this.cstInvocationStateUpdate = noop_default;
this.cstFinallyStateUpdate = noop_default;
this.cstPostTerminal = noop_default;
this.cstPostNonTerminal = noop_default;
this.cstPostRule = noop_default;
} else {
if (/full/i.test(this.nodeLocationTracking)) {
if (this.recoveryEnabled) {
this.setNodeLocationFromToken = setNodeLocationFull;
this.setNodeLocationFromNode = setNodeLocationFull;
this.cstPostRule = noop_default;
this.setInitialNodeLocation = this.setInitialNodeLocationFullRecovery;
} else {
this.setNodeLocationFromToken = noop_default;
this.setNodeLocationFromNode = noop_default;
this.cstPostRule = this.cstPostRuleFull;
this.setInitialNodeLocation = this.setInitialNodeLocationFullRegular;
}
} else if (/onlyOffset/i.test(this.nodeLocationTracking)) {
if (this.recoveryEnabled) {
this.setNodeLocationFromToken = setNodeLocationOnlyOffset;
this.setNodeLocationFromNode = setNodeLocationOnlyOffset;
this.cstPostRule = noop_default;
this.setInitialNodeLocation = this.setInitialNodeLocationOnlyOffsetRecovery;
} else {
this.setNodeLocationFromToken = noop_default;
this.setNodeLocationFromNode = noop_default;
this.cstPostRule = this.cstPostRuleOnlyOffset;
this.setInitialNodeLocation = this.setInitialNodeLocationOnlyOffsetRegular;
}
} else if (/none/i.test(this.nodeLocationTracking)) {
this.setNodeLocationFromToken = noop_default;
this.setNodeLocationFromNode = noop_default;
this.cstPostRule = noop_default;
this.setInitialNodeLocation = noop_default;
} else {
throw Error(`Invalid <nodeLocationTracking> config option: "${config.nodeLocationTracking}"`);
}
}
}
setInitialNodeLocationOnlyOffsetRecovery(cstNode) {
cstNode.location = {
startOffset: NaN,
endOffset: NaN
};
}
setInitialNodeLocationOnlyOffsetRegular(cstNode) {
cstNode.location = {
// without error recovery the starting Location of a new CstNode is guaranteed
// To be the next Token's startOffset (for valid inputs).
// For invalid inputs there won't be any CSTOutput so this potential
// inaccuracy does not matter
startOffset: this.LA(1).startOffset,
endOffset: NaN
};
}
setInitialNodeLocationFullRecovery(cstNode) {
cstNode.location = {
startOffset: NaN,
startLine: NaN,
startColumn: NaN,
endOffset: NaN,
endLine: NaN,
endColumn: NaN
};
}
/**
* @see setInitialNodeLocationOnlyOffsetRegular for explanation why this work
* @param cstNode
*/
setInitialNodeLocationFullRegular(cstNode) {
const nextToken = this.LA(1);
cstNode.location = {
startOffset: nextToken.startOffset,
startLine: nextToken.startLine,
startColumn: nextToken.startColumn,
endOffset: NaN,
endLine: NaN,
endColumn: NaN
};
}
cstInvocationStateUpdate(fullRuleName) {
const cstNode = {
name: fullRuleName,
children: /* @__PURE__ */ Object.create(null)
};
this.setInitialNodeLocation(cstNode);
this.CST_STACK.push(cstNode);
}
cstFinallyStateUpdate() {
this.CST_STACK.pop();
}
cstPostRuleFull(ruleCstNode) {
const prevToken = this.LA(0);
const loc = ruleCstNode.location;
if (loc.startOffset <= prevToken.startOffset === true) {
loc.endOffset = prevToken.endOffset;
loc.endLine = prevToken.endLine;
loc.endColumn = prevToken.endColumn;
} else {
loc.startOffset = NaN;
loc.startLine = NaN;
loc.startColumn = NaN;
}
}
cstPostRuleOnlyOffset(ruleCstNode) {
const prevToken = this.LA(0);
const loc = ruleCstNode.location;
if (loc.startOffset <= prevToken.startOffset === true) {
loc.endOffset = prevToken.endOffset;
} else {
loc.startOffset = NaN;
}
}
cstPostTerminal(key, consumedToken) {
const rootCst = this.CST_STACK[this.CST_STACK.length - 1];
addTerminalToCst(rootCst, consumedToken, key);
this.setNodeLocationFromToken(rootCst.location, consumedToken);
}
cstPostNonTerminal(ruleCstResult, ruleName) {
const preCstNode = this.CST_STACK[this.CST_STACK.length - 1];
addNoneTerminalToCst(preCstNode, ruleName, ruleCstResult);
this.setNodeLocationFromNode(preCstNode.location, ruleCstResult.location);
}
getBaseCstVisitorConstructor() {
if (isUndefined_default(this.baseCstVisitorConstructor)) {
const newBaseCstVisitorConstructor = createBaseSemanticVisitorConstructor(this.className, keys_default(this.gastProductionsCache));
this.baseCstVisitorConstructor = newBaseCstVisitorConstructor;
return newBaseCstVisitorConstructor;
}
return this.baseCstVisitorConstructor;
}
getBaseCstVisitorConstructorWithDefaults() {
if (isUndefined_default(this.baseCstVisitorWithDefaultsConstructor)) {
const newConstructor = createBaseVisitorConstructorWithDefaults(this.className, keys_default(this.gastProductionsCache), this.getBaseCstVisitorConstructor());
this.baseCstVisitorWithDefaultsConstructor = newConstructor;
return newConstructor;
}
return this.baseCstVisitorWithDefaultsConstructor;
}
getLastExplicitRuleShortName() {
const ruleStack = this.RULE_STACK;
return ruleStack[ruleStack.length - 1];
}
getPreviousExplicitRuleShortName() {
const ruleStack = this.RULE_STACK;
return ruleStack[ruleStack.length - 2];
}
getLastExplicitRuleOccurrenceIndex() {
const occurrenceStack = this.RULE_OCCURRENCE_STACK;
return occurrenceStack[occurrenceStack.length - 1];
}
};
var LexerAdapter = class {
static {
__name(this, "LexerAdapter");
}
static {
__name2(this, "LexerAdapter");
}
initLexerAdapter() {
this.tokVector = [];
this.tokVectorLength = 0;
this.currIdx = -1;
}
set input(newInput) {
if (this.selfAnalysisDone !== true) {
throw Error(`Missing <performSelfAnalysis> invocation at the end of the Parser's constructor.`);
}
this.reset();
this.tokVector = newInput;
this.tokVectorLength = newInput.length;
}
get input() {
return this.tokVector;
}
// skips a token and returns the next token
SKIP_TOKEN() {
if (this.currIdx <= this.tokVector.length - 2) {
this.consumeToken();
return this.LA(1);
} else {
return END_OF_FILE;
}
}
// Lexer (accessing Token vector) related methods which can be overridden to implement lazy lexers
// or lexers dependent on parser context.
LA(howMuch) {
const soughtIdx = this.currIdx + howMuch;
if (soughtIdx < 0 || this.tokVectorLength <= soughtIdx) {
return END_OF_FILE;
} else {
return this.tokVector[soughtIdx];
}
}
consumeToken() {
this.currIdx++;
}
exportLexerState() {
return this.currIdx;
}
importLexerState(newState2) {
this.currIdx = newState2;
}
resetLexerState() {
this.currIdx = -1;
}
moveToTerminatedState() {
this.currIdx = this.tokVector.length - 1;
}
getLexerPosition() {
return this.exportLexerState();
}
};
var RecognizerApi = class {
static {
__name(this, "RecognizerApi");
}
static {
__name2(this, "RecognizerApi");
}
ACTION(impl) {
return impl.call(this);
}
consume(idx, tokType, options) {
return this.consumeInternal(tokType, idx, options);
}
subrule(idx, ruleToCall, options) {
return this.subruleInternal(ruleToCall, idx, options);
}
option(idx, actionORMethodDef) {
return this.optionInternal(actionORMethodDef, idx);
}
or(idx, altsOrOpts) {
return this.orInternal(altsOrOpts, idx);
}
many(idx, actionORMethodDef) {
return this.manyInternal(idx, actionORMethodDef);
}
atLeastOne(idx, actionORMethodDef) {
return this.atLeastOneInternal(idx, actionORMethodDef);
}
CONSUME(tokType, options) {
return this.consumeInternal(tokType, 0, options);
}
CONSUME1(tokType, options) {
return this.consumeInternal(tokType, 1, options);
}
CONSUME2(tokType, options) {
return this.consumeInternal(tokType, 2, options);
}
CONSUME3(tokType, options) {
return this.consumeInternal(tokType, 3, options);
}
CONSUME4(tokType, options) {
return this.consumeInternal(tokType, 4, options);
}
CONSUME5(tokType, options) {
return this.consumeInternal(tokType, 5, options);
}
CONSUME6(tokType, options) {
return this.consumeInternal(tokType, 6, options);
}
CONSUME7(tokType, options) {
return this.consumeInternal(tokType, 7, options);
}
CONSUME8(tokType, options) {
return this.consumeInternal(tokType, 8, options);
}
CONSUME9(tokType, options) {
return this.consumeInternal(tokType, 9, options);
}
SUBRULE(ruleToCall, options) {
return this.subruleInternal(ruleToCall, 0, options);
}
SUBRULE1(ruleToCall, options) {
return this.subruleInternal(ruleToCall, 1, options);
}
SUBRULE2(ruleToCall, options) {
return this.subruleInternal(ruleToCall, 2, options);
}
SUBRULE3(ruleToCall, options) {
return this.subruleInternal(ruleToCall, 3, options);
}
SUBRULE4(ruleToCall, options) {
return this.subruleInternal(ruleToCall, 4, options);
}
SUBRULE5(ruleToCall, options) {
return this.subruleInternal(ruleToCall, 5, options);
}
SUBRULE6(ruleToCall, options) {
return this.subruleInternal(ruleToCall, 6, options);
}
SUBRULE7(ruleToCall, options) {
return this.subruleInternal(ruleToCall, 7, options);
}
SUBRULE8(ruleToCall, options) {
return this.subruleInternal(ruleToCall, 8, options);
}
SUBRULE9(ruleToCall, options) {
return this.subruleInternal(ruleToCall, 9, options);
}
OPTION(actionORMethodDef) {
return this.optionInternal(actionORMethodDef, 0);
}
OPTION1(actionORMethodDef) {
return this.optionInternal(actionORMethodDef, 1);
}
OPTION2(actionORMethodDef) {
return this.optionInternal(actionORMethodDef, 2);
}
OPTION3(actionORMethodDef) {
return this.optionInternal(actionORMethodDef, 3);
}
OPTION4(actionORMethodDef) {
return this.optionInternal(actionORMethodDef, 4);
}
OPTION5(actionORMethodDef) {
return this.optionInternal(actionORMethodDef, 5);
}
OPTION6(actionORMethodDef) {
return this.optionInternal(actionORMethodDef, 6);
}
OPTION7(actionORMethodDef) {
return this.optionInternal(actionORMethodDef, 7);
}
OPTION8(actionORMethodDef) {
return this.optionInternal(actionORMethodDef, 8);
}
OPTION9(actionORMethodDef) {
return this.optionInternal(actionORMethodDef, 9);
}
OR(altsOrOpts) {
return this.orInternal(altsOrOpts, 0);
}
OR1(altsOrOpts) {
return this.orInternal(altsOrOpts, 1);
}
OR2(altsOrOpts) {
return this.orInternal(altsOrOpts, 2);
}
OR3(altsOrOpts) {
return this.orInternal(altsOrOpts, 3);
}
OR4(altsOrOpts) {
return this.orInternal(altsOrOpts, 4);
}
OR5(altsOrOpts) {
return this.orInternal(altsOrOpts, 5);
}
OR6(altsOrOpts) {
return this.orInternal(altsOrOpts, 6);
}
OR7(altsOrOpts) {
return this.orInternal(altsOrOpts, 7);
}
OR8(altsOrOpts) {
return this.orInternal(altsOrOpts, 8);
}
OR9(altsOrOpts) {
return this.orInternal(altsOrOpts, 9);
}
MANY(actionORMethodDef) {
this.manyInternal(0, actionORMethodDef);
}
MANY1(actionORMethodDef) {
this.manyInternal(1, actionORMethodDef);
}
MANY2(actionORMethodDef) {
this.manyInternal(2, actionORMethodDef);
}
MANY3(actionORMethodDef) {
this.manyInternal(3, actionORMethodDef);
}
MANY4(actionORMethodDef) {
this.manyInternal(4, actionORMethodDef);
}
MANY5(actionORMethodDef) {
this.manyInternal(5, actionORMethodDef);
}
MANY6(actionORMethodDef) {
this.manyInternal(6, actionORMethodDef);
}
MANY7(actionORMethodDef) {
this.manyInternal(7, actionORMethodDef);
}
MANY8(actionORMethodDef) {
this.manyInternal(8, actionORMethodDef);
}
MANY9(actionORMethodDef) {
this.manyInternal(9, actionORMethodDef);
}
MANY_SEP(options) {
this.manySepFirstInternal(0, options);
}
MANY_SEP1(options) {
this.manySepFirstInternal(1, options);
}
MANY_SEP2(options) {
this.manySepFirstInternal(2, options);
}
MANY_SEP3(options) {
this.manySepFirstInternal(3, options);
}
MANY_SEP4(options) {
this.manySepFirstInternal(4, options);
}
MANY_SEP5(options) {
this.manySepFirstInternal(5, options);
}
MANY_SEP6(options) {
this.manySepFirstInternal(6, options);
}
MANY_SEP7(options) {
this.manySepFirstInternal(7, options);
}
MANY_SEP8(options) {
this.manySepFirstInternal(8, options);
}
MANY_SEP9(options) {
this.manySepFirstInternal(9, options);
}
AT_LEAST_ONE(actionORMethodDef) {
this.atLeastOneInternal(0, actionORMethodDef);
}
AT_LEAST_ONE1(actionORMethodDef) {
return this.atLeastOneInternal(1, actionORMethodDef);
}
AT_LEAST_ONE2(actionORMethodDef) {
this.atLeastOneInternal(2, actionORMethodDef);
}
AT_LEAST_ONE3(actionORMethodDef) {
this.atLeastOneInternal(3, actionORMethodDef);
}
AT_LEAST_ONE4(actionORMethodDef) {
this.atLeastOneInternal(4, actionORMethodDef);
}
AT_LEAST_ONE5(actionORMethodDef) {
this.atLeastOneInternal(5, actionORMethodDef);
}
AT_LEAST_ONE6(actionORMethodDef) {
this.atLeastOneInternal(6, actionORMethodDef);
}
AT_LEAST_ONE7(actionORMethodDef) {
this.atLeastOneInternal(7, actionORMethodDef);
}
AT_LEAST_ONE8(actionORMethodDef) {
this.atLeastOneInternal(8, actionORMethodDef);
}
AT_LEAST_ONE9(actionORMethodDef) {
this.atLeastOneInternal(9, actionORMethodDef);
}
AT_LEAST_ONE_SEP(options) {
this.atLeastOneSepFirstInternal(0, options);
}
AT_LEAST_ONE_SEP1(options) {
this.atLeastOneSepFirstInternal(1, options);
}
AT_LEAST_ONE_SEP2(options) {
this.atLeastOneSepFirstInternal(2, options);
}
AT_LEAST_ONE_SEP3(options) {
this.atLeastOneSepFirstInternal(3, options);
}
AT_LEAST_ONE_SEP4(options) {
this.atLeastOneSepFirstInternal(4, options);
}
AT_LEAST_ONE_SEP5(options) {
this.atLeastOneSepFirstInternal(5, options);
}
AT_LEAST_ONE_SEP6(options) {
this.atLeastOneSepFirstInternal(6, options);
}
AT_LEAST_ONE_SEP7(options) {
this.atLeastOneSepFirstInternal(7, options);
}
AT_LEAST_ONE_SEP8(options) {
this.atLeastOneSepFirstInternal(8, options);
}
AT_LEAST_ONE_SEP9(options) {
this.atLeastOneSepFirstInternal(9, options);
}
RULE(name, implementation, config = DEFAULT_RULE_CONFIG) {
if (includes_default(this.definedRulesNames, name)) {
const errMsg = defaultGrammarValidatorErrorProvider.buildDuplicateRuleNameError({
topLevelRule: name,
grammarName: this.className
});
const error = {
message: errMsg,
type: ParserDefinitionErrorType.DUPLICATE_RULE_NAME,
ruleName: name
};
this.definitionErrors.push(error);
}
this.definedRulesNames.push(name);
const ruleImplementation = this.defineRule(name, implementation, config);
this[name] = ruleImplementation;
return ruleImplementation;
}
OVERRIDE_RULE(name, impl, config = DEFAULT_RULE_CONFIG) {
const ruleErrors = validateRuleIsOverridden(name, this.definedRulesNames, this.className);
this.definitionErrors = this.definitionErrors.concat(ruleErrors);
const ruleImplementation = this.defineRule(name, impl, config);
this[name] = ruleImplementation;
return ruleImplementation;
}
BACKTRACK(grammarRule, args) {
return function() {
this.isBackTrackingStack.push(1);
const orgState = this.saveRecogState();
try {
grammarRule.apply(this, args);
return true;
} catch (e) {
if (isRecognitionException(e)) {
return false;
} else {
throw e;
}
} finally {
this.reloadRecogState(orgState);
this.isBackTrackingStack.pop();
}
};
}
// GAST export APIs
getGAstProductions() {
return this.gastProductionsCache;
}
getSerializedGastProductions() {
return serializeGrammar(values_default(this.gastProductionsCache));
}
};
var RecognizerEngine = class {
static {
__name(this, "RecognizerEngine");
}
static {
__name2(this, "RecognizerEngine");
}
initRecognizerEngine(tokenVocabulary, config) {
this.className = this.constructor.name;
this.shortRuleNameToFull = {};
this.fullRuleNameToShort = {};
this.ruleShortNameIdx = 256;
this.tokenMatcher = tokenStructuredMatcherNoCategories;
this.subruleIdx = 0;
this.definedRulesNames = [];
this.tokensMap = {};
this.isBackTrackingStack = [];
this.RULE_STACK = [];
this.RULE_OCCURRENCE_STACK = [];
this.gastProductionsCache = {};
if (has_default(config, "serializedGrammar")) {
throw Error("The Parser's configuration can no longer contain a <serializedGrammar> property.\n See: https://chevrotain.io/docs/changes/BREAKING_CHANGES.html#_6-0-0\n For Further details.");
}
if (isArray_default(tokenVocabulary)) {
if (isEmpty_default(tokenVocabulary)) {
throw Error("A Token Vocabulary cannot be empty.\n Note that the first argument for the parser constructor\n is no longer a Token vector (since v4.0).");
}
if (typeof tokenVocabulary[0].startOffset === "number") {
throw Error("The Parser constructor no longer accepts a token vector as the first argument.\n See: https://chevrotain.io/docs/changes/BREAKING_CHANGES.html#_4-0-0\n For Further details.");
}
}
if (isArray_default(tokenVocabulary)) {
this.tokensMap = reduce_default(tokenVocabulary, (acc, tokType) => {
acc[tokType.name] = tokType;
return acc;
}, {});
} else if (has_default(tokenVocabulary, "modes") && every_default(flatten_default(values_default(tokenVocabulary.modes)), isTokenType)) {
const allTokenTypes2 = flatten_default(values_default(tokenVocabulary.modes));
const uniqueTokens = uniq_default(allTokenTypes2);
this.tokensMap = reduce_default(uniqueTokens, (acc, tokType) => {
acc[tokType.name] = tokType;
return acc;
}, {});
} else if (isObject_default(tokenVocabulary)) {
this.tokensMap = clone_default(tokenVocabulary);
} else {
throw new Error("<tokensDictionary> argument must be An Array of Token constructors, A dictionary of Token constructors or an IMultiModeLexerDefinition");
}
this.tokensMap["EOF"] = EOF;
const allTokenTypes = has_default(tokenVocabulary, "modes") ? flatten_default(values_default(tokenVocabulary.modes)) : values_default(tokenVocabulary);
const noTokenCategoriesUsed = every_default(allTokenTypes, (tokenConstructor) => isEmpty_default(tokenConstructor.categoryMatches));
this.tokenMatcher = noTokenCategoriesUsed ? tokenStructuredMatcherNoCategories : tokenStructuredMatcher;
augmentTokenTypes(values_default(this.tokensMap));
}
defineRule(ruleName, impl, config) {
if (this.selfAnalysisDone) {
throw Error(`Grammar rule <${ruleName}> may not be defined after the 'performSelfAnalysis' method has been called'
Make sure that all grammar rule definitions are done before 'performSelfAnalysis' is called.`);
}
const resyncEnabled = has_default(config, "resyncEnabled") ? config.resyncEnabled : DEFAULT_RULE_CONFIG.resyncEnabled;
const recoveryValueFunc = has_default(config, "recoveryValueFunc") ? config.recoveryValueFunc : DEFAULT_RULE_CONFIG.recoveryValueFunc;
const shortName = this.ruleShortNameIdx << BITS_FOR_METHOD_TYPE + BITS_FOR_OCCURRENCE_IDX;
this.ruleShortNameIdx++;
this.shortRuleNameToFull[shortName] = ruleName;
this.fullRuleNameToShort[ruleName] = shortName;
let invokeRuleWithTry;
if (this.outputCst === true) {
invokeRuleWithTry = /* @__PURE__ */ __name2(/* @__PURE__ */ __name(function invokeRuleWithTry2(...args) {
try {
this.ruleInvocationStateUpdate(shortName, ruleName, this.subruleIdx);
impl.apply(this, args);
const cst = this.CST_STACK[this.CST_STACK.length - 1];
this.cstPostRule(cst);
return cst;
} catch (e) {
return this.invokeRuleCatch(e, resyncEnabled, recoveryValueFunc);
} finally {
this.ruleFinallyStateUpdate();
}
}, "invokeRuleWithTry2"), "invokeRuleWithTry");
} else {
invokeRuleWithTry = /* @__PURE__ */ __name2(/* @__PURE__ */ __name(function invokeRuleWithTryCst(...args) {
try {
this.ruleInvocationStateUpdate(shortName, ruleName, this.subruleIdx);
return impl.apply(this, args);
} catch (e) {
return this.invokeRuleCatch(e, resyncEnabled, recoveryValueFunc);
} finally {
this.ruleFinallyStateUpdate();
}
}, "invokeRuleWithTryCst"), "invokeRuleWithTryCst");
}
const wrappedGrammarRule = Object.assign(invokeRuleWithTry, { ruleName, originalGrammarAction: impl });
return wrappedGrammarRule;
}
invokeRuleCatch(e, resyncEnabledConfig, recoveryValueFunc) {
const isFirstInvokedRule = this.RULE_STACK.length === 1;
const reSyncEnabled = resyncEnabledConfig && !this.isBackTracking() && this.recoveryEnabled;
if (isRecognitionException(e)) {
const recogError = e;
if (reSyncEnabled) {
const reSyncTokType = this.findReSyncTokenType();
if (this.isInCurrentRuleReSyncSet(reSyncTokType)) {
recogError.resyncedTokens = this.reSyncTo(reSyncTokType);
if (this.outputCst) {
const partialCstResult = this.CST_STACK[this.CST_STACK.length - 1];
partialCstResult.recoveredNode = true;
return partialCstResult;
} else {
return recoveryValueFunc(e);
}
} else {
if (this.outputCst) {
const partialCstResult = this.CST_STACK[this.CST_STACK.length - 1];
partialCstResult.recoveredNode = true;
recogError.partialCstResult = partialCstResult;
}
throw recogError;
}
} else if (isFirstInvokedRule) {
this.moveToTerminatedState();
return recoveryValueFunc(e);
} else {
throw recogError;
}
} else {
throw e;
}
}
// Implementation of parsing DSL
optionInternal(actionORMethodDef, occurrence) {
const key = this.getKeyForAutomaticLookahead(OPTION_IDX, occurrence);
return this.optionInternalLogic(actionORMethodDef, occurrence, key);
}
optionInternalLogic(actionORMethodDef, occurrence, key) {
let lookAheadFunc = this.getLaFuncFromCache(key);
let action;
if (typeof actionORMethodDef !== "function") {
action = actionORMethodDef.DEF;
const predicate = actionORMethodDef.GATE;
if (predicate !== void 0) {
const orgLookaheadFunction = lookAheadFunc;
lookAheadFunc = /* @__PURE__ */ __name2(() => {
return predicate.call(this) && orgLookaheadFunction.call(this);
}, "lookAheadFunc");
}
} else {
action = actionORMethodDef;
}
if (lookAheadFunc.call(this) === true) {
return action.call(this);
}
return void 0;
}
atLeastOneInternal(prodOccurrence, actionORMethodDef) {
const laKey = this.getKeyForAutomaticLookahead(AT_LEAST_ONE_IDX, prodOccurrence);
return this.atLeastOneInternalLogic(prodOccurrence, actionORMethodDef, laKey);
}
atLeastOneInternalLogic(prodOccurrence, actionORMethodDef, key) {
let lookAheadFunc = this.getLaFuncFromCache(key);
let action;
if (typeof actionORMethodDef !== "function") {
action = actionORMethodDef.DEF;
const predicate = actionORMethodDef.GATE;
if (predicate !== void 0) {
const orgLookaheadFunction = lookAheadFunc;
lookAheadFunc = /* @__PURE__ */ __name2(() => {
return predicate.call(this) && orgLookaheadFunction.call(this);
}, "lookAheadFunc");
}
} else {
action = actionORMethodDef;
}
if (lookAheadFunc.call(this) === true) {
let notStuck = this.doSingleRepetition(action);
while (lookAheadFunc.call(this) === true && notStuck === true) {
notStuck = this.doSingleRepetition(action);
}
} else {
throw this.raiseEarlyExitException(prodOccurrence, PROD_TYPE.REPETITION_MANDATORY, actionORMethodDef.ERR_MSG);
}
this.attemptInRepetitionRecovery(this.atLeastOneInternal, [prodOccurrence, actionORMethodDef], lookAheadFunc, AT_LEAST_ONE_IDX, prodOccurrence, NextTerminalAfterAtLeastOneWalker);
}
atLeastOneSepFirstInternal(prodOccurrence, options) {
const laKey = this.getKeyForAutomaticLookahead(AT_LEAST_ONE_SEP_IDX, prodOccurrence);
this.atLeastOneSepFirstInternalLogic(prodOccurrence, options, laKey);
}
atLeastOneSepFirstInternalLogic(prodOccurrence, options, key) {
const action = options.DEF;
const separator = options.SEP;
const firstIterationLookaheadFunc = this.getLaFuncFromCache(key);
if (firstIterationLookaheadFunc.call(this) === true) {
action.call(this);
const separatorLookAheadFunc = /* @__PURE__ */ __name2(() => {
return this.tokenMatcher(this.LA(1), separator);
}, "separatorLookAheadFunc");
while (this.tokenMatcher(this.LA(1), separator) === true) {
this.CONSUME(separator);
action.call(this);
}
this.attemptInRepetitionRecovery(this.repetitionSepSecondInternal, [
prodOccurrence,
separator,
separatorLookAheadFunc,
action,
NextTerminalAfterAtLeastOneSepWalker
], separatorLookAheadFunc, AT_LEAST_ONE_SEP_IDX, prodOccurrence, NextTerminalAfterAtLeastOneSepWalker);
} else {
throw this.raiseEarlyExitException(prodOccurrence, PROD_TYPE.REPETITION_MANDATORY_WITH_SEPARATOR, options.ERR_MSG);
}
}
manyInternal(prodOccurrence, actionORMethodDef) {
const laKey = this.getKeyForAutomaticLookahead(MANY_IDX, prodOccurrence);
return this.manyInternalLogic(prodOccurrence, actionORMethodDef, laKey);
}
manyInternalLogic(prodOccurrence, actionORMethodDef, key) {
let lookaheadFunction = this.getLaFuncFromCache(key);
let action;
if (typeof actionORMethodDef !== "function") {
action = actionORMethodDef.DEF;
const predicate = actionORMethodDef.GATE;
if (predicate !== void 0) {
const orgLookaheadFunction = lookaheadFunction;
lookaheadFunction = /* @__PURE__ */ __name2(() => {
return predicate.call(this) && orgLookaheadFunction.call(this);
}, "lookaheadFunction");
}
} else {
action = actionORMethodDef;
}
let notStuck = true;
while (lookaheadFunction.call(this) === true && notStuck === true) {
notStuck = this.doSingleRepetition(action);
}
this.attemptInRepetitionRecovery(
this.manyInternal,
[prodOccurrence, actionORMethodDef],
lookaheadFunction,
MANY_IDX,
prodOccurrence,
NextTerminalAfterManyWalker,
// The notStuck parameter is only relevant when "attemptInRepetitionRecovery"
// is invoked from manyInternal, in the MANY_SEP case and AT_LEAST_ONE[_SEP]
// An infinite loop cannot occur as:
// - Either the lookahead is guaranteed to consume something (Single Token Separator)
// - AT_LEAST_ONE by definition is guaranteed to consume something (or error out).
notStuck
);
}
manySepFirstInternal(prodOccurrence, options) {
const laKey = this.getKeyForAutomaticLookahead(MANY_SEP_IDX, prodOccurrence);
this.manySepFirstInternalLogic(prodOccurrence, options, laKey);
}
manySepFirstInternalLogic(prodOccurrence, options, key) {
const action = options.DEF;
const separator = options.SEP;
const firstIterationLaFunc = this.getLaFuncFromCache(key);
if (firstIterationLaFunc.call(this) === true) {
action.call(this);
const separatorLookAheadFunc = /* @__PURE__ */ __name2(() => {
return this.tokenMatcher(this.LA(1), separator);
}, "separatorLookAheadFunc");
while (this.tokenMatcher(this.LA(1), separator) === true) {
this.CONSUME(separator);
action.call(this);
}
this.attemptInRepetitionRecovery(this.repetitionSepSecondInternal, [
prodOccurrence,
separator,
separatorLookAheadFunc,
action,
NextTerminalAfterManySepWalker
], separatorLookAheadFunc, MANY_SEP_IDX, prodOccurrence, NextTerminalAfterManySepWalker);
}
}
repetitionSepSecondInternal(prodOccurrence, separator, separatorLookAheadFunc, action, nextTerminalAfterWalker) {
while (separatorLookAheadFunc()) {
this.CONSUME(separator);
action.call(this);
}
this.attemptInRepetitionRecovery(this.repetitionSepSecondInternal, [
prodOccurrence,
separator,
separatorLookAheadFunc,
action,
nextTerminalAfterWalker
], separatorLookAheadFunc, AT_LEAST_ONE_SEP_IDX, prodOccurrence, nextTerminalAfterWalker);
}
doSingleRepetition(action) {
const beforeIteration = this.getLexerPosition();
action.call(this);
const afterIteration = this.getLexerPosition();
return afterIteration > beforeIteration;
}
orInternal(altsOrOpts, occurrence) {
const laKey = this.getKeyForAutomaticLookahead(OR_IDX, occurrence);
const alts = isArray_default(altsOrOpts) ? altsOrOpts : altsOrOpts.DEF;
const laFunc = this.getLaFuncFromCache(laKey);
const altIdxToTake = laFunc.call(this, alts);
if (altIdxToTake !== void 0) {
const chosenAlternative = alts[altIdxToTake];
return chosenAlternative.ALT.call(this);
}
this.raiseNoAltException(occurrence, altsOrOpts.ERR_MSG);
}
ruleFinallyStateUpdate() {
this.RULE_STACK.pop();
this.RULE_OCCURRENCE_STACK.pop();
this.cstFinallyStateUpdate();
if (this.RULE_STACK.length === 0 && this.isAtEndOfInput() === false) {
const firstRedundantTok = this.LA(1);
const errMsg = this.errorMessageProvider.buildNotAllInputParsedMessage({
firstRedundant: firstRedundantTok,
ruleName: this.getCurrRuleFullName()
});
this.SAVE_ERROR(new NotAllInputParsedException(errMsg, firstRedundantTok));
}
}
subruleInternal(ruleToCall, idx, options) {
let ruleResult;
try {
const args = options !== void 0 ? options.ARGS : void 0;
this.subruleIdx = idx;
ruleResult = ruleToCall.apply(this, args);
this.cstPostNonTerminal(ruleResult, options !== void 0 && options.LABEL !== void 0 ? options.LABEL : ruleToCall.ruleName);
return ruleResult;
} catch (e) {
throw this.subruleInternalError(e, options, ruleToCall.ruleName);
}
}
subruleInternalError(e, options, ruleName) {
if (isRecognitionException(e) && e.partialCstResult !== void 0) {
this.cstPostNonTerminal(e.partialCstResult, options !== void 0 && options.LABEL !== void 0 ? options.LABEL : ruleName);
delete e.partialCstResult;
}
throw e;
}
consumeInternal(tokType, idx, options) {
let consumedToken;
try {
const nextToken = this.LA(1);
if (this.tokenMatcher(nextToken, tokType) === true) {
this.consumeToken();
consumedToken = nextToken;
} else {
this.consumeInternalError(tokType, nextToken, options);
}
} catch (eFromConsumption) {
consumedToken = this.consumeInternalRecovery(tokType, idx, eFromConsumption);
}
this.cstPostTerminal(options !== void 0 && options.LABEL !== void 0 ? options.LABEL : tokType.name, consumedToken);
return consumedToken;
}
consumeInternalError(tokType, nextToken, options) {
let msg;
const previousToken = this.LA(0);
if (options !== void 0 && options.ERR_MSG) {
msg = options.ERR_MSG;
} else {
msg = this.errorMessageProvider.buildMismatchTokenMessage({
expected: tokType,
actual: nextToken,
previous: previousToken,
ruleName: this.getCurrRuleFullName()
});
}
throw this.SAVE_ERROR(new MismatchedTokenException(msg, nextToken, previousToken));
}
consumeInternalRecovery(tokType, idx, eFromConsumption) {
if (this.recoveryEnabled && // TODO: more robust checking of the exception type. Perhaps Typescript extending expressions?
eFromConsumption.name === "MismatchedTokenException" && !this.isBackTracking()) {
const follows = this.getFollowsForInRuleRecovery(tokType, idx);
try {
return this.tryInRuleRecovery(tokType, follows);
} catch (eFromInRuleRecovery) {
if (eFromInRuleRecovery.name === IN_RULE_RECOVERY_EXCEPTION) {
throw eFromConsumption;
} else {
throw eFromInRuleRecovery;
}
}
} else {
throw eFromConsumption;
}
}
saveRecogState() {
const savedErrors = this.errors;
const savedRuleStack = clone_default(this.RULE_STACK);
return {
errors: savedErrors,
lexerState: this.exportLexerState(),
RULE_STACK: savedRuleStack,
CST_STACK: this.CST_STACK
};
}
reloadRecogState(newState2) {
this.errors = newState2.errors;
this.importLexerState(newState2.lexerState);
this.RULE_STACK = newState2.RULE_STACK;
}
ruleInvocationStateUpdate(shortName, fullName, idxInCallingRule) {
this.RULE_OCCURRENCE_STACK.push(idxInCallingRule);
this.RULE_STACK.push(shortName);
this.cstInvocationStateUpdate(fullName);
}
isBackTracking() {
return this.isBackTrackingStack.length !== 0;
}
getCurrRuleFullName() {
const shortName = this.getLastExplicitRuleShortName();
return this.shortRuleNameToFull[shortName];
}
shortRuleNameToFullName(shortName) {
return this.shortRuleNameToFull[shortName];
}
isAtEndOfInput() {
return this.tokenMatcher(this.LA(1), EOF);
}
reset() {
this.resetLexerState();
this.subruleIdx = 0;
this.isBackTrackingStack = [];
this.errors = [];
this.RULE_STACK = [];
this.CST_STACK = [];
this.RULE_OCCURRENCE_STACK = [];
}
};
var ErrorHandler = class {
static {
__name(this, "ErrorHandler");
}
static {
__name2(this, "ErrorHandler");
}
initErrorHandler(config) {
this._errors = [];
this.errorMessageProvider = has_default(config, "errorMessageProvider") ? config.errorMessageProvider : DEFAULT_PARSER_CONFIG.errorMessageProvider;
}
SAVE_ERROR(error) {
if (isRecognitionException(error)) {
error.context = {
ruleStack: this.getHumanReadableRuleStack(),
ruleOccurrenceStack: clone_default(this.RULE_OCCURRENCE_STACK)
};
this._errors.push(error);
return error;
} else {
throw Error("Trying to save an Error which is not a RecognitionException");
}
}
get errors() {
return clone_default(this._errors);
}
set errors(newErrors) {
this._errors = newErrors;
}
// TODO: consider caching the error message computed information
raiseEarlyExitException(occurrence, prodType, userDefinedErrMsg) {
const ruleName = this.getCurrRuleFullName();
const ruleGrammar = this.getGAstProductions()[ruleName];
const lookAheadPathsPerAlternative = getLookaheadPathsForOptionalProd(occurrence, ruleGrammar, prodType, this.maxLookahead);
const insideProdPaths = lookAheadPathsPerAlternative[0];
const actualTokens = [];
for (let i = 1; i <= this.maxLookahead; i++) {
actualTokens.push(this.LA(i));
}
const msg = this.errorMessageProvider.buildEarlyExitMessage({
expectedIterationPaths: insideProdPaths,
actual: actualTokens,
previous: this.LA(0),
customUserDescription: userDefinedErrMsg,
ruleName
});
throw this.SAVE_ERROR(new EarlyExitException(msg, this.LA(1), this.LA(0)));
}
// TODO: consider caching the error message computed information
raiseNoAltException(occurrence, errMsgTypes) {
const ruleName = this.getCurrRuleFullName();
const ruleGrammar = this.getGAstProductions()[ruleName];
const lookAheadPathsPerAlternative = getLookaheadPathsForOr(occurrence, ruleGrammar, this.maxLookahead);
const actualTokens = [];
for (let i = 1; i <= this.maxLookahead; i++) {
actualTokens.push(this.LA(i));
}
const previousToken = this.LA(0);
const errMsg = this.errorMessageProvider.buildNoViableAltMessage({
expectedPathsPerAlt: lookAheadPathsPerAlternative,
actual: actualTokens,
previous: previousToken,
customUserDescription: errMsgTypes,
ruleName: this.getCurrRuleFullName()
});
throw this.SAVE_ERROR(new NoViableAltException(errMsg, this.LA(1), previousToken));
}
};
var ContentAssist = class {
static {
__name(this, "ContentAssist");
}
static {
__name2(this, "ContentAssist");
}
initContentAssist() {
}
computeContentAssist(startRuleName, precedingInput) {
const startRuleGast = this.gastProductionsCache[startRuleName];
if (isUndefined_default(startRuleGast)) {
throw Error(`Rule ->${startRuleName}<- does not exist in this grammar.`);
}
return nextPossibleTokensAfter([startRuleGast], precedingInput, this.tokenMatcher, this.maxLookahead);
}
// TODO: should this be a member method or a utility? it does not have any state or usage of 'this'...
// TODO: should this be more explicitly part of the public API?
getNextPossibleTokenTypes(grammarPath) {
const topRuleName = head_default(grammarPath.ruleStack);
const gastProductions = this.getGAstProductions();
const topProduction = gastProductions[topRuleName];
const nextPossibleTokenTypes = new NextAfterTokenWalker(topProduction, grammarPath).startWalking();
return nextPossibleTokenTypes;
}
};
var RECORDING_NULL_OBJECT = {
description: "This Object indicates the Parser is during Recording Phase"
};
Object.freeze(RECORDING_NULL_OBJECT);
var HANDLE_SEPARATOR = true;
var MAX_METHOD_IDX = Math.pow(2, BITS_FOR_OCCURRENCE_IDX) - 1;
var RFT = createToken({ name: "RECORDING_PHASE_TOKEN", pattern: Lexer.NA });
augmentTokenTypes([RFT]);
var RECORDING_PHASE_TOKEN = createTokenInstance(
RFT,
"This IToken indicates the Parser is in Recording Phase\n See: https://chevrotain.io/docs/guide/internals.html#grammar-recording for details",
// Using "-1" instead of NaN (as in EOF) because an actual number is less likely to
// cause errors if the output of LA or CONSUME would be (incorrectly) used during the recording phase.
-1,
-1,
-1,
-1,
-1,
-1
);
Object.freeze(RECORDING_PHASE_TOKEN);
var RECORDING_PHASE_CSTNODE = {
name: "This CSTNode indicates the Parser is in Recording Phase\n See: https://chevrotain.io/docs/guide/internals.html#grammar-recording for details",
children: {}
};
var GastRecorder = class {
static {
__name(this, "GastRecorder");
}
static {
__name2(this, "GastRecorder");
}
initGastRecorder(config) {
this.recordingProdStack = [];
this.RECORDING_PHASE = false;
}
enableRecording() {
this.RECORDING_PHASE = true;
this.TRACE_INIT("Enable Recording", () => {
for (let i = 0; i < 10; i++) {
const idx = i > 0 ? i : "";
this[`CONSUME${idx}`] = function(arg1, arg2) {
return this.consumeInternalRecord(arg1, i, arg2);
};
this[`SUBRULE${idx}`] = function(arg1, arg2) {
return this.subruleInternalRecord(arg1, i, arg2);
};
this[`OPTION${idx}`] = function(arg1) {
return this.optionInternalRecord(arg1, i);
};
this[`OR${idx}`] = function(arg1) {
return this.orInternalRecord(arg1, i);
};
this[`MANY${idx}`] = function(arg1) {
this.manyInternalRecord(i, arg1);
};
this[`MANY_SEP${idx}`] = function(arg1) {
this.manySepFirstInternalRecord(i, arg1);
};
this[`AT_LEAST_ONE${idx}`] = function(arg1) {
this.atLeastOneInternalRecord(i, arg1);
};
this[`AT_LEAST_ONE_SEP${idx}`] = function(arg1) {
this.atLeastOneSepFirstInternalRecord(i, arg1);
};
}
this[`consume`] = function(idx, arg1, arg2) {
return this.consumeInternalRecord(arg1, idx, arg2);
};
this[`subrule`] = function(idx, arg1, arg2) {
return this.subruleInternalRecord(arg1, idx, arg2);
};
this[`option`] = function(idx, arg1) {
return this.optionInternalRecord(arg1, idx);
};
this[`or`] = function(idx, arg1) {
return this.orInternalRecord(arg1, idx);
};
this[`many`] = function(idx, arg1) {
this.manyInternalRecord(idx, arg1);
};
this[`atLeastOne`] = function(idx, arg1) {
this.atLeastOneInternalRecord(idx, arg1);
};
this.ACTION = this.ACTION_RECORD;
this.BACKTRACK = this.BACKTRACK_RECORD;
this.LA = this.LA_RECORD;
});
}
disableRecording() {
this.RECORDING_PHASE = false;
this.TRACE_INIT("Deleting Recording methods", () => {
const that = this;
for (let i = 0; i < 10; i++) {
const idx = i > 0 ? i : "";
delete that[`CONSUME${idx}`];
delete that[`SUBRULE${idx}`];
delete that[`OPTION${idx}`];
delete that[`OR${idx}`];
delete that[`MANY${idx}`];
delete that[`MANY_SEP${idx}`];
delete that[`AT_LEAST_ONE${idx}`];
delete that[`AT_LEAST_ONE_SEP${idx}`];
}
delete that[`consume`];
delete that[`subrule`];
delete that[`option`];
delete that[`or`];
delete that[`many`];
delete that[`atLeastOne`];
delete that.ACTION;
delete that.BACKTRACK;
delete that.LA;
});
}
// Parser methods are called inside an ACTION?
// Maybe try/catch/finally on ACTIONS while disabling the recorders state changes?
// @ts-expect-error -- noop place holder
ACTION_RECORD(impl) {
}
// Executing backtracking logic will break our recording logic assumptions
BACKTRACK_RECORD(grammarRule, args) {
return () => true;
}
// LA is part of the official API and may be used for custom lookahead logic
// by end users who may forget to wrap it in ACTION or inside a GATE
LA_RECORD(howMuch) {
return END_OF_FILE;
}
topLevelRuleRecord(name, def) {
try {
const newTopLevelRule = new Rule({ definition: [], name });
newTopLevelRule.name = name;
this.recordingProdStack.push(newTopLevelRule);
def.call(this);
this.recordingProdStack.pop();
return newTopLevelRule;
} catch (originalError) {
if (originalError.KNOWN_RECORDER_ERROR !== true) {
try {
originalError.message = originalError.message + '\n This error was thrown during the "grammar recording phase" For more info see:\n https://chevrotain.io/docs/guide/internals.html#grammar-recording';
} catch (mutabilityError) {
throw originalError;
}
}
throw originalError;
}
}
// Implementation of parsing DSL
optionInternalRecord(actionORMethodDef, occurrence) {
return recordProd.call(this, Option, actionORMethodDef, occurrence);
}
atLeastOneInternalRecord(occurrence, actionORMethodDef) {
recordProd.call(this, RepetitionMandatory, actionORMethodDef, occurrence);
}
atLeastOneSepFirstInternalRecord(occurrence, options) {
recordProd.call(this, RepetitionMandatoryWithSeparator, options, occurrence, HANDLE_SEPARATOR);
}
manyInternalRecord(occurrence, actionORMethodDef) {
recordProd.call(this, Repetition, actionORMethodDef, occurrence);
}
manySepFirstInternalRecord(occurrence, options) {
recordProd.call(this, RepetitionWithSeparator, options, occurrence, HANDLE_SEPARATOR);
}
orInternalRecord(altsOrOpts, occurrence) {
return recordOrProd.call(this, altsOrOpts, occurrence);
}
subruleInternalRecord(ruleToCall, occurrence, options) {
assertMethodIdxIsValid(occurrence);
if (!ruleToCall || has_default(ruleToCall, "ruleName") === false) {
const error = new Error(`<SUBRULE${getIdxSuffix(occurrence)}> argument is invalid expecting a Parser method reference but got: <${JSON.stringify(ruleToCall)}>
inside top level rule: <${this.recordingProdStack[0].name}>`);
error.KNOWN_RECORDER_ERROR = true;
throw error;
}
const prevProd = last_default(this.recordingProdStack);
const ruleName = ruleToCall.ruleName;
const newNoneTerminal = new NonTerminal({
idx: occurrence,
nonTerminalName: ruleName,
label: options === null || options === void 0 ? void 0 : options.LABEL,
// The resolving of the `referencedRule` property will be done once all the Rule's GASTs have been created
referencedRule: void 0
});
prevProd.definition.push(newNoneTerminal);
return this.outputCst ? RECORDING_PHASE_CSTNODE : RECORDING_NULL_OBJECT;
}
consumeInternalRecord(tokType, occurrence, options) {
assertMethodIdxIsValid(occurrence);
if (!hasShortKeyProperty(tokType)) {
const error = new Error(`<CONSUME${getIdxSuffix(occurrence)}> argument is invalid expecting a TokenType reference but got: <${JSON.stringify(tokType)}>
inside top level rule: <${this.recordingProdStack[0].name}>`);
error.KNOWN_RECORDER_ERROR = true;
throw error;
}
const prevProd = last_default(this.recordingProdStack);
const newNoneTerminal = new Terminal({
idx: occurrence,
terminalType: tokType,
label: options === null || options === void 0 ? void 0 : options.LABEL
});
prevProd.definition.push(newNoneTerminal);
return RECORDING_PHASE_TOKEN;
}
};
function recordProd(prodConstructor, mainProdArg, occurrence, handleSep = false) {
assertMethodIdxIsValid(occurrence);
const prevProd = last_default(this.recordingProdStack);
const grammarAction = isFunction_default(mainProdArg) ? mainProdArg : mainProdArg.DEF;
const newProd = new prodConstructor({ definition: [], idx: occurrence });
if (handleSep) {
newProd.separator = mainProdArg.SEP;
}
if (has_default(mainProdArg, "MAX_LOOKAHEAD")) {
newProd.maxLookahead = mainProdArg.MAX_LOOKAHEAD;
}
this.recordingProdStack.push(newProd);
grammarAction.call(this);
prevProd.definition.push(newProd);
this.recordingProdStack.pop();
return RECORDING_NULL_OBJECT;
}
__name(recordProd, "recordProd");
__name2(recordProd, "recordProd");
function recordOrProd(mainProdArg, occurrence) {
assertMethodIdxIsValid(occurrence);
const prevProd = last_default(this.recordingProdStack);
const hasOptions = isArray_default(mainProdArg) === false;
const alts = hasOptions === false ? mainProdArg : mainProdArg.DEF;
const newOrProd = new Alternation({
definition: [],
idx: occurrence,
ignoreAmbiguities: hasOptions && mainProdArg.IGNORE_AMBIGUITIES === true
});
if (has_default(mainProdArg, "MAX_LOOKAHEAD")) {
newOrProd.maxLookahead = mainProdArg.MAX_LOOKAHEAD;
}
const hasPredicates = some_default(alts, (currAlt) => isFunction_default(currAlt.GATE));
newOrProd.hasPredicates = hasPredicates;
prevProd.definition.push(newOrProd);
forEach_default(alts, (currAlt) => {
const currAltFlat = new Alternative({ definition: [] });
newOrProd.definition.push(currAltFlat);
if (has_default(currAlt, "IGNORE_AMBIGUITIES")) {
currAltFlat.ignoreAmbiguities = currAlt.IGNORE_AMBIGUITIES;
} else if (has_default(currAlt, "GATE")) {
currAltFlat.ignoreAmbiguities = true;
}
this.recordingProdStack.push(currAltFlat);
currAlt.ALT.call(this);
this.recordingProdStack.pop();
});
return RECORDING_NULL_OBJECT;
}
__name(recordOrProd, "recordOrProd");
__name2(recordOrProd, "recordOrProd");
function getIdxSuffix(idx) {
return idx === 0 ? "" : `${idx}`;
}
__name(getIdxSuffix, "getIdxSuffix");
__name2(getIdxSuffix, "getIdxSuffix");
function assertMethodIdxIsValid(idx) {
if (idx < 0 || idx > MAX_METHOD_IDX) {
const error = new Error(
// The stack trace will contain all the needed details
`Invalid DSL Method idx value: <${idx}>
Idx value must be a none negative value smaller than ${MAX_METHOD_IDX + 1}`
);
error.KNOWN_RECORDER_ERROR = true;
throw error;
}
}
__name(assertMethodIdxIsValid, "assertMethodIdxIsValid");
__name2(assertMethodIdxIsValid, "assertMethodIdxIsValid");
var PerformanceTracer = class {
static {
__name(this, "PerformanceTracer");
}
static {
__name2(this, "PerformanceTracer");
}
initPerformanceTracer(config) {
if (has_default(config, "traceInitPerf")) {
const userTraceInitPerf = config.traceInitPerf;
const traceIsNumber = typeof userTraceInitPerf === "number";
this.traceInitMaxIdent = traceIsNumber ? userTraceInitPerf : Infinity;
this.traceInitPerf = traceIsNumber ? userTraceInitPerf > 0 : userTraceInitPerf;
} else {
this.traceInitMaxIdent = 0;
this.traceInitPerf = DEFAULT_PARSER_CONFIG.traceInitPerf;
}
this.traceInitIndent = -1;
}
TRACE_INIT(phaseDesc, phaseImpl) {
if (this.traceInitPerf === true) {
this.traceInitIndent++;
const indent = new Array(this.traceInitIndent + 1).join(" ");
if (this.traceInitIndent < this.traceInitMaxIdent) {
console.log(`${indent}--> <${phaseDesc}>`);
}
const { time, value } = timer(phaseImpl);
const traceMethod = time > 10 ? console.warn : console.log;
if (this.traceInitIndent < this.traceInitMaxIdent) {
traceMethod(`${indent}<-- <${phaseDesc}> time: ${time}ms`);
}
this.traceInitIndent--;
return value;
} else {
return phaseImpl();
}
}
};
function applyMixins(derivedCtor, baseCtors) {
baseCtors.forEach((baseCtor) => {
const baseProto = baseCtor.prototype;
Object.getOwnPropertyNames(baseProto).forEach((propName) => {
if (propName === "constructor") {
return;
}
const basePropDescriptor = Object.getOwnPropertyDescriptor(baseProto, propName);
if (basePropDescriptor && (basePropDescriptor.get || basePropDescriptor.set)) {
Object.defineProperty(derivedCtor.prototype, propName, basePropDescriptor);
} else {
derivedCtor.prototype[propName] = baseCtor.prototype[propName];
}
});
});
}
__name(applyMixins, "applyMixins");
__name2(applyMixins, "applyMixins");
var END_OF_FILE = createTokenInstance(EOF, "", NaN, NaN, NaN, NaN, NaN, NaN);
Object.freeze(END_OF_FILE);
var DEFAULT_PARSER_CONFIG = Object.freeze({
recoveryEnabled: false,
maxLookahead: 3,
dynamicTokensEnabled: false,
outputCst: true,
errorMessageProvider: defaultParserErrorProvider,
nodeLocationTracking: "none",
traceInitPerf: false,
skipValidations: false
});
var DEFAULT_RULE_CONFIG = Object.freeze({
recoveryValueFunc: /* @__PURE__ */ __name2(() => void 0, "recoveryValueFunc"),
resyncEnabled: true
});
var ParserDefinitionErrorType;
(function(ParserDefinitionErrorType2) {
ParserDefinitionErrorType2[ParserDefinitionErrorType2["INVALID_RULE_NAME"] = 0] = "INVALID_RULE_NAME";
ParserDefinitionErrorType2[ParserDefinitionErrorType2["DUPLICATE_RULE_NAME"] = 1] = "DUPLICATE_RULE_NAME";
ParserDefinitionErrorType2[ParserDefinitionErrorType2["INVALID_RULE_OVERRIDE"] = 2] = "INVALID_RULE_OVERRIDE";
ParserDefinitionErrorType2[ParserDefinitionErrorType2["DUPLICATE_PRODUCTIONS"] = 3] = "DUPLICATE_PRODUCTIONS";
ParserDefinitionErrorType2[ParserDefinitionErrorType2["UNRESOLVED_SUBRULE_REF"] = 4] = "UNRESOLVED_SUBRULE_REF";
ParserDefinitionErrorType2[ParserDefinitionErrorType2["LEFT_RECURSION"] = 5] = "LEFT_RECURSION";
ParserDefinitionErrorType2[ParserDefinitionErrorType2["NONE_LAST_EMPTY_ALT"] = 6] = "NONE_LAST_EMPTY_ALT";
ParserDefinitionErrorType2[ParserDefinitionErrorType2["AMBIGUOUS_ALTS"] = 7] = "AMBIGUOUS_ALTS";
ParserDefinitionErrorType2[ParserDefinitionErrorType2["CONFLICT_TOKENS_RULES_NAMESPACE"] = 8] = "CONFLICT_TOKENS_RULES_NAMESPACE";
ParserDefinitionErrorType2[ParserDefinitionErrorType2["INVALID_TOKEN_NAME"] = 9] = "INVALID_TOKEN_NAME";
ParserDefinitionErrorType2[ParserDefinitionErrorType2["NO_NON_EMPTY_LOOKAHEAD"] = 10] = "NO_NON_EMPTY_LOOKAHEAD";
ParserDefinitionErrorType2[ParserDefinitionErrorType2["AMBIGUOUS_PREFIX_ALTS"] = 11] = "AMBIGUOUS_PREFIX_ALTS";
ParserDefinitionErrorType2[ParserDefinitionErrorType2["TOO_MANY_ALTS"] = 12] = "TOO_MANY_ALTS";
ParserDefinitionErrorType2[ParserDefinitionErrorType2["CUSTOM_LOOKAHEAD_VALIDATION"] = 13] = "CUSTOM_LOOKAHEAD_VALIDATION";
})(ParserDefinitionErrorType || (ParserDefinitionErrorType = {}));
function EMPTY_ALT(value = void 0) {
return function() {
return value;
};
}
__name(EMPTY_ALT, "EMPTY_ALT");
__name2(EMPTY_ALT, "EMPTY_ALT");
var Parser = class _Parser {
static {
__name(this, "_Parser");
}
static {
__name2(this, "Parser");
}
/**
* @deprecated use the **instance** method with the same name instead
*/
static performSelfAnalysis(parserInstance) {
throw Error("The **static** `performSelfAnalysis` method has been deprecated. \nUse the **instance** method with the same name instead.");
}
performSelfAnalysis() {
this.TRACE_INIT("performSelfAnalysis", () => {
let defErrorsMsgs;
this.selfAnalysisDone = true;
const className = this.className;
this.TRACE_INIT("toFastProps", () => {
toFastProperties(this);
});
this.TRACE_INIT("Grammar Recording", () => {
try {
this.enableRecording();
forEach_default(this.definedRulesNames, (currRuleName) => {
const wrappedRule = this[currRuleName];
const originalGrammarAction = wrappedRule["originalGrammarAction"];
let recordedRuleGast;
this.TRACE_INIT(`${currRuleName} Rule`, () => {
recordedRuleGast = this.topLevelRuleRecord(currRuleName, originalGrammarAction);
});
this.gastProductionsCache[currRuleName] = recordedRuleGast;
});
} finally {
this.disableRecording();
}
});
let resolverErrors = [];
this.TRACE_INIT("Grammar Resolving", () => {
resolverErrors = resolveGrammar2({
rules: values_default(this.gastProductionsCache)
});
this.definitionErrors = this.definitionErrors.concat(resolverErrors);
});
this.TRACE_INIT("Grammar Validations", () => {
if (isEmpty_default(resolverErrors) && this.skipValidations === false) {
const validationErrors = validateGrammar2({
rules: values_default(this.gastProductionsCache),
tokenTypes: values_default(this.tokensMap),
errMsgProvider: defaultGrammarValidatorErrorProvider,
grammarName: className
});
const lookaheadValidationErrors = validateLookahead({
lookaheadStrategy: this.lookaheadStrategy,
rules: values_default(this.gastProductionsCache),
tokenTypes: values_default(this.tokensMap),
grammarName: className
});
this.definitionErrors = this.definitionErrors.concat(validationErrors, lookaheadValidationErrors);
}
});
if (isEmpty_default(this.definitionErrors)) {
if (this.recoveryEnabled) {
this.TRACE_INIT("computeAllProdsFollows", () => {
const allFollows = computeAllProdsFollows(values_default(this.gastProductionsCache));
this.resyncFollows = allFollows;
});
}
this.TRACE_INIT("ComputeLookaheadFunctions", () => {
var _a, _b;
(_b = (_a = this.lookaheadStrategy).initialize) === null || _b === void 0 ? void 0 : _b.call(_a, {
rules: values_default(this.gastProductionsCache)
});
this.preComputeLookaheadFunctions(values_default(this.gastProductionsCache));
});
}
if (!_Parser.DEFER_DEFINITION_ERRORS_HANDLING && !isEmpty_default(this.definitionErrors)) {
defErrorsMsgs = map_default(this.definitionErrors, (defError) => defError.message);
throw new Error(`Parser Definition Errors detected:
${defErrorsMsgs.join("\n-------------------------------\n")}`);
}
});
}
constructor(tokenVocabulary, config) {
this.definitionErrors = [];
this.selfAnalysisDone = false;
const that = this;
that.initErrorHandler(config);
that.initLexerAdapter();
that.initLooksAhead(config);
that.initRecognizerEngine(tokenVocabulary, config);
that.initRecoverable(config);
that.initTreeBuilder(config);
that.initContentAssist();
that.initGastRecorder(config);
that.initPerformanceTracer(config);
if (has_default(config, "ignoredIssues")) {
throw new Error("The <ignoredIssues> IParserConfig property has been deprecated.\n Please use the <IGNORE_AMBIGUITIES> flag on the relevant DSL method instead.\n See: https://chevrotain.io/docs/guide/resolving_grammar_errors.html#IGNORING_AMBIGUITIES\n For further details.");
}
this.skipValidations = has_default(config, "skipValidations") ? config.skipValidations : DEFAULT_PARSER_CONFIG.skipValidations;
}
};
Parser.DEFER_DEFINITION_ERRORS_HANDLING = false;
applyMixins(Parser, [
Recoverable,
LooksAhead,
TreeBuilder,
LexerAdapter,
RecognizerEngine,
RecognizerApi,
ErrorHandler,
ContentAssist,
GastRecorder,
PerformanceTracer
]);
var EmbeddedActionsParser = class extends Parser {
static {
__name(this, "EmbeddedActionsParser");
}
static {
__name2(this, "EmbeddedActionsParser");
}
constructor(tokenVocabulary, config = DEFAULT_PARSER_CONFIG) {
const configClone = clone_default(config);
configClone.outputCst = false;
super(tokenVocabulary, configClone);
}
};
function arrayMap2(array, iteratee) {
var index = -1, length = array == null ? 0 : array.length, result = Array(length);
while (++index < length) {
result[index] = iteratee(array[index], index, array);
}
return result;
}
__name(arrayMap2, "arrayMap2");
__name2(arrayMap2, "arrayMap");
var arrayMap_default2 = arrayMap2;
function listCacheClear2() {
this.__data__ = [];
this.size = 0;
}
__name(listCacheClear2, "listCacheClear2");
__name2(listCacheClear2, "listCacheClear");
var listCacheClear_default2 = listCacheClear2;
function eq2(value, other) {
return value === other || value !== value && other !== other;
}
__name(eq2, "eq2");
__name2(eq2, "eq");
var eq_default2 = eq2;
function assocIndexOf2(array, key) {
var length = array.length;
while (length--) {
if (eq_default2(array[length][0], key)) {
return length;
}
}
return -1;
}
__name(assocIndexOf2, "assocIndexOf2");
__name2(assocIndexOf2, "assocIndexOf");
var assocIndexOf_default2 = assocIndexOf2;
var arrayProto2 = Array.prototype;
var splice2 = arrayProto2.splice;
function listCacheDelete2(key) {
var data = this.__data__, index = assocIndexOf_default2(data, key);
if (index < 0) {
return false;
}
var lastIndex = data.length - 1;
if (index == lastIndex) {
data.pop();
} else {
splice2.call(data, index, 1);
}
--this.size;
return true;
}
__name(listCacheDelete2, "listCacheDelete2");
__name2(listCacheDelete2, "listCacheDelete");
var listCacheDelete_default2 = listCacheDelete2;
function listCacheGet2(key) {
var data = this.__data__, index = assocIndexOf_default2(data, key);
return index < 0 ? void 0 : data[index][1];
}
__name(listCacheGet2, "listCacheGet2");
__name2(listCacheGet2, "listCacheGet");
var listCacheGet_default2 = listCacheGet2;
function listCacheHas2(key) {
return assocIndexOf_default2(this.__data__, key) > -1;
}
__name(listCacheHas2, "listCacheHas2");
__name2(listCacheHas2, "listCacheHas");
var listCacheHas_default2 = listCacheHas2;
function listCacheSet2(key, value) {
var data = this.__data__, index = assocIndexOf_default2(data, key);
if (index < 0) {
++this.size;
data.push([key, value]);
} else {
data[index][1] = value;
}
return this;
}
__name(listCacheSet2, "listCacheSet2");
__name2(listCacheSet2, "listCacheSet");
var listCacheSet_default2 = listCacheSet2;
function ListCache2(entries) {
var index = -1, length = entries == null ? 0 : entries.length;
this.clear();
while (++index < length) {
var entry = entries[index];
this.set(entry[0], entry[1]);
}
}
__name(ListCache2, "ListCache2");
__name2(ListCache2, "ListCache");
ListCache2.prototype.clear = listCacheClear_default2;
ListCache2.prototype["delete"] = listCacheDelete_default2;
ListCache2.prototype.get = listCacheGet_default2;
ListCache2.prototype.has = listCacheHas_default2;
ListCache2.prototype.set = listCacheSet_default2;
var ListCache_default2 = ListCache2;
function stackClear2() {
this.__data__ = new ListCache_default2();
this.size = 0;
}
__name(stackClear2, "stackClear2");
__name2(stackClear2, "stackClear");
var stackClear_default2 = stackClear2;
function stackDelete2(key) {
var data = this.__data__, result = data["delete"](key);
this.size = data.size;
return result;
}
__name(stackDelete2, "stackDelete2");
__name2(stackDelete2, "stackDelete");
var stackDelete_default2 = stackDelete2;
function stackGet2(key) {
return this.__data__.get(key);
}
__name(stackGet2, "stackGet2");
__name2(stackGet2, "stackGet");
var stackGet_default2 = stackGet2;
function stackHas2(key) {
return this.__data__.has(key);
}
__name(stackHas2, "stackHas2");
__name2(stackHas2, "stackHas");
var stackHas_default2 = stackHas2;
var freeGlobal2 = typeof global == "object" && global && global.Object === Object && global;
var freeGlobal_default2 = freeGlobal2;
var freeSelf2 = typeof self == "object" && self && self.Object === Object && self;
var root2 = freeGlobal_default2 || freeSelf2 || Function("return this")();
var root_default2 = root2;
var Symbol3 = root_default2.Symbol;
var Symbol_default2 = Symbol3;
var objectProto21 = Object.prototype;
var hasOwnProperty18 = objectProto21.hasOwnProperty;
var nativeObjectToString3 = objectProto21.toString;
var symToStringTag3 = Symbol_default2 ? Symbol_default2.toStringTag : void 0;
function getRawTag2(value) {
var isOwn = hasOwnProperty18.call(value, symToStringTag3), tag = value[symToStringTag3];
try {
value[symToStringTag3] = void 0;
var unmasked = true;
} catch (e) {
}
var result = nativeObjectToString3.call(value);
if (unmasked) {
if (isOwn) {
value[symToStringTag3] = tag;
} else {
delete value[symToStringTag3];
}
}
return result;
}
__name(getRawTag2, "getRawTag2");
__name2(getRawTag2, "getRawTag");
var getRawTag_default2 = getRawTag2;
var objectProto22 = Object.prototype;
var nativeObjectToString4 = objectProto22.toString;
function objectToString2(value) {
return nativeObjectToString4.call(value);
}
__name(objectToString2, "objectToString2");
__name2(objectToString2, "objectToString");
var objectToString_default2 = objectToString2;
var nullTag2 = "[object Null]";
var undefinedTag2 = "[object Undefined]";
var symToStringTag4 = Symbol_default2 ? Symbol_default2.toStringTag : void 0;
function baseGetTag2(value) {
if (value == null) {
return value === void 0 ? undefinedTag2 : nullTag2;
}
return symToStringTag4 && symToStringTag4 in Object(value) ? getRawTag_default2(value) : objectToString_default2(value);
}
__name(baseGetTag2, "baseGetTag2");
__name2(baseGetTag2, "baseGetTag");
var baseGetTag_default2 = baseGetTag2;
function isObject2(value) {
var type = typeof value;
return value != null && (type == "object" || type == "function");
}
__name(isObject2, "isObject2");
__name2(isObject2, "isObject");
var isObject_default2 = isObject2;
var asyncTag2 = "[object AsyncFunction]";
var funcTag4 = "[object Function]";
var genTag3 = "[object GeneratorFunction]";
var proxyTag2 = "[object Proxy]";
function isFunction2(value) {
if (!isObject_default2(value)) {
return false;
}
var tag = baseGetTag_default2(value);
return tag == funcTag4 || tag == genTag3 || tag == asyncTag2 || tag == proxyTag2;
}
__name(isFunction2, "isFunction2");
__name2(isFunction2, "isFunction");
var isFunction_default2 = isFunction2;
var coreJsData2 = root_default2["__core-js_shared__"];
var coreJsData_default2 = coreJsData2;
var maskSrcKey2 = (function() {
var uid = /[^.]+$/.exec(coreJsData_default2 && coreJsData_default2.keys && coreJsData_default2.keys.IE_PROTO || "");
return uid ? "Symbol(src)_1." + uid : "";
})();
function isMasked2(func) {
return !!maskSrcKey2 && maskSrcKey2 in func;
}
__name(isMasked2, "isMasked2");
__name2(isMasked2, "isMasked");
var isMasked_default2 = isMasked2;
var funcProto3 = Function.prototype;
var funcToString3 = funcProto3.toString;
function toSource2(func) {
if (func != null) {
try {
return funcToString3.call(func);
} catch (e) {
}
try {
return func + "";
} catch (e) {
}
}
return "";
}
__name(toSource2, "toSource2");
__name2(toSource2, "toSource");
var toSource_default2 = toSource2;
var reRegExpChar2 = /[\\^$.*+?()[\]{}|]/g;
var reIsHostCtor2 = /^\[object .+?Constructor\]$/;
var funcProto4 = Function.prototype;
var objectProto23 = Object.prototype;
var funcToString4 = funcProto4.toString;
var hasOwnProperty19 = objectProto23.hasOwnProperty;
var reIsNative2 = RegExp(
"^" + funcToString4.call(hasOwnProperty19).replace(reRegExpChar2, "\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g, "$1.*?") + "$"
);
function baseIsNative2(value) {
if (!isObject_default2(value) || isMasked_default2(value)) {
return false;
}
var pattern = isFunction_default2(value) ? reIsNative2 : reIsHostCtor2;
return pattern.test(toSource_default2(value));
}
__name(baseIsNative2, "baseIsNative2");
__name2(baseIsNative2, "baseIsNative");
var baseIsNative_default2 = baseIsNative2;
function getValue2(object, key) {
return object == null ? void 0 : object[key];
}
__name(getValue2, "getValue2");
__name2(getValue2, "getValue");
var getValue_default2 = getValue2;
function getNative2(object, key) {
var value = getValue_default2(object, key);
return baseIsNative_default2(value) ? value : void 0;
}
__name(getNative2, "getNative2");
__name2(getNative2, "getNative");
var getNative_default2 = getNative2;
var Map3 = getNative_default2(root_default2, "Map");
var Map_default2 = Map3;
var nativeCreate2 = getNative_default2(Object, "create");
var nativeCreate_default2 = nativeCreate2;
function hashClear2() {
this.__data__ = nativeCreate_default2 ? nativeCreate_default2(null) : {};
this.size = 0;
}
__name(hashClear2, "hashClear2");
__name2(hashClear2, "hashClear");
var hashClear_default2 = hashClear2;
function hashDelete2(key) {
var result = this.has(key) && delete this.__data__[key];
this.size -= result ? 1 : 0;
return result;
}
__name(hashDelete2, "hashDelete2");
__name2(hashDelete2, "hashDelete");
var hashDelete_default2 = hashDelete2;
var HASH_UNDEFINED4 = "__lodash_hash_undefined__";
var objectProto24 = Object.prototype;
var hasOwnProperty20 = objectProto24.hasOwnProperty;
function hashGet2(key) {
var data = this.__data__;
if (nativeCreate_default2) {
var result = data[key];
return result === HASH_UNDEFINED4 ? void 0 : result;
}
return hasOwnProperty20.call(data, key) ? data[key] : void 0;
}
__name(hashGet2, "hashGet2");
__name2(hashGet2, "hashGet");
var hashGet_default2 = hashGet2;
var objectProto25 = Object.prototype;
var hasOwnProperty21 = objectProto25.hasOwnProperty;
function hashHas2(key) {
var data = this.__data__;
return nativeCreate_default2 ? data[key] !== void 0 : hasOwnProperty21.call(data, key);
}
__name(hashHas2, "hashHas2");
__name2(hashHas2, "hashHas");
var hashHas_default2 = hashHas2;
var HASH_UNDEFINED5 = "__lodash_hash_undefined__";
function hashSet2(key, value) {
var data = this.__data__;
this.size += this.has(key) ? 0 : 1;
data[key] = nativeCreate_default2 && value === void 0 ? HASH_UNDEFINED5 : value;
return this;
}
__name(hashSet2, "hashSet2");
__name2(hashSet2, "hashSet");
var hashSet_default2 = hashSet2;
function Hash2(entries) {
var index = -1, length = entries == null ? 0 : entries.length;
this.clear();
while (++index < length) {
var entry = entries[index];
this.set(entry[0], entry[1]);
}
}
__name(Hash2, "Hash2");
__name2(Hash2, "Hash");
Hash2.prototype.clear = hashClear_default2;
Hash2.prototype["delete"] = hashDelete_default2;
Hash2.prototype.get = hashGet_default2;
Hash2.prototype.has = hashHas_default2;
Hash2.prototype.set = hashSet_default2;
var Hash_default2 = Hash2;
function mapCacheClear2() {
this.size = 0;
this.__data__ = {
"hash": new Hash_default2(),
"map": new (Map_default2 || ListCache_default2)(),
"string": new Hash_default2()
};
}
__name(mapCacheClear2, "mapCacheClear2");
__name2(mapCacheClear2, "mapCacheClear");
var mapCacheClear_default2 = mapCacheClear2;
function isKeyable2(value) {
var type = typeof value;
return type == "string" || type == "number" || type == "symbol" || type == "boolean" ? value !== "__proto__" : value === null;
}
__name(isKeyable2, "isKeyable2");
__name2(isKeyable2, "isKeyable");
var isKeyable_default2 = isKeyable2;
function getMapData2(map3, key) {
var data = map3.__data__;
return isKeyable_default2(key) ? data[typeof key == "string" ? "string" : "hash"] : data.map;
}
__name(getMapData2, "getMapData2");
__name2(getMapData2, "getMapData");
var getMapData_default2 = getMapData2;
function mapCacheDelete2(key) {
var result = getMapData_default2(this, key)["delete"](key);
this.size -= result ? 1 : 0;
return result;
}
__name(mapCacheDelete2, "mapCacheDelete2");
__name2(mapCacheDelete2, "mapCacheDelete");
var mapCacheDelete_default2 = mapCacheDelete2;
function mapCacheGet2(key) {
return getMapData_default2(this, key).get(key);
}
__name(mapCacheGet2, "mapCacheGet2");
__name2(mapCacheGet2, "mapCacheGet");
var mapCacheGet_default2 = mapCacheGet2;
function mapCacheHas2(key) {
return getMapData_default2(this, key).has(key);
}
__name(mapCacheHas2, "mapCacheHas2");
__name2(mapCacheHas2, "mapCacheHas");
var mapCacheHas_default2 = mapCacheHas2;
function mapCacheSet2(key, value) {
var data = getMapData_default2(this, key), size = data.size;
data.set(key, value);
this.size += data.size == size ? 0 : 1;
return this;
}
__name(mapCacheSet2, "mapCacheSet2");
__name2(mapCacheSet2, "mapCacheSet");
var mapCacheSet_default2 = mapCacheSet2;
function MapCache2(entries) {
var index = -1, length = entries == null ? 0 : entries.length;
this.clear();
while (++index < length) {
var entry = entries[index];
this.set(entry[0], entry[1]);
}
}
__name(MapCache2, "MapCache2");
__name2(MapCache2, "MapCache");
MapCache2.prototype.clear = mapCacheClear_default2;
MapCache2.prototype["delete"] = mapCacheDelete_default2;
MapCache2.prototype.get = mapCacheGet_default2;
MapCache2.prototype.has = mapCacheHas_default2;
MapCache2.prototype.set = mapCacheSet_default2;
var MapCache_default2 = MapCache2;
var LARGE_ARRAY_SIZE4 = 200;
function stackSet2(key, value) {
var data = this.__data__;
if (data instanceof ListCache_default2) {
var pairs = data.__data__;
if (!Map_default2 || pairs.length < LARGE_ARRAY_SIZE4 - 1) {
pairs.push([key, value]);
this.size = ++data.size;
return this;
}
data = this.__data__ = new MapCache_default2(pairs);
}
data.set(key, value);
this.size = data.size;
return this;
}
__name(stackSet2, "stackSet2");
__name2(stackSet2, "stackSet");
var stackSet_default2 = stackSet2;
function Stack2(entries) {
var data = this.__data__ = new ListCache_default2(entries);
this.size = data.size;
}
__name(Stack2, "Stack2");
__name2(Stack2, "Stack");
Stack2.prototype.clear = stackClear_default2;
Stack2.prototype["delete"] = stackDelete_default2;
Stack2.prototype.get = stackGet_default2;
Stack2.prototype.has = stackHas_default2;
Stack2.prototype.set = stackSet_default2;
var Stack_default2 = Stack2;
var HASH_UNDEFINED6 = "__lodash_hash_undefined__";
function setCacheAdd2(value) {
this.__data__.set(value, HASH_UNDEFINED6);
return this;
}
__name(setCacheAdd2, "setCacheAdd2");
__name2(setCacheAdd2, "setCacheAdd");
var setCacheAdd_default2 = setCacheAdd2;
function setCacheHas2(value) {
return this.__data__.has(value);
}
__name(setCacheHas2, "setCacheHas2");
__name2(setCacheHas2, "setCacheHas");
var setCacheHas_default2 = setCacheHas2;
function SetCache2(values2) {
var index = -1, length = values2 == null ? 0 : values2.length;
this.__data__ = new MapCache_default2();
while (++index < length) {
this.add(values2[index]);
}
}
__name(SetCache2, "SetCache2");
__name2(SetCache2, "SetCache");
SetCache2.prototype.add = SetCache2.prototype.push = setCacheAdd_default2;
SetCache2.prototype.has = setCacheHas_default2;
var SetCache_default2 = SetCache2;
function arraySome2(array, predicate) {
var index = -1, length = array == null ? 0 : array.length;
while (++index < length) {
if (predicate(array[index], index, array)) {
return true;
}
}
return false;
}
__name(arraySome2, "arraySome2");
__name2(arraySome2, "arraySome");
var arraySome_default2 = arraySome2;
function cacheHas2(cache, key) {
return cache.has(key);
}
__name(cacheHas2, "cacheHas2");
__name2(cacheHas2, "cacheHas");
var cacheHas_default2 = cacheHas2;
var COMPARE_PARTIAL_FLAG7 = 1;
var COMPARE_UNORDERED_FLAG5 = 2;
function equalArrays2(array, other, bitmask, customizer, equalFunc, stack) {
var isPartial = bitmask & COMPARE_PARTIAL_FLAG7, arrLength = array.length, othLength = other.length;
if (arrLength != othLength && !(isPartial && othLength > arrLength)) {
return false;
}
var arrStacked = stack.get(array);
var othStacked = stack.get(other);
if (arrStacked && othStacked) {
return arrStacked == other && othStacked == array;
}
var index = -1, result = true, seen = bitmask & COMPARE_UNORDERED_FLAG5 ? new SetCache_default2() : void 0;
stack.set(array, other);
stack.set(other, array);
while (++index < arrLength) {
var arrValue = array[index], othValue = other[index];
if (customizer) {
var compared = isPartial ? customizer(othValue, arrValue, index, other, array, stack) : customizer(arrValue, othValue, index, array, other, stack);
}
if (compared !== void 0) {
if (compared) {
continue;
}
result = false;
break;
}
if (seen) {
if (!arraySome_default2(other, function(othValue2, othIndex) {
if (!cacheHas_default2(seen, othIndex) && (arrValue === othValue2 || equalFunc(arrValue, othValue2, bitmask, customizer, stack))) {
return seen.push(othIndex);
}
})) {
result = false;
break;
}
} else if (!(arrValue === othValue || equalFunc(arrValue, othValue, bitmask, customizer, stack))) {
result = false;
break;
}
}
stack["delete"](array);
stack["delete"](other);
return result;
}
__name(equalArrays2, "equalArrays2");
__name2(equalArrays2, "equalArrays");
var equalArrays_default2 = equalArrays2;
var Uint8Array3 = root_default2.Uint8Array;
var Uint8Array_default2 = Uint8Array3;
function mapToArray2(map3) {
var index = -1, result = Array(map3.size);
map3.forEach(function(value, key) {
result[++index] = [key, value];
});
return result;
}
__name(mapToArray2, "mapToArray2");
__name2(mapToArray2, "mapToArray");
var mapToArray_default2 = mapToArray2;
function setToArray2(set) {
var index = -1, result = Array(set.size);
set.forEach(function(value) {
result[++index] = value;
});
return result;
}
__name(setToArray2, "setToArray2");
__name2(setToArray2, "setToArray");
var setToArray_default2 = setToArray2;
var COMPARE_PARTIAL_FLAG8 = 1;
var COMPARE_UNORDERED_FLAG6 = 2;
var boolTag5 = "[object Boolean]";
var dateTag5 = "[object Date]";
var errorTag4 = "[object Error]";
var mapTag8 = "[object Map]";
var numberTag5 = "[object Number]";
var regexpTag6 = "[object RegExp]";
var setTag8 = "[object Set]";
var stringTag6 = "[object String]";
var symbolTag5 = "[object Symbol]";
var arrayBufferTag5 = "[object ArrayBuffer]";
var dataViewTag6 = "[object DataView]";
var symbolProto4 = Symbol_default2 ? Symbol_default2.prototype : void 0;
var symbolValueOf3 = symbolProto4 ? symbolProto4.valueOf : void 0;
function equalByTag2(object, other, tag, bitmask, customizer, equalFunc, stack) {
switch (tag) {
case dataViewTag6:
if (object.byteLength != other.byteLength || object.byteOffset != other.byteOffset) {
return false;
}
object = object.buffer;
other = other.buffer;
case arrayBufferTag5:
if (object.byteLength != other.byteLength || !equalFunc(new Uint8Array_default2(object), new Uint8Array_default2(other))) {
return false;
}
return true;
case boolTag5:
case dateTag5:
case numberTag5:
return eq_default2(+object, +other);
case errorTag4:
return object.name == other.name && object.message == other.message;
case regexpTag6:
case stringTag6:
return object == other + "";
case mapTag8:
var convert = mapToArray_default2;
case setTag8:
var isPartial = bitmask & COMPARE_PARTIAL_FLAG8;
convert || (convert = setToArray_default2);
if (object.size != other.size && !isPartial) {
return false;
}
var stacked = stack.get(object);
if (stacked) {
return stacked == other;
}
bitmask |= COMPARE_UNORDERED_FLAG6;
stack.set(object, other);
var result = equalArrays_default2(convert(object), convert(other), bitmask, customizer, equalFunc, stack);
stack["delete"](object);
return result;
case symbolTag5:
if (symbolValueOf3) {
return symbolValueOf3.call(object) == symbolValueOf3.call(other);
}
}
return false;
}
__name(equalByTag2, "equalByTag2");
__name2(equalByTag2, "equalByTag");
var equalByTag_default2 = equalByTag2;
function arrayPush2(array, values2) {
var index = -1, length = values2.length, offset = array.length;
while (++index < length) {
array[offset + index] = values2[index];
}
return array;
}
__name(arrayPush2, "arrayPush2");
__name2(arrayPush2, "arrayPush");
var arrayPush_default2 = arrayPush2;
var isArray2 = Array.isArray;
var isArray_default2 = isArray2;
function baseGetAllKeys2(object, keysFunc, symbolsFunc) {
var result = keysFunc(object);
return isArray_default2(object) ? result : arrayPush_default2(result, symbolsFunc(object));
}
__name(baseGetAllKeys2, "baseGetAllKeys2");
__name2(baseGetAllKeys2, "baseGetAllKeys");
var baseGetAllKeys_default2 = baseGetAllKeys2;
function arrayFilter2(array, predicate) {
var index = -1, length = array == null ? 0 : array.length, resIndex = 0, result = [];
while (++index < length) {
var value = array[index];
if (predicate(value, index, array)) {
result[resIndex++] = value;
}
}
return result;
}
__name(arrayFilter2, "arrayFilter2");
__name2(arrayFilter2, "arrayFilter");
var arrayFilter_default2 = arrayFilter2;
function stubArray2() {
return [];
}
__name(stubArray2, "stubArray2");
__name2(stubArray2, "stubArray");
var stubArray_default2 = stubArray2;
var objectProto26 = Object.prototype;
var propertyIsEnumerable3 = objectProto26.propertyIsEnumerable;
var nativeGetSymbols3 = Object.getOwnPropertySymbols;
var getSymbols2 = !nativeGetSymbols3 ? stubArray_default2 : function(object) {
if (object == null) {
return [];
}
object = Object(object);
return arrayFilter_default2(nativeGetSymbols3(object), function(symbol) {
return propertyIsEnumerable3.call(object, symbol);
});
};
var getSymbols_default2 = getSymbols2;
function baseTimes2(n, iteratee) {
var index = -1, result = Array(n);
while (++index < n) {
result[index] = iteratee(index);
}
return result;
}
__name(baseTimes2, "baseTimes2");
__name2(baseTimes2, "baseTimes");
var baseTimes_default2 = baseTimes2;
function isObjectLike2(value) {
return value != null && typeof value == "object";
}
__name(isObjectLike2, "isObjectLike2");
__name2(isObjectLike2, "isObjectLike");
var isObjectLike_default2 = isObjectLike2;
var argsTag5 = "[object Arguments]";
function baseIsArguments2(value) {
return isObjectLike_default2(value) && baseGetTag_default2(value) == argsTag5;
}
__name(baseIsArguments2, "baseIsArguments2");
__name2(baseIsArguments2, "baseIsArguments");
var baseIsArguments_default2 = baseIsArguments2;
var objectProto27 = Object.prototype;
var hasOwnProperty22 = objectProto27.hasOwnProperty;
var propertyIsEnumerable4 = objectProto27.propertyIsEnumerable;
var isArguments2 = baseIsArguments_default2(/* @__PURE__ */ (function() {
return arguments;
})()) ? baseIsArguments_default2 : function(value) {
return isObjectLike_default2(value) && hasOwnProperty22.call(value, "callee") && !propertyIsEnumerable4.call(value, "callee");
};
var isArguments_default2 = isArguments2;
function stubFalse2() {
return false;
}
__name(stubFalse2, "stubFalse2");
__name2(stubFalse2, "stubFalse");
var stubFalse_default2 = stubFalse2;
var freeExports4 = typeof exports == "object" && exports && !exports.nodeType && exports;
var freeModule4 = freeExports4 && typeof module == "object" && module && !module.nodeType && module;
var moduleExports4 = freeModule4 && freeModule4.exports === freeExports4;
var Buffer4 = moduleExports4 ? root_default2.Buffer : void 0;
var nativeIsBuffer2 = Buffer4 ? Buffer4.isBuffer : void 0;
var isBuffer2 = nativeIsBuffer2 || stubFalse_default2;
var isBuffer_default2 = isBuffer2;
var MAX_SAFE_INTEGER3 = 9007199254740991;
var reIsUint2 = /^(?:0|[1-9]\d*)$/;
function isIndex2(value, length) {
var type = typeof value;
length = length == null ? MAX_SAFE_INTEGER3 : length;
return !!length && (type == "number" || type != "symbol" && reIsUint2.test(value)) && (value > -1 && value % 1 == 0 && value < length);
}
__name(isIndex2, "isIndex2");
__name2(isIndex2, "isIndex");
var isIndex_default2 = isIndex2;
var MAX_SAFE_INTEGER4 = 9007199254740991;
function isLength2(value) {
return typeof value == "number" && value > -1 && value % 1 == 0 && value <= MAX_SAFE_INTEGER4;
}
__name(isLength2, "isLength2");
__name2(isLength2, "isLength");
var isLength_default2 = isLength2;
var argsTag6 = "[object Arguments]";
var arrayTag4 = "[object Array]";
var boolTag6 = "[object Boolean]";
var dateTag6 = "[object Date]";
var errorTag5 = "[object Error]";
var funcTag5 = "[object Function]";
var mapTag9 = "[object Map]";
var numberTag6 = "[object Number]";
var objectTag5 = "[object Object]";
var regexpTag7 = "[object RegExp]";
var setTag9 = "[object Set]";
var stringTag7 = "[object String]";
var weakMapTag4 = "[object WeakMap]";
var arrayBufferTag6 = "[object ArrayBuffer]";
var dataViewTag7 = "[object DataView]";
var float32Tag4 = "[object Float32Array]";
var float64Tag4 = "[object Float64Array]";
var int8Tag4 = "[object Int8Array]";
var int16Tag4 = "[object Int16Array]";
var int32Tag4 = "[object Int32Array]";
var uint8Tag4 = "[object Uint8Array]";
var uint8ClampedTag4 = "[object Uint8ClampedArray]";
var uint16Tag4 = "[object Uint16Array]";
var uint32Tag4 = "[object Uint32Array]";
var typedArrayTags2 = {};
typedArrayTags2[float32Tag4] = typedArrayTags2[float64Tag4] = typedArrayTags2[int8Tag4] = typedArrayTags2[int16Tag4] = typedArrayTags2[int32Tag4] = typedArrayTags2[uint8Tag4] = typedArrayTags2[uint8ClampedTag4] = typedArrayTags2[uint16Tag4] = typedArrayTags2[uint32Tag4] = true;
typedArrayTags2[argsTag6] = typedArrayTags2[arrayTag4] = typedArrayTags2[arrayBufferTag6] = typedArrayTags2[boolTag6] = typedArrayTags2[dataViewTag7] = typedArrayTags2[dateTag6] = typedArrayTags2[errorTag5] = typedArrayTags2[funcTag5] = typedArrayTags2[mapTag9] = typedArrayTags2[numberTag6] = typedArrayTags2[objectTag5] = typedArrayTags2[regexpTag7] = typedArrayTags2[setTag9] = typedArrayTags2[stringTag7] = typedArrayTags2[weakMapTag4] = false;
function baseIsTypedArray2(value) {
return isObjectLike_default2(value) && isLength_default2(value.length) && !!typedArrayTags2[baseGetTag_default2(value)];
}
__name(baseIsTypedArray2, "baseIsTypedArray2");
__name2(baseIsTypedArray2, "baseIsTypedArray");
var baseIsTypedArray_default2 = baseIsTypedArray2;
function baseUnary2(func) {
return function(value) {
return func(value);
};
}
__name(baseUnary2, "baseUnary2");
__name2(baseUnary2, "baseUnary");
var baseUnary_default2 = baseUnary2;
var freeExports5 = typeof exports == "object" && exports && !exports.nodeType && exports;
var freeModule5 = freeExports5 && typeof module == "object" && module && !module.nodeType && module;
var moduleExports5 = freeModule5 && freeModule5.exports === freeExports5;
var freeProcess2 = moduleExports5 && freeGlobal_default2.process;
var nodeUtil2 = (function() {
try {
var types = freeModule5 && freeModule5.require && freeModule5.require("util").types;
if (types) {
return types;
}
return freeProcess2 && freeProcess2.binding && freeProcess2.binding("util");
} catch (e) {
}
})();
var nodeUtil_default2 = nodeUtil2;
var nodeIsTypedArray2 = nodeUtil_default2 && nodeUtil_default2.isTypedArray;
var isTypedArray2 = nodeIsTypedArray2 ? baseUnary_default2(nodeIsTypedArray2) : baseIsTypedArray_default2;
var isTypedArray_default2 = isTypedArray2;
var objectProto28 = Object.prototype;
var hasOwnProperty23 = objectProto28.hasOwnProperty;
function arrayLikeKeys2(value, inherited) {
var isArr = isArray_default2(value), isArg = !isArr && isArguments_default2(value), isBuff = !isArr && !isArg && isBuffer_default2(value), isType2 = !isArr && !isArg && !isBuff && isTypedArray_default2(value), skipIndexes = isArr || isArg || isBuff || isType2, result = skipIndexes ? baseTimes_default2(value.length, String) : [], length = result.length;
for (var key in value) {
if ((inherited || hasOwnProperty23.call(value, key)) && !(skipIndexes && // Safari 9 has enumerable `arguments.length` in strict mode.
(key == "length" || // Node.js 0.10 has enumerable non-index properties on buffers.
isBuff && (key == "offset" || key == "parent") || // PhantomJS 2 has enumerable non-index properties on typed arrays.
isType2 && (key == "buffer" || key == "byteLength" || key == "byteOffset") || // Skip index properties.
isIndex_default2(key, length)))) {
result.push(key);
}
}
return result;
}
__name(arrayLikeKeys2, "arrayLikeKeys2");
__name2(arrayLikeKeys2, "arrayLikeKeys");
var arrayLikeKeys_default2 = arrayLikeKeys2;
var objectProto29 = Object.prototype;
function isPrototype2(value) {
var Ctor = value && value.constructor, proto = typeof Ctor == "function" && Ctor.prototype || objectProto29;
return value === proto;
}
__name(isPrototype2, "isPrototype2");
__name2(isPrototype2, "isPrototype");
var isPrototype_default2 = isPrototype2;
function overArg2(func, transform) {
return function(arg) {
return func(transform(arg));
};
}
__name(overArg2, "overArg2");
__name2(overArg2, "overArg");
var overArg_default2 = overArg2;
var nativeKeys2 = overArg_default2(Object.keys, Object);
var nativeKeys_default2 = nativeKeys2;
var objectProto30 = Object.prototype;
var hasOwnProperty24 = objectProto30.hasOwnProperty;
function baseKeys2(object) {
if (!isPrototype_default2(object)) {
return nativeKeys_default2(object);
}
var result = [];
for (var key in Object(object)) {
if (hasOwnProperty24.call(object, key) && key != "constructor") {
result.push(key);
}
}
return result;
}
__name(baseKeys2, "baseKeys2");
__name2(baseKeys2, "baseKeys");
var baseKeys_default2 = baseKeys2;
function isArrayLike2(value) {
return value != null && isLength_default2(value.length) && !isFunction_default2(value);
}
__name(isArrayLike2, "isArrayLike2");
__name2(isArrayLike2, "isArrayLike");
var isArrayLike_default2 = isArrayLike2;
function keys2(object) {
return isArrayLike_default2(object) ? arrayLikeKeys_default2(object) : baseKeys_default2(object);
}
__name(keys2, "keys2");
__name2(keys2, "keys");
var keys_default2 = keys2;
function getAllKeys2(object) {
return baseGetAllKeys_default2(object, keys_default2, getSymbols_default2);
}
__name(getAllKeys2, "getAllKeys2");
__name2(getAllKeys2, "getAllKeys");
var getAllKeys_default2 = getAllKeys2;
var COMPARE_PARTIAL_FLAG9 = 1;
var objectProto31 = Object.prototype;
var hasOwnProperty25 = objectProto31.hasOwnProperty;
function equalObjects2(object, other, bitmask, customizer, equalFunc, stack) {
var isPartial = bitmask & COMPARE_PARTIAL_FLAG9, objProps = getAllKeys_default2(object), objLength = objProps.length, othProps = getAllKeys_default2(other), othLength = othProps.length;
if (objLength != othLength && !isPartial) {
return false;
}
var index = objLength;
while (index--) {
var key = objProps[index];
if (!(isPartial ? key in other : hasOwnProperty25.call(other, key))) {
return false;
}
}
var objStacked = stack.get(object);
var othStacked = stack.get(other);
if (objStacked && othStacked) {
return objStacked == other && othStacked == object;
}
var result = true;
stack.set(object, other);
stack.set(other, object);
var skipCtor = isPartial;
while (++index < objLength) {
key = objProps[index];
var objValue = object[key], othValue = other[key];
if (customizer) {
var compared = isPartial ? customizer(othValue, objValue, key, other, object, stack) : customizer(objValue, othValue, key, object, other, stack);
}
if (!(compared === void 0 ? objValue === othValue || equalFunc(objValue, othValue, bitmask, customizer, stack) : compared)) {
result = false;
break;
}
skipCtor || (skipCtor = key == "constructor");
}
if (result && !skipCtor) {
var objCtor = object.constructor, othCtor = other.constructor;
if (objCtor != othCtor && ("constructor" in object && "constructor" in other) && !(typeof objCtor == "function" && objCtor instanceof objCtor && typeof othCtor == "function" && othCtor instanceof othCtor)) {
result = false;
}
}
stack["delete"](object);
stack["delete"](other);
return result;
}
__name(equalObjects2, "equalObjects2");
__name2(equalObjects2, "equalObjects");
var equalObjects_default2 = equalObjects2;
var DataView2 = getNative_default2(root_default2, "DataView");
var DataView_default2 = DataView2;
var Promise3 = getNative_default2(root_default2, "Promise");
var Promise_default2 = Promise3;
var Set3 = getNative_default2(root_default2, "Set");
var Set_default2 = Set3;
var WeakMap2 = getNative_default2(root_default2, "WeakMap");
var WeakMap_default2 = WeakMap2;
var mapTag10 = "[object Map]";
var objectTag6 = "[object Object]";
var promiseTag2 = "[object Promise]";
var setTag10 = "[object Set]";
var weakMapTag5 = "[object WeakMap]";
var dataViewTag8 = "[object DataView]";
var dataViewCtorString2 = toSource_default2(DataView_default2);
var mapCtorString2 = toSource_default2(Map_default2);
var promiseCtorString2 = toSource_default2(Promise_default2);
var setCtorString2 = toSource_default2(Set_default2);
var weakMapCtorString2 = toSource_default2(WeakMap_default2);
var getTag2 = baseGetTag_default2;
if (DataView_default2 && getTag2(new DataView_default2(new ArrayBuffer(1))) != dataViewTag8 || Map_default2 && getTag2(new Map_default2()) != mapTag10 || Promise_default2 && getTag2(Promise_default2.resolve()) != promiseTag2 || Set_default2 && getTag2(new Set_default2()) != setTag10 || WeakMap_default2 && getTag2(new WeakMap_default2()) != weakMapTag5) {
getTag2 = /* @__PURE__ */ __name2(function(value) {
var result = baseGetTag_default2(value), Ctor = result == objectTag6 ? value.constructor : void 0, ctorString = Ctor ? toSource_default2(Ctor) : "";
if (ctorString) {
switch (ctorString) {
case dataViewCtorString2:
return dataViewTag8;
case mapCtorString2:
return mapTag10;
case promiseCtorString2:
return promiseTag2;
case setCtorString2:
return setTag10;
case weakMapCtorString2:
return weakMapTag5;
}
}
return result;
}, "getTag");
}
var getTag_default2 = getTag2;
var COMPARE_PARTIAL_FLAG10 = 1;
var argsTag7 = "[object Arguments]";
var arrayTag5 = "[object Array]";
var objectTag7 = "[object Object]";
var objectProto32 = Object.prototype;
var hasOwnProperty26 = objectProto32.hasOwnProperty;
function baseIsEqualDeep2(object, other, bitmask, customizer, equalFunc, stack) {
var objIsArr = isArray_default2(object), othIsArr = isArray_default2(other), objTag = objIsArr ? arrayTag5 : getTag_default2(object), othTag = othIsArr ? arrayTag5 : getTag_default2(other);
objTag = objTag == argsTag7 ? objectTag7 : objTag;
othTag = othTag == argsTag7 ? objectTag7 : othTag;
var objIsObj = objTag == objectTag7, othIsObj = othTag == objectTag7, isSameTag = objTag == othTag;
if (isSameTag && isBuffer_default2(object)) {
if (!isBuffer_default2(other)) {
return false;
}
objIsArr = true;
objIsObj = false;
}
if (isSameTag && !objIsObj) {
stack || (stack = new Stack_default2());
return objIsArr || isTypedArray_default2(object) ? equalArrays_default2(object, other, bitmask, customizer, equalFunc, stack) : equalByTag_default2(object, other, objTag, bitmask, customizer, equalFunc, stack);
}
if (!(bitmask & COMPARE_PARTIAL_FLAG10)) {
var objIsWrapped = objIsObj && hasOwnProperty26.call(object, "__wrapped__"), othIsWrapped = othIsObj && hasOwnProperty26.call(other, "__wrapped__");
if (objIsWrapped || othIsWrapped) {
var objUnwrapped = objIsWrapped ? object.value() : object, othUnwrapped = othIsWrapped ? other.value() : other;
stack || (stack = new Stack_default2());
return equalFunc(objUnwrapped, othUnwrapped, bitmask, customizer, stack);
}
}
if (!isSameTag) {
return false;
}
stack || (stack = new Stack_default2());
return equalObjects_default2(object, other, bitmask, customizer, equalFunc, stack);
}
__name(baseIsEqualDeep2, "baseIsEqualDeep2");
__name2(baseIsEqualDeep2, "baseIsEqualDeep");
var baseIsEqualDeep_default2 = baseIsEqualDeep2;
function baseIsEqual2(value, other, bitmask, customizer, stack) {
if (value === other) {
return true;
}
if (value == null || other == null || !isObjectLike_default2(value) && !isObjectLike_default2(other)) {
return value !== value && other !== other;
}
return baseIsEqualDeep_default2(value, other, bitmask, customizer, baseIsEqual2, stack);
}
__name(baseIsEqual2, "baseIsEqual2");
__name2(baseIsEqual2, "baseIsEqual");
var baseIsEqual_default2 = baseIsEqual2;
var COMPARE_PARTIAL_FLAG11 = 1;
var COMPARE_UNORDERED_FLAG7 = 2;
function baseIsMatch2(object, source, matchData, customizer) {
var index = matchData.length, length = index, noCustomizer = !customizer;
if (object == null) {
return !length;
}
object = Object(object);
while (index--) {
var data = matchData[index];
if (noCustomizer && data[2] ? data[1] !== object[data[0]] : !(data[0] in object)) {
return false;
}
}
while (++index < length) {
data = matchData[index];
var key = data[0], objValue = object[key], srcValue = data[1];
if (noCustomizer && data[2]) {
if (objValue === void 0 && !(key in object)) {
return false;
}
} else {
var stack = new Stack_default2();
if (customizer) {
var result = customizer(objValue, srcValue, key, object, source, stack);
}
if (!(result === void 0 ? baseIsEqual_default2(srcValue, objValue, COMPARE_PARTIAL_FLAG11 | COMPARE_UNORDERED_FLAG7, customizer, stack) : result)) {
return false;
}
}
}
return true;
}
__name(baseIsMatch2, "baseIsMatch2");
__name2(baseIsMatch2, "baseIsMatch");
var baseIsMatch_default2 = baseIsMatch2;
function isStrictComparable2(value) {
return value === value && !isObject_default2(value);
}
__name(isStrictComparable2, "isStrictComparable2");
__name2(isStrictComparable2, "isStrictComparable");
var isStrictComparable_default2 = isStrictComparable2;
function getMatchData2(object) {
var result = keys_default2(object), length = result.length;
while (length--) {
var key = result[length], value = object[key];
result[length] = [key, value, isStrictComparable_default2(value)];
}
return result;
}
__name(getMatchData2, "getMatchData2");
__name2(getMatchData2, "getMatchData");
var getMatchData_default2 = getMatchData2;
function matchesStrictComparable2(key, srcValue) {
return function(object) {
if (object == null) {
return false;
}
return object[key] === srcValue && (srcValue !== void 0 || key in Object(object));
};
}
__name(matchesStrictComparable2, "matchesStrictComparable2");
__name2(matchesStrictComparable2, "matchesStrictComparable");
var matchesStrictComparable_default2 = matchesStrictComparable2;
function baseMatches2(source) {
var matchData = getMatchData_default2(source);
if (matchData.length == 1 && matchData[0][2]) {
return matchesStrictComparable_default2(matchData[0][0], matchData[0][1]);
}
return function(object) {
return object === source || baseIsMatch_default2(object, source, matchData);
};
}
__name(baseMatches2, "baseMatches2");
__name2(baseMatches2, "baseMatches");
var baseMatches_default2 = baseMatches2;
var symbolTag6 = "[object Symbol]";
function isSymbol2(value) {
return typeof value == "symbol" || isObjectLike_default2(value) && baseGetTag_default2(value) == symbolTag6;
}
__name(isSymbol2, "isSymbol2");
__name2(isSymbol2, "isSymbol");
var isSymbol_default2 = isSymbol2;
var reIsDeepProp2 = /\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\\]|\\.)*?\1)\]/;
var reIsPlainProp2 = /^\w*$/;
function isKey2(value, object) {
if (isArray_default2(value)) {
return false;
}
var type = typeof value;
if (type == "number" || type == "symbol" || type == "boolean" || value == null || isSymbol_default2(value)) {
return true;
}
return reIsPlainProp2.test(value) || !reIsDeepProp2.test(value) || object != null && value in Object(object);
}
__name(isKey2, "isKey2");
__name2(isKey2, "isKey");
var isKey_default2 = isKey2;
var FUNC_ERROR_TEXT3 = "Expected a function";
function memoize2(func, resolver) {
if (typeof func != "function" || resolver != null && typeof resolver != "function") {
throw new TypeError(FUNC_ERROR_TEXT3);
}
var memoized = /* @__PURE__ */ __name2(function() {
var args = arguments, key = resolver ? resolver.apply(this, args) : args[0], cache = memoized.cache;
if (cache.has(key)) {
return cache.get(key);
}
var result = func.apply(this, args);
memoized.cache = cache.set(key, result) || cache;
return result;
}, "memoized");
memoized.cache = new (memoize2.Cache || MapCache_default2)();
return memoized;
}
__name(memoize2, "memoize2");
__name2(memoize2, "memoize");
memoize2.Cache = MapCache_default2;
var memoize_default2 = memoize2;
var MAX_MEMOIZE_SIZE2 = 500;
function memoizeCapped2(func) {
var result = memoize_default2(func, function(key) {
if (cache.size === MAX_MEMOIZE_SIZE2) {
cache.clear();
}
return key;
});
var cache = result.cache;
return result;
}
__name(memoizeCapped2, "memoizeCapped2");
__name2(memoizeCapped2, "memoizeCapped");
var memoizeCapped_default2 = memoizeCapped2;
var rePropName2 = /[^.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|$))/g;
var reEscapeChar2 = /\\(\\)?/g;
var stringToPath2 = memoizeCapped_default2(function(string) {
var result = [];
if (string.charCodeAt(0) === 46) {
result.push("");
}
string.replace(rePropName2, function(match, number, quote, subString) {
result.push(quote ? subString.replace(reEscapeChar2, "$1") : number || match);
});
return result;
});
var stringToPath_default2 = stringToPath2;
var INFINITY5 = 1 / 0;
var symbolProto5 = Symbol_default2 ? Symbol_default2.prototype : void 0;
var symbolToString2 = symbolProto5 ? symbolProto5.toString : void 0;
function baseToString2(value) {
if (typeof value == "string") {
return value;
}
if (isArray_default2(value)) {
return arrayMap_default2(value, baseToString2) + "";
}
if (isSymbol_default2(value)) {
return symbolToString2 ? symbolToString2.call(value) : "";
}
var result = value + "";
return result == "0" && 1 / value == -INFINITY5 ? "-0" : result;
}
__name(baseToString2, "baseToString2");
__name2(baseToString2, "baseToString");
var baseToString_default2 = baseToString2;
function toString3(value) {
return value == null ? "" : baseToString_default2(value);
}
__name(toString3, "toString3");
__name2(toString3, "toString");
var toString_default2 = toString3;
function castPath2(value, object) {
if (isArray_default2(value)) {
return value;
}
return isKey_default2(value, object) ? [value] : stringToPath_default2(toString_default2(value));
}
__name(castPath2, "castPath2");
__name2(castPath2, "castPath");
var castPath_default2 = castPath2;
var INFINITY6 = 1 / 0;
function toKey2(value) {
if (typeof value == "string" || isSymbol_default2(value)) {
return value;
}
var result = value + "";
return result == "0" && 1 / value == -INFINITY6 ? "-0" : result;
}
__name(toKey2, "toKey2");
__name2(toKey2, "toKey");
var toKey_default2 = toKey2;
function baseGet2(object, path) {
path = castPath_default2(path, object);
var index = 0, length = path.length;
while (object != null && index < length) {
object = object[toKey_default2(path[index++])];
}
return index && index == length ? object : void 0;
}
__name(baseGet2, "baseGet2");
__name2(baseGet2, "baseGet");
var baseGet_default2 = baseGet2;
function get2(object, path, defaultValue) {
var result = object == null ? void 0 : baseGet_default2(object, path);
return result === void 0 ? defaultValue : result;
}
__name(get2, "get2");
__name2(get2, "get");
var get_default2 = get2;
function baseHasIn2(object, key) {
return object != null && key in Object(object);
}
__name(baseHasIn2, "baseHasIn2");
__name2(baseHasIn2, "baseHasIn");
var baseHasIn_default2 = baseHasIn2;
function hasPath2(object, path, hasFunc) {
path = castPath_default2(path, object);
var index = -1, length = path.length, result = false;
while (++index < length) {
var key = toKey_default2(path[index]);
if (!(result = object != null && hasFunc(object, key))) {
break;
}
object = object[key];
}
if (result || ++index != length) {
return result;
}
length = object == null ? 0 : object.length;
return !!length && isLength_default2(length) && isIndex_default2(key, length) && (isArray_default2(object) || isArguments_default2(object));
}
__name(hasPath2, "hasPath2");
__name2(hasPath2, "hasPath");
var hasPath_default2 = hasPath2;
function hasIn2(object, path) {
return object != null && hasPath_default2(object, path, baseHasIn_default2);
}
__name(hasIn2, "hasIn2");
__name2(hasIn2, "hasIn");
var hasIn_default2 = hasIn2;
var COMPARE_PARTIAL_FLAG12 = 1;
var COMPARE_UNORDERED_FLAG8 = 2;
function baseMatchesProperty2(path, srcValue) {
if (isKey_default2(path) && isStrictComparable_default2(srcValue)) {
return matchesStrictComparable_default2(toKey_default2(path), srcValue);
}
return function(object) {
var objValue = get_default2(object, path);
return objValue === void 0 && objValue === srcValue ? hasIn_default2(object, path) : baseIsEqual_default2(srcValue, objValue, COMPARE_PARTIAL_FLAG12 | COMPARE_UNORDERED_FLAG8);
};
}
__name(baseMatchesProperty2, "baseMatchesProperty2");
__name2(baseMatchesProperty2, "baseMatchesProperty");
var baseMatchesProperty_default2 = baseMatchesProperty2;
function identity2(value) {
return value;
}
__name(identity2, "identity2");
__name2(identity2, "identity");
var identity_default2 = identity2;
function baseProperty2(key) {
return function(object) {
return object == null ? void 0 : object[key];
};
}
__name(baseProperty2, "baseProperty2");
__name2(baseProperty2, "baseProperty");
var baseProperty_default2 = baseProperty2;
function basePropertyDeep2(path) {
return function(object) {
return baseGet_default2(object, path);
};
}
__name(basePropertyDeep2, "basePropertyDeep2");
__name2(basePropertyDeep2, "basePropertyDeep");
var basePropertyDeep_default2 = basePropertyDeep2;
function property2(path) {
return isKey_default2(path) ? baseProperty_default2(toKey_default2(path)) : basePropertyDeep_default2(path);
}
__name(property2, "property2");
__name2(property2, "property");
var property_default2 = property2;
function baseIteratee2(value) {
if (typeof value == "function") {
return value;
}
if (value == null) {
return identity_default2;
}
if (typeof value == "object") {
return isArray_default2(value) ? baseMatchesProperty_default2(value[0], value[1]) : baseMatches_default2(value);
}
return property_default2(value);
}
__name(baseIteratee2, "baseIteratee2");
__name2(baseIteratee2, "baseIteratee");
var baseIteratee_default2 = baseIteratee2;
function createBaseFor2(fromRight) {
return function(object, iteratee, keysFunc) {
var index = -1, iterable = Object(object), props = keysFunc(object), length = props.length;
while (length--) {
var key = props[fromRight ? length : ++index];
if (iteratee(iterable[key], key, iterable) === false) {
break;
}
}
return object;
};
}
__name(createBaseFor2, "createBaseFor2");
__name2(createBaseFor2, "createBaseFor");
var createBaseFor_default2 = createBaseFor2;
var baseFor2 = createBaseFor_default2();
var baseFor_default2 = baseFor2;
function baseForOwn2(object, iteratee) {
return object && baseFor_default2(object, iteratee, keys_default2);
}
__name(baseForOwn2, "baseForOwn2");
__name2(baseForOwn2, "baseForOwn");
var baseForOwn_default2 = baseForOwn2;
function createBaseEach2(eachFunc, fromRight) {
return function(collection, iteratee) {
if (collection == null) {
return collection;
}
if (!isArrayLike_default2(collection)) {
return eachFunc(collection, iteratee);
}
var length = collection.length, index = fromRight ? length : -1, iterable = Object(collection);
while (fromRight ? index-- : ++index < length) {
if (iteratee(iterable[index], index, iterable) === false) {
break;
}
}
return collection;
};
}
__name(createBaseEach2, "createBaseEach2");
__name2(createBaseEach2, "createBaseEach");
var createBaseEach_default2 = createBaseEach2;
var baseEach2 = createBaseEach_default2(baseForOwn_default2);
var baseEach_default2 = baseEach2;
function baseMap2(collection, iteratee) {
var index = -1, result = isArrayLike_default2(collection) ? Array(collection.length) : [];
baseEach_default2(collection, function(value, key, collection2) {
result[++index] = iteratee(value, key, collection2);
});
return result;
}
__name(baseMap2, "baseMap2");
__name2(baseMap2, "baseMap");
var baseMap_default2 = baseMap2;
function map2(collection, iteratee) {
var func = isArray_default2(collection) ? arrayMap_default2 : baseMap_default2;
return func(collection, baseIteratee_default2(iteratee, 3));
}
__name(map2, "map2");
__name2(map2, "map");
var map_default2 = map2;
function baseFilter2(collection, predicate) {
var result = [];
baseEach_default2(collection, function(value, index, collection2) {
if (predicate(value, index, collection2)) {
result.push(value);
}
});
return result;
}
__name(baseFilter2, "baseFilter2");
__name2(baseFilter2, "baseFilter");
var baseFilter_default2 = baseFilter2;
function filter2(collection, predicate) {
var func = isArray_default2(collection) ? arrayFilter_default2 : baseFilter_default2;
return func(collection, baseIteratee_default2(predicate, 3));
}
__name(filter2, "filter2");
__name2(filter2, "filter");
var filter_default2 = filter2;
function buildATNKey(rule, type, occurrence) {
return `${rule.name}_${type}_${occurrence}`;
}
__name(buildATNKey, "buildATNKey");
__name2(buildATNKey, "buildATNKey");
var ATN_BASIC = 1;
var ATN_RULE_START = 2;
var ATN_PLUS_BLOCK_START = 4;
var ATN_STAR_BLOCK_START = 5;
var ATN_RULE_STOP = 7;
var ATN_BLOCK_END = 8;
var ATN_STAR_LOOP_BACK = 9;
var ATN_STAR_LOOP_ENTRY = 10;
var ATN_PLUS_LOOP_BACK = 11;
var ATN_LOOP_END = 12;
var AbstractTransition = class {
static {
__name(this, "AbstractTransition");
}
static {
__name2(this, "AbstractTransition");
}
constructor(target) {
this.target = target;
}
isEpsilon() {
return false;
}
};
var AtomTransition = class extends AbstractTransition {
static {
__name(this, "AtomTransition");
}
static {
__name2(this, "AtomTransition");
}
constructor(target, tokenType) {
super(target);
this.tokenType = tokenType;
}
};
var EpsilonTransition = class extends AbstractTransition {
static {
__name(this, "EpsilonTransition");
}
static {
__name2(this, "EpsilonTransition");
}
constructor(target) {
super(target);
}
isEpsilon() {
return true;
}
};
var RuleTransition = class extends AbstractTransition {
static {
__name(this, "RuleTransition");
}
static {
__name2(this, "RuleTransition");
}
constructor(ruleStart, rule, followState) {
super(ruleStart);
this.rule = rule;
this.followState = followState;
}
isEpsilon() {
return true;
}
};
function createATN(rules) {
const atn = {
decisionMap: {},
decisionStates: [],
ruleToStartState: /* @__PURE__ */ new Map(),
ruleToStopState: /* @__PURE__ */ new Map(),
states: []
};
createRuleStartAndStopATNStates(atn, rules);
const ruleLength = rules.length;
for (let i = 0; i < ruleLength; i++) {
const rule = rules[i];
const ruleBlock = block(atn, rule, rule);
if (ruleBlock === void 0) {
continue;
}
buildRuleHandle(atn, rule, ruleBlock);
}
return atn;
}
__name(createATN, "createATN");
__name2(createATN, "createATN");
function createRuleStartAndStopATNStates(atn, rules) {
const ruleLength = rules.length;
for (let i = 0; i < ruleLength; i++) {
const rule = rules[i];
const start = newState(atn, rule, void 0, {
type: ATN_RULE_START
});
const stop = newState(atn, rule, void 0, {
type: ATN_RULE_STOP
});
start.stop = stop;
atn.ruleToStartState.set(rule, start);
atn.ruleToStopState.set(rule, stop);
}
}
__name(createRuleStartAndStopATNStates, "createRuleStartAndStopATNStates");
__name2(createRuleStartAndStopATNStates, "createRuleStartAndStopATNStates");
function atom(atn, rule, production) {
if (production instanceof Terminal) {
return tokenRef(atn, rule, production.terminalType, production);
} else if (production instanceof NonTerminal) {
return ruleRef(atn, rule, production);
} else if (production instanceof Alternation) {
return alternation(atn, rule, production);
} else if (production instanceof Option) {
return option(atn, rule, production);
} else if (production instanceof Repetition) {
return repetition(atn, rule, production);
} else if (production instanceof RepetitionWithSeparator) {
return repetitionSep(atn, rule, production);
} else if (production instanceof RepetitionMandatory) {
return repetitionMandatory(atn, rule, production);
} else if (production instanceof RepetitionMandatoryWithSeparator) {
return repetitionMandatorySep(atn, rule, production);
} else {
return block(atn, rule, production);
}
}
__name(atom, "atom");
__name2(atom, "atom");
function repetition(atn, rule, repetition2) {
const starState = newState(atn, rule, repetition2, {
type: ATN_STAR_BLOCK_START
});
defineDecisionState(atn, starState);
const handle = makeAlts(atn, rule, starState, repetition2, block(atn, rule, repetition2));
return star(atn, rule, repetition2, handle);
}
__name(repetition, "repetition");
__name2(repetition, "repetition");
function repetitionSep(atn, rule, repetition2) {
const starState = newState(atn, rule, repetition2, {
type: ATN_STAR_BLOCK_START
});
defineDecisionState(atn, starState);
const handle = makeAlts(atn, rule, starState, repetition2, block(atn, rule, repetition2));
const sep = tokenRef(atn, rule, repetition2.separator, repetition2);
return star(atn, rule, repetition2, handle, sep);
}
__name(repetitionSep, "repetitionSep");
__name2(repetitionSep, "repetitionSep");
function repetitionMandatory(atn, rule, repetition2) {
const plusState = newState(atn, rule, repetition2, {
type: ATN_PLUS_BLOCK_START
});
defineDecisionState(atn, plusState);
const handle = makeAlts(atn, rule, plusState, repetition2, block(atn, rule, repetition2));
return plus(atn, rule, repetition2, handle);
}
__name(repetitionMandatory, "repetitionMandatory");
__name2(repetitionMandatory, "repetitionMandatory");
function repetitionMandatorySep(atn, rule, repetition2) {
const plusState = newState(atn, rule, repetition2, {
type: ATN_PLUS_BLOCK_START
});
defineDecisionState(atn, plusState);
const handle = makeAlts(atn, rule, plusState, repetition2, block(atn, rule, repetition2));
const sep = tokenRef(atn, rule, repetition2.separator, repetition2);
return plus(atn, rule, repetition2, handle, sep);
}
__name(repetitionMandatorySep, "repetitionMandatorySep");
__name2(repetitionMandatorySep, "repetitionMandatorySep");
function alternation(atn, rule, alternation2) {
const start = newState(atn, rule, alternation2, {
type: ATN_BASIC
});
defineDecisionState(atn, start);
const alts = map_default2(alternation2.definition, (e) => atom(atn, rule, e));
const handle = makeAlts(atn, rule, start, alternation2, ...alts);
return handle;
}
__name(alternation, "alternation");
__name2(alternation, "alternation");
function option(atn, rule, option2) {
const start = newState(atn, rule, option2, {
type: ATN_BASIC
});
defineDecisionState(atn, start);
const handle = makeAlts(atn, rule, start, option2, block(atn, rule, option2));
return optional(atn, rule, option2, handle);
}
__name(option, "option");
__name2(option, "option");
function block(atn, rule, block2) {
const handles = filter_default2(map_default2(block2.definition, (e) => atom(atn, rule, e)), (e) => e !== void 0);
if (handles.length === 1) {
return handles[0];
} else if (handles.length === 0) {
return void 0;
} else {
return makeBlock(atn, handles);
}
}
__name(block, "block");
__name2(block, "block");
function plus(atn, rule, plus2, handle, sep) {
const blkStart = handle.left;
const blkEnd = handle.right;
const loop = newState(atn, rule, plus2, {
type: ATN_PLUS_LOOP_BACK
});
defineDecisionState(atn, loop);
const end = newState(atn, rule, plus2, {
type: ATN_LOOP_END
});
blkStart.loopback = loop;
end.loopback = loop;
atn.decisionMap[buildATNKey(rule, sep ? "RepetitionMandatoryWithSeparator" : "RepetitionMandatory", plus2.idx)] = loop;
epsilon(blkEnd, loop);
if (sep === void 0) {
epsilon(loop, blkStart);
epsilon(loop, end);
} else {
epsilon(loop, end);
epsilon(loop, sep.left);
epsilon(sep.right, blkStart);
}
return {
left: blkStart,
right: end
};
}
__name(plus, "plus");
__name2(plus, "plus");
function star(atn, rule, star2, handle, sep) {
const start = handle.left;
const end = handle.right;
const entry = newState(atn, rule, star2, {
type: ATN_STAR_LOOP_ENTRY
});
defineDecisionState(atn, entry);
const loopEnd = newState(atn, rule, star2, {
type: ATN_LOOP_END
});
const loop = newState(atn, rule, star2, {
type: ATN_STAR_LOOP_BACK
});
entry.loopback = loop;
loopEnd.loopback = loop;
epsilon(entry, start);
epsilon(entry, loopEnd);
epsilon(end, loop);
if (sep !== void 0) {
epsilon(loop, loopEnd);
epsilon(loop, sep.left);
epsilon(sep.right, start);
} else {
epsilon(loop, entry);
}
atn.decisionMap[buildATNKey(rule, sep ? "RepetitionWithSeparator" : "Repetition", star2.idx)] = entry;
return {
left: entry,
right: loopEnd
};
}
__name(star, "star");
__name2(star, "star");
function optional(atn, rule, optional2, handle) {
const start = handle.left;
const end = handle.right;
epsilon(start, end);
atn.decisionMap[buildATNKey(rule, "Option", optional2.idx)] = start;
return handle;
}
__name(optional, "optional");
__name2(optional, "optional");
function defineDecisionState(atn, state) {
atn.decisionStates.push(state);
state.decision = atn.decisionStates.length - 1;
return state.decision;
}
__name(defineDecisionState, "defineDecisionState");
__name2(defineDecisionState, "defineDecisionState");
function makeAlts(atn, rule, start, production, ...alts) {
const end = newState(atn, rule, production, {
type: ATN_BLOCK_END,
start
});
start.end = end;
for (const alt of alts) {
if (alt !== void 0) {
epsilon(start, alt.left);
epsilon(alt.right, end);
} else {
epsilon(start, end);
}
}
const handle = {
left: start,
right: end
};
atn.decisionMap[buildATNKey(rule, getProdType2(production), production.idx)] = start;
return handle;
}
__name(makeAlts, "makeAlts");
__name2(makeAlts, "makeAlts");
function getProdType2(production) {
if (production instanceof Alternation) {
return "Alternation";
} else if (production instanceof Option) {
return "Option";
} else if (production instanceof Repetition) {
return "Repetition";
} else if (production instanceof RepetitionWithSeparator) {
return "RepetitionWithSeparator";
} else if (production instanceof RepetitionMandatory) {
return "RepetitionMandatory";
} else if (production instanceof RepetitionMandatoryWithSeparator) {
return "RepetitionMandatoryWithSeparator";
} else {
throw new Error("Invalid production type encountered");
}
}
__name(getProdType2, "getProdType2");
__name2(getProdType2, "getProdType");
function makeBlock(atn, alts) {
const altsLength = alts.length;
for (let i = 0; i < altsLength - 1; i++) {
const handle = alts[i];
let transition;
if (handle.left.transitions.length === 1) {
transition = handle.left.transitions[0];
}
const isRuleTransition = transition instanceof RuleTransition;
const ruleTransition = transition;
const next = alts[i + 1].left;
if (handle.left.type === ATN_BASIC && handle.right.type === ATN_BASIC && transition !== void 0 && (isRuleTransition && ruleTransition.followState === handle.right || transition.target === handle.right)) {
if (isRuleTransition) {
ruleTransition.followState = next;
} else {
transition.target = next;
}
removeState(atn, handle.right);
} else {
epsilon(handle.right, next);
}
}
const first2 = alts[0];
const last2 = alts[altsLength - 1];
return {
left: first2.left,
right: last2.right
};
}
__name(makeBlock, "makeBlock");
__name2(makeBlock, "makeBlock");
function tokenRef(atn, rule, tokenType, production) {
const left = newState(atn, rule, production, {
type: ATN_BASIC
});
const right = newState(atn, rule, production, {
type: ATN_BASIC
});
addTransition(left, new AtomTransition(right, tokenType));
return {
left,
right
};
}
__name(tokenRef, "tokenRef");
__name2(tokenRef, "tokenRef");
function ruleRef(atn, currentRule, nonTerminal) {
const rule = nonTerminal.referencedRule;
const start = atn.ruleToStartState.get(rule);
const left = newState(atn, currentRule, nonTerminal, {
type: ATN_BASIC
});
const right = newState(atn, currentRule, nonTerminal, {
type: ATN_BASIC
});
const call = new RuleTransition(start, rule, right);
addTransition(left, call);
return {
left,
right
};
}
__name(ruleRef, "ruleRef");
__name2(ruleRef, "ruleRef");
function buildRuleHandle(atn, rule, block2) {
const start = atn.ruleToStartState.get(rule);
epsilon(start, block2.left);
const stop = atn.ruleToStopState.get(rule);
epsilon(block2.right, stop);
const handle = {
left: start,
right: stop
};
return handle;
}
__name(buildRuleHandle, "buildRuleHandle");
__name2(buildRuleHandle, "buildRuleHandle");
function epsilon(a, b) {
const transition = new EpsilonTransition(b);
addTransition(a, transition);
}
__name(epsilon, "epsilon");
__name2(epsilon, "epsilon");
function newState(atn, rule, production, partial) {
const t = Object.assign({
atn,
production,
epsilonOnlyTransitions: false,
rule,
transitions: [],
nextTokenWithinRule: [],
stateNumber: atn.states.length
}, partial);
atn.states.push(t);
return t;
}
__name(newState, "newState");
__name2(newState, "newState");
function addTransition(state, transition) {
if (state.transitions.length === 0) {
state.epsilonOnlyTransitions = transition.isEpsilon();
}
state.transitions.push(transition);
}
__name(addTransition, "addTransition");
__name2(addTransition, "addTransition");
function removeState(atn, state) {
atn.states.splice(atn.states.indexOf(state), 1);
}
__name(removeState, "removeState");
__name2(removeState, "removeState");
var DFA_ERROR = {};
var ATNConfigSet = class {
static {
__name(this, "ATNConfigSet");
}
static {
__name2(this, "ATNConfigSet");
}
constructor() {
this.map = {};
this.configs = [];
}
get size() {
return this.configs.length;
}
finalize() {
this.map = {};
}
add(config) {
const key = getATNConfigKey(config);
if (!(key in this.map)) {
this.map[key] = this.configs.length;
this.configs.push(config);
}
}
get elements() {
return this.configs;
}
get alts() {
return map_default2(this.configs, (e) => e.alt);
}
get key() {
let value = "";
for (const k in this.map) {
value += k + ":";
}
return value;
}
};
function getATNConfigKey(config, alt = true) {
return `${alt ? `a${config.alt}` : ""}s${config.state.stateNumber}:${config.stack.map((e) => e.stateNumber.toString()).join("_")}`;
}
__name(getATNConfigKey, "getATNConfigKey");
__name2(getATNConfigKey, "getATNConfigKey");
function baseExtremum(array, iteratee, comparator) {
var index = -1, length = array.length;
while (++index < length) {
var value = array[index], current = iteratee(value);
if (current != null && (computed === void 0 ? current === current && !isSymbol_default2(current) : comparator(current, computed))) {
var computed = current, result = value;
}
}
return result;
}
__name(baseExtremum, "baseExtremum");
__name2(baseExtremum, "baseExtremum");
var baseExtremum_default = baseExtremum;
function baseLt(value, other) {
return value < other;
}
__name(baseLt, "baseLt");
__name2(baseLt, "baseLt");
var baseLt_default = baseLt;
function min(array) {
return array && array.length ? baseExtremum_default(array, identity_default2, baseLt_default) : void 0;
}
__name(min, "min");
__name2(min, "min");
var min_default = min;
var spreadableSymbol2 = Symbol_default2 ? Symbol_default2.isConcatSpreadable : void 0;
function isFlattenable2(value) {
return isArray_default2(value) || isArguments_default2(value) || !!(spreadableSymbol2 && value && value[spreadableSymbol2]);
}
__name(isFlattenable2, "isFlattenable2");
__name2(isFlattenable2, "isFlattenable");
var isFlattenable_default2 = isFlattenable2;
function baseFlatten2(array, depth, predicate, isStrict, result) {
var index = -1, length = array.length;
predicate || (predicate = isFlattenable_default2);
result || (result = []);
while (++index < length) {
var value = array[index];
if (depth > 0 && predicate(value)) {
if (depth > 1) {
baseFlatten2(value, depth - 1, predicate, isStrict, result);
} else {
arrayPush_default2(result, value);
}
} else if (!isStrict) {
result[result.length] = value;
}
}
return result;
}
__name(baseFlatten2, "baseFlatten2");
__name2(baseFlatten2, "baseFlatten");
var baseFlatten_default2 = baseFlatten2;
function flatMap2(collection, iteratee) {
return baseFlatten_default2(map_default2(collection, iteratee), 1);
}
__name(flatMap2, "flatMap2");
__name2(flatMap2, "flatMap");
var flatMap_default2 = flatMap2;
function baseFindIndex2(array, predicate, fromIndex, fromRight) {
var length = array.length, index = fromIndex + (fromRight ? 1 : -1);
while (fromRight ? index-- : ++index < length) {
if (predicate(array[index], index, array)) {
return index;
}
}
return -1;
}
__name(baseFindIndex2, "baseFindIndex2");
__name2(baseFindIndex2, "baseFindIndex");
var baseFindIndex_default2 = baseFindIndex2;
function baseIsNaN2(value) {
return value !== value;
}
__name(baseIsNaN2, "baseIsNaN2");
__name2(baseIsNaN2, "baseIsNaN");
var baseIsNaN_default2 = baseIsNaN2;
function strictIndexOf2(array, value, fromIndex) {
var index = fromIndex - 1, length = array.length;
while (++index < length) {
if (array[index] === value) {
return index;
}
}
return -1;
}
__name(strictIndexOf2, "strictIndexOf2");
__name2(strictIndexOf2, "strictIndexOf");
var strictIndexOf_default2 = strictIndexOf2;
function baseIndexOf2(array, value, fromIndex) {
return value === value ? strictIndexOf_default2(array, value, fromIndex) : baseFindIndex_default2(array, baseIsNaN_default2, fromIndex);
}
__name(baseIndexOf2, "baseIndexOf2");
__name2(baseIndexOf2, "baseIndexOf");
var baseIndexOf_default2 = baseIndexOf2;
function arrayIncludes2(array, value) {
var length = array == null ? 0 : array.length;
return !!length && baseIndexOf_default2(array, value, 0) > -1;
}
__name(arrayIncludes2, "arrayIncludes2");
__name2(arrayIncludes2, "arrayIncludes");
var arrayIncludes_default2 = arrayIncludes2;
function arrayIncludesWith2(array, value, comparator) {
var index = -1, length = array == null ? 0 : array.length;
while (++index < length) {
if (comparator(value, array[index])) {
return true;
}
}
return false;
}
__name(arrayIncludesWith2, "arrayIncludesWith2");
__name2(arrayIncludesWith2, "arrayIncludesWith");
var arrayIncludesWith_default2 = arrayIncludesWith2;
function noop2() {
}
__name(noop2, "noop2");
__name2(noop2, "noop");
var noop_default2 = noop2;
var INFINITY7 = 1 / 0;
var createSet2 = !(Set_default2 && 1 / setToArray_default2(new Set_default2([, -0]))[1] == INFINITY7) ? noop_default2 : function(values2) {
return new Set_default2(values2);
};
var createSet_default2 = createSet2;
var LARGE_ARRAY_SIZE5 = 200;
function baseUniq2(array, iteratee, comparator) {
var index = -1, includes2 = arrayIncludes_default2, length = array.length, isCommon = true, result = [], seen = result;
if (comparator) {
isCommon = false;
includes2 = arrayIncludesWith_default2;
} else if (length >= LARGE_ARRAY_SIZE5) {
var set = iteratee ? null : createSet_default2(array);
if (set) {
return setToArray_default2(set);
}
isCommon = false;
includes2 = cacheHas_default2;
seen = new SetCache_default2();
} else {
seen = iteratee ? [] : result;
}
outer:
while (++index < length) {
var value = array[index], computed = iteratee ? iteratee(value) : value;
value = comparator || value !== 0 ? value : 0;
if (isCommon && computed === computed) {
var seenIndex = seen.length;
while (seenIndex--) {
if (seen[seenIndex] === computed) {
continue outer;
}
}
if (iteratee) {
seen.push(computed);
}
result.push(value);
} else if (!includes2(seen, computed, comparator)) {
if (seen !== result) {
seen.push(computed);
}
result.push(value);
}
}
return result;
}
__name(baseUniq2, "baseUniq2");
__name2(baseUniq2, "baseUniq");
var baseUniq_default2 = baseUniq2;
function uniqBy(array, iteratee) {
return array && array.length ? baseUniq_default2(array, baseIteratee_default2(iteratee, 2)) : [];
}
__name(uniqBy, "uniqBy");
__name2(uniqBy, "uniqBy");
var uniqBy_default = uniqBy;
function flatten2(array) {
var length = array == null ? 0 : array.length;
return length ? baseFlatten_default2(array, 1) : [];
}
__name(flatten2, "flatten2");
__name2(flatten2, "flatten");
var flatten_default2 = flatten2;
function arrayEach2(array, iteratee) {
var index = -1, length = array == null ? 0 : array.length;
while (++index < length) {
if (iteratee(array[index], index, array) === false) {
break;
}
}
return array;
}
__name(arrayEach2, "arrayEach2");
__name2(arrayEach2, "arrayEach");
var arrayEach_default2 = arrayEach2;
function castFunction2(value) {
return typeof value == "function" ? value : identity_default2;
}
__name(castFunction2, "castFunction2");
__name2(castFunction2, "castFunction");
var castFunction_default2 = castFunction2;
function forEach2(collection, iteratee) {
var func = isArray_default2(collection) ? arrayEach_default2 : baseEach_default2;
return func(collection, castFunction_default2(iteratee));
}
__name(forEach2, "forEach2");
__name2(forEach2, "forEach");
var forEach_default2 = forEach2;
var mapTag11 = "[object Map]";
var setTag11 = "[object Set]";
var objectProto33 = Object.prototype;
var hasOwnProperty27 = objectProto33.hasOwnProperty;
function isEmpty2(value) {
if (value == null) {
return true;
}
if (isArrayLike_default2(value) && (isArray_default2(value) || typeof value == "string" || typeof value.splice == "function" || isBuffer_default2(value) || isTypedArray_default2(value) || isArguments_default2(value))) {
return !value.length;
}
var tag = getTag_default2(value);
if (tag == mapTag11 || tag == setTag11) {
return !value.size;
}
if (isPrototype_default2(value)) {
return !baseKeys_default2(value).length;
}
for (var key in value) {
if (hasOwnProperty27.call(value, key)) {
return false;
}
}
return true;
}
__name(isEmpty2, "isEmpty2");
__name2(isEmpty2, "isEmpty");
var isEmpty_default2 = isEmpty2;
function arrayReduce2(array, iteratee, accumulator, initAccum) {
var index = -1, length = array == null ? 0 : array.length;
if (initAccum && length) {
accumulator = array[++index];
}
while (++index < length) {
accumulator = iteratee(accumulator, array[index], index, array);
}
return accumulator;
}
__name(arrayReduce2, "arrayReduce2");
__name2(arrayReduce2, "arrayReduce");
var arrayReduce_default2 = arrayReduce2;
function baseReduce2(collection, iteratee, accumulator, initAccum, eachFunc) {
eachFunc(collection, function(value, index, collection2) {
accumulator = initAccum ? (initAccum = false, value) : iteratee(accumulator, value, index, collection2);
});
return accumulator;
}
__name(baseReduce2, "baseReduce2");
__name2(baseReduce2, "baseReduce");
var baseReduce_default2 = baseReduce2;
function reduce2(collection, iteratee, accumulator) {
var func = isArray_default2(collection) ? arrayReduce_default2 : baseReduce_default2, initAccum = arguments.length < 3;
return func(collection, baseIteratee_default2(iteratee, 4), accumulator, initAccum, baseEach_default2);
}
__name(reduce2, "reduce2");
__name2(reduce2, "reduce");
var reduce_default2 = reduce2;
function createDFACache(startState, decision) {
const map3 = {};
return (predicateSet) => {
const key = predicateSet.toString();
let existing = map3[key];
if (existing !== void 0) {
return existing;
} else {
existing = {
atnStartState: startState,
decision,
states: {}
};
map3[key] = existing;
return existing;
}
};
}
__name(createDFACache, "createDFACache");
__name2(createDFACache, "createDFACache");
var PredicateSet = class {
static {
__name(this, "PredicateSet");
}
static {
__name2(this, "PredicateSet");
}
constructor() {
this.predicates = [];
}
is(index) {
return index >= this.predicates.length || this.predicates[index];
}
set(index, value) {
this.predicates[index] = value;
}
toString() {
let value = "";
const size = this.predicates.length;
for (let i = 0; i < size; i++) {
value += this.predicates[i] === true ? "1" : "0";
}
return value;
}
};
var EMPTY_PREDICATES = new PredicateSet();
var LLStarLookaheadStrategy = class extends LLkLookaheadStrategy {
static {
__name(this, "LLStarLookaheadStrategy");
}
static {
__name2(this, "LLStarLookaheadStrategy");
}
constructor(options) {
var _a;
super();
this.logging = (_a = options === null || options === void 0 ? void 0 : options.logging) !== null && _a !== void 0 ? _a : ((message) => console.log(message));
}
initialize(options) {
this.atn = createATN(options.rules);
this.dfas = initATNSimulator(this.atn);
}
validateAmbiguousAlternationAlternatives() {
return [];
}
validateEmptyOrAlternatives() {
return [];
}
buildLookaheadForAlternation(options) {
const { prodOccurrence, rule, hasPredicates, dynamicTokensEnabled } = options;
const dfas = this.dfas;
const logging = this.logging;
const key = buildATNKey(rule, "Alternation", prodOccurrence);
const decisionState = this.atn.decisionMap[key];
const decisionIndex = decisionState.decision;
const partialAlts = map_default2(getLookaheadPaths({
maxLookahead: 1,
occurrence: prodOccurrence,
prodType: "Alternation",
rule
}), (currAlt) => map_default2(currAlt, (path) => path[0]));
if (isLL1Sequence(partialAlts, false) && !dynamicTokensEnabled) {
const choiceToAlt = reduce_default2(partialAlts, (result, currAlt, idx) => {
forEach_default2(currAlt, (currTokType) => {
if (currTokType) {
result[currTokType.tokenTypeIdx] = idx;
forEach_default2(currTokType.categoryMatches, (currExtendingType) => {
result[currExtendingType] = idx;
});
}
});
return result;
}, {});
if (hasPredicates) {
return function(orAlts) {
var _a;
const nextToken = this.LA(1);
const prediction = choiceToAlt[nextToken.tokenTypeIdx];
if (orAlts !== void 0 && prediction !== void 0) {
const gate = (_a = orAlts[prediction]) === null || _a === void 0 ? void 0 : _a.GATE;
if (gate !== void 0 && gate.call(this) === false) {
return void 0;
}
}
return prediction;
};
} else {
return function() {
const nextToken = this.LA(1);
return choiceToAlt[nextToken.tokenTypeIdx];
};
}
} else if (hasPredicates) {
return function(orAlts) {
const predicates = new PredicateSet();
const length = orAlts === void 0 ? 0 : orAlts.length;
for (let i = 0; i < length; i++) {
const gate = orAlts === null || orAlts === void 0 ? void 0 : orAlts[i].GATE;
predicates.set(i, gate === void 0 || gate.call(this));
}
const result = adaptivePredict.call(this, dfas, decisionIndex, predicates, logging);
return typeof result === "number" ? result : void 0;
};
} else {
return function() {
const result = adaptivePredict.call(this, dfas, decisionIndex, EMPTY_PREDICATES, logging);
return typeof result === "number" ? result : void 0;
};
}
}
buildLookaheadForOptional(options) {
const { prodOccurrence, rule, prodType, dynamicTokensEnabled } = options;
const dfas = this.dfas;
const logging = this.logging;
const key = buildATNKey(rule, prodType, prodOccurrence);
const decisionState = this.atn.decisionMap[key];
const decisionIndex = decisionState.decision;
const alts = map_default2(getLookaheadPaths({
maxLookahead: 1,
occurrence: prodOccurrence,
prodType,
rule
}), (e) => {
return map_default2(e, (g) => g[0]);
});
if (isLL1Sequence(alts) && alts[0][0] && !dynamicTokensEnabled) {
const alt = alts[0];
const singleTokensTypes = flatten_default2(alt);
if (singleTokensTypes.length === 1 && isEmpty_default2(singleTokensTypes[0].categoryMatches)) {
const expectedTokenType = singleTokensTypes[0];
const expectedTokenUniqueKey = expectedTokenType.tokenTypeIdx;
return function() {
return this.LA(1).tokenTypeIdx === expectedTokenUniqueKey;
};
} else {
const choiceToAlt = reduce_default2(singleTokensTypes, (result, currTokType) => {
if (currTokType !== void 0) {
result[currTokType.tokenTypeIdx] = true;
forEach_default2(currTokType.categoryMatches, (currExtendingType) => {
result[currExtendingType] = true;
});
}
return result;
}, {});
return function() {
const nextToken = this.LA(1);
return choiceToAlt[nextToken.tokenTypeIdx] === true;
};
}
}
return function() {
const result = adaptivePredict.call(this, dfas, decisionIndex, EMPTY_PREDICATES, logging);
return typeof result === "object" ? false : result === 0;
};
}
};
function isLL1Sequence(sequences, allowEmpty = true) {
const fullSet = /* @__PURE__ */ new Set();
for (const alt of sequences) {
const altSet = /* @__PURE__ */ new Set();
for (const tokType of alt) {
if (tokType === void 0) {
if (allowEmpty) {
break;
} else {
return false;
}
}
const indices = [tokType.tokenTypeIdx].concat(tokType.categoryMatches);
for (const index of indices) {
if (fullSet.has(index)) {
if (!altSet.has(index)) {
return false;
}
} else {
fullSet.add(index);
altSet.add(index);
}
}
}
}
return true;
}
__name(isLL1Sequence, "isLL1Sequence");
__name2(isLL1Sequence, "isLL1Sequence");
function initATNSimulator(atn) {
const decisionLength = atn.decisionStates.length;
const decisionToDFA = Array(decisionLength);
for (let i = 0; i < decisionLength; i++) {
decisionToDFA[i] = createDFACache(atn.decisionStates[i], i);
}
return decisionToDFA;
}
__name(initATNSimulator, "initATNSimulator");
__name2(initATNSimulator, "initATNSimulator");
function adaptivePredict(dfaCaches, decision, predicateSet, logging) {
const dfa = dfaCaches[decision](predicateSet);
let start = dfa.start;
if (start === void 0) {
const closure2 = computeStartState(dfa.atnStartState);
start = addDFAState(dfa, newDFAState(closure2));
dfa.start = start;
}
const alt = performLookahead.apply(this, [dfa, start, predicateSet, logging]);
return alt;
}
__name(adaptivePredict, "adaptivePredict");
__name2(adaptivePredict, "adaptivePredict");
function performLookahead(dfa, s0, predicateSet, logging) {
let previousD = s0;
let i = 1;
const path = [];
let t = this.LA(i++);
while (true) {
let d = getExistingTargetState(previousD, t);
if (d === void 0) {
d = computeLookaheadTarget.apply(this, [dfa, previousD, t, i, predicateSet, logging]);
}
if (d === DFA_ERROR) {
return buildAdaptivePredictError(path, previousD, t);
}
if (d.isAcceptState === true) {
return d.prediction;
}
previousD = d;
path.push(t);
t = this.LA(i++);
}
}
__name(performLookahead, "performLookahead");
__name2(performLookahead, "performLookahead");
function computeLookaheadTarget(dfa, previousD, token, lookahead, predicateSet, logging) {
const reach = computeReachSet(previousD.configs, token, predicateSet);
if (reach.size === 0) {
addDFAEdge(dfa, previousD, token, DFA_ERROR);
return DFA_ERROR;
}
let newState2 = newDFAState(reach);
const predictedAlt = getUniqueAlt(reach, predicateSet);
if (predictedAlt !== void 0) {
newState2.isAcceptState = true;
newState2.prediction = predictedAlt;
newState2.configs.uniqueAlt = predictedAlt;
} else if (hasConflictTerminatingPrediction(reach)) {
const prediction = min_default(reach.alts);
newState2.isAcceptState = true;
newState2.prediction = prediction;
newState2.configs.uniqueAlt = prediction;
reportLookaheadAmbiguity.apply(this, [dfa, lookahead, reach.alts, logging]);
}
newState2 = addDFAEdge(dfa, previousD, token, newState2);
return newState2;
}
__name(computeLookaheadTarget, "computeLookaheadTarget");
__name2(computeLookaheadTarget, "computeLookaheadTarget");
function reportLookaheadAmbiguity(dfa, lookahead, ambiguityIndices, logging) {
const prefixPath = [];
for (let i = 1; i <= lookahead; i++) {
prefixPath.push(this.LA(i).tokenType);
}
const atnState = dfa.atnStartState;
const topLevelRule = atnState.rule;
const production = atnState.production;
const message = buildAmbiguityError({
topLevelRule,
ambiguityIndices,
production,
prefixPath
});
logging(message);
}
__name(reportLookaheadAmbiguity, "reportLookaheadAmbiguity");
__name2(reportLookaheadAmbiguity, "reportLookaheadAmbiguity");
function buildAmbiguityError(options) {
const pathMsg = map_default2(options.prefixPath, (currtok) => tokenLabel2(currtok)).join(", ");
const occurrence = options.production.idx === 0 ? "" : options.production.idx;
let currMessage = `Ambiguous Alternatives Detected: <${options.ambiguityIndices.join(", ")}> in <${getProductionDslName2(options.production)}${occurrence}> inside <${options.topLevelRule.name}> Rule,
<${pathMsg}> may appears as a prefix path in all these alternatives.
`;
currMessage = currMessage + `See: https://chevrotain.io/docs/guide/resolving_grammar_errors.html#AMBIGUOUS_ALTERNATIVES
For Further details.`;
return currMessage;
}
__name(buildAmbiguityError, "buildAmbiguityError");
__name2(buildAmbiguityError, "buildAmbiguityError");
function getProductionDslName2(prod) {
if (prod instanceof NonTerminal) {
return "SUBRULE";
} else if (prod instanceof Option) {
return "OPTION";
} else if (prod instanceof Alternation) {
return "OR";
} else if (prod instanceof RepetitionMandatory) {
return "AT_LEAST_ONE";
} else if (prod instanceof RepetitionMandatoryWithSeparator) {
return "AT_LEAST_ONE_SEP";
} else if (prod instanceof RepetitionWithSeparator) {
return "MANY_SEP";
} else if (prod instanceof Repetition) {
return "MANY";
} else if (prod instanceof Terminal) {
return "CONSUME";
} else {
throw Error("non exhaustive match");
}
}
__name(getProductionDslName2, "getProductionDslName2");
__name2(getProductionDslName2, "getProductionDslName");
function buildAdaptivePredictError(path, previous, current) {
const nextTransitions = flatMap_default2(previous.configs.elements, (e) => e.state.transitions);
const nextTokenTypes = uniqBy_default(nextTransitions.filter((e) => e instanceof AtomTransition).map((e) => e.tokenType), (e) => e.tokenTypeIdx);
return {
actualToken: current,
possibleTokenTypes: nextTokenTypes,
tokenPath: path
};
}
__name(buildAdaptivePredictError, "buildAdaptivePredictError");
__name2(buildAdaptivePredictError, "buildAdaptivePredictError");
function getExistingTargetState(state, token) {
return state.edges[token.tokenTypeIdx];
}
__name(getExistingTargetState, "getExistingTargetState");
__name2(getExistingTargetState, "getExistingTargetState");
function computeReachSet(configs, token, predicateSet) {
const intermediate = new ATNConfigSet();
const skippedStopStates = [];
for (const c of configs.elements) {
if (predicateSet.is(c.alt) === false) {
continue;
}
if (c.state.type === ATN_RULE_STOP) {
skippedStopStates.push(c);
continue;
}
const transitionLength = c.state.transitions.length;
for (let i = 0; i < transitionLength; i++) {
const transition = c.state.transitions[i];
const target = getReachableTarget(transition, token);
if (target !== void 0) {
intermediate.add({
state: target,
alt: c.alt,
stack: c.stack
});
}
}
}
let reach;
if (skippedStopStates.length === 0 && intermediate.size === 1) {
reach = intermediate;
}
if (reach === void 0) {
reach = new ATNConfigSet();
for (const c of intermediate.elements) {
closure(c, reach);
}
}
if (skippedStopStates.length > 0 && !hasConfigInRuleStopState(reach)) {
for (const c of skippedStopStates) {
reach.add(c);
}
}
return reach;
}
__name(computeReachSet, "computeReachSet");
__name2(computeReachSet, "computeReachSet");
function getReachableTarget(transition, token) {
if (transition instanceof AtomTransition && tokenMatcher(token, transition.tokenType)) {
return transition.target;
}
return void 0;
}
__name(getReachableTarget, "getReachableTarget");
__name2(getReachableTarget, "getReachableTarget");
function getUniqueAlt(configs, predicateSet) {
let alt;
for (const c of configs.elements) {
if (predicateSet.is(c.alt) === true) {
if (alt === void 0) {
alt = c.alt;
} else if (alt !== c.alt) {
return void 0;
}
}
}
return alt;
}
__name(getUniqueAlt, "getUniqueAlt");
__name2(getUniqueAlt, "getUniqueAlt");
function newDFAState(closure2) {
return {
configs: closure2,
edges: {},
isAcceptState: false,
prediction: -1
};
}
__name(newDFAState, "newDFAState");
__name2(newDFAState, "newDFAState");
function addDFAEdge(dfa, from, token, to) {
to = addDFAState(dfa, to);
from.edges[token.tokenTypeIdx] = to;
return to;
}
__name(addDFAEdge, "addDFAEdge");
__name2(addDFAEdge, "addDFAEdge");
function addDFAState(dfa, state) {
if (state === DFA_ERROR) {
return state;
}
const mapKey = state.configs.key;
const existing = dfa.states[mapKey];
if (existing !== void 0) {
return existing;
}
state.configs.finalize();
dfa.states[mapKey] = state;
return state;
}
__name(addDFAState, "addDFAState");
__name2(addDFAState, "addDFAState");
function computeStartState(atnState) {
const configs = new ATNConfigSet();
const numberOfTransitions = atnState.transitions.length;
for (let i = 0; i < numberOfTransitions; i++) {
const target = atnState.transitions[i].target;
const config = {
state: target,
alt: i,
stack: []
};
closure(config, configs);
}
return configs;
}
__name(computeStartState, "computeStartState");
__name2(computeStartState, "computeStartState");
function closure(config, configs) {
const p = config.state;
if (p.type === ATN_RULE_STOP) {
if (config.stack.length > 0) {
const atnStack = [...config.stack];
const followState = atnStack.pop();
const followConfig = {
state: followState,
alt: config.alt,
stack: atnStack
};
closure(followConfig, configs);
} else {
configs.add(config);
}
return;
}
if (!p.epsilonOnlyTransitions) {
configs.add(config);
}
const transitionLength = p.transitions.length;
for (let i = 0; i < transitionLength; i++) {
const transition = p.transitions[i];
const c = getEpsilonTarget(config, transition);
if (c !== void 0) {
closure(c, configs);
}
}
}
__name(closure, "closure");
__name2(closure, "closure");
function getEpsilonTarget(config, transition) {
if (transition instanceof EpsilonTransition) {
return {
state: transition.target,
alt: config.alt,
stack: config.stack
};
} else if (transition instanceof RuleTransition) {
const stack = [...config.stack, transition.followState];
return {
state: transition.target,
alt: config.alt,
stack
};
}
return void 0;
}
__name(getEpsilonTarget, "getEpsilonTarget");
__name2(getEpsilonTarget, "getEpsilonTarget");
function hasConfigInRuleStopState(configs) {
for (const c of configs.elements) {
if (c.state.type === ATN_RULE_STOP) {
return true;
}
}
return false;
}
__name(hasConfigInRuleStopState, "hasConfigInRuleStopState");
__name2(hasConfigInRuleStopState, "hasConfigInRuleStopState");
function allConfigsInRuleStopStates(configs) {
for (const c of configs.elements) {
if (c.state.type !== ATN_RULE_STOP) {
return false;
}
}
return true;
}
__name(allConfigsInRuleStopStates, "allConfigsInRuleStopStates");
__name2(allConfigsInRuleStopStates, "allConfigsInRuleStopStates");
function hasConflictTerminatingPrediction(configs) {
if (allConfigsInRuleStopStates(configs)) {
return true;
}
const altSets = getConflictingAltSets(configs.elements);
const heuristic = hasConflictingAltSet(altSets) && !hasStateAssociatedWithOneAlt(altSets);
return heuristic;
}
__name(hasConflictTerminatingPrediction, "hasConflictTerminatingPrediction");
__name2(hasConflictTerminatingPrediction, "hasConflictTerminatingPrediction");
function getConflictingAltSets(configs) {
const configToAlts = /* @__PURE__ */ new Map();
for (const c of configs) {
const key = getATNConfigKey(c, false);
let alts = configToAlts.get(key);
if (alts === void 0) {
alts = {};
configToAlts.set(key, alts);
}
alts[c.alt] = true;
}
return configToAlts;
}
__name(getConflictingAltSets, "getConflictingAltSets");
__name2(getConflictingAltSets, "getConflictingAltSets");
function hasConflictingAltSet(altSets) {
for (const value of Array.from(altSets.values())) {
if (Object.keys(value).length > 1) {
return true;
}
}
return false;
}
__name(hasConflictingAltSet, "hasConflictingAltSet");
__name2(hasConflictingAltSet, "hasConflictingAltSet");
function hasStateAssociatedWithOneAlt(altSets) {
for (const value of Array.from(altSets.values())) {
if (Object.keys(value).length === 1) {
return true;
}
}
return false;
}
__name(hasStateAssociatedWithOneAlt, "hasStateAssociatedWithOneAlt");
__name2(hasStateAssociatedWithOneAlt, "hasStateAssociatedWithOneAlt");
init_main();
var CstNodeBuilder = class {
static {
__name(this, "CstNodeBuilder");
}
static {
__name2(this, "CstNodeBuilder");
}
constructor() {
this.nodeStack = [];
}
get current() {
return this.nodeStack[this.nodeStack.length - 1] ?? this.rootNode;
}
buildRootNode(input) {
this.rootNode = new RootCstNodeImpl(input);
this.rootNode.root = this.rootNode;
this.nodeStack = [this.rootNode];
return this.rootNode;
}
buildCompositeNode(feature) {
const compositeNode = new CompositeCstNodeImpl();
compositeNode.grammarSource = feature;
compositeNode.root = this.rootNode;
this.current.content.push(compositeNode);
this.nodeStack.push(compositeNode);
return compositeNode;
}
buildLeafNode(token, feature) {
const leafNode = new LeafCstNodeImpl(token.startOffset, token.image.length, tokenToRange(token), token.tokenType, !feature);
leafNode.grammarSource = feature;
leafNode.root = this.rootNode;
this.current.content.push(leafNode);
return leafNode;
}
removeNode(node) {
const parent = node.container;
if (parent) {
const index = parent.content.indexOf(node);
if (index >= 0) {
parent.content.splice(index, 1);
}
}
}
addHiddenNodes(tokens) {
const nodes = [];
for (const token of tokens) {
const leafNode = new LeafCstNodeImpl(token.startOffset, token.image.length, tokenToRange(token), token.tokenType, true);
leafNode.root = this.rootNode;
nodes.push(leafNode);
}
let current = this.current;
let added = false;
if (current.content.length > 0) {
current.content.push(...nodes);
return;
}
while (current.container) {
const index = current.container.content.indexOf(current);
if (index > 0) {
current.container.content.splice(index, 0, ...nodes);
added = true;
break;
}
current = current.container;
}
if (!added) {
this.rootNode.content.unshift(...nodes);
}
}
construct(item) {
const current = this.current;
if (typeof item.$type === "string" && !item.$infixName) {
this.current.astNode = item;
}
item.$cstNode = current;
const node = this.nodeStack.pop();
if (node?.content.length === 0) {
this.removeNode(node);
}
}
};
var AbstractCstNode = class {
static {
__name(this, "AbstractCstNode");
}
static {
__name2(this, "AbstractCstNode");
}
get hidden() {
return false;
}
get astNode() {
const node = typeof this._astNode?.$type === "string" ? this._astNode : this.container?.astNode;
if (!node) {
throw new Error("This node has no associated AST element");
}
return node;
}
set astNode(value) {
this._astNode = value;
}
get text() {
return this.root.fullText.substring(this.offset, this.end);
}
};
var LeafCstNodeImpl = class extends AbstractCstNode {
static {
__name(this, "LeafCstNodeImpl");
}
static {
__name2(this, "LeafCstNodeImpl");
}
get offset() {
return this._offset;
}
get length() {
return this._length;
}
get end() {
return this._offset + this._length;
}
get hidden() {
return this._hidden;
}
get tokenType() {
return this._tokenType;
}
get range() {
return this._range;
}
constructor(offset, length, range, tokenType, hidden = false) {
super();
this._hidden = hidden;
this._offset = offset;
this._tokenType = tokenType;
this._length = length;
this._range = range;
}
};
var CompositeCstNodeImpl = class extends AbstractCstNode {
static {
__name(this, "CompositeCstNodeImpl");
}
static {
__name2(this, "CompositeCstNodeImpl");
}
constructor() {
super(...arguments);
this.content = new CstNodeContainer(this);
}
get offset() {
return this.firstNonHiddenNode?.offset ?? 0;
}
get length() {
return this.end - this.offset;
}
get end() {
return this.lastNonHiddenNode?.end ?? 0;
}
get range() {
const firstNode = this.firstNonHiddenNode;
const lastNode = this.lastNonHiddenNode;
if (firstNode && lastNode) {
if (this._rangeCache === void 0) {
const { range: firstRange } = firstNode;
const { range: lastRange } = lastNode;
this._rangeCache = { start: firstRange.start, end: lastRange.end.line < firstRange.start.line ? firstRange.start : lastRange.end };
}
return this._rangeCache;
} else {
return { start: Position.create(0, 0), end: Position.create(0, 0) };
}
}
get firstNonHiddenNode() {
for (const child of this.content) {
if (!child.hidden) {
return child;
}
}
return this.content[0];
}
get lastNonHiddenNode() {
for (let i = this.content.length - 1; i >= 0; i--) {
const child = this.content[i];
if (!child.hidden) {
return child;
}
}
return this.content[this.content.length - 1];
}
};
var CstNodeContainer = class _CstNodeContainer extends Array {
static {
__name(this, "_CstNodeContainer");
}
static {
__name2(this, "CstNodeContainer");
}
constructor(parent) {
super();
this.parent = parent;
Object.setPrototypeOf(this, _CstNodeContainer.prototype);
}
push(...items) {
this.addParents(items);
return super.push(...items);
}
unshift(...items) {
this.addParents(items);
return super.unshift(...items);
}
splice(start, count, ...items) {
this.addParents(items);
return super.splice(start, count, ...items);
}
addParents(items) {
for (const item of items) {
item.container = this.parent;
}
}
};
var RootCstNodeImpl = class extends CompositeCstNodeImpl {
static {
__name(this, "RootCstNodeImpl");
}
static {
__name2(this, "RootCstNodeImpl");
}
get text() {
return this._text.substring(this.offset, this.end);
}
get fullText() {
return this._text;
}
constructor(input) {
super();
this._text = "";
this._text = input ?? "";
}
};
var DatatypeSymbol = Symbol("Datatype");
function isDataTypeNode(node) {
return node.$type === DatatypeSymbol;
}
__name(isDataTypeNode, "isDataTypeNode");
__name2(isDataTypeNode, "isDataTypeNode");
var ruleSuffix = "\u200B";
var withRuleSuffix = /* @__PURE__ */ __name2((name) => name.endsWith(ruleSuffix) ? name : name + ruleSuffix, "withRuleSuffix");
var AbstractLangiumParser = class {
static {
__name(this, "AbstractLangiumParser");
}
static {
__name2(this, "AbstractLangiumParser");
}
constructor(services) {
this._unorderedGroups = /* @__PURE__ */ new Map();
this.allRules = /* @__PURE__ */ new Map();
this.lexer = services.parser.Lexer;
const tokens = this.lexer.definition;
const production = services.LanguageMetaData.mode === "production";
if (services.shared.profilers.LangiumProfiler?.isActive("parsing")) {
this.wrapper = new ProfilerWrapper(tokens, {
...services.parser.ParserConfig,
skipValidations: production,
errorMessageProvider: services.parser.ParserErrorMessageProvider
}, services.shared.profilers.LangiumProfiler.createTask("parsing", services.LanguageMetaData.languageId));
} else {
this.wrapper = new ChevrotainWrapper(tokens, {
...services.parser.ParserConfig,
skipValidations: production,
errorMessageProvider: services.parser.ParserErrorMessageProvider
});
}
}
alternatives(idx, choices) {
this.wrapper.wrapOr(idx, choices);
}
optional(idx, callback) {
this.wrapper.wrapOption(idx, callback);
}
many(idx, callback) {
this.wrapper.wrapMany(idx, callback);
}
atLeastOne(idx, callback) {
this.wrapper.wrapAtLeastOne(idx, callback);
}
getRule(name) {
return this.allRules.get(name);
}
isRecording() {
return this.wrapper.IS_RECORDING;
}
get unorderedGroups() {
return this._unorderedGroups;
}
getRuleStack() {
return this.wrapper.RULE_STACK;
}
finalize() {
this.wrapper.wrapSelfAnalysis();
}
};
var LangiumParser = class extends AbstractLangiumParser {
static {
__name(this, "LangiumParser");
}
static {
__name2(this, "LangiumParser");
}
get current() {
return this.stack[this.stack.length - 1];
}
constructor(services) {
super(services);
this.nodeBuilder = new CstNodeBuilder();
this.stack = [];
this.assignmentMap = /* @__PURE__ */ new Map();
this.operatorPrecedence = /* @__PURE__ */ new Map();
this.linker = services.references.Linker;
this.converter = services.parser.ValueConverter;
this.astReflection = services.shared.AstReflection;
}
rule(rule, impl) {
const type = this.computeRuleType(rule);
let infixName = void 0;
if (isInfixRule(rule)) {
infixName = rule.name;
this.registerPrecedenceMap(rule);
}
const ruleMethod = this.wrapper.DEFINE_RULE(withRuleSuffix(rule.name), this.startImplementation(type, infixName, impl).bind(this));
this.allRules.set(rule.name, ruleMethod);
if (isParserRule(rule) && rule.entry) {
this.mainRule = ruleMethod;
}
return ruleMethod;
}
registerPrecedenceMap(rule) {
const name = rule.name;
const map3 = /* @__PURE__ */ new Map();
for (let i = 0; i < rule.operators.precedences.length; i++) {
const precedence = rule.operators.precedences[i];
for (const keyword of precedence.operators) {
map3.set(keyword.value, {
precedence: i,
rightAssoc: precedence.associativity === "right"
});
}
}
this.operatorPrecedence.set(name, map3);
}
computeRuleType(rule) {
if (isInfixRule(rule)) {
return getTypeName(rule);
} else if (rule.fragment) {
return void 0;
} else if (isDataTypeRule(rule)) {
return DatatypeSymbol;
} else {
return getTypeName(rule);
}
}
parse(input, options = {}) {
this.nodeBuilder.buildRootNode(input);
const lexerResult = this.lexerResult = this.lexer.tokenize(input);
this.wrapper.input = lexerResult.tokens;
const ruleMethod = options.rule ? this.allRules.get(options.rule) : this.mainRule;
if (!ruleMethod) {
throw new Error(options.rule ? `No rule found with name '${options.rule}'` : "No main rule available.");
}
const result = this.doParse(ruleMethod);
this.nodeBuilder.addHiddenNodes(lexerResult.hidden);
this.unorderedGroups.clear();
this.lexerResult = void 0;
linkContentToContainer(result, { deep: true });
return {
value: result,
lexerErrors: lexerResult.errors,
lexerReport: lexerResult.report,
parserErrors: this.wrapper.errors
};
}
doParse(rule) {
let result = this.wrapper.rule(rule);
if (this.stack.length > 0) {
result = this.construct();
}
if (result === void 0) {
throw new Error("No result from parser");
} else if (this.stack.length > 0) {
throw new Error("Parser stack is not empty after parsing");
}
return result;
}
startImplementation($type, infixName, implementation) {
return (args) => {
const createNode = !this.isRecording() && $type !== void 0;
if (createNode) {
const node = { $type };
this.stack.push(node);
if ($type === DatatypeSymbol) {
node.value = "";
} else if (infixName !== void 0) {
node.$infixName = infixName;
}
}
implementation(args);
return createNode ? this.construct() : void 0;
};
}
extractHiddenTokens(token) {
const hiddenTokens = this.lexerResult.hidden;
if (!hiddenTokens.length) {
return [];
}
const offset = token.startOffset;
for (let i = 0; i < hiddenTokens.length; i++) {
const token2 = hiddenTokens[i];
if (token2.startOffset > offset) {
return hiddenTokens.splice(0, i);
}
}
return hiddenTokens.splice(0, hiddenTokens.length);
}
consume(idx, tokenType, feature) {
const token = this.wrapper.wrapConsume(idx, tokenType);
if (!this.isRecording() && this.isValidToken(token)) {
const hiddenTokens = this.extractHiddenTokens(token);
this.nodeBuilder.addHiddenNodes(hiddenTokens);
const leafNode = this.nodeBuilder.buildLeafNode(token, feature);
const { assignment, crossRef } = this.getAssignment(feature);
const current = this.current;
if (assignment) {
const convertedValue = isKeyword(feature) ? token.image : this.converter.convert(token.image, leafNode);
this.assign(assignment.operator, assignment.feature, convertedValue, leafNode, crossRef);
} else if (isDataTypeNode(current)) {
let text = token.image;
if (!isKeyword(feature)) {
text = this.converter.convert(text, leafNode).toString();
}
current.value += text;
}
}
}
/**
* Most consumed parser tokens are valid. However there are two cases in which they are not valid:
*
* 1. They were inserted during error recovery by the parser. These tokens don't really exist and should not be further processed
* 2. They contain invalid token ranges. This might include the special EOF token, or other tokens produced by invalid token builders.
*/
isValidToken(token) {
return !token.isInsertedInRecovery && !isNaN(token.startOffset) && typeof token.endOffset === "number" && !isNaN(token.endOffset);
}
subrule(idx, rule, fragment, feature, args) {
let cstNode;
if (!this.isRecording() && !fragment) {
cstNode = this.nodeBuilder.buildCompositeNode(feature);
}
let result;
try {
result = this.wrapper.wrapSubrule(idx, rule, args);
} finally {
if (!this.isRecording()) {
if (result === void 0 && !fragment) {
result = this.construct();
}
if (result !== void 0 && cstNode && cstNode.length > 0) {
this.performSubruleAssignment(result, feature, cstNode);
}
}
}
}
performSubruleAssignment(result, feature, cstNode) {
const { assignment, crossRef } = this.getAssignment(feature);
if (assignment) {
this.assign(assignment.operator, assignment.feature, result, cstNode, crossRef);
} else if (!assignment) {
const current = this.current;
if (isDataTypeNode(current)) {
current.value += result.toString();
} else if (typeof result === "object" && result) {
const object = this.assignWithoutOverride(result, current);
const newItem = object;
this.stack.pop();
this.stack.push(newItem);
}
}
}
action($type, action) {
if (!this.isRecording()) {
let last2 = this.current;
if (action.feature && action.operator) {
last2 = this.construct();
this.nodeBuilder.removeNode(last2.$cstNode);
const node = this.nodeBuilder.buildCompositeNode(action);
node.content.push(last2.$cstNode);
const newItem = { $type };
this.stack.push(newItem);
this.assign(action.operator, action.feature, last2, last2.$cstNode);
} else {
last2.$type = $type;
}
}
}
construct() {
if (this.isRecording()) {
return void 0;
}
const obj = this.stack.pop();
this.nodeBuilder.construct(obj);
if ("$infixName" in obj) {
return this.constructInfix(obj, this.operatorPrecedence.get(obj.$infixName));
} else if (isDataTypeNode(obj)) {
return this.converter.convert(obj.value, obj.$cstNode);
} else {
assignMandatoryProperties(this.astReflection, obj);
}
return obj;
}
constructInfix(obj, precedence) {
const parts = obj.parts;
if (!Array.isArray(parts) || parts.length === 0) {
return void 0;
}
const operators = obj.operators;
if (!Array.isArray(operators) || parts.length < 2) {
return parts[0];
}
let lowestPrecedenceIdx = 0;
let lowestPrecedenceValue = -1;
for (let i = 0; i < operators.length; i++) {
const operator = operators[i];
const opPrecedence = precedence.get(operator) ?? {
precedence: Infinity,
rightAssoc: false
};
if (opPrecedence.precedence > lowestPrecedenceValue) {
lowestPrecedenceValue = opPrecedence.precedence;
lowestPrecedenceIdx = i;
} else if (opPrecedence.precedence === lowestPrecedenceValue) {
if (!opPrecedence.rightAssoc) {
lowestPrecedenceIdx = i;
}
}
}
const leftOperators = operators.slice(0, lowestPrecedenceIdx);
const rightOperators = operators.slice(lowestPrecedenceIdx + 1);
const leftParts = parts.slice(0, lowestPrecedenceIdx + 1);
const rightParts = parts.slice(lowestPrecedenceIdx + 1);
const leftInfix = {
$infixName: obj.$infixName,
$type: obj.$type,
$cstNode: obj.$cstNode,
parts: leftParts,
operators: leftOperators
};
const rightInfix = {
$infixName: obj.$infixName,
$type: obj.$type,
$cstNode: obj.$cstNode,
parts: rightParts,
operators: rightOperators
};
const leftTree = this.constructInfix(leftInfix, precedence);
const rightTree = this.constructInfix(rightInfix, precedence);
return {
$type: obj.$type,
$cstNode: obj.$cstNode,
left: leftTree,
operator: operators[lowestPrecedenceIdx],
right: rightTree
};
}
getAssignment(feature) {
if (!this.assignmentMap.has(feature)) {
const assignment = getContainerOfType(feature, isAssignment);
this.assignmentMap.set(feature, {
assignment,
crossRef: assignment && isCrossReference(assignment.terminal) ? assignment.terminal.isMulti ? "multi" : "single" : void 0
});
}
return this.assignmentMap.get(feature);
}
assign(operator, feature, value, cstNode, crossRef) {
const obj = this.current;
let item;
if (crossRef === "single" && typeof value === "string") {
item = this.linker.buildReference(obj, feature, cstNode, value);
} else if (crossRef === "multi" && typeof value === "string") {
item = this.linker.buildMultiReference(obj, feature, cstNode, value);
} else {
item = value;
}
switch (operator) {
case "=": {
obj[feature] = item;
break;
}
case "?=": {
obj[feature] = true;
break;
}
case "+=": {
if (!Array.isArray(obj[feature])) {
obj[feature] = [];
}
obj[feature].push(item);
}
}
}
assignWithoutOverride(target, source) {
for (const [name, existingValue] of Object.entries(source)) {
const newValue = target[name];
if (newValue === void 0) {
target[name] = existingValue;
} else if (Array.isArray(newValue) && Array.isArray(existingValue)) {
existingValue.push(...newValue);
target[name] = existingValue;
}
}
const targetCstNode = target.$cstNode;
if (targetCstNode) {
targetCstNode.astNode = void 0;
target.$cstNode = void 0;
}
return target;
}
get definitionErrors() {
return this.wrapper.definitionErrors;
}
};
var AbstractParserErrorMessageProvider = class {
static {
__name(this, "AbstractParserErrorMessageProvider");
}
static {
__name2(this, "AbstractParserErrorMessageProvider");
}
buildMismatchTokenMessage(options) {
return defaultParserErrorProvider.buildMismatchTokenMessage(options);
}
buildNotAllInputParsedMessage(options) {
return defaultParserErrorProvider.buildNotAllInputParsedMessage(options);
}
buildNoViableAltMessage(options) {
return defaultParserErrorProvider.buildNoViableAltMessage(options);
}
buildEarlyExitMessage(options) {
return defaultParserErrorProvider.buildEarlyExitMessage(options);
}
};
var LangiumParserErrorMessageProvider = class extends AbstractParserErrorMessageProvider {
static {
__name(this, "LangiumParserErrorMessageProvider");
}
static {
__name2(this, "LangiumParserErrorMessageProvider");
}
buildMismatchTokenMessage({ expected, actual }) {
const expectedMsg = expected.LABEL ? "`" + expected.LABEL + "`" : expected.name.endsWith(":KW") ? `keyword '${expected.name.substring(0, expected.name.length - 3)}'` : `token of type '${expected.name}'`;
return `Expecting ${expectedMsg} but found \`${actual.image}\`.`;
}
buildNotAllInputParsedMessage({ firstRedundant }) {
return `Expecting end of file but found \`${firstRedundant.image}\`.`;
}
};
var LangiumCompletionParser = class extends AbstractLangiumParser {
static {
__name(this, "LangiumCompletionParser");
}
static {
__name2(this, "LangiumCompletionParser");
}
constructor() {
super(...arguments);
this.tokens = [];
this.elementStack = [];
this.lastElementStack = [];
this.nextTokenIndex = 0;
this.stackSize = 0;
}
action() {
}
construct() {
return void 0;
}
parse(input) {
this.resetState();
const tokens = this.lexer.tokenize(input, { mode: "partial" });
this.tokens = tokens.tokens;
this.wrapper.input = [...this.tokens];
this.mainRule.call(this.wrapper, {});
this.unorderedGroups.clear();
return {
tokens: this.tokens,
elementStack: [...this.lastElementStack],
tokenIndex: this.nextTokenIndex
};
}
rule(rule, impl) {
const ruleMethod = this.wrapper.DEFINE_RULE(withRuleSuffix(rule.name), this.startImplementation(impl).bind(this));
this.allRules.set(rule.name, ruleMethod);
if (rule.entry) {
this.mainRule = ruleMethod;
}
return ruleMethod;
}
resetState() {
this.elementStack = [];
this.lastElementStack = [];
this.nextTokenIndex = 0;
this.stackSize = 0;
}
startImplementation(implementation) {
return (args) => {
const size = this.keepStackSize();
try {
implementation(args);
} finally {
this.resetStackSize(size);
}
};
}
removeUnexpectedElements() {
this.elementStack.splice(this.stackSize);
}
keepStackSize() {
const size = this.elementStack.length;
this.stackSize = size;
return size;
}
resetStackSize(size) {
this.removeUnexpectedElements();
this.stackSize = size;
}
consume(idx, tokenType, feature) {
this.wrapper.wrapConsume(idx, tokenType);
if (!this.isRecording()) {
this.lastElementStack = [...this.elementStack, feature];
this.nextTokenIndex = this.currIdx + 1;
}
}
subrule(idx, rule, fragment, feature, args) {
this.before(feature);
this.wrapper.wrapSubrule(idx, rule, args);
this.after(feature);
}
before(element) {
if (!this.isRecording()) {
this.elementStack.push(element);
}
}
after(element) {
if (!this.isRecording()) {
const index = this.elementStack.lastIndexOf(element);
if (index >= 0) {
this.elementStack.splice(index);
}
}
}
get currIdx() {
return this.wrapper.currIdx;
}
};
var defaultConfig = {
recoveryEnabled: true,
nodeLocationTracking: "full",
skipValidations: true,
errorMessageProvider: new LangiumParserErrorMessageProvider()
};
var ChevrotainWrapper = class extends EmbeddedActionsParser {
static {
__name(this, "ChevrotainWrapper");
}
static {
__name2(this, "ChevrotainWrapper");
}
constructor(tokens, config) {
const useDefaultLookahead = config && "maxLookahead" in config;
super(tokens, {
...defaultConfig,
lookaheadStrategy: useDefaultLookahead ? new LLkLookaheadStrategy({ maxLookahead: config.maxLookahead }) : new LLStarLookaheadStrategy({
// If validations are skipped, don't log the lookahead warnings
logging: config.skipValidations ? () => {
} : void 0
}),
...config
});
}
get IS_RECORDING() {
return this.RECORDING_PHASE;
}
DEFINE_RULE(name, impl, config) {
return this.RULE(name, impl, config);
}
wrapSelfAnalysis() {
this.performSelfAnalysis();
}
wrapConsume(idx, tokenType) {
return this.consume(idx, tokenType, void 0);
}
wrapSubrule(idx, rule, args) {
return this.subrule(idx, rule, {
ARGS: [args]
});
}
wrapOr(idx, choices) {
this.or(idx, choices);
}
wrapOption(idx, callback) {
this.option(idx, callback);
}
wrapMany(idx, callback) {
this.many(idx, callback);
}
wrapAtLeastOne(idx, callback) {
this.atLeastOne(idx, callback);
}
rule(rule) {
return rule.call(this, {});
}
};
var ProfilerWrapper = class extends ChevrotainWrapper {
static {
__name(this, "ProfilerWrapper");
}
static {
__name2(this, "ProfilerWrapper");
}
constructor(tokens, config, task) {
super(tokens, config);
this.task = task;
}
rule(rule) {
this.task.start();
this.task.startSubTask(this.ruleName(rule));
try {
return super.rule(rule);
} finally {
this.task.stopSubTask(this.ruleName(rule));
this.task.stop();
}
}
ruleName(rule) {
return rule.ruleName;
}
subrule(idx, ruleToCall, options) {
this.task.startSubTask(this.ruleName(ruleToCall));
try {
return super.subrule(idx, ruleToCall, options);
} finally {
this.task.stopSubTask(this.ruleName(ruleToCall));
}
}
};
function createParser(grammar, parser, tokens) {
const parserContext = {
parser,
tokens,
ruleNames: /* @__PURE__ */ new Map()
};
buildRules(parserContext, grammar);
return parser;
}
__name(createParser, "createParser");
__name2(createParser, "createParser");
function buildRules(parserContext, grammar) {
const reachable = getAllReachableRules(grammar, false);
const parserRules = stream(grammar.rules).filter(isParserRule).filter((rule) => reachable.has(rule));
for (const rule of parserRules) {
const ctx = {
...parserContext,
consume: 1,
optional: 1,
subrule: 1,
many: 1,
or: 1
};
parserContext.parser.rule(rule, buildElement(ctx, rule.definition));
}
const infixRules = stream(grammar.rules).filter(isInfixRule).filter((rule) => reachable.has(rule));
for (const rule of infixRules) {
parserContext.parser.rule(rule, buildInfixRule(parserContext, rule));
}
}
__name(buildRules, "buildRules");
__name2(buildRules, "buildRules");
function buildInfixRule(ctx, rule) {
const expressionRule = rule.call.rule.ref;
if (!expressionRule) {
throw new Error("Could not resolve reference to infix operator rule: " + rule.call.rule.$refText);
}
if (isTerminalRule(expressionRule)) {
throw new Error("Cannot use terminal rule in infix expression");
}
const allKeywords = rule.operators.precedences.flatMap((e) => e.operators);
const outerGroup = {
$type: "Group",
elements: []
};
const part1Assignment = {
$container: outerGroup,
$type: "Assignment",
feature: "parts",
operator: "+=",
terminal: rule.call
};
const innerGroup = {
$container: outerGroup,
$type: "Group",
elements: [],
cardinality: "*"
};
outerGroup.elements.push(part1Assignment, innerGroup);
const alternatives = {
$type: "Alternatives",
elements: allKeywords
};
const operatorAssignment = {
$container: innerGroup,
$type: "Assignment",
feature: "operators",
operator: "+=",
terminal: alternatives
};
const part2Assignment = {
...part1Assignment,
$container: innerGroup
};
innerGroup.elements.push(operatorAssignment, part2Assignment);
const tokens = allKeywords.map((e) => ctx.tokens[e.value]);
const orAlts = tokens.map((token, index) => ({
ALT: /* @__PURE__ */ __name2(() => ctx.parser.consume(index, token, operatorAssignment), "ALT")
}));
let subrule;
return (args) => {
subrule ?? (subrule = getRule(ctx, expressionRule));
ctx.parser.subrule(0, subrule, false, part1Assignment, args);
ctx.parser.many(0, {
DEF: /* @__PURE__ */ __name2(() => {
ctx.parser.alternatives(0, orAlts);
ctx.parser.subrule(1, subrule, false, part2Assignment, args);
}, "DEF")
});
};
}
__name(buildInfixRule, "buildInfixRule");
__name2(buildInfixRule, "buildInfixRule");
function buildElement(ctx, element, ignoreGuard = false) {
let method;
if (isKeyword(element)) {
method = buildKeyword(ctx, element);
} else if (isAction(element)) {
method = buildAction(ctx, element);
} else if (isAssignment(element)) {
method = buildElement(ctx, element.terminal);
} else if (isCrossReference(element)) {
method = buildCrossReference(ctx, element);
} else if (isRuleCall(element)) {
method = buildRuleCall(ctx, element);
} else if (isAlternatives(element)) {
method = buildAlternatives(ctx, element);
} else if (isUnorderedGroup(element)) {
method = buildUnorderedGroup(ctx, element);
} else if (isGroup(element)) {
method = buildGroup(ctx, element);
} else if (isEndOfFile(element)) {
const idx = ctx.consume++;
method = /* @__PURE__ */ __name2(() => ctx.parser.consume(idx, EOF, element), "method");
} else {
throw new ErrorWithLocation(element.$cstNode, `Unexpected element type: ${element.$type}`);
}
return wrap(ctx, ignoreGuard ? void 0 : getGuardCondition(element), method, element.cardinality);
}
__name(buildElement, "buildElement");
__name2(buildElement, "buildElement");
function buildAction(ctx, action) {
const actionType = getTypeName(action);
return () => ctx.parser.action(actionType, action);
}
__name(buildAction, "buildAction");
__name2(buildAction, "buildAction");
function buildRuleCall(ctx, ruleCall) {
const rule = ruleCall.rule.ref;
if (isAbstractParserRule(rule)) {
const idx = ctx.subrule++;
const fragment = isParserRule(rule) && rule.fragment;
const predicate = ruleCall.arguments.length > 0 ? buildRuleCallPredicate(rule, ruleCall.arguments) : () => ({});
let subrule;
return (args) => {
subrule ?? (subrule = getRule(ctx, rule));
ctx.parser.subrule(idx, subrule, fragment, ruleCall, predicate(args));
};
} else if (isTerminalRule(rule)) {
const idx = ctx.consume++;
const method = getToken(ctx, rule.name);
return () => ctx.parser.consume(idx, method, ruleCall);
} else if (!rule) {
throw new ErrorWithLocation(ruleCall.$cstNode, `Undefined rule: ${ruleCall.rule.$refText}`);
} else {
assertUnreachable(rule);
}
}
__name(buildRuleCall, "buildRuleCall");
__name2(buildRuleCall, "buildRuleCall");
function buildRuleCallPredicate(rule, namedArgs) {
const hasNamedArguments = namedArgs.some((arg) => arg.calledByName);
if (hasNamedArguments) {
const namedPredicates = namedArgs.map((arg) => ({
parameterName: arg.parameter?.ref?.name,
predicate: buildPredicate(arg.value)
}));
return (args) => {
const ruleArgs = {};
for (const { parameterName, predicate } of namedPredicates) {
if (parameterName) {
ruleArgs[parameterName] = predicate(args);
}
}
return ruleArgs;
};
} else {
const predicates = namedArgs.map((arg) => buildPredicate(arg.value));
return (args) => {
const ruleArgs = {};
for (let i = 0; i < predicates.length; i++) {
if (i < rule.parameters.length) {
const parameterName = rule.parameters[i].name;
const predicate = predicates[i];
ruleArgs[parameterName] = predicate(args);
}
}
return ruleArgs;
};
}
}
__name(buildRuleCallPredicate, "buildRuleCallPredicate");
__name2(buildRuleCallPredicate, "buildRuleCallPredicate");
function buildPredicate(condition) {
if (isDisjunction(condition)) {
const left = buildPredicate(condition.left);
const right = buildPredicate(condition.right);
return (args) => left(args) || right(args);
} else if (isConjunction(condition)) {
const left = buildPredicate(condition.left);
const right = buildPredicate(condition.right);
return (args) => left(args) && right(args);
} else if (isNegation(condition)) {
const value = buildPredicate(condition.value);
return (args) => !value(args);
} else if (isParameterReference(condition)) {
const name = condition.parameter.ref.name;
return (args) => args !== void 0 && args[name] === true;
} else if (isBooleanLiteral(condition)) {
const value = Boolean(condition.true);
return () => value;
}
assertUnreachable(condition);
}
__name(buildPredicate, "buildPredicate");
__name2(buildPredicate, "buildPredicate");
function buildAlternatives(ctx, alternatives) {
if (alternatives.elements.length === 1) {
return buildElement(ctx, alternatives.elements[0]);
} else {
const methods = [];
for (const element of alternatives.elements) {
const predicatedMethod = {
// Since we handle the guard condition in the alternative already
// We can ignore the group guard condition inside
ALT: buildElement(ctx, element, true)
};
const guard = getGuardCondition(element);
if (guard) {
predicatedMethod.GATE = buildPredicate(guard);
}
methods.push(predicatedMethod);
}
const idx = ctx.or++;
return (args) => ctx.parser.alternatives(idx, methods.map((method) => {
const alt = {
ALT: /* @__PURE__ */ __name2(() => method.ALT(args), "ALT")
};
const gate = method.GATE;
if (gate) {
alt.GATE = () => gate(args);
}
return alt;
}));
}
}
__name(buildAlternatives, "buildAlternatives");
__name2(buildAlternatives, "buildAlternatives");
function buildUnorderedGroup(ctx, group) {
if (group.elements.length === 1) {
return buildElement(ctx, group.elements[0]);
}
const methods = [];
for (const element of group.elements) {
const predicatedMethod = {
// Since we handle the guard condition in the alternative already
// We can ignore the group guard condition inside
ALT: buildElement(ctx, element, true)
};
const guard = getGuardCondition(element);
if (guard) {
predicatedMethod.GATE = buildPredicate(guard);
}
methods.push(predicatedMethod);
}
const orIdx = ctx.or++;
const idFunc = /* @__PURE__ */ __name2((groupIdx, lParser) => {
const stackId = lParser.getRuleStack().join("-");
return `uGroup_${groupIdx}_${stackId}`;
}, "idFunc");
const alternatives = /* @__PURE__ */ __name2((args) => ctx.parser.alternatives(orIdx, methods.map((method, idx) => {
const alt = { ALT: /* @__PURE__ */ __name2(() => true, "ALT") };
const parser = ctx.parser;
alt.ALT = () => {
method.ALT(args);
if (!parser.isRecording()) {
const key = idFunc(orIdx, parser);
if (!parser.unorderedGroups.get(key)) {
parser.unorderedGroups.set(key, []);
}
const groupState = parser.unorderedGroups.get(key);
if (typeof groupState?.[idx] === "undefined") {
groupState[idx] = true;
}
}
};
const gate = method.GATE;
if (gate) {
alt.GATE = () => gate(args);
} else {
alt.GATE = () => {
const trackedAlternatives = parser.unorderedGroups.get(idFunc(orIdx, parser));
const allow = !trackedAlternatives?.[idx];
return allow;
};
}
return alt;
})), "alternatives");
const wrapped = wrap(ctx, getGuardCondition(group), alternatives, "*");
return (args) => {
wrapped(args);
if (!ctx.parser.isRecording()) {
ctx.parser.unorderedGroups.delete(idFunc(orIdx, ctx.parser));
}
};
}
__name(buildUnorderedGroup, "buildUnorderedGroup");
__name2(buildUnorderedGroup, "buildUnorderedGroup");
function buildGroup(ctx, group) {
const methods = group.elements.map((e) => buildElement(ctx, e));
return (args) => methods.forEach((method) => method(args));
}
__name(buildGroup, "buildGroup");
__name2(buildGroup, "buildGroup");
function getGuardCondition(element) {
if (isGroup(element)) {
return element.guardCondition;
}
return void 0;
}
__name(getGuardCondition, "getGuardCondition");
__name2(getGuardCondition, "getGuardCondition");
function buildCrossReference(ctx, crossRef, terminal = crossRef.terminal) {
if (!terminal) {
if (!crossRef.type.ref) {
throw new Error("Could not resolve reference to type: " + crossRef.type.$refText);
}
const assignment = findNameAssignment(crossRef.type.ref);
const assignTerminal = assignment?.terminal;
if (!assignTerminal) {
throw new Error("Could not find name assignment for type: " + getTypeName(crossRef.type.ref));
}
return buildCrossReference(ctx, crossRef, assignTerminal);
} else if (isRuleCall(terminal) && isParserRule(terminal.rule.ref)) {
const rule = terminal.rule.ref;
const idx = ctx.subrule++;
let subrule;
return (args) => {
subrule ?? (subrule = getRule(ctx, rule));
ctx.parser.subrule(idx, subrule, false, crossRef, args);
};
} else if (isRuleCall(terminal) && isTerminalRule(terminal.rule.ref)) {
const idx = ctx.consume++;
const terminalRule = getToken(ctx, terminal.rule.ref.name);
return () => ctx.parser.consume(idx, terminalRule, crossRef);
} else if (isKeyword(terminal)) {
const idx = ctx.consume++;
const keyword = getToken(ctx, terminal.value);
return () => ctx.parser.consume(idx, keyword, crossRef);
} else {
throw new Error("Could not build cross reference parser");
}
}
__name(buildCrossReference, "buildCrossReference");
__name2(buildCrossReference, "buildCrossReference");
function buildKeyword(ctx, keyword) {
const idx = ctx.consume++;
const token = ctx.tokens[keyword.value];
if (!token) {
throw new Error("Could not find token for keyword: " + keyword.value);
}
return () => ctx.parser.consume(idx, token, keyword);
}
__name(buildKeyword, "buildKeyword");
__name2(buildKeyword, "buildKeyword");
function wrap(ctx, guard, method, cardinality) {
const gate = guard && buildPredicate(guard);
if (!cardinality) {
if (gate) {
const idx = ctx.or++;
return (args) => ctx.parser.alternatives(idx, [
{
ALT: /* @__PURE__ */ __name2(() => method(args), "ALT"),
GATE: /* @__PURE__ */ __name2(() => gate(args), "GATE")
},
{
ALT: EMPTY_ALT(),
GATE: /* @__PURE__ */ __name2(() => !gate(args), "GATE")
}
]);
} else {
return method;
}
}
if (cardinality === "*") {
const idx = ctx.many++;
return (args) => ctx.parser.many(idx, {
DEF: /* @__PURE__ */ __name2(() => method(args), "DEF"),
GATE: gate ? () => gate(args) : void 0
});
} else if (cardinality === "+") {
const idx = ctx.many++;
if (gate) {
const orIdx = ctx.or++;
return (args) => ctx.parser.alternatives(orIdx, [
{
ALT: /* @__PURE__ */ __name2(() => ctx.parser.atLeastOne(idx, {
DEF: /* @__PURE__ */ __name2(() => method(args), "DEF")
}), "ALT"),
GATE: /* @__PURE__ */ __name2(() => gate(args), "GATE")
},
{
ALT: EMPTY_ALT(),
GATE: /* @__PURE__ */ __name2(() => !gate(args), "GATE")
}
]);
} else {
return (args) => ctx.parser.atLeastOne(idx, {
DEF: /* @__PURE__ */ __name2(() => method(args), "DEF")
});
}
} else if (cardinality === "?") {
const idx = ctx.optional++;
return (args) => ctx.parser.optional(idx, {
DEF: /* @__PURE__ */ __name2(() => method(args), "DEF"),
GATE: gate ? () => gate(args) : void 0
});
} else {
assertUnreachable(cardinality);
}
}
__name(wrap, "wrap");
__name2(wrap, "wrap");
function getRule(ctx, element) {
const name = getRuleName(ctx, element);
const rule = ctx.parser.getRule(name);
if (!rule)
throw new Error(`Rule "${name}" not found."`);
return rule;
}
__name(getRule, "getRule");
__name2(getRule, "getRule");
function getRuleName(ctx, element) {
if (isAbstractParserRule(element)) {
return element.name;
} else if (ctx.ruleNames.has(element)) {
return ctx.ruleNames.get(element);
} else {
let item = element;
let parent = item.$container;
let ruleName = element.$type;
while (!isParserRule(parent)) {
if (isGroup(parent) || isAlternatives(parent) || isUnorderedGroup(parent)) {
const index = parent.elements.indexOf(item);
ruleName = index.toString() + ":" + ruleName;
}
item = parent;
parent = parent.$container;
}
const rule = parent;
ruleName = rule.name + ":" + ruleName;
ctx.ruleNames.set(element, ruleName);
return ruleName;
}
}
__name(getRuleName, "getRuleName");
__name2(getRuleName, "getRuleName");
function getToken(ctx, name) {
const token = ctx.tokens[name];
if (!token)
throw new Error(`Token "${name}" not found."`);
return token;
}
__name(getToken, "getToken");
__name2(getToken, "getToken");
function createCompletionParser(services) {
const grammar = services.Grammar;
const lexer = services.parser.Lexer;
const parser = new LangiumCompletionParser(services);
createParser(grammar, parser, lexer.definition);
parser.finalize();
return parser;
}
__name(createCompletionParser, "createCompletionParser");
__name2(createCompletionParser, "createCompletionParser");
function createLangiumParser(services) {
const parser = prepareLangiumParser(services);
parser.finalize();
return parser;
}
__name(createLangiumParser, "createLangiumParser");
__name2(createLangiumParser, "createLangiumParser");
function prepareLangiumParser(services) {
const grammar = services.Grammar;
const lexer = services.parser.Lexer;
const parser = new LangiumParser(services);
return createParser(grammar, parser, lexer.definition);
}
__name(prepareLangiumParser, "prepareLangiumParser");
__name2(prepareLangiumParser, "prepareLangiumParser");
var DefaultTokenBuilder = class {
static {
__name(this, "DefaultTokenBuilder");
}
static {
__name2(this, "DefaultTokenBuilder");
}
constructor() {
this.diagnostics = [];
}
buildTokens(grammar, options) {
const reachableRules = stream(getAllReachableRules(grammar, false));
const terminalTokens = this.buildTerminalTokens(reachableRules);
const tokens = this.buildKeywordTokens(reachableRules, terminalTokens, options);
tokens.push(...terminalTokens);
return tokens;
}
// eslint-disable-next-line @typescript-eslint/no-unused-vars
flushLexingReport(text) {
return { diagnostics: this.popDiagnostics() };
}
popDiagnostics() {
const diagnostics = [...this.diagnostics];
this.diagnostics = [];
return diagnostics;
}
buildTerminalTokens(rules) {
return rules.filter(isTerminalRule).filter((e) => !e.fragment).map((terminal) => this.buildTerminalToken(terminal)).toArray();
}
buildTerminalToken(terminal) {
const regex = terminalRegex(terminal);
const pattern = this.requiresCustomPattern(regex) ? this.regexPatternFunction(regex) : regex;
const tokenType = {
name: terminal.name,
PATTERN: pattern
};
if (typeof pattern === "function") {
tokenType.LINE_BREAKS = true;
}
if (terminal.hidden) {
tokenType.GROUP = isWhitespace(regex) ? Lexer.SKIPPED : "hidden";
}
return tokenType;
}
requiresCustomPattern(regex) {
if (regex.flags.includes("u") || regex.flags.includes("s")) {
return true;
} else {
return false;
}
}
regexPatternFunction(regex) {
const stickyRegex = new RegExp(regex, regex.flags + "y");
return (text, offset) => {
stickyRegex.lastIndex = offset;
const execResult = stickyRegex.exec(text);
return execResult;
};
}
buildKeywordTokens(rules, terminalTokens, options) {
return rules.filter(isAbstractParserRule).flatMap((rule) => streamAllContents(rule).filter(isKeyword)).distinct((e) => e.value).toArray().sort((a, b) => b.value.length - a.value.length).map((keyword) => this.buildKeywordToken(keyword, terminalTokens, Boolean(options?.caseInsensitive)));
}
buildKeywordToken(keyword, terminalTokens, caseInsensitive) {
const keywordPattern = this.buildKeywordPattern(keyword, caseInsensitive);
const tokenType = {
name: keyword.value,
PATTERN: keywordPattern,
LONGER_ALT: this.findLongerAlt(keyword, terminalTokens)
};
if (typeof keywordPattern === "function") {
tokenType.LINE_BREAKS = true;
}
return tokenType;
}
buildKeywordPattern(keyword, caseInsensitive) {
return caseInsensitive ? new RegExp(escapeRegExp(keyword.value), "i") : keyword.value;
}
findLongerAlt(keyword, terminalTokens) {
return terminalTokens.reduce((longerAlts, token) => {
const pattern = token?.PATTERN;
if (pattern?.source && partialMatches("^" + pattern.source + "$", keyword.value)) {
longerAlts.push(token);
}
return longerAlts;
}, []);
}
};
var DefaultValueConverter = class {
static {
__name(this, "DefaultValueConverter");
}
static {
__name2(this, "DefaultValueConverter");
}
convert(input, cstNode) {
let feature = cstNode.grammarSource;
if (isCrossReference(feature)) {
feature = getCrossReferenceTerminal(feature);
}
if (isRuleCall(feature)) {
const rule = feature.rule.ref;
if (!rule) {
throw new Error("This cst node was not parsed by a rule.");
}
return this.runConverter(rule, input, cstNode);
}
return input;
}
// eslint-disable-next-line @typescript-eslint/no-unused-vars
runConverter(rule, input, cstNode) {
switch (rule.name.toUpperCase()) {
case "INT":
return ValueConverter.convertInt(input);
case "STRING":
return ValueConverter.convertString(input);
case "ID":
return ValueConverter.convertID(input);
}
switch (getRuleType(rule)?.toLowerCase()) {
case "number":
return ValueConverter.convertNumber(input);
case "boolean":
return ValueConverter.convertBoolean(input);
case "bigint":
return ValueConverter.convertBigint(input);
case "date":
return ValueConverter.convertDate(input);
default:
return input;
}
}
};
var ValueConverter;
(function(ValueConverter2) {
function convertString(input) {
let result = "";
for (let i = 1; i < input.length - 1; i++) {
const c = input.charAt(i);
if (c === "\\") {
const c1 = input.charAt(++i);
result += convertEscapeCharacter(c1);
} else {
result += c;
}
}
return result;
}
__name(convertString, "convertString");
__name2(convertString, "convertString");
ValueConverter2.convertString = convertString;
function convertEscapeCharacter(char) {
switch (char) {
case "b":
return "\b";
case "f":
return "\f";
case "n":
return "\n";
case "r":
return "\r";
case "t":
return " ";
case "v":
return "\v";
case "0":
return "\0";
default:
return char;
}
}
__name(convertEscapeCharacter, "convertEscapeCharacter");
__name2(convertEscapeCharacter, "convertEscapeCharacter");
function convertID(input) {
if (input.charAt(0) === "^") {
return input.substring(1);
} else {
return input;
}
}
__name(convertID, "convertID");
__name2(convertID, "convertID");
ValueConverter2.convertID = convertID;
function convertInt(input) {
return parseInt(input);
}
__name(convertInt, "convertInt");
__name2(convertInt, "convertInt");
ValueConverter2.convertInt = convertInt;
function convertBigint(input) {
return BigInt(input);
}
__name(convertBigint, "convertBigint");
__name2(convertBigint, "convertBigint");
ValueConverter2.convertBigint = convertBigint;
function convertDate(input) {
return new Date(input);
}
__name(convertDate, "convertDate");
__name2(convertDate, "convertDate");
ValueConverter2.convertDate = convertDate;
function convertNumber(input) {
return Number(input);
}
__name(convertNumber, "convertNumber");
__name2(convertNumber, "convertNumber");
ValueConverter2.convertNumber = convertNumber;
function convertBoolean(input) {
return input.toLowerCase() === "true";
}
__name(convertBoolean, "convertBoolean");
__name2(convertBoolean, "convertBoolean");
ValueConverter2.convertBoolean = convertBoolean;
})(ValueConverter || (ValueConverter = {}));
var cancellation_exports = {};
__reExport(cancellation_exports, __toESM(require_cancellation(), 1));
function delayNextTick() {
return new Promise((resolve) => {
if (typeof setImmediate === "undefined") {
setTimeout(resolve, 0);
} else {
setImmediate(resolve);
}
});
}
__name(delayNextTick, "delayNextTick");
__name2(delayNextTick, "delayNextTick");
var lastTick = 0;
var globalInterruptionPeriod = 10;
function startCancelableOperation() {
lastTick = performance.now();
return new cancellation_exports.CancellationTokenSource();
}
__name(startCancelableOperation, "startCancelableOperation");
__name2(startCancelableOperation, "startCancelableOperation");
function setInterruptionPeriod(period) {
globalInterruptionPeriod = period;
}
__name(setInterruptionPeriod, "setInterruptionPeriod");
__name2(setInterruptionPeriod, "setInterruptionPeriod");
var OperationCancelled = Symbol("OperationCancelled");
function isOperationCancelled(err) {
return err === OperationCancelled;
}
__name(isOperationCancelled, "isOperationCancelled");
__name2(isOperationCancelled, "isOperationCancelled");
async function interruptAndCheck(token) {
if (token === cancellation_exports.CancellationToken.None) {
return;
}
const current = performance.now();
if (current - lastTick >= globalInterruptionPeriod) {
lastTick = current;
await delayNextTick();
lastTick = performance.now();
}
if (token.isCancellationRequested) {
throw OperationCancelled;
}
}
__name(interruptAndCheck, "interruptAndCheck");
__name2(interruptAndCheck, "interruptAndCheck");
var Deferred = class {
static {
__name(this, "Deferred");
}
static {
__name2(this, "Deferred");
}
constructor() {
this.promise = new Promise((resolve, reject2) => {
this.resolve = (arg) => {
resolve(arg);
return this;
};
this.reject = (err) => {
reject2(err);
return this;
};
});
}
};
var FullTextDocument2 = class _FullTextDocument {
static {
__name(this, "_FullTextDocument");
}
static {
__name2(this, "FullTextDocument");
}
constructor(uri, languageId, version, content) {
this._uri = uri;
this._languageId = languageId;
this._version = version;
this._content = content;
this._lineOffsets = void 0;
}
get uri() {
return this._uri;
}
get languageId() {
return this._languageId;
}
get version() {
return this._version;
}
getText(range) {
if (range) {
const start = this.offsetAt(range.start);
const end = this.offsetAt(range.end);
return this._content.substring(start, end);
}
return this._content;
}
update(changes, version) {
for (const change of changes) {
if (_FullTextDocument.isIncremental(change)) {
const range = getWellformedRange(change.range);
const startOffset = this.offsetAt(range.start);
const endOffset = this.offsetAt(range.end);
this._content = this._content.substring(0, startOffset) + change.text + this._content.substring(endOffset, this._content.length);
const startLine = Math.max(range.start.line, 0);
const endLine = Math.max(range.end.line, 0);
let lineOffsets = this._lineOffsets;
const addedLineOffsets = computeLineOffsets(change.text, false, startOffset);
if (endLine - startLine === addedLineOffsets.length) {
for (let i = 0, len = addedLineOffsets.length; i < len; i++) {
lineOffsets[i + startLine + 1] = addedLineOffsets[i];
}
} else {
if (addedLineOffsets.length < 1e4) {
lineOffsets.splice(startLine + 1, endLine - startLine, ...addedLineOffsets);
} else {
this._lineOffsets = lineOffsets = lineOffsets.slice(0, startLine + 1).concat(addedLineOffsets, lineOffsets.slice(endLine + 1));
}
}
const diff = change.text.length - (endOffset - startOffset);
if (diff !== 0) {
for (let i = startLine + 1 + addedLineOffsets.length, len = lineOffsets.length; i < len; i++) {
lineOffsets[i] = lineOffsets[i] + diff;
}
}
} else if (_FullTextDocument.isFull(change)) {
this._content = change.text;
this._lineOffsets = void 0;
} else {
throw new Error("Unknown change event received");
}
}
this._version = version;
}
getLineOffsets() {
if (this._lineOffsets === void 0) {
this._lineOffsets = computeLineOffsets(this._content, true);
}
return this._lineOffsets;
}
positionAt(offset) {
offset = Math.max(Math.min(offset, this._content.length), 0);
const lineOffsets = this.getLineOffsets();
let low = 0, high = lineOffsets.length;
if (high === 0) {
return { line: 0, character: offset };
}
while (low < high) {
const mid = Math.floor((low + high) / 2);
if (lineOffsets[mid] > offset) {
high = mid;
} else {
low = mid + 1;
}
}
const line = low - 1;
offset = this.ensureBeforeEOL(offset, lineOffsets[line]);
return { line, character: offset - lineOffsets[line] };
}
offsetAt(position) {
const lineOffsets = this.getLineOffsets();
if (position.line >= lineOffsets.length) {
return this._content.length;
} else if (position.line < 0) {
return 0;
}
const lineOffset = lineOffsets[position.line];
if (position.character <= 0) {
return lineOffset;
}
const nextLineOffset = position.line + 1 < lineOffsets.length ? lineOffsets[position.line + 1] : this._content.length;
const offset = Math.min(lineOffset + position.character, nextLineOffset);
return this.ensureBeforeEOL(offset, lineOffset);
}
ensureBeforeEOL(offset, lineOffset) {
while (offset > lineOffset && isEOL(this._content.charCodeAt(offset - 1))) {
offset--;
}
return offset;
}
get lineCount() {
return this.getLineOffsets().length;
}
static isIncremental(event) {
const candidate = event;
return candidate !== void 0 && candidate !== null && typeof candidate.text === "string" && candidate.range !== void 0 && (candidate.rangeLength === void 0 || typeof candidate.rangeLength === "number");
}
static isFull(event) {
const candidate = event;
return candidate !== void 0 && candidate !== null && typeof candidate.text === "string" && candidate.range === void 0 && candidate.rangeLength === void 0;
}
};
var TextDocument2;
(function(TextDocument3) {
function create(uri, languageId, version, content) {
return new FullTextDocument2(uri, languageId, version, content);
}
__name(create, "create");
__name2(create, "create");
TextDocument3.create = create;
function update(document, changes, version) {
if (document instanceof FullTextDocument2) {
document.update(changes, version);
return document;
} else {
throw new Error("TextDocument.update: document must be created by TextDocument.create");
}
}
__name(update, "update");
__name2(update, "update");
TextDocument3.update = update;
function applyEdits(document, edits) {
const text = document.getText();
const sortedEdits = mergeSort(edits.map(getWellformedEdit), (a, b) => {
const diff = a.range.start.line - b.range.start.line;
if (diff === 0) {
return a.range.start.character - b.range.start.character;
}
return diff;
});
let lastModifiedOffset = 0;
const spans = [];
for (const e of sortedEdits) {
const startOffset = document.offsetAt(e.range.start);
if (startOffset < lastModifiedOffset) {
throw new Error("Overlapping edit");
} else if (startOffset > lastModifiedOffset) {
spans.push(text.substring(lastModifiedOffset, startOffset));
}
if (e.newText.length) {
spans.push(e.newText);
}
lastModifiedOffset = document.offsetAt(e.range.end);
}
spans.push(text.substr(lastModifiedOffset));
return spans.join("");
}
__name(applyEdits, "applyEdits");
__name2(applyEdits, "applyEdits");
TextDocument3.applyEdits = applyEdits;
})(TextDocument2 || (TextDocument2 = {}));
function mergeSort(data, compare) {
if (data.length <= 1) {
return data;
}
const p = data.length / 2 | 0;
const left = data.slice(0, p);
const right = data.slice(p);
mergeSort(left, compare);
mergeSort(right, compare);
let leftIdx = 0;
let rightIdx = 0;
let i = 0;
while (leftIdx < left.length && rightIdx < right.length) {
const ret = compare(left[leftIdx], right[rightIdx]);
if (ret <= 0) {
data[i++] = left[leftIdx++];
} else {
data[i++] = right[rightIdx++];
}
}
while (leftIdx < left.length) {
data[i++] = left[leftIdx++];
}
while (rightIdx < right.length) {
data[i++] = right[rightIdx++];
}
return data;
}
__name(mergeSort, "mergeSort");
__name2(mergeSort, "mergeSort");
function computeLineOffsets(text, isAtLineStart, textOffset = 0) {
const result = isAtLineStart ? [textOffset] : [];
for (let i = 0; i < text.length; i++) {
const ch = text.charCodeAt(i);
if (isEOL(ch)) {
if (ch === 13 && i + 1 < text.length && text.charCodeAt(i + 1) === 10) {
i++;
}
result.push(textOffset + i + 1);
}
}
return result;
}
__name(computeLineOffsets, "computeLineOffsets");
__name2(computeLineOffsets, "computeLineOffsets");
function isEOL(char) {
return char === 13 || char === 10;
}
__name(isEOL, "isEOL");
__name2(isEOL, "isEOL");
function getWellformedRange(range) {
const start = range.start;
const end = range.end;
if (start.line > end.line || start.line === end.line && start.character > end.character) {
return { start: end, end: start };
}
return range;
}
__name(getWellformedRange, "getWellformedRange");
__name2(getWellformedRange, "getWellformedRange");
function getWellformedEdit(textEdit) {
const range = getWellformedRange(textEdit.range);
if (range !== textEdit.range) {
return { newText: textEdit.newText, range };
}
return textEdit;
}
__name(getWellformedEdit, "getWellformedEdit");
__name2(getWellformedEdit, "getWellformedEdit");
var LIB;
(() => {
"use strict";
var t = { 975: (t2) => {
function e2(t3) {
if ("string" != typeof t3) throw new TypeError("Path must be a string. Received " + JSON.stringify(t3));
}
__name(e2, "e2");
__name2(e2, "e");
function r2(t3, e3) {
for (var r3, n3 = "", i2 = 0, o2 = -1, s2 = 0, h2 = 0; h2 <= t3.length; ++h2) {
if (h2 < t3.length) r3 = t3.charCodeAt(h2);
else {
if (47 === r3) break;
r3 = 47;
}
if (47 === r3) {
if (o2 === h2 - 1 || 1 === s2) ;
else if (o2 !== h2 - 1 && 2 === s2) {
if (n3.length < 2 || 2 !== i2 || 46 !== n3.charCodeAt(n3.length - 1) || 46 !== n3.charCodeAt(n3.length - 2)) {
if (n3.length > 2) {
var a2 = n3.lastIndexOf("/");
if (a2 !== n3.length - 1) {
-1 === a2 ? (n3 = "", i2 = 0) : i2 = (n3 = n3.slice(0, a2)).length - 1 - n3.lastIndexOf("/"), o2 = h2, s2 = 0;
continue;
}
} else if (2 === n3.length || 1 === n3.length) {
n3 = "", i2 = 0, o2 = h2, s2 = 0;
continue;
}
}
e3 && (n3.length > 0 ? n3 += "/.." : n3 = "..", i2 = 2);
} else n3.length > 0 ? n3 += "/" + t3.slice(o2 + 1, h2) : n3 = t3.slice(o2 + 1, h2), i2 = h2 - o2 - 1;
o2 = h2, s2 = 0;
} else 46 === r3 && -1 !== s2 ? ++s2 : s2 = -1;
}
return n3;
}
__name(r2, "r2");
__name2(r2, "r");
var n2 = { resolve: /* @__PURE__ */ __name2(function() {
for (var t3, n3 = "", i2 = false, o2 = arguments.length - 1; o2 >= -1 && !i2; o2--) {
var s2;
o2 >= 0 ? s2 = arguments[o2] : (void 0 === t3 && (t3 = process.cwd()), s2 = t3), e2(s2), 0 !== s2.length && (n3 = s2 + "/" + n3, i2 = 47 === s2.charCodeAt(0));
}
return n3 = r2(n3, !i2), i2 ? n3.length > 0 ? "/" + n3 : "/" : n3.length > 0 ? n3 : ".";
}, "resolve"), normalize: /* @__PURE__ */ __name2(function(t3) {
if (e2(t3), 0 === t3.length) return ".";
var n3 = 47 === t3.charCodeAt(0), i2 = 47 === t3.charCodeAt(t3.length - 1);
return 0 !== (t3 = r2(t3, !n3)).length || n3 || (t3 = "."), t3.length > 0 && i2 && (t3 += "/"), n3 ? "/" + t3 : t3;
}, "normalize"), isAbsolute: /* @__PURE__ */ __name2(function(t3) {
return e2(t3), t3.length > 0 && 47 === t3.charCodeAt(0);
}, "isAbsolute"), join: /* @__PURE__ */ __name2(function() {
if (0 === arguments.length) return ".";
for (var t3, r3 = 0; r3 < arguments.length; ++r3) {
var i2 = arguments[r3];
e2(i2), i2.length > 0 && (void 0 === t3 ? t3 = i2 : t3 += "/" + i2);
}
return void 0 === t3 ? "." : n2.normalize(t3);
}, "join"), relative: /* @__PURE__ */ __name2(function(t3, r3) {
if (e2(t3), e2(r3), t3 === r3) return "";
if ((t3 = n2.resolve(t3)) === (r3 = n2.resolve(r3))) return "";
for (var i2 = 1; i2 < t3.length && 47 === t3.charCodeAt(i2); ++i2) ;
for (var o2 = t3.length, s2 = o2 - i2, h2 = 1; h2 < r3.length && 47 === r3.charCodeAt(h2); ++h2) ;
for (var a2 = r3.length - h2, c2 = s2 < a2 ? s2 : a2, f2 = -1, u2 = 0; u2 <= c2; ++u2) {
if (u2 === c2) {
if (a2 > c2) {
if (47 === r3.charCodeAt(h2 + u2)) return r3.slice(h2 + u2 + 1);
if (0 === u2) return r3.slice(h2 + u2);
} else s2 > c2 && (47 === t3.charCodeAt(i2 + u2) ? f2 = u2 : 0 === u2 && (f2 = 0));
break;
}
var l2 = t3.charCodeAt(i2 + u2);
if (l2 !== r3.charCodeAt(h2 + u2)) break;
47 === l2 && (f2 = u2);
}
var g2 = "";
for (u2 = i2 + f2 + 1; u2 <= o2; ++u2) u2 !== o2 && 47 !== t3.charCodeAt(u2) || (0 === g2.length ? g2 += ".." : g2 += "/..");
return g2.length > 0 ? g2 + r3.slice(h2 + f2) : (h2 += f2, 47 === r3.charCodeAt(h2) && ++h2, r3.slice(h2));
}, "relative"), _makeLong: /* @__PURE__ */ __name2(function(t3) {
return t3;
}, "_makeLong"), dirname: /* @__PURE__ */ __name2(function(t3) {
if (e2(t3), 0 === t3.length) return ".";
for (var r3 = t3.charCodeAt(0), n3 = 47 === r3, i2 = -1, o2 = true, s2 = t3.length - 1; s2 >= 1; --s2) if (47 === (r3 = t3.charCodeAt(s2))) {
if (!o2) {
i2 = s2;
break;
}
} else o2 = false;
return -1 === i2 ? n3 ? "/" : "." : n3 && 1 === i2 ? "//" : t3.slice(0, i2);
}, "dirname"), basename: /* @__PURE__ */ __name2(function(t3, r3) {
if (void 0 !== r3 && "string" != typeof r3) throw new TypeError('"ext" argument must be a string');
e2(t3);
var n3, i2 = 0, o2 = -1, s2 = true;
if (void 0 !== r3 && r3.length > 0 && r3.length <= t3.length) {
if (r3.length === t3.length && r3 === t3) return "";
var h2 = r3.length - 1, a2 = -1;
for (n3 = t3.length - 1; n3 >= 0; --n3) {
var c2 = t3.charCodeAt(n3);
if (47 === c2) {
if (!s2) {
i2 = n3 + 1;
break;
}
} else -1 === a2 && (s2 = false, a2 = n3 + 1), h2 >= 0 && (c2 === r3.charCodeAt(h2) ? -1 == --h2 && (o2 = n3) : (h2 = -1, o2 = a2));
}
return i2 === o2 ? o2 = a2 : -1 === o2 && (o2 = t3.length), t3.slice(i2, o2);
}
for (n3 = t3.length - 1; n3 >= 0; --n3) if (47 === t3.charCodeAt(n3)) {
if (!s2) {
i2 = n3 + 1;
break;
}
} else -1 === o2 && (s2 = false, o2 = n3 + 1);
return -1 === o2 ? "" : t3.slice(i2, o2);
}, "basename"), extname: /* @__PURE__ */ __name2(function(t3) {
e2(t3);
for (var r3 = -1, n3 = 0, i2 = -1, o2 = true, s2 = 0, h2 = t3.length - 1; h2 >= 0; --h2) {
var a2 = t3.charCodeAt(h2);
if (47 !== a2) -1 === i2 && (o2 = false, i2 = h2 + 1), 46 === a2 ? -1 === r3 ? r3 = h2 : 1 !== s2 && (s2 = 1) : -1 !== r3 && (s2 = -1);
else if (!o2) {
n3 = h2 + 1;
break;
}
}
return -1 === r3 || -1 === i2 || 0 === s2 || 1 === s2 && r3 === i2 - 1 && r3 === n3 + 1 ? "" : t3.slice(r3, i2);
}, "extname"), format: /* @__PURE__ */ __name2(function(t3) {
if (null === t3 || "object" != typeof t3) throw new TypeError('The "pathObject" argument must be of type Object. Received type ' + typeof t3);
return (function(t4, e3) {
var r3 = e3.dir || e3.root, n3 = e3.base || (e3.name || "") + (e3.ext || "");
return r3 ? r3 === e3.root ? r3 + n3 : r3 + "/" + n3 : n3;
})(0, t3);
}, "format"), parse: /* @__PURE__ */ __name2(function(t3) {
e2(t3);
var r3 = { root: "", dir: "", base: "", ext: "", name: "" };
if (0 === t3.length) return r3;
var n3, i2 = t3.charCodeAt(0), o2 = 47 === i2;
o2 ? (r3.root = "/", n3 = 1) : n3 = 0;
for (var s2 = -1, h2 = 0, a2 = -1, c2 = true, f2 = t3.length - 1, u2 = 0; f2 >= n3; --f2) if (47 !== (i2 = t3.charCodeAt(f2))) -1 === a2 && (c2 = false, a2 = f2 + 1), 46 === i2 ? -1 === s2 ? s2 = f2 : 1 !== u2 && (u2 = 1) : -1 !== s2 && (u2 = -1);
else if (!c2) {
h2 = f2 + 1;
break;
}
return -1 === s2 || -1 === a2 || 0 === u2 || 1 === u2 && s2 === a2 - 1 && s2 === h2 + 1 ? -1 !== a2 && (r3.base = r3.name = 0 === h2 && o2 ? t3.slice(1, a2) : t3.slice(h2, a2)) : (0 === h2 && o2 ? (r3.name = t3.slice(1, s2), r3.base = t3.slice(1, a2)) : (r3.name = t3.slice(h2, s2), r3.base = t3.slice(h2, a2)), r3.ext = t3.slice(s2, a2)), h2 > 0 ? r3.dir = t3.slice(0, h2 - 1) : o2 && (r3.dir = "/"), r3;
}, "parse"), sep: "/", delimiter: ":", win32: null, posix: null };
n2.posix = n2, t2.exports = n2;
} }, e = {};
function r(n2) {
var i2 = e[n2];
if (void 0 !== i2) return i2.exports;
var o2 = e[n2] = { exports: {} };
return t[n2](o2, o2.exports, r), o2.exports;
}
__name(r, "r");
__name2(r, "r");
r.d = (t2, e2) => {
for (var n2 in e2) r.o(e2, n2) && !r.o(t2, n2) && Object.defineProperty(t2, n2, { enumerable: true, get: e2[n2] });
}, r.o = (t2, e2) => Object.prototype.hasOwnProperty.call(t2, e2), r.r = (t2) => {
"undefined" != typeof Symbol && Symbol.toStringTag && Object.defineProperty(t2, Symbol.toStringTag, { value: "Module" }), Object.defineProperty(t2, "__esModule", { value: true });
};
var n = {};
let i;
if (r.r(n), r.d(n, { URI: /* @__PURE__ */ __name2(() => l, "URI"), Utils: /* @__PURE__ */ __name2(() => I, "Utils") }), "object" == typeof process) i = "win32" === process.platform;
else if ("object" == typeof navigator) {
let t2 = navigator.userAgent;
i = t2.indexOf("Windows") >= 0;
}
const o = /^\w[\w\d+.-]*$/, s = /^\//, h = /^\/\//;
function a(t2, e2) {
if (!t2.scheme && e2) throw new Error(`[UriError]: Scheme is missing: {scheme: "", authority: "${t2.authority}", path: "${t2.path}", query: "${t2.query}", fragment: "${t2.fragment}"}`);
if (t2.scheme && !o.test(t2.scheme)) throw new Error("[UriError]: Scheme contains illegal characters.");
if (t2.path) {
if (t2.authority) {
if (!s.test(t2.path)) throw new Error('[UriError]: If a URI contains an authority component, then the path component must either be empty or begin with a slash ("/") character');
} else if (h.test(t2.path)) throw new Error('[UriError]: If a URI does not contain an authority component, then the path cannot begin with two slash characters ("//")');
}
}
__name(a, "a");
__name2(a, "a");
const c = "", f = "/", u = /^(([^:/?#]+?):)?(\/\/([^/?#]*))?([^?#]*)(\?([^#]*))?(#(.*))?/;
class l {
static {
__name(this, "l");
}
static {
__name2(this, "l");
}
static isUri(t2) {
return t2 instanceof l || !!t2 && "string" == typeof t2.authority && "string" == typeof t2.fragment && "string" == typeof t2.path && "string" == typeof t2.query && "string" == typeof t2.scheme && "string" == typeof t2.fsPath && "function" == typeof t2.with && "function" == typeof t2.toString;
}
scheme;
authority;
path;
query;
fragment;
constructor(t2, e2, r2, n2, i2, o2 = false) {
"object" == typeof t2 ? (this.scheme = t2.scheme || c, this.authority = t2.authority || c, this.path = t2.path || c, this.query = t2.query || c, this.fragment = t2.fragment || c) : (this.scheme = /* @__PURE__ */ (function(t3, e3) {
return t3 || e3 ? t3 : "file";
})(t2, o2), this.authority = e2 || c, this.path = (function(t3, e3) {
switch (t3) {
case "https":
case "http":
case "file":
e3 ? e3[0] !== f && (e3 = f + e3) : e3 = f;
}
return e3;
})(this.scheme, r2 || c), this.query = n2 || c, this.fragment = i2 || c, a(this, o2));
}
get fsPath() {
return v(this, false);
}
with(t2) {
if (!t2) return this;
let { scheme: e2, authority: r2, path: n2, query: i2, fragment: o2 } = t2;
return void 0 === e2 ? e2 = this.scheme : null === e2 && (e2 = c), void 0 === r2 ? r2 = this.authority : null === r2 && (r2 = c), void 0 === n2 ? n2 = this.path : null === n2 && (n2 = c), void 0 === i2 ? i2 = this.query : null === i2 && (i2 = c), void 0 === o2 ? o2 = this.fragment : null === o2 && (o2 = c), e2 === this.scheme && r2 === this.authority && n2 === this.path && i2 === this.query && o2 === this.fragment ? this : new d(e2, r2, n2, i2, o2);
}
static parse(t2, e2 = false) {
const r2 = u.exec(t2);
return r2 ? new d(r2[2] || c, w(r2[4] || c), w(r2[5] || c), w(r2[7] || c), w(r2[9] || c), e2) : new d(c, c, c, c, c);
}
static file(t2) {
let e2 = c;
if (i && (t2 = t2.replace(/\\/g, f)), t2[0] === f && t2[1] === f) {
const r2 = t2.indexOf(f, 2);
-1 === r2 ? (e2 = t2.substring(2), t2 = f) : (e2 = t2.substring(2, r2), t2 = t2.substring(r2) || f);
}
return new d("file", e2, t2, c, c);
}
static from(t2) {
const e2 = new d(t2.scheme, t2.authority, t2.path, t2.query, t2.fragment);
return a(e2, true), e2;
}
toString(t2 = false) {
return b(this, t2);
}
toJSON() {
return this;
}
static revive(t2) {
if (t2) {
if (t2 instanceof l) return t2;
{
const e2 = new d(t2);
return e2._formatted = t2.external, e2._fsPath = t2._sep === g ? t2.fsPath : null, e2;
}
}
return t2;
}
}
const g = i ? 1 : void 0;
class d extends l {
static {
__name(this, "d");
}
static {
__name2(this, "d");
}
_formatted = null;
_fsPath = null;
get fsPath() {
return this._fsPath || (this._fsPath = v(this, false)), this._fsPath;
}
toString(t2 = false) {
return t2 ? b(this, true) : (this._formatted || (this._formatted = b(this, false)), this._formatted);
}
toJSON() {
const t2 = { $mid: 1 };
return this._fsPath && (t2.fsPath = this._fsPath, t2._sep = g), this._formatted && (t2.external = this._formatted), this.path && (t2.path = this.path), this.scheme && (t2.scheme = this.scheme), this.authority && (t2.authority = this.authority), this.query && (t2.query = this.query), this.fragment && (t2.fragment = this.fragment), t2;
}
}
const p = { 58: "%3A", 47: "%2F", 63: "%3F", 35: "%23", 91: "%5B", 93: "%5D", 64: "%40", 33: "%21", 36: "%24", 38: "%26", 39: "%27", 40: "%28", 41: "%29", 42: "%2A", 43: "%2B", 44: "%2C", 59: "%3B", 61: "%3D", 32: "%20" };
function m(t2, e2, r2) {
let n2, i2 = -1;
for (let o2 = 0; o2 < t2.length; o2++) {
const s2 = t2.charCodeAt(o2);
if (s2 >= 97 && s2 <= 122 || s2 >= 65 && s2 <= 90 || s2 >= 48 && s2 <= 57 || 45 === s2 || 46 === s2 || 95 === s2 || 126 === s2 || e2 && 47 === s2 || r2 && 91 === s2 || r2 && 93 === s2 || r2 && 58 === s2) -1 !== i2 && (n2 += encodeURIComponent(t2.substring(i2, o2)), i2 = -1), void 0 !== n2 && (n2 += t2.charAt(o2));
else {
void 0 === n2 && (n2 = t2.substr(0, o2));
const e3 = p[s2];
void 0 !== e3 ? (-1 !== i2 && (n2 += encodeURIComponent(t2.substring(i2, o2)), i2 = -1), n2 += e3) : -1 === i2 && (i2 = o2);
}
}
return -1 !== i2 && (n2 += encodeURIComponent(t2.substring(i2))), void 0 !== n2 ? n2 : t2;
}
__name(m, "m");
__name2(m, "m");
function y(t2) {
let e2;
for (let r2 = 0; r2 < t2.length; r2++) {
const n2 = t2.charCodeAt(r2);
35 === n2 || 63 === n2 ? (void 0 === e2 && (e2 = t2.substr(0, r2)), e2 += p[n2]) : void 0 !== e2 && (e2 += t2[r2]);
}
return void 0 !== e2 ? e2 : t2;
}
__name(y, "y");
__name2(y, "y");
function v(t2, e2) {
let r2;
return r2 = t2.authority && t2.path.length > 1 && "file" === t2.scheme ? `//${t2.authority}${t2.path}` : 47 === t2.path.charCodeAt(0) && (t2.path.charCodeAt(1) >= 65 && t2.path.charCodeAt(1) <= 90 || t2.path.charCodeAt(1) >= 97 && t2.path.charCodeAt(1) <= 122) && 58 === t2.path.charCodeAt(2) ? e2 ? t2.path.substr(1) : t2.path[1].toLowerCase() + t2.path.substr(2) : t2.path, i && (r2 = r2.replace(/\//g, "\\")), r2;
}
__name(v, "v");
__name2(v, "v");
function b(t2, e2) {
const r2 = e2 ? y : m;
let n2 = "", { scheme: i2, authority: o2, path: s2, query: h2, fragment: a2 } = t2;
if (i2 && (n2 += i2, n2 += ":"), (o2 || "file" === i2) && (n2 += f, n2 += f), o2) {
let t3 = o2.indexOf("@");
if (-1 !== t3) {
const e3 = o2.substr(0, t3);
o2 = o2.substr(t3 + 1), t3 = e3.lastIndexOf(":"), -1 === t3 ? n2 += r2(e3, false, false) : (n2 += r2(e3.substr(0, t3), false, false), n2 += ":", n2 += r2(e3.substr(t3 + 1), false, true)), n2 += "@";
}
o2 = o2.toLowerCase(), t3 = o2.lastIndexOf(":"), -1 === t3 ? n2 += r2(o2, false, true) : (n2 += r2(o2.substr(0, t3), false, true), n2 += o2.substr(t3));
}
if (s2) {
if (s2.length >= 3 && 47 === s2.charCodeAt(0) && 58 === s2.charCodeAt(2)) {
const t3 = s2.charCodeAt(1);
t3 >= 65 && t3 <= 90 && (s2 = `/${String.fromCharCode(t3 + 32)}:${s2.substr(3)}`);
} else if (s2.length >= 2 && 58 === s2.charCodeAt(1)) {
const t3 = s2.charCodeAt(0);
t3 >= 65 && t3 <= 90 && (s2 = `${String.fromCharCode(t3 + 32)}:${s2.substr(2)}`);
}
n2 += r2(s2, true, false);
}
return h2 && (n2 += "?", n2 += r2(h2, false, false)), a2 && (n2 += "#", n2 += e2 ? a2 : m(a2, false, false)), n2;
}
__name(b, "b");
__name2(b, "b");
function C(t2) {
try {
return decodeURIComponent(t2);
} catch {
return t2.length > 3 ? t2.substr(0, 3) + C(t2.substr(3)) : t2;
}
}
__name(C, "C");
__name2(C, "C");
const A = /(%[0-9A-Za-z][0-9A-Za-z])+/g;
function w(t2) {
return t2.match(A) ? t2.replace(A, ((t3) => C(t3))) : t2;
}
__name(w, "w");
__name2(w, "w");
var x = r(975);
const P = x.posix || x, _ = "/";
var I;
!(function(t2) {
t2.joinPath = function(t3, ...e2) {
return t3.with({ path: P.join(t3.path, ...e2) });
}, t2.resolvePath = function(t3, ...e2) {
let r2 = t3.path, n2 = false;
r2[0] !== _ && (r2 = _ + r2, n2 = true);
let i2 = P.resolve(r2, ...e2);
return n2 && i2[0] === _ && !t3.authority && (i2 = i2.substring(1)), t3.with({ path: i2 });
}, t2.dirname = function(t3) {
if (0 === t3.path.length || t3.path === _) return t3;
let e2 = P.dirname(t3.path);
return 1 === e2.length && 46 === e2.charCodeAt(0) && (e2 = ""), t3.with({ path: e2 });
}, t2.basename = function(t3) {
return P.basename(t3.path);
}, t2.extname = function(t3) {
return P.extname(t3.path);
};
})(I || (I = {})), LIB = n;
})();
var { URI: URI2, Utils } = LIB;
var UriUtils;
(function(UriUtils2) {
UriUtils2.basename = Utils.basename;
UriUtils2.dirname = Utils.dirname;
UriUtils2.extname = Utils.extname;
UriUtils2.joinPath = Utils.joinPath;
UriUtils2.resolvePath = Utils.resolvePath;
const isWindows = typeof process === "object" && process?.platform === "win32";
function equals(a, b) {
return a?.toString() === b?.toString();
}
__name(equals, "equals");
__name2(equals, "equals");
UriUtils2.equals = equals;
function relative(from, to) {
const fromPath = typeof from === "string" ? URI2.parse(from).path : from.path;
const toPath = typeof to === "string" ? URI2.parse(to).path : to.path;
const fromParts = fromPath.split("/").filter((e) => e.length > 0);
const toParts = toPath.split("/").filter((e) => e.length > 0);
if (isWindows) {
const upperCaseDriveLetter = /^[A-Z]:$/;
if (fromParts[0] && upperCaseDriveLetter.test(fromParts[0])) {
fromParts[0] = fromParts[0].toLowerCase();
}
if (toParts[0] && upperCaseDriveLetter.test(toParts[0])) {
toParts[0] = toParts[0].toLowerCase();
}
if (fromParts[0] !== toParts[0]) {
return toPath.substring(1);
}
}
let i = 0;
for (; i < fromParts.length; i++) {
if (fromParts[i] !== toParts[i]) {
break;
}
}
const backPart = "../".repeat(fromParts.length - i);
const toPart = toParts.slice(i).join("/");
return backPart + toPart;
}
__name(relative, "relative");
__name2(relative, "relative");
UriUtils2.relative = relative;
function normalize(uri) {
return URI2.parse(uri.toString()).toString();
}
__name(normalize, "normalize");
__name2(normalize, "normalize");
UriUtils2.normalize = normalize;
function contains(parent, child) {
let parentPath = typeof parent === "string" ? parent : parent.path;
let childPath = typeof child === "string" ? child : child.path;
if (childPath.charAt(childPath.length - 1) === "/") {
childPath = childPath.slice(0, -1);
}
if (parentPath.charAt(parentPath.length - 1) === "/") {
parentPath = parentPath.slice(0, -1);
}
if (childPath === parentPath) {
return true;
}
if (childPath.length < parentPath.length) {
return false;
}
if (childPath.charAt(parentPath.length) !== "/") {
return false;
}
return childPath.startsWith(parentPath);
}
__name(contains, "contains");
__name2(contains, "contains");
UriUtils2.contains = contains;
})(UriUtils || (UriUtils = {}));
var UriTrie = class {
static {
__name(this, "UriTrie");
}
static {
__name2(this, "UriTrie");
}
constructor() {
this.root = { name: "", children: /* @__PURE__ */ new Map() };
}
normalizeUri(uri) {
return UriUtils.normalize(uri);
}
clear() {
this.root.children.clear();
}
insert(uri, element) {
const node = this.getNode(this.normalizeUri(uri), true);
node.element = element;
}
delete(uri) {
const nodeToDelete = this.getNode(this.normalizeUri(uri), false);
if (nodeToDelete?.parent) {
nodeToDelete.parent.children.delete(nodeToDelete.name);
}
}
has(uri) {
return this.getNode(this.normalizeUri(uri), false)?.element !== void 0;
}
hasNode(uri) {
return this.getNode(this.normalizeUri(uri), false) !== void 0;
}
find(uri) {
return this.getNode(this.normalizeUri(uri), false)?.element;
}
findNode(uri) {
const uriString = this.normalizeUri(uri);
const node = this.getNode(uriString, false);
if (!node) {
return void 0;
}
return {
name: node.name,
uri: UriUtils.joinPath(URI2.parse(uriString), node.name).toString(),
element: node.element
};
}
findChildren(uri) {
const uriString = this.normalizeUri(uri);
const node = this.getNode(uriString, false);
if (!node) {
return [];
}
return Array.from(node.children.values()).map((child) => ({
name: child.name,
uri: UriUtils.joinPath(URI2.parse(uriString), child.name).toString(),
element: child.element
}));
}
all() {
return this.collectValues(this.root);
}
findAll(prefix) {
const node = this.getNode(UriUtils.normalize(prefix), false);
if (!node) {
return [];
}
return this.collectValues(node);
}
getNode(uri, create) {
const parts = uri.split("/");
if (uri.charAt(uri.length - 1) === "/") {
parts.pop();
}
let current = this.root;
for (const part of parts) {
let child = current.children.get(part);
if (!child) {
if (create) {
child = {
name: part,
children: /* @__PURE__ */ new Map(),
parent: current
};
current.children.set(part, child);
} else {
return void 0;
}
}
current = child;
}
return current;
}
collectValues(node) {
const result = [];
if (node.element) {
result.push(node.element);
}
for (const child of node.children.values()) {
result.push(...this.collectValues(child));
}
return result;
}
};
var DocumentState;
(function(DocumentState2) {
DocumentState2[DocumentState2["Changed"] = 0] = "Changed";
DocumentState2[DocumentState2["Parsed"] = 1] = "Parsed";
DocumentState2[DocumentState2["IndexedContent"] = 2] = "IndexedContent";
DocumentState2[DocumentState2["ComputedScopes"] = 3] = "ComputedScopes";
DocumentState2[DocumentState2["Linked"] = 4] = "Linked";
DocumentState2[DocumentState2["IndexedReferences"] = 5] = "IndexedReferences";
DocumentState2[DocumentState2["Validated"] = 6] = "Validated";
})(DocumentState || (DocumentState = {}));
var DefaultLangiumDocumentFactory = class {
static {
__name(this, "DefaultLangiumDocumentFactory");
}
static {
__name2(this, "DefaultLangiumDocumentFactory");
}
constructor(services) {
this.serviceRegistry = services.ServiceRegistry;
this.textDocuments = services.workspace.TextDocuments;
this.fileSystemProvider = services.workspace.FileSystemProvider;
}
async fromUri(uri, cancellationToken = cancellation_exports.CancellationToken.None) {
const content = await this.fileSystemProvider.readFile(uri);
return this.createAsync(uri, content, cancellationToken);
}
fromTextDocument(textDocument, uri, token) {
uri = uri ?? URI2.parse(textDocument.uri);
if (cancellation_exports.CancellationToken.is(token)) {
return this.createAsync(uri, textDocument, token);
} else {
return this.create(uri, textDocument, token);
}
}
fromString(text, uri, token) {
if (cancellation_exports.CancellationToken.is(token)) {
return this.createAsync(uri, text, token);
} else {
return this.create(uri, text, token);
}
}
fromModel(model, uri) {
return this.create(uri, { $model: model });
}
create(uri, content, options) {
if (typeof content === "string") {
const parseResult = this.parse(uri, content, options);
return this.createLangiumDocument(parseResult, uri, void 0, content);
} else if ("$model" in content) {
const parseResult = { value: content.$model, parserErrors: [], lexerErrors: [] };
return this.createLangiumDocument(parseResult, uri);
} else {
const parseResult = this.parse(uri, content.getText(), options);
return this.createLangiumDocument(parseResult, uri, content);
}
}
async createAsync(uri, content, cancelToken) {
if (typeof content === "string") {
const parseResult = await this.parseAsync(uri, content, cancelToken);
return this.createLangiumDocument(parseResult, uri, void 0, content);
} else {
const parseResult = await this.parseAsync(uri, content.getText(), cancelToken);
return this.createLangiumDocument(parseResult, uri, content);
}
}
/**
* Create a LangiumDocument from a given parse result.
*
* A TextDocument is created on demand if it is not provided as argument here. Usually this
* should not be necessary because the main purpose of the TextDocument is to convert between
* text ranges and offsets, which is done solely in LSP request handling.
*
* With the introduction of {@link update} below this method is supposed to be mainly called
* during workspace initialization and on addition/recognition of new files, while changes in
* existing documents are processed via {@link update}.
*/
createLangiumDocument(parseResult, uri, textDocument, text) {
let document;
if (textDocument) {
document = {
parseResult,
uri,
state: DocumentState.Parsed,
references: [],
textDocument
};
} else {
const textDocumentGetter = this.createTextDocumentGetter(uri, text);
document = {
parseResult,
uri,
state: DocumentState.Parsed,
references: [],
get textDocument() {
return textDocumentGetter();
}
};
}
parseResult.value.$document = document;
return document;
}
async update(document, cancellationToken) {
const oldText = document.parseResult.value.$cstNode?.root.fullText;
const textDocument = this.textDocuments?.get(document.uri.toString());
const text = textDocument ? textDocument.getText() : await this.fileSystemProvider.readFile(document.uri);
if (textDocument) {
Object.defineProperty(document, "textDocument", {
value: textDocument
});
} else {
const textDocumentGetter = this.createTextDocumentGetter(document.uri, text);
Object.defineProperty(document, "textDocument", {
get: textDocumentGetter
});
}
if (oldText !== text) {
document.parseResult = await this.parseAsync(document.uri, text, cancellationToken);
document.parseResult.value.$document = document;
}
document.state = DocumentState.Parsed;
return document;
}
parse(uri, text, options) {
const services = this.serviceRegistry.getServices(uri);
return services.parser.LangiumParser.parse(text, options);
}
parseAsync(uri, text, cancellationToken) {
const services = this.serviceRegistry.getServices(uri);
return services.parser.AsyncParser.parse(text, cancellationToken);
}
createTextDocumentGetter(uri, text) {
const serviceRegistry = this.serviceRegistry;
let textDoc = void 0;
return () => {
return textDoc ?? (textDoc = TextDocument2.create(uri.toString(), serviceRegistry.getServices(uri).LanguageMetaData.languageId, 0, text ?? ""));
};
}
};
var DefaultLangiumDocuments = class {
static {
__name(this, "DefaultLangiumDocuments");
}
static {
__name2(this, "DefaultLangiumDocuments");
}
constructor(services) {
this.documentTrie = new UriTrie();
this.services = services;
this.langiumDocumentFactory = services.workspace.LangiumDocumentFactory;
this.documentBuilder = () => services.workspace.DocumentBuilder;
}
get all() {
return stream(this.documentTrie.all());
}
addDocument(document) {
const uriString = document.uri.toString();
if (this.documentTrie.has(uriString)) {
throw new Error(`A document with the URI '${uriString}' is already present.`);
}
this.documentTrie.insert(uriString, document);
}
getDocument(uri) {
const uriString = uri.toString();
return this.documentTrie.find(uriString);
}
getDocuments(folder) {
const uriString = folder.toString();
return this.documentTrie.findAll(uriString);
}
async getOrCreateDocument(uri, cancellationToken) {
let document = this.getDocument(uri);
if (document) {
return document;
}
document = await this.langiumDocumentFactory.fromUri(uri, cancellationToken);
this.addDocument(document);
return document;
}
createDocument(uri, text, cancellationToken) {
if (cancellationToken) {
return this.langiumDocumentFactory.fromString(text, uri, cancellationToken).then((document) => {
this.addDocument(document);
return document;
});
} else {
const document = this.langiumDocumentFactory.fromString(text, uri);
this.addDocument(document);
return document;
}
}
hasDocument(uri) {
return this.documentTrie.has(uri.toString());
}
/**
* @deprecated Since 4.2 use `DocumentBuilder.resetToState(DocumentState.Changed)` instead
* TODO remove this for the next major release
*/
invalidateDocument(uri) {
const uriString = uri.toString();
const langiumDoc = this.documentTrie.find(uriString);
if (langiumDoc) {
this.documentBuilder().resetToState(langiumDoc, DocumentState.Changed);
}
return langiumDoc;
}
deleteDocument(uri) {
const uriString = uri.toString();
const langiumDoc = this.documentTrie.find(uriString);
if (langiumDoc) {
langiumDoc.state = DocumentState.Changed;
this.documentTrie.delete(uriString);
}
return langiumDoc;
}
deleteDocuments(folder) {
const uriString = folder.toString();
const langiumDocs = this.documentTrie.findAll(uriString);
for (const langiumDoc of langiumDocs) {
langiumDoc.state = DocumentState.Changed;
}
this.documentTrie.delete(uriString);
return langiumDocs;
}
};
var RefResolving = Symbol("RefResolving");
var DefaultLinker = class {
static {
__name(this, "DefaultLinker");
}
static {
__name2(this, "DefaultLinker");
}
constructor(services) {
this.reflection = services.shared.AstReflection;
this.langiumDocuments = () => services.shared.workspace.LangiumDocuments;
this.scopeProvider = services.references.ScopeProvider;
this.astNodeLocator = services.workspace.AstNodeLocator;
this.profiler = services.shared.profilers.LangiumProfiler;
this.languageId = services.LanguageMetaData.languageId;
}
async link(document, cancelToken = cancellation_exports.CancellationToken.None) {
if (this.profiler?.isActive("linking")) {
const task = this.profiler.createTask("linking", this.languageId);
task.start();
try {
for (const node of streamAst(document.parseResult.value)) {
await interruptAndCheck(cancelToken);
streamReferences(node).forEach((ref) => {
const name = `${node.$type}:${ref.property}`;
task.startSubTask(name);
try {
this.doLink(ref, document);
} finally {
task.stopSubTask(name);
}
});
}
} finally {
task.stop();
}
} else {
for (const node of streamAst(document.parseResult.value)) {
await interruptAndCheck(cancelToken);
streamReferences(node).forEach((ref) => this.doLink(ref, document));
}
}
}
doLink(refInfo, document) {
const ref = refInfo.reference;
if ("_ref" in ref && ref._ref === void 0) {
ref._ref = RefResolving;
try {
const description = this.getCandidate(refInfo);
if (isLinkingError(description)) {
ref._ref = description;
} else {
ref._nodeDescription = description;
const linkedNode = this.loadAstNode(description);
ref._ref = linkedNode ?? this.createLinkingError(refInfo, description);
}
} catch (err) {
console.error(`An error occurred while resolving reference to '${ref.$refText}':`, err);
const errorMessage = err.message ?? String(err);
ref._ref = {
info: refInfo,
message: `An error occurred while resolving reference to '${ref.$refText}': ${errorMessage}`
};
}
document.references.push(ref);
} else if ("_items" in ref && ref._items === void 0) {
ref._items = RefResolving;
try {
const descriptions = this.getCandidates(refInfo);
const items = [];
if (isLinkingError(descriptions)) {
ref._linkingError = descriptions;
} else {
for (const description of descriptions) {
const linkedNode = this.loadAstNode(description);
if (linkedNode) {
items.push({ ref: linkedNode, $nodeDescription: description });
}
}
}
ref._items = items;
} catch (err) {
ref._linkingError = {
info: refInfo,
message: `An error occurred while resolving reference to '${ref.$refText}': ${err}`
};
ref._items = [];
}
document.references.push(ref);
}
}
unlink(document) {
for (const ref of document.references) {
if ("_ref" in ref) {
ref._ref = void 0;
delete ref._nodeDescription;
} else if ("_items" in ref) {
ref._items = void 0;
delete ref._linkingError;
}
}
document.references = [];
}
getCandidate(refInfo) {
const scope = this.scopeProvider.getScope(refInfo);
const description = scope.getElement(refInfo.reference.$refText);
return description ?? this.createLinkingError(refInfo);
}
getCandidates(refInfo) {
const scope = this.scopeProvider.getScope(refInfo);
const descriptions = scope.getElements(refInfo.reference.$refText).distinct((desc) => `${desc.documentUri}#${desc.path}`).toArray();
return descriptions.length > 0 ? descriptions : this.createLinkingError(refInfo);
}
buildReference(node, property3, refNode, refText) {
const linker = this;
const reference = {
$refNode: refNode,
$refText: refText,
_ref: void 0,
get ref() {
if (isAstNode(this._ref)) {
return this._ref;
} else if (isAstNodeDescription(this._nodeDescription)) {
const linkedNode = linker.loadAstNode(this._nodeDescription);
this._ref = linkedNode ?? linker.createLinkingError({ reference, container: node, property: property3 }, this._nodeDescription);
} else if (this._ref === void 0) {
this._ref = RefResolving;
const document = findRootNode(node).$document;
const refData = linker.getLinkedNode({ reference, container: node, property: property3 });
if (refData.error && document && document.state < DocumentState.ComputedScopes) {
return this._ref = void 0;
}
this._ref = refData.node ?? refData.error;
this._nodeDescription = refData.descr;
document?.references.push(this);
} else if (this._ref === RefResolving) {
linker.throwCyclicReferenceError(node, property3, refText);
}
return isAstNode(this._ref) ? this._ref : void 0;
},
get $nodeDescription() {
return this._nodeDescription;
},
get error() {
return isLinkingError(this._ref) ? this._ref : void 0;
}
};
return reference;
}
buildMultiReference(node, property3, refNode, refText) {
const linker = this;
const reference = {
$refNode: refNode,
$refText: refText,
_items: void 0,
get items() {
if (Array.isArray(this._items)) {
return this._items;
} else if (this._items === void 0) {
this._items = RefResolving;
const document = findRootNode(node).$document;
const descriptions = linker.getCandidates({
reference,
container: node,
property: property3
});
const items = [];
if (isLinkingError(descriptions)) {
this._linkingError = descriptions;
} else {
for (const description of descriptions) {
const linkedNode = linker.loadAstNode(description);
if (linkedNode) {
items.push({ ref: linkedNode, $nodeDescription: description });
}
}
}
this._items = items;
document?.references.push(this);
} else if (this._items === RefResolving) {
linker.throwCyclicReferenceError(node, property3, refText);
}
return Array.isArray(this._items) ? this._items : [];
},
get error() {
if (this._linkingError) {
return this._linkingError;
}
const refs = this.items;
if (refs.length > 0) {
return void 0;
} else {
return this._linkingError = linker.createLinkingError({ reference, container: node, property: property3 });
}
}
};
return reference;
}
throwCyclicReferenceError(node, property3, refText) {
throw new Error(`Cyclic reference resolution detected: ${this.astNodeLocator.getAstNodePath(node)}/${property3} (symbol '${refText}')`);
}
getLinkedNode(refInfo) {
try {
const description = this.getCandidate(refInfo);
if (isLinkingError(description)) {
return { error: description };
}
const linkedNode = this.loadAstNode(description);
if (linkedNode) {
return { node: linkedNode, descr: description };
} else {
return {
descr: description,
error: this.createLinkingError(refInfo, description)
};
}
} catch (err) {
console.error(`An error occurred while resolving reference to '${refInfo.reference.$refText}':`, err);
const errorMessage = err.message ?? String(err);
return {
error: {
info: refInfo,
message: `An error occurred while resolving reference to '${refInfo.reference.$refText}': ${errorMessage}`
}
};
}
}
loadAstNode(nodeDescription) {
if (nodeDescription.node) {
return nodeDescription.node;
}
const doc = this.langiumDocuments().getDocument(nodeDescription.documentUri);
if (!doc) {
return void 0;
}
return this.astNodeLocator.getAstNode(doc.parseResult.value, nodeDescription.path);
}
createLinkingError(refInfo, targetDescription) {
const document = findRootNode(refInfo.container).$document;
if (document && document.state < DocumentState.ComputedScopes) {
console.warn(`Attempted reference resolution before document reached ComputedScopes state (${document.uri}).`);
}
const referenceType = this.reflection.getReferenceType(refInfo);
return {
info: refInfo,
message: `Could not resolve reference to ${referenceType} named '${refInfo.reference.$refText}'.`,
targetDescription
};
}
};
function isNamed(node) {
return typeof node.name === "string";
}
__name(isNamed, "isNamed");
__name2(isNamed, "isNamed");
var DefaultNameProvider = class {
static {
__name(this, "DefaultNameProvider");
}
static {
__name2(this, "DefaultNameProvider");
}
getName(node) {
if (isNamed(node)) {
return node.name;
}
return void 0;
}
getNameNode(node) {
return findNodeForProperty(node.$cstNode, "name");
}
};
var DefaultReferences = class {
static {
__name(this, "DefaultReferences");
}
static {
__name2(this, "DefaultReferences");
}
constructor(services) {
this.nameProvider = services.references.NameProvider;
this.index = services.shared.workspace.IndexManager;
this.nodeLocator = services.workspace.AstNodeLocator;
this.documents = services.shared.workspace.LangiumDocuments;
this.hasMultiReference = streamAst(services.Grammar).some((node) => isCrossReference(node) && node.isMulti);
}
findDeclarations(sourceCstNode) {
if (sourceCstNode) {
const assignment = findAssignment(sourceCstNode);
const nodeElem = sourceCstNode.astNode;
if (assignment && nodeElem) {
const reference = nodeElem[assignment.feature];
if (isReference(reference) || isMultiReference(reference)) {
return getReferenceNodes(reference);
} else if (Array.isArray(reference)) {
for (const ref of reference) {
if ((isReference(ref) || isMultiReference(ref)) && ref.$refNode && ref.$refNode.offset <= sourceCstNode.offset && ref.$refNode.end >= sourceCstNode.end) {
return getReferenceNodes(ref);
}
}
}
}
if (nodeElem) {
const nameNode = this.nameProvider.getNameNode(nodeElem);
if (nameNode && (nameNode === sourceCstNode || isChildNode(sourceCstNode, nameNode))) {
return this.getSelfNodes(nodeElem);
}
}
}
return [];
}
/**
* Returns all self-references for the specified node.
* Since the node can be part of a multi-reference, this method returns all nodes that are part of the same multi-reference.
*/
getSelfNodes(node) {
if (!this.hasMultiReference) {
return [node];
} else {
const references = this.index.findAllReferences(node, this.nodeLocator.getAstNodePath(node));
const headNode = this.getNodeFromReferenceDescription(references.head());
if (headNode) {
for (const ref of streamReferences(headNode)) {
if (isMultiReference(ref.reference) && ref.reference.items.some((item) => item.ref === node)) {
return ref.reference.items.map((item) => item.ref);
}
}
}
return [node];
}
}
getNodeFromReferenceDescription(ref) {
if (!ref) {
return void 0;
}
const doc = this.documents.getDocument(ref.sourceUri);
if (doc) {
return this.nodeLocator.getAstNode(doc.parseResult.value, ref.sourcePath);
}
return void 0;
}
findDeclarationNodes(sourceCstNode) {
const astNodes = this.findDeclarations(sourceCstNode);
const cstNodes = [];
for (const astNode of astNodes) {
const cstNode = this.nameProvider.getNameNode(astNode) ?? astNode.$cstNode;
if (cstNode) {
cstNodes.push(cstNode);
}
}
return cstNodes;
}
findReferences(targetNode, options) {
const refs = [];
if (options.includeDeclaration) {
refs.push(...this.getSelfReferences(targetNode));
}
let indexReferences = this.index.findAllReferences(targetNode, this.nodeLocator.getAstNodePath(targetNode));
if (options.documentUri) {
indexReferences = indexReferences.filter((ref) => UriUtils.equals(ref.sourceUri, options.documentUri));
}
refs.push(...indexReferences);
return stream(refs);
}
getSelfReferences(targetNode) {
const selfNodes = this.getSelfNodes(targetNode);
const references = [];
for (const selfNode of selfNodes) {
const nameNode = this.nameProvider.getNameNode(selfNode);
if (nameNode) {
const doc = getDocument(selfNode);
const path = this.nodeLocator.getAstNodePath(selfNode);
references.push({
sourceUri: doc.uri,
sourcePath: path,
targetUri: doc.uri,
targetPath: path,
segment: toDocumentSegment(nameNode),
local: true
});
}
}
return references;
}
};
var MultiMap = class {
static {
__name(this, "MultiMap");
}
static {
__name2(this, "MultiMap");
}
constructor(elements) {
this.map = /* @__PURE__ */ new Map();
if (elements) {
for (const [key, value] of elements) {
this.add(key, value);
}
}
}
/**
* The total number of values in the multimap.
*/
get size() {
return Reduction.sum(stream(this.map.values()).map((a) => a.length));
}
/**
* Clear all entries in the multimap.
*/
clear() {
this.map.clear();
}
/**
* Operates differently depending on whether a `value` is given:
* * With a value, this method deletes the specific key / value pair from the multimap.
* * Without a value, all values associated with the given key are deleted.
*
* @returns `true` if a value existed and has been removed, or `false` if the specified
* key / value does not exist.
*/
delete(key, value) {
if (value === void 0) {
return this.map.delete(key);
} else {
const values2 = this.map.get(key);
if (values2) {
const index = values2.indexOf(value);
if (index >= 0) {
if (values2.length === 1) {
this.map.delete(key);
} else {
values2.splice(index, 1);
}
return true;
}
}
return false;
}
}
/**
* Returns an array of all values associated with the given key. If no value exists,
* an empty array is returned.
*
* _Note:_ The returned array is assumed not to be modified. Use the `set` method to add a
* value and `delete` to remove a value from the multimap.
*/
get(key) {
return this.map.get(key) ?? [];
}
/**
* Returns a stream of all values associated with the given key. If no value exists,
* {@link EMPTY_STREAM} is returned.
*/
getStream(key) {
const values2 = this.map.get(key);
return values2 ? stream(values2) : EMPTY_STREAM;
}
/**
* Operates differently depending on whether a `value` is given:
* * With a value, this method returns `true` if the specific key / value pair is present in the multimap.
* * Without a value, this method returns `true` if the given key is present in the multimap.
*/
has(key, value) {
if (value === void 0) {
return this.map.has(key);
} else {
const values2 = this.map.get(key);
if (values2) {
return values2.indexOf(value) >= 0;
}
return false;
}
}
/**
* Add the given key / value pair to the multimap.
*/
add(key, value) {
if (this.map.has(key)) {
this.map.get(key).push(value);
} else {
this.map.set(key, [value]);
}
return this;
}
/**
* Add the given set of key / value pairs to the multimap.
*/
addAll(key, values2) {
if (this.map.has(key)) {
this.map.get(key).push(...values2);
} else {
this.map.set(key, Array.from(values2));
}
return this;
}
/**
* Invokes the given callback function for every key / value pair in the multimap.
*/
forEach(callbackfn) {
this.map.forEach((array, key) => array.forEach((value) => callbackfn(value, key, this)));
}
/**
* Returns an iterator of key, value pairs for every entry in the map.
*/
[Symbol.iterator]() {
return this.entries().iterator();
}
/**
* Returns a stream of key, value pairs for every entry in the map.
*/
entries() {
return stream(this.map.entries()).flatMap(([key, array]) => array.map((value) => [key, value]));
}
/**
* Returns a stream of keys in the map.
*/
keys() {
return stream(this.map.keys());
}
/**
* Returns a stream of values in the map.
*/
values() {
return stream(this.map.values()).flat();
}
/**
* Returns a stream of key, value set pairs for every key in the map.
*/
entriesGroupedByKey() {
return stream(this.map.entries());
}
};
var BiMap = class {
static {
__name(this, "BiMap");
}
static {
__name2(this, "BiMap");
}
get size() {
return this.map.size;
}
constructor(elements) {
this.map = /* @__PURE__ */ new Map();
this.inverse = /* @__PURE__ */ new Map();
if (elements) {
for (const [key, value] of elements) {
this.set(key, value);
}
}
}
clear() {
this.map.clear();
this.inverse.clear();
}
set(key, value) {
this.map.set(key, value);
this.inverse.set(value, key);
return this;
}
get(key) {
return this.map.get(key);
}
getKey(value) {
return this.inverse.get(value);
}
delete(key) {
const value = this.map.get(key);
if (value !== void 0) {
this.map.delete(key);
this.inverse.delete(value);
return true;
}
return false;
}
};
var DefaultScopeComputation = class {
static {
__name(this, "DefaultScopeComputation");
}
static {
__name2(this, "DefaultScopeComputation");
}
constructor(services) {
this.nameProvider = services.references.NameProvider;
this.descriptions = services.workspace.AstNodeDescriptionProvider;
}
async collectExportedSymbols(document, cancelToken = cancellation_exports.CancellationToken.None) {
return this.collectExportedSymbolsForNode(document.parseResult.value, document, void 0, cancelToken);
}
/**
* Creates {@link AstNodeDescription AstNodeDescriptions} for the given {@link AstNode parentNode} and its children.
* The list of children to be considered is determined by the function parameter {@link children}.
* By default only the direct children of {@link parentNode} are visited, nested nodes are not exported.
*
* @param parentNode AST node to be exported, i.e., of which an {@link AstNodeDescription} shall be added to the returned list.
* @param document The document containing the AST node to be exported.
* @param children A function called with {@link parentNode} as single argument and returning an {@link Iterable} supplying the children to be visited, which must be directly or transitively contained in {@link parentNode}.
* @param cancelToken Indicates when to cancel the current operation.
* @throws `OperationCancelled` if a user action occurs during execution.
* @returns A list of {@link AstNodeDescription AstNodeDescriptions} to be published to index.
*/
async collectExportedSymbolsForNode(parentNode, document, children = streamContents, cancelToken = cancellation_exports.CancellationToken.None) {
const exports2 = [];
this.addExportedSymbol(parentNode, exports2, document);
for (const node of children(parentNode)) {
await interruptAndCheck(cancelToken);
this.addExportedSymbol(node, exports2, document);
}
return exports2;
}
/**
* Adds a single node to the list of exports if it has a name. Override this method to change how
* symbols are exported, e.g. by modifying their exported name.
*/
addExportedSymbol(node, exports2, document) {
const name = this.nameProvider.getName(node);
if (name) {
exports2.push(this.descriptions.createDescription(node, name, document));
}
}
// --- local symbols gathering ---
async collectLocalSymbols(document, cancelToken = cancellation_exports.CancellationToken.None) {
const rootNode = document.parseResult.value;
const symbols = new MultiMap();
for (const node of streamAllContents(rootNode)) {
await interruptAndCheck(cancelToken);
this.addLocalSymbol(node, document, symbols);
}
return symbols;
}
/**
* Adds a single node to the local symbols of its containing document if it has a name.
* The default implementation makes the node visible in the subtree of its container if it does have a container.
* Override this method to change this, e.g. by increasing the visibility to a higher level in the AST.
*/
addLocalSymbol(node, document, symbols) {
const container = node.$container;
if (container) {
const name = this.nameProvider.getName(node);
if (name) {
symbols.add(container, this.descriptions.createDescription(node, name, document));
}
}
}
};
var StreamScope = class {
static {
__name(this, "StreamScope");
}
static {
__name2(this, "StreamScope");
}
constructor(elements, outerScope, options) {
this.elements = elements;
this.outerScope = outerScope;
this.caseInsensitive = options?.caseInsensitive ?? false;
this.concatOuterScope = options?.concatOuterScope ?? true;
}
getAllElements() {
if (this.outerScope) {
return this.elements.concat(this.outerScope.getAllElements());
} else {
return this.elements;
}
}
getElement(name) {
const lowerCaseName = this.caseInsensitive ? name.toLowerCase() : name;
const local = this.caseInsensitive ? this.elements.find((e) => e.name.toLowerCase() === lowerCaseName) : this.elements.find((e) => e.name === name);
if (local) {
return local;
}
if (this.outerScope) {
return this.outerScope.getElement(name);
}
return void 0;
}
getElements(name) {
const lowerCaseName = this.caseInsensitive ? name.toLowerCase() : name;
const local = this.caseInsensitive ? this.elements.filter((e) => e.name.toLowerCase() === lowerCaseName) : this.elements.filter((e) => e.name === name);
if ((this.concatOuterScope || local.isEmpty()) && this.outerScope) {
return local.concat(this.outerScope.getElements(name));
} else {
return local;
}
}
};
var MapScope = class {
static {
__name(this, "MapScope");
}
static {
__name2(this, "MapScope");
}
constructor(elements, outerScope, options) {
this.elements = /* @__PURE__ */ new Map();
this.caseInsensitive = options?.caseInsensitive ?? false;
this.concatOuterScope = options?.concatOuterScope ?? true;
for (const element of elements) {
const name = this.caseInsensitive ? element.name.toLowerCase() : element.name;
this.elements.set(name, element);
}
this.outerScope = outerScope;
}
getElement(name) {
const localName = this.caseInsensitive ? name.toLowerCase() : name;
const local = this.elements.get(localName);
if (local) {
return local;
}
if (this.outerScope) {
return this.outerScope.getElement(name);
}
return void 0;
}
getElements(name) {
const localName = this.caseInsensitive ? name.toLowerCase() : name;
const local = this.elements.get(localName);
const arr = local ? [local] : [];
if ((this.concatOuterScope || arr.length > 0) && this.outerScope) {
return stream(arr).concat(this.outerScope.getElements(name));
} else {
return stream(arr);
}
}
getAllElements() {
let elementStream = stream(this.elements.values());
if (this.outerScope) {
elementStream = elementStream.concat(this.outerScope.getAllElements());
}
return elementStream;
}
};
var MultiMapScope = class {
static {
__name(this, "MultiMapScope");
}
static {
__name2(this, "MultiMapScope");
}
constructor(elements, outerScope, options) {
this.elements = new MultiMap();
this.caseInsensitive = options?.caseInsensitive ?? false;
this.concatOuterScope = options?.concatOuterScope ?? true;
for (const element of elements) {
const name = this.caseInsensitive ? element.name.toLowerCase() : element.name;
this.elements.add(name, element);
}
this.outerScope = outerScope;
}
getElement(name) {
const localName = this.caseInsensitive ? name.toLowerCase() : name;
const local = this.elements.get(localName)[0];
if (local) {
return local;
}
if (this.outerScope) {
return this.outerScope.getElement(name);
}
return void 0;
}
getElements(name) {
const localName = this.caseInsensitive ? name.toLowerCase() : name;
const local = this.elements.get(localName);
if ((this.concatOuterScope || local.length === 0) && this.outerScope) {
return stream(local).concat(this.outerScope.getElements(name));
} else {
return stream(local);
}
}
getAllElements() {
let elementStream = stream(this.elements.values());
if (this.outerScope) {
elementStream = elementStream.concat(this.outerScope.getAllElements());
}
return elementStream;
}
};
var EMPTY_SCOPE = {
getElement() {
return void 0;
},
getElements() {
return EMPTY_STREAM;
},
getAllElements() {
return EMPTY_STREAM;
}
};
var DisposableCache = class {
static {
__name(this, "DisposableCache");
}
static {
__name2(this, "DisposableCache");
}
constructor() {
this.toDispose = [];
this.isDisposed = false;
}
onDispose(disposable) {
this.toDispose.push(disposable);
}
dispose() {
this.throwIfDisposed();
this.clear();
this.isDisposed = true;
this.toDispose.forEach((disposable) => disposable.dispose());
}
throwIfDisposed() {
if (this.isDisposed) {
throw new Error("This cache has already been disposed");
}
}
};
var SimpleCache = class extends DisposableCache {
static {
__name(this, "SimpleCache");
}
static {
__name2(this, "SimpleCache");
}
constructor() {
super(...arguments);
this.cache = /* @__PURE__ */ new Map();
}
has(key) {
this.throwIfDisposed();
return this.cache.has(key);
}
set(key, value) {
this.throwIfDisposed();
this.cache.set(key, value);
}
get(key, provider) {
this.throwIfDisposed();
if (this.cache.has(key)) {
return this.cache.get(key);
} else if (provider) {
const value = provider();
this.cache.set(key, value);
return value;
} else {
return void 0;
}
}
delete(key) {
this.throwIfDisposed();
return this.cache.delete(key);
}
clear() {
this.throwIfDisposed();
this.cache.clear();
}
};
var ContextCache = class extends DisposableCache {
static {
__name(this, "ContextCache");
}
static {
__name2(this, "ContextCache");
}
constructor(converter) {
super();
this.cache = /* @__PURE__ */ new Map();
this.converter = converter ?? ((value) => value);
}
has(contextKey, key) {
this.throwIfDisposed();
return this.cacheForContext(contextKey).has(key);
}
set(contextKey, key, value) {
this.throwIfDisposed();
this.cacheForContext(contextKey).set(key, value);
}
get(contextKey, key, provider) {
this.throwIfDisposed();
const contextCache = this.cacheForContext(contextKey);
if (contextCache.has(key)) {
return contextCache.get(key);
} else if (provider) {
const value = provider();
contextCache.set(key, value);
return value;
} else {
return void 0;
}
}
delete(contextKey, key) {
this.throwIfDisposed();
return this.cacheForContext(contextKey).delete(key);
}
clear(contextKey) {
this.throwIfDisposed();
if (contextKey) {
const mapKey = this.converter(contextKey);
this.cache.delete(mapKey);
} else {
this.cache.clear();
}
}
cacheForContext(contextKey) {
const mapKey = this.converter(contextKey);
let documentCache = this.cache.get(mapKey);
if (!documentCache) {
documentCache = /* @__PURE__ */ new Map();
this.cache.set(mapKey, documentCache);
}
return documentCache;
}
};
var DocumentCache = class extends ContextCache {
static {
__name(this, "DocumentCache");
}
static {
__name2(this, "DocumentCache");
}
/**
* Creates a new document cache.
*
* @param sharedServices Service container instance to hook into document lifecycle events.
* @param state Optional document state on which the cache should evict.
* If not provided, the cache will evict on `DocumentBuilder#onUpdate`.
* *Deleted* documents are considered in both cases.
*
* Providing a state here will use `DocumentBuilder#onDocumentPhase` instead,
* which triggers on all documents that have been affected by this change, assuming that the
* state is `DocumentState.Linked` or a later state.
*/
constructor(sharedServices, state) {
super((uri) => uri.toString());
if (state) {
this.toDispose.push(sharedServices.workspace.DocumentBuilder.onDocumentPhase(state, (document) => {
this.clear(document.uri.toString());
}));
this.toDispose.push(sharedServices.workspace.DocumentBuilder.onUpdate((_changed, deleted) => {
for (const uri of deleted) {
this.clear(uri);
}
}));
} else {
this.toDispose.push(sharedServices.workspace.DocumentBuilder.onUpdate((changed, deleted) => {
const allUris = changed.concat(deleted);
for (const uri of allUris) {
this.clear(uri);
}
}));
}
}
};
var WorkspaceCache = class extends SimpleCache {
static {
__name(this, "WorkspaceCache");
}
static {
__name2(this, "WorkspaceCache");
}
/**
* Creates a new workspace cache.
*
* @param sharedServices Service container instance to hook into document lifecycle events.
* @param state Optional document state on which the cache should evict.
* If not provided, the cache will evict on `DocumentBuilder#onUpdate`.
* *Deleted* documents are considered in both cases.
*/
constructor(sharedServices, state) {
super();
if (state) {
this.toDispose.push(sharedServices.workspace.DocumentBuilder.onBuildPhase(state, () => {
this.clear();
}));
this.toDispose.push(sharedServices.workspace.DocumentBuilder.onUpdate((_changed, deleted) => {
if (deleted.length > 0) {
this.clear();
}
}));
} else {
this.toDispose.push(sharedServices.workspace.DocumentBuilder.onUpdate(() => {
this.clear();
}));
}
}
};
var DefaultScopeProvider = class {
static {
__name(this, "DefaultScopeProvider");
}
static {
__name2(this, "DefaultScopeProvider");
}
constructor(services) {
this.reflection = services.shared.AstReflection;
this.nameProvider = services.references.NameProvider;
this.descriptions = services.workspace.AstNodeDescriptionProvider;
this.indexManager = services.shared.workspace.IndexManager;
this.globalScopeCache = new WorkspaceCache(services.shared);
}
getScope(context) {
const scopes = [];
const referenceType = this.reflection.getReferenceType(context);
const localSymbols = getDocument(context.container).localSymbols;
if (localSymbols) {
let currentNode = context.container;
do {
if (localSymbols.has(currentNode)) {
scopes.push(localSymbols.getStream(currentNode).filter((desc) => this.reflection.isSubtype(desc.type, referenceType)));
}
currentNode = currentNode.$container;
} while (currentNode);
}
let result = this.getGlobalScope(referenceType, context);
for (let i = scopes.length - 1; i >= 0; i--) {
result = this.createScope(scopes[i], result);
}
return result;
}
/**
* Create a scope for the given collection of AST node descriptions.
*/
createScope(elements, outerScope, options) {
return new StreamScope(stream(elements), outerScope, options);
}
/**
* Create a scope for the given collection of AST nodes, which need to be transformed into respective
* descriptions first. This is done using the `NameProvider` and `AstNodeDescriptionProvider` services.
*/
createScopeForNodes(elements, outerScope, options) {
const s = stream(elements).map((e) => {
const name = this.nameProvider.getName(e);
if (name) {
return this.descriptions.createDescription(e, name);
}
return void 0;
}).nonNullable();
return new StreamScope(s, outerScope, options);
}
/**
* Create a global scope filtered for the given reference type.
*/
getGlobalScope(referenceType, _context) {
return this.globalScopeCache.get(referenceType, () => new MultiMapScope(this.indexManager.allElements(referenceType)));
}
};
function isAstNodeWithComment(node) {
return typeof node.$comment === "string";
}
__name(isAstNodeWithComment, "isAstNodeWithComment");
__name2(isAstNodeWithComment, "isAstNodeWithComment");
function isIntermediateReference(obj) {
return typeof obj === "object" && !!obj && ("$ref" in obj || "$error" in obj);
}
__name(isIntermediateReference, "isIntermediateReference");
__name2(isIntermediateReference, "isIntermediateReference");
var DefaultJsonSerializer = class {
static {
__name(this, "DefaultJsonSerializer");
}
static {
__name2(this, "DefaultJsonSerializer");
}
constructor(services) {
this.ignoreProperties = /* @__PURE__ */ new Set(["$container", "$containerProperty", "$containerIndex", "$document", "$cstNode"]);
this.langiumDocuments = services.shared.workspace.LangiumDocuments;
this.astNodeLocator = services.workspace.AstNodeLocator;
this.nameProvider = services.references.NameProvider;
this.commentProvider = services.documentation.CommentProvider;
}
serialize(node, options) {
const serializeOptions = options ?? {};
const specificReplacer = options?.replacer;
const defaultReplacer = /* @__PURE__ */ __name2((key, value) => this.replacer(key, value, serializeOptions), "defaultReplacer");
const replacer = specificReplacer ? (key, value) => specificReplacer(key, value, defaultReplacer) : defaultReplacer;
try {
this.currentDocument = getDocument(node);
return JSON.stringify(node, replacer, options?.space);
} finally {
this.currentDocument = void 0;
}
}
deserialize(content, options) {
const deserializeOptions = options ?? {};
const root3 = JSON.parse(content);
this.linkNode(root3, root3, deserializeOptions);
return root3;
}
replacer(key, value, { refText, sourceText, textRegions, comments, uriConverter }) {
if (this.ignoreProperties.has(key)) {
return void 0;
} else if (isReference(value)) {
const refValue = value.ref;
const $refText = refText ? value.$refText : void 0;
if (refValue) {
const targetDocument = getDocument(refValue);
let targetUri = "";
if (this.currentDocument && this.currentDocument !== targetDocument) {
if (uriConverter) {
targetUri = uriConverter(targetDocument.uri, refValue);
} else {
targetUri = targetDocument.uri.toString();
}
}
const targetPath = this.astNodeLocator.getAstNodePath(refValue);
return {
$ref: `${targetUri}#${targetPath}`,
$refText
};
} else {
return {
$error: value.error?.message ?? "Could not resolve reference",
$refText
};
}
} else if (isMultiReference(value)) {
const $refText = refText ? value.$refText : void 0;
const $refs = [];
for (const item of value.items) {
const refValue = item.ref;
const targetDocument = getDocument(item.ref);
let targetUri = "";
if (this.currentDocument && this.currentDocument !== targetDocument) {
if (uriConverter) {
targetUri = uriConverter(targetDocument.uri, refValue);
} else {
targetUri = targetDocument.uri.toString();
}
}
const targetPath = this.astNodeLocator.getAstNodePath(refValue);
$refs.push(`${targetUri}#${targetPath}`);
}
return {
$refs,
$refText
};
} else if (isAstNode(value)) {
let astNode = void 0;
if (textRegions) {
astNode = this.addAstNodeRegionWithAssignmentsTo({ ...value });
if ((!key || value.$document) && astNode?.$textRegion) {
astNode.$textRegion.documentURI = this.currentDocument?.uri.toString();
}
}
if (sourceText && !key) {
astNode ?? (astNode = { ...value });
astNode.$sourceText = value.$cstNode?.text;
}
if (comments) {
astNode ?? (astNode = { ...value });
const comment = this.commentProvider.getComment(value);
if (comment) {
astNode.$comment = comment.replace(/\r/g, "");
}
}
return astNode ?? value;
} else {
return value;
}
}
addAstNodeRegionWithAssignmentsTo(node) {
const createDocumentSegment = /* @__PURE__ */ __name2((cstNode) => ({
offset: cstNode.offset,
end: cstNode.end,
length: cstNode.length,
range: cstNode.range
}), "createDocumentSegment");
if (node.$cstNode) {
const textRegion = node.$textRegion = createDocumentSegment(node.$cstNode);
const assignments = textRegion.assignments = {};
Object.keys(node).filter((key) => !key.startsWith("$")).forEach((key) => {
const propertyAssignments = findNodesForProperty(node.$cstNode, key).map(createDocumentSegment);
if (propertyAssignments.length !== 0) {
assignments[key] = propertyAssignments;
}
});
return node;
}
return void 0;
}
linkNode(node, root3, options, container, containerProperty, containerIndex) {
for (const [propertyName, item] of Object.entries(node)) {
if (Array.isArray(item)) {
for (let index = 0; index < item.length; index++) {
const element = item[index];
if (isIntermediateReference(element)) {
item[index] = this.reviveReference(node, propertyName, root3, element, options);
} else if (isAstNode(element)) {
this.linkNode(element, root3, options, node, propertyName, index);
}
}
} else if (isIntermediateReference(item)) {
node[propertyName] = this.reviveReference(node, propertyName, root3, item, options);
} else if (isAstNode(item)) {
this.linkNode(item, root3, options, node, propertyName);
}
}
const mutable = node;
mutable.$container = container;
mutable.$containerProperty = containerProperty;
mutable.$containerIndex = containerIndex;
}
reviveReference(container, property3, root3, reference, options) {
let refText = reference.$refText;
let error = reference.$error;
let ref;
if (reference.$ref) {
const refNode = this.getRefNode(root3, reference.$ref, options.uriConverter);
if (isAstNode(refNode)) {
if (!refText) {
refText = this.nameProvider.getName(refNode);
}
return {
$refText: refText ?? "",
ref: refNode
};
} else {
error = refNode;
}
} else if (reference.$refs) {
const refs = [];
for (const refUri of reference.$refs) {
const refNode = this.getRefNode(root3, refUri, options.uriConverter);
if (isAstNode(refNode)) {
refs.push({ ref: refNode });
}
}
if (refs.length === 0) {
ref = {
$refText: refText ?? "",
items: refs
};
error ?? (error = "Could not resolve multi-reference");
} else {
return {
$refText: refText ?? "",
items: refs
};
}
}
if (error) {
ref ?? (ref = {
$refText: refText ?? "",
ref: void 0
});
ref.error = {
info: {
container,
property: property3,
reference: ref
},
message: error
};
return ref;
} else {
return void 0;
}
}
getRefNode(root3, uri, uriConverter) {
try {
const fragmentIndex = uri.indexOf("#");
if (fragmentIndex === 0) {
const node2 = this.astNodeLocator.getAstNode(root3, uri.substring(1));
if (!node2) {
return "Could not resolve path: " + uri;
}
return node2;
}
if (fragmentIndex < 0) {
const documentUri2 = uriConverter ? uriConverter(uri) : URI2.parse(uri);
const document2 = this.langiumDocuments.getDocument(documentUri2);
if (!document2) {
return "Could not find document for URI: " + uri;
}
return document2.parseResult.value;
}
const documentUri = uriConverter ? uriConverter(uri.substring(0, fragmentIndex)) : URI2.parse(uri.substring(0, fragmentIndex));
const document = this.langiumDocuments.getDocument(documentUri);
if (!document) {
return "Could not find document for URI: " + uri;
}
if (fragmentIndex === uri.length - 1) {
return document.parseResult.value;
}
const node = this.astNodeLocator.getAstNode(document.parseResult.value, uri.substring(fragmentIndex + 1));
if (!node) {
return "Could not resolve URI: " + uri;
}
return node;
} catch (err) {
return String(err);
}
}
};
var DefaultServiceRegistry = class {
static {
__name(this, "DefaultServiceRegistry");
}
static {
__name2(this, "DefaultServiceRegistry");
}
/**
* @deprecated Since 3.1.0. Use the new `fileExtensionMap` (or `languageIdMap`) property instead.
*/
get map() {
return this.fileExtensionMap;
}
constructor(services) {
this.languageIdMap = /* @__PURE__ */ new Map();
this.fileExtensionMap = /* @__PURE__ */ new Map();
this.fileNameMap = /* @__PURE__ */ new Map();
this.textDocuments = services?.workspace.TextDocuments;
}
register(language) {
const data = language.LanguageMetaData;
for (const ext of data.fileExtensions) {
if (this.fileExtensionMap.has(ext)) {
console.warn(`The file extension ${ext} is used by multiple languages. It is now assigned to '${data.languageId}'.`);
}
this.fileExtensionMap.set(ext, language);
}
if (data.fileNames) {
for (const name of data.fileNames) {
if (this.fileNameMap.has(name)) {
console.warn(`The file name ${name} is used by multiple languages. It is now assigned to '${data.languageId}'.`);
}
this.fileNameMap.set(name, language);
}
}
this.languageIdMap.set(data.languageId, language);
}
getServices(uri) {
if (this.languageIdMap.size === 0) {
throw new Error("The service registry is empty. Use `register` to register the services of a language.");
}
const languageId = this.textDocuments?.get(uri)?.languageId;
if (languageId !== void 0) {
const services2 = this.languageIdMap.get(languageId);
if (services2) {
return services2;
}
}
const ext = UriUtils.extname(uri);
const name = UriUtils.basename(uri);
const services = this.fileNameMap.get(name) ?? this.fileExtensionMap.get(ext);
if (!services) {
if (languageId) {
throw new Error(`The service registry contains no services for the extension '${ext}' for language '${languageId}'.`);
} else {
throw new Error(`The service registry contains no services for the extension '${ext}'.`);
}
}
return services;
}
hasServices(uri) {
try {
this.getServices(uri);
return true;
} catch {
return false;
}
}
get all() {
return Array.from(this.languageIdMap.values());
}
};
function diagnosticData(code) {
return { code };
}
__name(diagnosticData, "diagnosticData");
__name2(diagnosticData, "diagnosticData");
var ValidationCategory;
(function(ValidationCategory2) {
ValidationCategory2.defaults = ["fast", "slow", "built-in"];
ValidationCategory2.all = ValidationCategory2.defaults;
})(ValidationCategory || (ValidationCategory = {}));
var ValidationRegistry = class {
static {
__name(this, "ValidationRegistry");
}
static {
__name2(this, "ValidationRegistry");
}
constructor(services) {
this.entries = new MultiMap();
this.knownCategories = new Set(ValidationCategory.defaults);
this.entriesBefore = [];
this.entriesAfter = [];
this.reflection = services.shared.AstReflection;
}
/**
* Register a set of validation checks. Each value in the record can be either a single validation check (i.e. a function)
* or an array of validation checks.
*
* @param checksRecord Set of validation checks to register.
* @param thisObj Optional object to be used as `this` when calling the validation check functions.
* @param category Optional category for the validation checks (defaults to `'fast'`).
*/
register(checksRecord, thisObj = this, category = "fast") {
if (category === "built-in") {
throw new Error("The 'built-in' category is reserved for lexer, parser, and linker errors.");
}
this.knownCategories.add(category);
for (const [type, ch] of Object.entries(checksRecord)) {
const callbacks = ch;
if (Array.isArray(callbacks)) {
for (const check of callbacks) {
const entry = {
check: this.wrapValidationException(check, thisObj),
category
};
this.addEntry(type, entry);
}
} else if (typeof callbacks === "function") {
const entry = {
check: this.wrapValidationException(callbacks, thisObj),
category
};
this.addEntry(type, entry);
} else {
assertUnreachable(callbacks);
}
}
}
wrapValidationException(check, thisObj) {
return async (node, accept, cancelToken) => {
await this.handleException(() => check.call(thisObj, node, accept, cancelToken), "An error occurred during validation", accept, node);
};
}
async handleException(functionality, messageContext, accept, node) {
try {
await functionality();
} catch (err) {
if (isOperationCancelled(err)) {
throw err;
}
console.error(`${messageContext}:`, err);
if (err instanceof Error && err.stack) {
console.error(err.stack);
}
const messageDetails = err instanceof Error ? err.message : String(err);
accept("error", `${messageContext}: ${messageDetails}`, { node });
}
}
addEntry(type, entry) {
if (type === "AstNode") {
this.entries.add("AstNode", entry);
return;
}
for (const subtype of this.reflection.getAllSubTypes(type)) {
this.entries.add(subtype, entry);
}
}
getChecks(type, categories) {
let checks = stream(this.entries.get(type)).concat(this.entries.get("AstNode"));
if (categories) {
checks = checks.filter((entry) => categories.includes(entry.category));
}
return checks.map((entry) => entry.check);
}
/**
* Register logic which will be executed once before validating all the nodes of an AST/Langium document.
* This helps to prepare or initialize some information which are required or reusable for the following checks on the AstNodes.
*
* As an example, for validating unique fully-qualified names of nodes in the AST,
* here the map for mapping names to nodes could be established.
* During the usual checks on the nodes, they are put into this map with their name.
*
* Note that this approach makes validations stateful, which is relevant e.g. when cancelling the validation.
* Therefore it is recommended to clear stored information
* _before_ validating an AST to validate each AST unaffected from other ASTs
* AND _after_ validating the AST to free memory by information which are no longer used.
*
* @param checkBefore a set-up function which will be called once before actually validating an AST
* @param thisObj Optional object to be used as `this` when calling the validation check functions.
*/
registerBeforeDocument(checkBefore, thisObj = this) {
this.entriesBefore.push(this.wrapPreparationException(checkBefore, "An error occurred during set-up of the validation", thisObj));
}
/**
* Register logic which will be executed once after validating all the nodes of an AST/Langium document.
* This helps to finally evaluate information which are collected during the checks on the AstNodes.
*
* As an example, for validating unique fully-qualified names of nodes in the AST,
* here the map with all the collected nodes and their names is checked
* and validation hints are created for all nodes with the same name.
*
* Note that this approach makes validations stateful, which is relevant e.g. when cancelling the validation.
* Therefore it is recommended to clear stored information
* _before_ validating an AST to validate each AST unaffected from other ASTs
* AND _after_ validating the AST to free memory by information which are no longer used.
*
* @param checkBefore a set-up function which will be called once before actually validating an AST
* @param thisObj Optional object to be used as `this` when calling the validation check functions.
*/
registerAfterDocument(checkAfter, thisObj = this) {
this.entriesAfter.push(this.wrapPreparationException(checkAfter, "An error occurred during tear-down of the validation", thisObj));
}
wrapPreparationException(check, messageContext, thisObj) {
return async (rootNode, accept, categories, cancelToken) => {
await this.handleException(() => check.call(thisObj, rootNode, accept, categories, cancelToken), messageContext, accept, rootNode);
};
}
get checksBefore() {
return this.entriesBefore;
}
get checksAfter() {
return this.entriesAfter;
}
getAllValidationCategories(_document) {
return this.knownCategories;
}
};
var VALIDATE_EACH_NODE = Object.freeze({
validateNode: true,
validateChildren: true
});
var DefaultDocumentValidator = class {
static {
__name(this, "DefaultDocumentValidator");
}
static {
__name2(this, "DefaultDocumentValidator");
}
constructor(services) {
this.validationRegistry = services.validation.ValidationRegistry;
this.metadata = services.LanguageMetaData;
this.profiler = services.shared.profilers.LangiumProfiler;
this.languageId = services.LanguageMetaData.languageId;
}
async validateDocument(document, options = {}, cancelToken = cancellation_exports.CancellationToken.None) {
const parseResult = document.parseResult;
const diagnostics = [];
await interruptAndCheck(cancelToken);
if (!options.categories || options.categories.includes("built-in")) {
this.processLexingErrors(parseResult, diagnostics, options);
if (options.stopAfterLexingErrors && diagnostics.some((d) => d.data?.code === DocumentValidator.LexingError)) {
return diagnostics;
}
this.processParsingErrors(parseResult, diagnostics, options);
if (options.stopAfterParsingErrors && diagnostics.some((d) => d.data?.code === DocumentValidator.ParsingError)) {
return diagnostics;
}
this.processLinkingErrors(document, diagnostics, options);
if (options.stopAfterLinkingErrors && diagnostics.some((d) => d.data?.code === DocumentValidator.LinkingError)) {
return diagnostics;
}
}
try {
diagnostics.push(...await this.validateAst(parseResult.value, options, cancelToken));
} catch (err) {
if (isOperationCancelled(err)) {
throw err;
}
console.error("An error occurred during validation:", err);
}
await interruptAndCheck(cancelToken);
return diagnostics;
}
processLexingErrors(parseResult, diagnostics, _options) {
const lexerDiagnostics = [...parseResult.lexerErrors, ...parseResult.lexerReport?.diagnostics ?? []];
for (const lexerDiagnostic of lexerDiagnostics) {
const severity = lexerDiagnostic.severity ?? "error";
const diagnostic = {
severity: toDiagnosticSeverity(severity),
range: {
start: {
line: lexerDiagnostic.line - 1,
character: lexerDiagnostic.column - 1
},
end: {
line: lexerDiagnostic.line - 1,
character: lexerDiagnostic.column + lexerDiagnostic.length - 1
}
},
message: lexerDiagnostic.message,
data: toDiagnosticData(severity),
source: this.getSource()
};
diagnostics.push(diagnostic);
}
}
processParsingErrors(parseResult, diagnostics, _options) {
for (const parserError of parseResult.parserErrors) {
let range = void 0;
if (isNaN(parserError.token.startOffset)) {
if ("previousToken" in parserError) {
const token = parserError.previousToken;
if (!isNaN(token.startOffset)) {
const position = { line: token.endLine - 1, character: token.endColumn };
range = { start: position, end: position };
} else {
const position = { line: 0, character: 0 };
range = { start: position, end: position };
}
}
} else {
range = tokenToRange(parserError.token);
}
if (range) {
const diagnostic = {
severity: toDiagnosticSeverity("error"),
range,
message: parserError.message,
data: diagnosticData(DocumentValidator.ParsingError),
source: this.getSource()
};
diagnostics.push(diagnostic);
}
}
}
processLinkingErrors(document, diagnostics, _options) {
for (const reference of document.references) {
const linkingError = reference.error;
if (linkingError) {
const info = {
node: linkingError.info.container,
range: reference.$refNode?.range,
property: linkingError.info.property,
index: linkingError.info.index,
data: {
code: DocumentValidator.LinkingError,
containerType: linkingError.info.container.$type,
property: linkingError.info.property,
refText: linkingError.info.reference.$refText
}
};
diagnostics.push(this.toDiagnostic("error", linkingError.message, info));
}
}
}
async validateAst(rootNode, options, cancelToken = cancellation_exports.CancellationToken.None) {
const validationItems = [];
const acceptor = /* @__PURE__ */ __name2((severity, message, info) => {
validationItems.push(this.toDiagnostic(severity, message, info));
}, "acceptor");
await this.validateAstBefore(rootNode, options, acceptor, cancelToken);
await this.validateAstNodes(rootNode, options, acceptor, cancelToken);
await this.validateAstAfter(rootNode, options, acceptor, cancelToken);
return validationItems;
}
async validateAstBefore(rootNode, options, acceptor, cancelToken = cancellation_exports.CancellationToken.None) {
const checksBefore = this.validationRegistry.checksBefore;
for (const checkBefore of checksBefore) {
await interruptAndCheck(cancelToken);
await checkBefore(rootNode, acceptor, options.categories ?? [], cancelToken);
}
}
async validateAstNodes(rootNode, options, acceptor, cancelToken = cancellation_exports.CancellationToken.None) {
if (this.profiler?.isActive("validating")) {
const task = this.profiler.createTask("validating", this.languageId);
task.start();
try {
const nodes = streamAst(rootNode).iterator();
for (const node of nodes) {
task.startSubTask(node.$type);
const nodeOptions = this.validateSingleNodeOptions(node, options);
if (nodeOptions.validateNode) {
try {
const checks = this.validationRegistry.getChecks(node.$type, options.categories);
for (const check of checks) {
await check(node, acceptor, cancelToken);
}
} finally {
task.stopSubTask(node.$type);
}
}
if (!nodeOptions.validateChildren) {
nodes.prune();
}
}
} finally {
task.stop();
}
} else {
const nodes = streamAst(rootNode).iterator();
for (const node of nodes) {
await interruptAndCheck(cancelToken);
const nodeOptions = this.validateSingleNodeOptions(node, options);
if (nodeOptions.validateNode) {
const checks = this.validationRegistry.getChecks(node.$type, options.categories);
for (const check of checks) {
await check(node, acceptor, cancelToken);
}
}
if (!nodeOptions.validateChildren) {
nodes.prune();
}
}
}
}
validateSingleNodeOptions(_node, _options) {
return VALIDATE_EACH_NODE;
}
async validateAstAfter(rootNode, options, acceptor, cancelToken = cancellation_exports.CancellationToken.None) {
const checksAfter = this.validationRegistry.checksAfter;
for (const checkAfter of checksAfter) {
await interruptAndCheck(cancelToken);
await checkAfter(rootNode, acceptor, options.categories ?? [], cancelToken);
}
}
toDiagnostic(severity, message, info) {
return {
message,
range: getDiagnosticRange(info),
severity: toDiagnosticSeverity(severity),
code: info.code,
codeDescription: info.codeDescription,
tags: info.tags,
relatedInformation: info.relatedInformation,
data: info.data,
source: this.getSource()
};
}
getSource() {
return this.metadata.languageId;
}
};
function getDiagnosticRange(info) {
if (info.range) {
return info.range;
}
let cstNode;
if (typeof info.property === "string") {
cstNode = findNodeForProperty(info.node.$cstNode, info.property, info.index);
} else if (typeof info.keyword === "string") {
cstNode = findNodeForKeyword(info.node.$cstNode, info.keyword, info.index);
}
cstNode ?? (cstNode = info.node.$cstNode);
if (!cstNode) {
return {
start: { line: 0, character: 0 },
end: { line: 0, character: 0 }
};
}
return cstNode.range;
}
__name(getDiagnosticRange, "getDiagnosticRange");
__name2(getDiagnosticRange, "getDiagnosticRange");
function toDiagnosticSeverity(severity) {
switch (severity) {
case "error":
return 1;
case "warning":
return 2;
case "info":
return 3;
case "hint":
return 4;
default:
throw new Error("Invalid diagnostic severity: " + severity);
}
}
__name(toDiagnosticSeverity, "toDiagnosticSeverity");
__name2(toDiagnosticSeverity, "toDiagnosticSeverity");
function toDiagnosticData(severity) {
switch (severity) {
case "error":
return diagnosticData(DocumentValidator.LexingError);
case "warning":
return diagnosticData(DocumentValidator.LexingWarning);
case "info":
return diagnosticData(DocumentValidator.LexingInfo);
case "hint":
return diagnosticData(DocumentValidator.LexingHint);
default:
throw new Error("Invalid diagnostic severity: " + severity);
}
}
__name(toDiagnosticData, "toDiagnosticData");
__name2(toDiagnosticData, "toDiagnosticData");
var DocumentValidator;
(function(DocumentValidator2) {
DocumentValidator2.LexingError = "lexing-error";
DocumentValidator2.LexingWarning = "lexing-warning";
DocumentValidator2.LexingInfo = "lexing-info";
DocumentValidator2.LexingHint = "lexing-hint";
DocumentValidator2.ParsingError = "parsing-error";
DocumentValidator2.LinkingError = "linking-error";
})(DocumentValidator || (DocumentValidator = {}));
var DefaultAstNodeDescriptionProvider = class {
static {
__name(this, "DefaultAstNodeDescriptionProvider");
}
static {
__name2(this, "DefaultAstNodeDescriptionProvider");
}
constructor(services) {
this.astNodeLocator = services.workspace.AstNodeLocator;
this.nameProvider = services.references.NameProvider;
}
createDescription(node, name, document) {
const doc = document ?? getDocument(node);
name ?? (name = this.nameProvider.getName(node));
const path = this.astNodeLocator.getAstNodePath(node);
if (!name) {
throw new Error(`Node at path ${path} has no name.`);
}
let nameNodeSegment;
const nameSegmentGetter = /* @__PURE__ */ __name2(() => nameNodeSegment ?? (nameNodeSegment = toDocumentSegment(this.nameProvider.getNameNode(node) ?? node.$cstNode)), "nameSegmentGetter");
return {
node,
name,
get nameSegment() {
return nameSegmentGetter();
},
selectionSegment: toDocumentSegment(node.$cstNode),
type: node.$type,
documentUri: doc.uri,
path
};
}
};
var DefaultReferenceDescriptionProvider = class {
static {
__name(this, "DefaultReferenceDescriptionProvider");
}
static {
__name2(this, "DefaultReferenceDescriptionProvider");
}
constructor(services) {
this.nodeLocator = services.workspace.AstNodeLocator;
}
async createDescriptions(document, cancelToken = cancellation_exports.CancellationToken.None) {
const descr = [];
const rootNode = document.parseResult.value;
for (const astNode of streamAst(rootNode)) {
await interruptAndCheck(cancelToken);
streamReferences(astNode).forEach((refInfo) => {
if (!refInfo.reference.error) {
descr.push(...this.createInfoDescriptions(refInfo));
}
});
}
return descr;
}
createInfoDescriptions(refInfo) {
const reference = refInfo.reference;
if (reference.error || !reference.$refNode) {
return [];
}
let items = [];
if (isReference(reference) && reference.$nodeDescription) {
items = [reference.$nodeDescription];
} else if (isMultiReference(reference)) {
items = reference.items.map((e) => e.$nodeDescription).filter((e) => e !== void 0);
}
const sourceUri = getDocument(refInfo.container).uri;
const sourcePath = this.nodeLocator.getAstNodePath(refInfo.container);
const descriptions = [];
const segment = toDocumentSegment(reference.$refNode);
for (const item of items) {
descriptions.push({
sourceUri,
sourcePath,
targetUri: item.documentUri,
targetPath: item.path,
segment,
local: UriUtils.equals(item.documentUri, sourceUri)
});
}
return descriptions;
}
};
var DefaultAstNodeLocator = class {
static {
__name(this, "DefaultAstNodeLocator");
}
static {
__name2(this, "DefaultAstNodeLocator");
}
constructor() {
this.segmentSeparator = "/";
this.indexSeparator = "@";
}
getAstNodePath(node) {
if (node.$container) {
const containerPath = this.getAstNodePath(node.$container);
const newSegment = this.getPathSegment(node);
const nodePath = containerPath + this.segmentSeparator + newSegment;
return nodePath;
}
return "";
}
getPathSegment({ $containerProperty, $containerIndex }) {
if (!$containerProperty) {
throw new Error("Missing '$containerProperty' in AST node.");
}
if ($containerIndex !== void 0) {
return $containerProperty + this.indexSeparator + $containerIndex;
}
return $containerProperty;
}
getAstNode(node, path) {
const segments = path.split(this.segmentSeparator);
return segments.reduce((previousValue, currentValue) => {
if (!previousValue || currentValue.length === 0) {
return previousValue;
}
const propertyIndex = currentValue.indexOf(this.indexSeparator);
if (propertyIndex > 0) {
const property3 = currentValue.substring(0, propertyIndex);
const arrayIndex = parseInt(currentValue.substring(propertyIndex + 1));
const array = previousValue[property3];
return array?.[arrayIndex];
}
return previousValue[currentValue];
}, node);
}
};
var event_exports = {};
__reExport(event_exports, __toESM(require_events(), 1));
var DefaultConfigurationProvider = class {
static {
__name(this, "DefaultConfigurationProvider");
}
static {
__name2(this, "DefaultConfigurationProvider");
}
constructor(services) {
this._ready = new Deferred();
this.onConfigurationSectionUpdateEmitter = new event_exports.Emitter();
this.settings = {};
this.workspaceConfig = false;
this.serviceRegistry = services.ServiceRegistry;
}
get ready() {
return this._ready.promise;
}
initialize(params) {
this.workspaceConfig = params.capabilities.workspace?.configuration ?? false;
}
async initialized(params) {
if (this.workspaceConfig) {
if (params.register) {
const languages = this.serviceRegistry.all;
params.register({
// Listen to configuration changes for all languages
section: languages.map((lang) => this.toSectionName(lang.LanguageMetaData.languageId))
});
}
if (params.fetchConfiguration) {
const configToUpdate = this.serviceRegistry.all.map((lang) => ({
// Fetch the configuration changes for all languages
section: this.toSectionName(lang.LanguageMetaData.languageId)
}));
const configs = await params.fetchConfiguration(configToUpdate);
configToUpdate.forEach((conf, idx) => {
this.updateSectionConfiguration(conf.section, configs[idx]);
});
}
}
this._ready.resolve();
}
/**
* Updates the cached configurations using the `change` notification parameters.
*
* @param change The parameters of a change configuration notification.
* `settings` property of the change object could be expressed as `Record<string, Record<string, any>>`
*/
updateConfiguration(change) {
if (typeof change.settings !== "object" || change.settings === null) {
return;
}
Object.entries(change.settings).forEach(([section, configuration]) => {
this.updateSectionConfiguration(section, configuration);
this.onConfigurationSectionUpdateEmitter.fire({ section, configuration });
});
}
updateSectionConfiguration(section, configuration) {
this.settings[section] = configuration;
}
/**
* Returns a configuration value stored for the given language.
*
* @param language The language id
* @param configuration Configuration name
*/
async getConfiguration(language, configuration) {
await this.ready;
const sectionName = this.toSectionName(language);
if (this.settings[sectionName]) {
return this.settings[sectionName][configuration];
}
}
toSectionName(languageId) {
return `${languageId}`;
}
get onConfigurationSectionUpdate() {
return this.onConfigurationSectionUpdateEmitter.event;
}
};
var import_vscode_languageserver_protocol = __toESM(require_main2(), 1);
var Disposable;
(function(Disposable2) {
function create(callback) {
return {
dispose: /* @__PURE__ */ __name2(async () => await callback(), "dispose")
};
}
__name(create, "create");
__name2(create, "create");
Disposable2.create = create;
})(Disposable || (Disposable = {}));
var DefaultDocumentBuilder = class {
static {
__name(this, "DefaultDocumentBuilder");
}
static {
__name2(this, "DefaultDocumentBuilder");
}
constructor(services) {
this.updateBuildOptions = {
// Default: run only the built-in validation checks and those in the _fast_ category (includes those without category)
validation: {
categories: ["built-in", "fast"]
}
};
this.updateListeners = [];
this.buildPhaseListeners = new MultiMap();
this.documentPhaseListeners = new MultiMap();
this.buildState = /* @__PURE__ */ new Map();
this.documentBuildWaiters = /* @__PURE__ */ new Map();
this.currentState = DocumentState.Changed;
this.langiumDocuments = services.workspace.LangiumDocuments;
this.langiumDocumentFactory = services.workspace.LangiumDocumentFactory;
this.textDocuments = services.workspace.TextDocuments;
this.indexManager = services.workspace.IndexManager;
this.fileSystemProvider = services.workspace.FileSystemProvider;
this.workspaceManager = () => services.workspace.WorkspaceManager;
this.serviceRegistry = services.ServiceRegistry;
}
async build(documents, options = {}, cancelToken = cancellation_exports.CancellationToken.None) {
for (const document of documents) {
const key = document.uri.toString();
if (document.state === DocumentState.Validated) {
if (typeof options.validation === "boolean" && options.validation) {
this.resetToState(document, DocumentState.IndexedReferences);
} else if (typeof options.validation === "object") {
const categories = this.findMissingValidationCategories(document, options);
if (categories.length > 0) {
this.buildState.set(key, {
completed: false,
options: {
validation: {
categories
}
},
result: this.buildState.get(key)?.result
});
document.state = DocumentState.IndexedReferences;
}
}
} else {
this.buildState.delete(key);
}
}
this.currentState = DocumentState.Changed;
await this.emitUpdate(documents.map((e) => e.uri), []);
await this.buildDocuments(documents, options, cancelToken);
}
async update(changed, deleted, cancelToken = cancellation_exports.CancellationToken.None) {
this.currentState = DocumentState.Changed;
const deletedUris = [];
for (const deletedUri of deleted) {
const deletedDocs = this.langiumDocuments.deleteDocuments(deletedUri);
for (const doc of deletedDocs) {
deletedUris.push(doc.uri);
this.cleanUpDeleted(doc);
}
}
const changedUris = (await Promise.all(changed.map((uri) => this.findChangedUris(uri)))).flat();
for (const changedUri of changedUris) {
let changedDocument = this.langiumDocuments.getDocument(changedUri);
if (changedDocument === void 0) {
changedDocument = this.langiumDocumentFactory.fromModel({ $type: "INVALID" }, changedUri);
changedDocument.state = DocumentState.Changed;
this.langiumDocuments.addDocument(changedDocument);
}
this.resetToState(changedDocument, DocumentState.Changed);
}
const allChangedUris = stream(changedUris).concat(deletedUris).map((uri) => uri.toString()).toSet();
this.langiumDocuments.all.filter((doc) => !allChangedUris.has(doc.uri.toString()) && this.shouldRelink(doc, allChangedUris)).forEach((doc) => this.resetToState(doc, DocumentState.ComputedScopes));
await this.emitUpdate(changedUris, deletedUris);
await interruptAndCheck(cancelToken);
const rebuildDocuments = this.sortDocuments(this.langiumDocuments.all.filter((doc) => (
// This includes those that were reported as changed and those that we selected for relinking
doc.state < DocumentState.Validated || !this.buildState.get(doc.uri.toString())?.completed || this.resultsAreIncomplete(doc, this.updateBuildOptions)
)).toArray());
await this.buildDocuments(rebuildDocuments, this.updateBuildOptions, cancelToken);
}
resultsAreIncomplete(document, options) {
return this.findMissingValidationCategories(document, options).length >= 1;
}
findMissingValidationCategories(document, options) {
const state = this.buildState.get(document.uri.toString());
const allCategories = this.serviceRegistry.getServices(document.uri).validation.ValidationRegistry.getAllValidationCategories(document);
const executedCategories = state?.result?.validationChecks ? new Set(state?.result?.validationChecks) : state?.completed ? allCategories : /* @__PURE__ */ new Set();
const requestedCategories = options === void 0 || options.validation === true ? allCategories : typeof options.validation === "object" ? options.validation.categories ?? allCategories : [];
return stream(requestedCategories).filter((requested) => !executedCategories.has(requested)).toArray();
}
async findChangedUris(changed) {
const document = this.langiumDocuments.getDocument(changed) ?? this.textDocuments?.get(changed);
if (document) {
return [changed];
}
try {
const stat = await this.fileSystemProvider.stat(changed);
if (stat.isDirectory) {
const uris = await this.workspaceManager().searchFolder(changed);
return uris;
} else if (this.workspaceManager().shouldIncludeEntry(stat)) {
return [changed];
}
} catch {
}
return [];
}
async emitUpdate(changed, deleted) {
await Promise.all(this.updateListeners.map((listener) => listener(changed, deleted)));
}
/**
* Sort the given documents by priority. By default, documents with an open text document are prioritized.
* This is useful to ensure that visible documents show their diagnostics before all other documents.
*
* This improves the responsiveness in large workspaces as users usually don't care about diagnostics
* in files that are currently not opened in the editor.
*/
sortDocuments(documents) {
let left = 0;
let right = documents.length - 1;
while (left < right) {
while (left < documents.length && this.hasTextDocument(documents[left])) {
left++;
}
while (right >= 0 && !this.hasTextDocument(documents[right])) {
right--;
}
if (left < right) {
[documents[left], documents[right]] = [documents[right], documents[left]];
}
}
return documents;
}
hasTextDocument(doc) {
return Boolean(this.textDocuments?.get(doc.uri));
}
/**
* Check whether the given document should be relinked after changes were found in the given URIs.
*/
shouldRelink(document, changedUris) {
if (document.references.some((ref) => ref.error !== void 0)) {
return true;
}
return this.indexManager.isAffected(document, changedUris);
}
onUpdate(callback) {
this.updateListeners.push(callback);
return Disposable.create(() => {
const index = this.updateListeners.indexOf(callback);
if (index >= 0) {
this.updateListeners.splice(index, 1);
}
});
}
resetToState(document, state) {
switch (state) {
case DocumentState.Changed: {
}
case DocumentState.Parsed:
this.indexManager.removeContent(document.uri);
// Fall through
case DocumentState.IndexedContent:
document.localSymbols = void 0;
// Fall through
case DocumentState.ComputedScopes: {
const linker = this.serviceRegistry.getServices(document.uri).references.Linker;
linker.unlink(document);
}
case DocumentState.Linked:
this.indexManager.removeReferences(document.uri);
// Fall through
case DocumentState.IndexedReferences:
document.diagnostics = void 0;
this.buildState.delete(document.uri.toString());
// Fall through
case DocumentState.Validated:
}
if (document.state > state) {
document.state = state;
}
}
cleanUpDeleted(document) {
this.buildState.delete(document.uri.toString());
this.indexManager.remove(document.uri);
document.state = DocumentState.Changed;
}
/**
* Build the given documents by stepping through all build phases. If a document's state indicates
* that a certain build phase is already done, the phase is skipped for that document.
*
* @param documents The documents to build.
* @param options the {@link BuildOptions} to use.
* @param cancelToken A cancellation token that can be used to cancel the build.
* @returns A promise that resolves when the build is done.
*/
async buildDocuments(documents, options, cancelToken) {
this.prepareBuild(documents, options);
await this.runCancelable(documents, DocumentState.Parsed, cancelToken, (doc) => this.langiumDocumentFactory.update(doc, cancelToken));
await this.runCancelable(documents, DocumentState.IndexedContent, cancelToken, (doc) => this.indexManager.updateContent(doc, cancelToken));
await this.runCancelable(documents, DocumentState.ComputedScopes, cancelToken, async (doc) => {
const scopeComputation = this.serviceRegistry.getServices(doc.uri).references.ScopeComputation;
doc.localSymbols = await scopeComputation.collectLocalSymbols(doc, cancelToken);
});
const toBeLinked = documents.filter((doc) => this.shouldLink(doc));
await this.runCancelable(toBeLinked, DocumentState.Linked, cancelToken, (doc) => {
const linker = this.serviceRegistry.getServices(doc.uri).references.Linker;
return linker.link(doc, cancelToken);
});
await this.runCancelable(toBeLinked, DocumentState.IndexedReferences, cancelToken, (doc) => this.indexManager.updateReferences(doc, cancelToken));
const toBeValidated = documents.filter((doc) => {
if (this.shouldValidate(doc)) {
return true;
} else {
this.markAsCompleted(doc);
return false;
}
});
await this.runCancelable(toBeValidated, DocumentState.Validated, cancelToken, async (doc) => {
await this.validate(doc, cancelToken);
this.markAsCompleted(doc);
});
}
markAsCompleted(document) {
const state = this.buildState.get(document.uri.toString());
if (state) {
state.completed = true;
}
}
/**
* Runs prior to beginning the build process to update the {@link DocumentBuildState} for each document
*
* @param documents collection of documents to be built
* @param options the {@link BuildOptions} to use
*/
prepareBuild(documents, options) {
for (const doc of documents) {
const key = doc.uri.toString();
const state = this.buildState.get(key);
if (!state || state.completed) {
this.buildState.set(key, {
completed: false,
options,
result: state?.result
});
} else {
}
}
}
/**
* Runs a cancelable operation on a set of documents to bring them to a specified {@link DocumentState}.
*
* @param documents The array of documents to process.
* @param targetState The target {@link DocumentState} to bring the documents to.
* @param cancelToken A token that can be used to cancel the operation.
* @param callback A function to be called for each document.
* @returns A promise that resolves when all documents have been processed or the operation is canceled.
* @throws Will throw `OperationCancelled` if the operation is canceled via a `CancellationToken`.
*/
async runCancelable(documents, targetState, cancelToken, callback) {
for (const document of documents) {
if (document.state < targetState) {
await interruptAndCheck(cancelToken);
await callback(document);
document.state = targetState;
await this.notifyDocumentPhase(document, targetState, cancelToken);
}
}
const targetStateDocs = documents.filter((doc) => doc.state === targetState);
await this.notifyBuildPhase(targetStateDocs, targetState, cancelToken);
this.currentState = targetState;
}
onBuildPhase(targetState, callback) {
this.buildPhaseListeners.add(targetState, callback);
return Disposable.create(() => {
this.buildPhaseListeners.delete(targetState, callback);
});
}
onDocumentPhase(targetState, callback) {
this.documentPhaseListeners.add(targetState, callback);
return Disposable.create(() => {
this.documentPhaseListeners.delete(targetState, callback);
});
}
waitUntil(state, uriOrToken, cancelToken) {
let uri = void 0;
if (uriOrToken && "path" in uriOrToken) {
uri = uriOrToken;
} else {
cancelToken = uriOrToken;
}
cancelToken ?? (cancelToken = cancellation_exports.CancellationToken.None);
if (uri) {
return this.awaitDocumentState(state, uri, cancelToken);
} else {
return this.awaitBuilderState(state, cancelToken);
}
}
awaitDocumentState(state, uri, cancelToken) {
const document = this.langiumDocuments.getDocument(uri);
if (!document) {
return Promise.reject(new import_vscode_languageserver_protocol.ResponseError(import_vscode_languageserver_protocol.LSPErrorCodes.ServerCancelled, `No document found for URI: ${uri.toString()}`));
} else if (document.state >= state) {
return Promise.resolve(uri);
} else if (cancelToken.isCancellationRequested) {
return Promise.reject(OperationCancelled);
} else if (this.currentState >= state && state > document.state) {
return Promise.reject(new import_vscode_languageserver_protocol.ResponseError(import_vscode_languageserver_protocol.LSPErrorCodes.RequestFailed, `Document state of ${uri.toString()} is ${DocumentState[document.state]}, requiring ${DocumentState[state]}, but workspace state is already ${DocumentState[this.currentState]}. Returning undefined.`));
}
return new Promise((resolve, reject2) => {
const buildDisposable = this.onDocumentPhase(state, (doc) => {
if (UriUtils.equals(doc.uri, uri)) {
buildDisposable.dispose();
cancelDisposable.dispose();
resolve(doc.uri);
}
});
const cancelDisposable = cancelToken.onCancellationRequested(() => {
buildDisposable.dispose();
cancelDisposable.dispose();
reject2(OperationCancelled);
});
});
}
awaitBuilderState(state, cancelToken) {
if (this.currentState >= state) {
return Promise.resolve();
} else if (cancelToken.isCancellationRequested) {
return Promise.reject(OperationCancelled);
}
return new Promise((resolve, reject2) => {
const buildDisposable = this.onBuildPhase(state, () => {
buildDisposable.dispose();
cancelDisposable.dispose();
resolve();
});
const cancelDisposable = cancelToken.onCancellationRequested(() => {
buildDisposable.dispose();
cancelDisposable.dispose();
reject2(OperationCancelled);
});
});
}
async notifyDocumentPhase(document, state, cancelToken) {
const listeners = this.documentPhaseListeners.get(state);
const listenersCopy = listeners.slice();
for (const listener of listenersCopy) {
try {
await interruptAndCheck(cancelToken);
await listener(document, cancelToken);
} catch (err) {
if (!isOperationCancelled(err)) {
throw err;
}
}
}
}
async notifyBuildPhase(documents, state, cancelToken) {
if (documents.length === 0) {
return;
}
const listeners = this.buildPhaseListeners.get(state);
const listenersCopy = listeners.slice();
for (const listener of listenersCopy) {
await interruptAndCheck(cancelToken);
await listener(documents, cancelToken);
}
}
/**
* Determine whether the given document should be linked during a build. The default
* implementation checks the `eagerLinking` property of the build options. If it's set to `true`
* or `undefined`, the document is included in the linking phase. This also affects the
* references indexing phase, which depends on eager linking.
*/
shouldLink(document) {
return this.getBuildOptions(document).eagerLinking ?? true;
}
/**
* Determine whether the given document should be validated during a build. The default
* implementation checks the `validation` property of the build options. If it's set to `true`
* or a `ValidationOptions` object, the document is included in the validation phase.
*/
shouldValidate(document) {
return Boolean(this.getBuildOptions(document).validation);
}
/**
* Run validation checks on the given document and store the resulting diagnostics in the document.
* If the document already contains diagnostics, the new ones are added to the list.
*/
async validate(document, cancelToken) {
const validator = this.serviceRegistry.getServices(document.uri).validation.DocumentValidator;
const options = this.getBuildOptions(document);
const validationOptions = typeof options.validation === "object" ? { ...options.validation } : {};
validationOptions.categories = this.findMissingValidationCategories(document, options);
const diagnostics = await validator.validateDocument(document, validationOptions, cancelToken);
if (document.diagnostics) {
document.diagnostics.push(...diagnostics);
} else {
document.diagnostics = diagnostics;
}
const state = this.buildState.get(document.uri.toString());
if (state) {
state.result ?? (state.result = {});
if (state.result.validationChecks) {
state.result.validationChecks = stream(state.result.validationChecks).concat(validationOptions.categories).distinct().toArray();
} else {
state.result.validationChecks = [...validationOptions.categories];
}
}
}
getBuildOptions(document) {
return this.buildState.get(document.uri.toString())?.options ?? {};
}
};
var DefaultIndexManager = class {
static {
__name(this, "DefaultIndexManager");
}
static {
__name2(this, "DefaultIndexManager");
}
constructor(services) {
this.symbolIndex = /* @__PURE__ */ new Map();
this.symbolByTypeIndex = new ContextCache();
this.referenceIndex = /* @__PURE__ */ new Map();
this.documents = services.workspace.LangiumDocuments;
this.serviceRegistry = services.ServiceRegistry;
this.astReflection = services.AstReflection;
}
findAllReferences(targetNode, astNodePath) {
const targetDocUri = getDocument(targetNode).uri;
const result = [];
this.referenceIndex.forEach((docRefs) => {
docRefs.forEach((refDescr) => {
if (UriUtils.equals(refDescr.targetUri, targetDocUri) && refDescr.targetPath === astNodePath) {
result.push(refDescr);
}
});
});
return stream(result);
}
allElements(nodeType, uris) {
let documentUris = stream(this.symbolIndex.keys());
if (uris) {
documentUris = documentUris.filter((uri) => !uris || uris.has(uri));
}
return documentUris.map((uri) => this.getFileDescriptions(uri, nodeType)).flat();
}
getFileDescriptions(uri, nodeType) {
if (!nodeType) {
return this.symbolIndex.get(uri) ?? [];
}
const descriptions = this.symbolByTypeIndex.get(uri, nodeType, () => {
const allFileDescriptions = this.symbolIndex.get(uri) ?? [];
return allFileDescriptions.filter((e) => this.astReflection.isSubtype(e.type, nodeType));
});
return descriptions;
}
remove(uri) {
this.removeContent(uri);
this.removeReferences(uri);
}
removeContent(uri) {
const uriString = uri.toString();
this.symbolIndex.delete(uriString);
this.symbolByTypeIndex.clear(uriString);
}
removeReferences(uri) {
const uriString = uri.toString();
this.referenceIndex.delete(uriString);
}
async updateContent(document, cancelToken = cancellation_exports.CancellationToken.None) {
const services = this.serviceRegistry.getServices(document.uri);
const exports2 = await services.references.ScopeComputation.collectExportedSymbols(document, cancelToken);
const uri = document.uri.toString();
this.symbolIndex.set(uri, exports2);
this.symbolByTypeIndex.clear(uri);
}
async updateReferences(document, cancelToken = cancellation_exports.CancellationToken.None) {
const services = this.serviceRegistry.getServices(document.uri);
const indexData = await services.workspace.ReferenceDescriptionProvider.createDescriptions(document, cancelToken);
this.referenceIndex.set(document.uri.toString(), indexData);
}
isAffected(document, changedUris) {
const references = this.referenceIndex.get(document.uri.toString());
if (!references) {
return false;
}
return references.some((ref) => !ref.local && changedUris.has(ref.targetUri.toString()));
}
};
var DefaultWorkspaceManager = class {
static {
__name(this, "DefaultWorkspaceManager");
}
static {
__name2(this, "DefaultWorkspaceManager");
}
constructor(services) {
this.initialBuildOptions = {};
this._ready = new Deferred();
this.serviceRegistry = services.ServiceRegistry;
this.langiumDocuments = services.workspace.LangiumDocuments;
this.documentBuilder = services.workspace.DocumentBuilder;
this.fileSystemProvider = services.workspace.FileSystemProvider;
this.mutex = services.workspace.WorkspaceLock;
}
get ready() {
return this._ready.promise;
}
get workspaceFolders() {
return this.folders;
}
initialize(params) {
this.folders = params.workspaceFolders ?? void 0;
}
initialized(_params) {
return this.mutex.write((token) => this.initializeWorkspace(this.folders ?? [], token));
}
async initializeWorkspace(folders, cancelToken = cancellation_exports.CancellationToken.None) {
const documents = await this.performStartup(folders);
await interruptAndCheck(cancelToken);
await this.documentBuilder.build(documents, this.initialBuildOptions, cancelToken);
}
/**
* Performs the uninterruptable startup sequence of the workspace manager.
* This methods loads all documents in the workspace and other documents and returns them.
*/
async performStartup(folders) {
const documents = [];
const collector = /* @__PURE__ */ __name2((document) => {
documents.push(document);
if (!this.langiumDocuments.hasDocument(document.uri)) {
this.langiumDocuments.addDocument(document);
}
}, "collector");
await this.loadAdditionalDocuments(folders, collector);
const uris = [];
await Promise.all(folders.map((wf) => this.getRootFolder(wf)).map(async (entry) => this.traverseFolder(entry, uris)));
const uniqueUris = stream(uris).distinct((uri) => uri.toString()).filter((uri) => !this.langiumDocuments.hasDocument(uri));
await this.loadWorkspaceDocuments(uniqueUris, collector);
this._ready.resolve();
return documents;
}
async loadWorkspaceDocuments(uris, collector) {
await Promise.all(uris.map(async (uri) => {
const document = await this.langiumDocuments.getOrCreateDocument(uri);
collector(document);
}));
}
/**
* Load all additional documents that shall be visible in the context of the given workspace
* folders and add them to the collector. This can be used to include built-in libraries of
* your language, which can be either loaded from provided files or constructed in memory.
*/
loadAdditionalDocuments(_folders, _collector) {
return Promise.resolve();
}
/**
* Determine the root folder of the source documents in the given workspace folder.
* The default implementation returns the URI of the workspace folder, but you can override
* this to return a subfolder like `src` instead.
*/
getRootFolder(workspaceFolder) {
return URI2.parse(workspaceFolder.uri);
}
/**
* Traverse the file system folder identified by the given URI and its subfolders. All
* contained files that match the file extensions are added to the `uris` array.
*/
async traverseFolder(folderPath, uris) {
try {
const content = await this.fileSystemProvider.readDirectory(folderPath);
await Promise.all(content.map(async (entry) => {
if (this.shouldIncludeEntry(entry)) {
if (entry.isDirectory) {
await this.traverseFolder(entry.uri, uris);
} else if (entry.isFile) {
uris.push(entry.uri);
}
}
}));
} catch (e) {
console.error("Failure to read directory content of " + folderPath.toString(true), e);
}
}
async searchFolder(uri) {
const uris = [];
await this.traverseFolder(uri, uris);
return uris;
}
/**
* Determine whether the given folder entry shall be included while indexing the workspace.
*/
shouldIncludeEntry(entry) {
const name = UriUtils.basename(entry.uri);
if (name.startsWith(".")) {
return false;
}
if (entry.isDirectory) {
return name !== "node_modules" && name !== "out";
} else if (entry.isFile) {
return this.serviceRegistry.hasServices(entry.uri);
}
return false;
}
};
var DefaultLexerErrorMessageProvider = class {
static {
__name(this, "DefaultLexerErrorMessageProvider");
}
static {
__name2(this, "DefaultLexerErrorMessageProvider");
}
buildUnexpectedCharactersMessage(fullText, startOffset, length, line, column) {
return defaultLexerErrorProvider.buildUnexpectedCharactersMessage(fullText, startOffset, length, line, column);
}
buildUnableToPopLexerModeMessage(token) {
return defaultLexerErrorProvider.buildUnableToPopLexerModeMessage(token);
}
};
var DEFAULT_TOKENIZE_OPTIONS = { mode: "full" };
var DefaultLexer = class {
static {
__name(this, "DefaultLexer");
}
static {
__name2(this, "DefaultLexer");
}
constructor(services) {
this.errorMessageProvider = services.parser.LexerErrorMessageProvider;
this.tokenBuilder = services.parser.TokenBuilder;
const tokens = this.tokenBuilder.buildTokens(services.Grammar, {
caseInsensitive: services.LanguageMetaData.caseInsensitive
});
this.tokenTypes = this.toTokenTypeDictionary(tokens);
const lexerTokens = isTokenTypeDictionary(tokens) ? Object.values(tokens) : tokens;
const production = services.LanguageMetaData.mode === "production";
this.chevrotainLexer = new Lexer(lexerTokens, {
positionTracking: "full",
skipValidations: production,
errorMessageProvider: this.errorMessageProvider
});
}
get definition() {
return this.tokenTypes;
}
tokenize(text, _options = DEFAULT_TOKENIZE_OPTIONS) {
const chevrotainResult = this.chevrotainLexer.tokenize(text);
return {
tokens: chevrotainResult.tokens,
errors: chevrotainResult.errors,
hidden: chevrotainResult.groups.hidden ?? [],
report: this.tokenBuilder.flushLexingReport?.(text)
};
}
toTokenTypeDictionary(buildTokens) {
if (isTokenTypeDictionary(buildTokens))
return buildTokens;
const tokens = isIMultiModeLexerDefinition(buildTokens) ? Object.values(buildTokens.modes).flat() : buildTokens;
const res = {};
tokens.forEach((token) => res[token.name] = token);
return res;
}
};
function isTokenTypeArray(tokenVocabulary) {
return Array.isArray(tokenVocabulary) && (tokenVocabulary.length === 0 || "name" in tokenVocabulary[0]);
}
__name(isTokenTypeArray, "isTokenTypeArray");
__name2(isTokenTypeArray, "isTokenTypeArray");
function isIMultiModeLexerDefinition(tokenVocabulary) {
return tokenVocabulary && "modes" in tokenVocabulary && "defaultMode" in tokenVocabulary;
}
__name(isIMultiModeLexerDefinition, "isIMultiModeLexerDefinition");
__name2(isIMultiModeLexerDefinition, "isIMultiModeLexerDefinition");
function isTokenTypeDictionary(tokenVocabulary) {
return !isTokenTypeArray(tokenVocabulary) && !isIMultiModeLexerDefinition(tokenVocabulary);
}
__name(isTokenTypeDictionary, "isTokenTypeDictionary");
__name2(isTokenTypeDictionary, "isTokenTypeDictionary");
init_main();
function parseJSDoc(node, start, options) {
let opts;
let position;
if (typeof node === "string") {
position = start;
opts = options;
} else {
position = node.range.start;
opts = start;
}
if (!position) {
position = Position.create(0, 0);
}
const lines = getLines(node);
const normalizedOptions = normalizeOptions(opts);
const tokens = tokenize({
lines,
position,
options: normalizedOptions
});
return parseJSDocComment({
index: 0,
tokens,
position
});
}
__name(parseJSDoc, "parseJSDoc");
__name2(parseJSDoc, "parseJSDoc");
function isJSDoc(node, options) {
const normalizedOptions = normalizeOptions(options);
const lines = getLines(node);
if (lines.length === 0) {
return false;
}
const first2 = lines[0];
const last2 = lines[lines.length - 1];
const firstRegex = normalizedOptions.start;
const lastRegex = normalizedOptions.end;
return Boolean(firstRegex?.exec(first2)) && Boolean(lastRegex?.exec(last2));
}
__name(isJSDoc, "isJSDoc");
__name2(isJSDoc, "isJSDoc");
function getLines(node) {
let content = "";
if (typeof node === "string") {
content = node;
} else {
content = node.text;
}
const lines = content.split(NEWLINE_REGEXP);
return lines;
}
__name(getLines, "getLines");
__name2(getLines, "getLines");
var tagRegex = /\s*(@([\p{L}][\p{L}\p{N}]*)?)/uy;
var inlineTagRegex = /\{(@[\p{L}][\p{L}\p{N}]*)(\s*)([^\r\n}]+)?\}/gu;
function tokenize(context) {
const tokens = [];
let currentLine = context.position.line;
let currentCharacter = context.position.character;
for (let i = 0; i < context.lines.length; i++) {
const first2 = i === 0;
const last2 = i === context.lines.length - 1;
let line = context.lines[i];
let index = 0;
if (first2 && context.options.start) {
const match = context.options.start?.exec(line);
if (match) {
index = match.index + match[0].length;
}
} else {
const match = context.options.line?.exec(line);
if (match) {
index = match.index + match[0].length;
}
}
if (last2) {
const match = context.options.end?.exec(line);
if (match) {
line = line.substring(0, match.index);
}
}
line = line.substring(0, lastCharacter(line));
const whitespaceEnd = skipWhitespace(line, index);
if (whitespaceEnd >= line.length) {
if (tokens.length > 0) {
const position = Position.create(currentLine, currentCharacter);
tokens.push({
type: "break",
content: "",
range: Range.create(position, position)
});
}
} else {
tagRegex.lastIndex = index;
const tagMatch = tagRegex.exec(line);
if (tagMatch) {
const fullMatch = tagMatch[0];
const value = tagMatch[1];
const start = Position.create(currentLine, currentCharacter + index);
const end = Position.create(currentLine, currentCharacter + index + fullMatch.length);
tokens.push({
type: "tag",
content: value,
range: Range.create(start, end)
});
index += fullMatch.length;
index = skipWhitespace(line, index);
}
if (index < line.length) {
const rest = line.substring(index);
const inlineTagMatches = Array.from(rest.matchAll(inlineTagRegex));
tokens.push(...buildInlineTokens(inlineTagMatches, rest, currentLine, currentCharacter + index));
}
}
currentLine++;
currentCharacter = 0;
}
if (tokens.length > 0 && tokens[tokens.length - 1].type === "break") {
return tokens.slice(0, -1);
}
return tokens;
}
__name(tokenize, "tokenize");
__name2(tokenize, "tokenize");
function buildInlineTokens(tags, line, lineIndex, characterIndex) {
const tokens = [];
if (tags.length === 0) {
const start = Position.create(lineIndex, characterIndex);
const end = Position.create(lineIndex, characterIndex + line.length);
tokens.push({
type: "text",
content: line,
range: Range.create(start, end)
});
} else {
let lastIndex = 0;
for (const match of tags) {
const matchIndex = match.index;
const startContent = line.substring(lastIndex, matchIndex);
if (startContent.length > 0) {
tokens.push({
type: "text",
content: line.substring(lastIndex, matchIndex),
range: Range.create(Position.create(lineIndex, lastIndex + characterIndex), Position.create(lineIndex, matchIndex + characterIndex))
});
}
let offset = startContent.length + 1;
const tagName = match[1];
tokens.push({
type: "inline-tag",
content: tagName,
range: Range.create(Position.create(lineIndex, lastIndex + offset + characterIndex), Position.create(lineIndex, lastIndex + offset + tagName.length + characterIndex))
});
offset += tagName.length;
if (match.length === 4) {
offset += match[2].length;
const value = match[3];
tokens.push({
type: "text",
content: value,
range: Range.create(Position.create(lineIndex, lastIndex + offset + characterIndex), Position.create(lineIndex, lastIndex + offset + value.length + characterIndex))
});
} else {
tokens.push({
type: "text",
content: "",
range: Range.create(Position.create(lineIndex, lastIndex + offset + characterIndex), Position.create(lineIndex, lastIndex + offset + characterIndex))
});
}
lastIndex = matchIndex + match[0].length;
}
const endContent = line.substring(lastIndex);
if (endContent.length > 0) {
tokens.push({
type: "text",
content: endContent,
range: Range.create(Position.create(lineIndex, lastIndex + characterIndex), Position.create(lineIndex, lastIndex + characterIndex + endContent.length))
});
}
}
return tokens;
}
__name(buildInlineTokens, "buildInlineTokens");
__name2(buildInlineTokens, "buildInlineTokens");
var nonWhitespaceRegex = /\S/;
var whitespaceEndRegex = /\s*$/;
function skipWhitespace(line, index) {
const match = line.substring(index).match(nonWhitespaceRegex);
if (match) {
return index + match.index;
} else {
return line.length;
}
}
__name(skipWhitespace, "skipWhitespace");
__name2(skipWhitespace, "skipWhitespace");
function lastCharacter(line) {
const match = line.match(whitespaceEndRegex);
if (match && typeof match.index === "number") {
return match.index;
}
return void 0;
}
__name(lastCharacter, "lastCharacter");
__name2(lastCharacter, "lastCharacter");
function parseJSDocComment(context) {
const startPosition = Position.create(context.position.line, context.position.character);
if (context.tokens.length === 0) {
return new JSDocCommentImpl([], Range.create(startPosition, startPosition));
}
const elements = [];
while (context.index < context.tokens.length) {
const element = parseJSDocElement(context, elements[elements.length - 1]);
if (element) {
elements.push(element);
}
}
const start = elements[0]?.range.start ?? startPosition;
const end = elements[elements.length - 1]?.range.end ?? startPosition;
return new JSDocCommentImpl(elements, Range.create(start, end));
}
__name(parseJSDocComment, "parseJSDocComment");
__name2(parseJSDocComment, "parseJSDocComment");
function parseJSDocElement(context, last2) {
const next = context.tokens[context.index];
if (next.type === "tag") {
return parseJSDocTag(context, false);
} else if (next.type === "text" || next.type === "inline-tag") {
return parseJSDocText(context);
} else {
appendEmptyLine(next, last2);
context.index++;
return void 0;
}
}
__name(parseJSDocElement, "parseJSDocElement");
__name2(parseJSDocElement, "parseJSDocElement");
function appendEmptyLine(token, element) {
if (element) {
const line = new JSDocLineImpl("", token.range);
if ("inlines" in element) {
element.inlines.push(line);
} else {
element.content.inlines.push(line);
}
}
}
__name(appendEmptyLine, "appendEmptyLine");
__name2(appendEmptyLine, "appendEmptyLine");
function parseJSDocText(context) {
let token = context.tokens[context.index];
const firstToken = token;
let lastToken = token;
const lines = [];
while (token && token.type !== "break" && token.type !== "tag") {
lines.push(parseJSDocInline(context));
lastToken = token;
token = context.tokens[context.index];
}
return new JSDocTextImpl(lines, Range.create(firstToken.range.start, lastToken.range.end));
}
__name(parseJSDocText, "parseJSDocText");
__name2(parseJSDocText, "parseJSDocText");
function parseJSDocInline(context) {
const token = context.tokens[context.index];
if (token.type === "inline-tag") {
return parseJSDocTag(context, true);
} else {
return parseJSDocLine(context);
}
}
__name(parseJSDocInline, "parseJSDocInline");
__name2(parseJSDocInline, "parseJSDocInline");
function parseJSDocTag(context, inline) {
const tagToken = context.tokens[context.index++];
const name = tagToken.content.substring(1);
const nextToken = context.tokens[context.index];
if (nextToken?.type === "text") {
if (inline) {
const docLine = parseJSDocLine(context);
return new JSDocTagImpl(name, new JSDocTextImpl([docLine], docLine.range), inline, Range.create(tagToken.range.start, docLine.range.end));
} else {
const textDoc = parseJSDocText(context);
return new JSDocTagImpl(name, textDoc, inline, Range.create(tagToken.range.start, textDoc.range.end));
}
} else {
const range = tagToken.range;
return new JSDocTagImpl(name, new JSDocTextImpl([], range), inline, range);
}
}
__name(parseJSDocTag, "parseJSDocTag");
__name2(parseJSDocTag, "parseJSDocTag");
function parseJSDocLine(context) {
const token = context.tokens[context.index++];
return new JSDocLineImpl(token.content, token.range);
}
__name(parseJSDocLine, "parseJSDocLine");
__name2(parseJSDocLine, "parseJSDocLine");
function normalizeOptions(options) {
if (!options) {
return normalizeOptions({
start: "/**",
end: "*/",
line: "*"
});
}
const { start, end, line } = options;
return {
start: normalizeOption(start, true),
end: normalizeOption(end, false),
line: normalizeOption(line, true)
};
}
__name(normalizeOptions, "normalizeOptions");
__name2(normalizeOptions, "normalizeOptions");
function normalizeOption(option2, start) {
if (typeof option2 === "string" || typeof option2 === "object") {
const escaped = typeof option2 === "string" ? escapeRegExp(option2) : option2.source;
if (start) {
return new RegExp(`^\\s*${escaped}`);
} else {
return new RegExp(`\\s*${escaped}\\s*$`);
}
} else {
return option2;
}
}
__name(normalizeOption, "normalizeOption");
__name2(normalizeOption, "normalizeOption");
var JSDocCommentImpl = class {
static {
__name(this, "JSDocCommentImpl");
}
static {
__name2(this, "JSDocCommentImpl");
}
constructor(elements, range) {
this.elements = elements;
this.range = range;
}
getTag(name) {
return this.getAllTags().find((e) => e.name === name);
}
getTags(name) {
return this.getAllTags().filter((e) => e.name === name);
}
getAllTags() {
return this.elements.filter((e) => "name" in e);
}
toString() {
let value = "";
for (const element of this.elements) {
if (value.length === 0) {
value = element.toString();
} else {
const text = element.toString();
value += fillNewlines(value) + text;
}
}
return value.trim();
}
toMarkdown(options) {
let value = "";
for (const element of this.elements) {
if (value.length === 0) {
value = element.toMarkdown(options);
} else {
const text = element.toMarkdown(options);
value += fillNewlines(value) + text;
}
}
return value.trim();
}
};
var JSDocTagImpl = class {
static {
__name(this, "JSDocTagImpl");
}
static {
__name2(this, "JSDocTagImpl");
}
constructor(name, content, inline, range) {
this.name = name;
this.content = content;
this.inline = inline;
this.range = range;
}
toString() {
let text = `@${this.name}`;
const content = this.content.toString();
if (this.content.inlines.length === 1) {
text = `${text} ${content}`;
} else if (this.content.inlines.length > 1) {
text = `${text}
${content}`;
}
if (this.inline) {
return `{${text}}`;
} else {
return text;
}
}
toMarkdown(options) {
return options?.renderTag?.(this) ?? this.toMarkdownDefault(options);
}
toMarkdownDefault(options) {
const content = this.content.toMarkdown(options);
if (this.inline) {
const rendered = renderInlineTag(this.name, content, options ?? {});
if (typeof rendered === "string") {
return rendered;
}
}
let marker = "";
if (options?.tag === "italic" || options?.tag === void 0) {
marker = "*";
} else if (options?.tag === "bold") {
marker = "**";
} else if (options?.tag === "bold-italic") {
marker = "***";
}
let text = `${marker}@${this.name}${marker}`;
if (this.content.inlines.length === 1) {
text = `${text} \u2014 ${content}`;
} else if (this.content.inlines.length > 1) {
text = `${text}
${content}`;
}
if (this.inline) {
return `{${text}}`;
} else {
return text;
}
}
};
function renderInlineTag(tag, content, options) {
if (tag === "linkplain" || tag === "linkcode" || tag === "link") {
const index = content.indexOf(" ");
let display = content;
if (index > 0) {
const displayStart = skipWhitespace(content, index);
display = content.substring(displayStart);
content = content.substring(0, index);
}
if (tag === "linkcode" || tag === "link" && options.link === "code") {
display = `\`${display}\``;
}
const renderedLink = options.renderLink?.(content, display) ?? renderLinkDefault(content, display);
return renderedLink;
}
return void 0;
}
__name(renderInlineTag, "renderInlineTag");
__name2(renderInlineTag, "renderInlineTag");
function renderLinkDefault(content, display) {
try {
URI2.parse(content, true);
return `[${display}](${content})`;
} catch {
return content;
}
}
__name(renderLinkDefault, "renderLinkDefault");
__name2(renderLinkDefault, "renderLinkDefault");
var JSDocTextImpl = class {
static {
__name(this, "JSDocTextImpl");
}
static {
__name2(this, "JSDocTextImpl");
}
constructor(lines, range) {
this.inlines = lines;
this.range = range;
}
toString() {
let text = "";
for (let i = 0; i < this.inlines.length; i++) {
const inline = this.inlines[i];
const next = this.inlines[i + 1];
text += inline.toString();
if (next && next.range.start.line > inline.range.start.line) {
text += "\n";
}
}
return text;
}
toMarkdown(options) {
let text = "";
for (let i = 0; i < this.inlines.length; i++) {
const inline = this.inlines[i];
const next = this.inlines[i + 1];
text += inline.toMarkdown(options);
if (next && next.range.start.line > inline.range.start.line) {
text += "\n";
}
}
return text;
}
};
var JSDocLineImpl = class {
static {
__name(this, "JSDocLineImpl");
}
static {
__name2(this, "JSDocLineImpl");
}
constructor(text, range) {
this.text = text;
this.range = range;
}
toString() {
return this.text;
}
toMarkdown() {
return this.text;
}
};
function fillNewlines(text) {
if (text.endsWith("\n")) {
return "\n";
} else {
return "\n\n";
}
}
__name(fillNewlines, "fillNewlines");
__name2(fillNewlines, "fillNewlines");
var JSDocDocumentationProvider = class {
static {
__name(this, "JSDocDocumentationProvider");
}
static {
__name2(this, "JSDocDocumentationProvider");
}
constructor(services) {
this.indexManager = services.shared.workspace.IndexManager;
this.commentProvider = services.documentation.CommentProvider;
}
getDocumentation(node) {
const comment = this.commentProvider.getComment(node);
if (comment && isJSDoc(comment)) {
const parsedJSDoc = parseJSDoc(comment);
return parsedJSDoc.toMarkdown({
renderLink: /* @__PURE__ */ __name2((link, display) => {
return this.documentationLinkRenderer(node, link, display);
}, "renderLink"),
renderTag: /* @__PURE__ */ __name2((tag) => {
return this.documentationTagRenderer(node, tag);
}, "renderTag")
});
}
return void 0;
}
documentationLinkRenderer(node, name, display) {
const description = this.findNameInLocalSymbols(node, name) ?? this.findNameInGlobalScope(node, name);
if (description && description.nameSegment) {
const line = description.nameSegment.range.start.line + 1;
const character = description.nameSegment.range.start.character + 1;
const uri = description.documentUri.with({ fragment: `L${line},${character}` });
return `[${display}](${uri.toString()})`;
} else {
return void 0;
}
}
documentationTagRenderer(_node, _tag) {
return void 0;
}
findNameInLocalSymbols(node, name) {
const document = getDocument(node);
const precomputed = document.localSymbols;
if (!precomputed) {
return void 0;
}
let currentNode = node;
do {
const allDescriptions = precomputed.getStream(currentNode);
const description = allDescriptions.find((e) => e.name === name);
if (description) {
return description;
}
currentNode = currentNode.$container;
} while (currentNode);
return void 0;
}
findNameInGlobalScope(node, name) {
const description = this.indexManager.allElements().find((e) => e.name === name);
return description;
}
};
var DefaultCommentProvider = class {
static {
__name(this, "DefaultCommentProvider");
}
static {
__name2(this, "DefaultCommentProvider");
}
constructor(services) {
this.grammarConfig = () => services.parser.GrammarConfig;
}
getComment(node) {
if (isAstNodeWithComment(node)) {
return node.$comment;
}
return findCommentNode(node.$cstNode, this.grammarConfig().multilineCommentRules)?.text;
}
};
var DefaultAsyncParser = class {
static {
__name(this, "DefaultAsyncParser");
}
static {
__name2(this, "DefaultAsyncParser");
}
constructor(services) {
this.syncParser = services.parser.LangiumParser;
}
parse(text, _cancelToken) {
return Promise.resolve(this.syncParser.parse(text));
}
};
var AbstractThreadedAsyncParser = class {
static {
__name(this, "AbstractThreadedAsyncParser");
}
static {
__name2(this, "AbstractThreadedAsyncParser");
}
constructor(services) {
this.threadCount = 8;
this.terminationDelay = 200;
this.workerPool = [];
this.queue = [];
this.hydrator = services.serializer.Hydrator;
}
initializeWorkers() {
while (this.workerPool.length < this.threadCount) {
const worker = this.createWorker();
worker.onReady(() => {
if (this.queue.length > 0) {
const deferred = this.queue.shift();
if (deferred) {
worker.lock();
deferred.resolve(worker);
}
}
});
this.workerPool.push(worker);
}
}
async parse(text, cancelToken) {
const worker = await this.acquireParserWorker(cancelToken);
const deferred = new Deferred();
let timeout;
const cancellation = cancelToken.onCancellationRequested(() => {
timeout = setTimeout(() => {
this.terminateWorker(worker);
}, this.terminationDelay);
});
worker.parse(text).then((result) => {
const hydrated = this.hydrator.hydrate(result);
deferred.resolve(hydrated);
}).catch((err) => {
deferred.reject(err);
}).finally(() => {
cancellation.dispose();
clearTimeout(timeout);
});
return deferred.promise;
}
terminateWorker(worker) {
worker.terminate();
const index = this.workerPool.indexOf(worker);
if (index >= 0) {
this.workerPool.splice(index, 1);
}
}
async acquireParserWorker(cancelToken) {
this.initializeWorkers();
for (const worker of this.workerPool) {
if (worker.ready) {
worker.lock();
return worker;
}
}
const deferred = new Deferred();
cancelToken.onCancellationRequested(() => {
const index = this.queue.indexOf(deferred);
if (index >= 0) {
this.queue.splice(index, 1);
}
deferred.reject(OperationCancelled);
});
this.queue.push(deferred);
return deferred.promise;
}
};
var ParserWorker = class {
static {
__name(this, "ParserWorker");
}
static {
__name2(this, "ParserWorker");
}
get ready() {
return this._ready;
}
get onReady() {
return this.onReadyEmitter.event;
}
constructor(sendMessage, onMessage, onError, terminate) {
this.onReadyEmitter = new event_exports.Emitter();
this.deferred = new Deferred();
this._ready = true;
this._parsing = false;
this.sendMessage = sendMessage;
this._terminate = terminate;
onMessage((result) => {
const parseResult = result;
this.deferred.resolve(parseResult);
this.unlock();
});
onError((error) => {
this.deferred.reject(error);
this.unlock();
});
}
terminate() {
this.deferred.reject(OperationCancelled);
this._terminate();
}
lock() {
this._ready = false;
}
unlock() {
this._parsing = false;
this._ready = true;
this.onReadyEmitter.fire();
}
parse(text) {
if (this._parsing) {
throw new Error("Parser worker is busy");
}
this._parsing = true;
this.deferred = new Deferred();
this.sendMessage(text);
return this.deferred.promise;
}
};
var DefaultWorkspaceLock = class {
static {
__name(this, "DefaultWorkspaceLock");
}
static {
__name2(this, "DefaultWorkspaceLock");
}
constructor() {
this.previousTokenSource = new cancellation_exports.CancellationTokenSource();
this.writeQueue = [];
this.readQueue = [];
this.done = true;
}
write(action) {
this.cancelWrite();
const tokenSource = startCancelableOperation();
this.previousTokenSource = tokenSource;
return this.enqueue(this.writeQueue, action, tokenSource.token);
}
read(action) {
return this.enqueue(this.readQueue, action);
}
enqueue(queue, action, cancellationToken = cancellation_exports.CancellationToken.None) {
const deferred = new Deferred();
const entry = {
action,
deferred,
cancellationToken
};
queue.push(entry);
this.performNextOperation();
return deferred.promise;
}
async performNextOperation() {
if (!this.done) {
return;
}
const entries = [];
if (this.writeQueue.length > 0) {
entries.push(this.writeQueue.shift());
} else if (this.readQueue.length > 0) {
entries.push(...this.readQueue.splice(0, this.readQueue.length));
} else {
return;
}
this.done = false;
await Promise.all(entries.map(async ({ action, deferred, cancellationToken }) => {
try {
const result = await Promise.resolve().then(() => action(cancellationToken));
deferred.resolve(result);
} catch (err) {
if (isOperationCancelled(err)) {
deferred.resolve(void 0);
} else {
deferred.reject(err);
}
}
}));
this.done = true;
this.performNextOperation();
}
cancelWrite() {
this.previousTokenSource.cancel();
}
};
var DefaultHydrator = class {
static {
__name(this, "DefaultHydrator");
}
static {
__name2(this, "DefaultHydrator");
}
constructor(services) {
this.grammarElementIdMap = new BiMap();
this.tokenTypeIdMap = new BiMap();
this.grammar = services.Grammar;
this.lexer = services.parser.Lexer;
this.linker = services.references.Linker;
}
dehydrate(result) {
return {
lexerErrors: result.lexerErrors,
lexerReport: result.lexerReport ? this.dehydrateLexerReport(result.lexerReport) : void 0,
// We need to create shallow copies of the errors
// The original errors inherit from the `Error` class, which is not transferable across worker threads
parserErrors: result.parserErrors.map((e) => ({ ...e, message: e.message })),
value: this.dehydrateAstNode(result.value, this.createDehyrationContext(result.value))
};
}
dehydrateLexerReport(lexerReport) {
return lexerReport;
}
createDehyrationContext(node) {
const astNodes = /* @__PURE__ */ new Map();
const cstNodes = /* @__PURE__ */ new Map();
for (const astNode of streamAst(node)) {
astNodes.set(astNode, {});
}
if (node.$cstNode) {
for (const cstNode of streamCst(node.$cstNode)) {
cstNodes.set(cstNode, {});
}
}
return {
astNodes,
cstNodes
};
}
dehydrateAstNode(node, context) {
const obj = context.astNodes.get(node);
obj.$type = node.$type;
obj.$containerIndex = node.$containerIndex;
obj.$containerProperty = node.$containerProperty;
if (node.$cstNode !== void 0) {
obj.$cstNode = this.dehydrateCstNode(node.$cstNode, context);
}
for (const [name, value] of Object.entries(node)) {
if (name.startsWith("$")) {
continue;
}
if (Array.isArray(value)) {
const arr = [];
obj[name] = arr;
for (const item of value) {
if (isAstNode(item)) {
arr.push(this.dehydrateAstNode(item, context));
} else if (isReference(item)) {
arr.push(this.dehydrateReference(item, context));
} else {
arr.push(item);
}
}
} else if (isAstNode(value)) {
obj[name] = this.dehydrateAstNode(value, context);
} else if (isReference(value)) {
obj[name] = this.dehydrateReference(value, context);
} else if (value !== void 0) {
obj[name] = value;
}
}
return obj;
}
dehydrateReference(reference, context) {
const obj = {};
obj.$refText = reference.$refText;
if (reference.$refNode) {
obj.$refNode = context.cstNodes.get(reference.$refNode);
}
return obj;
}
dehydrateCstNode(node, context) {
const cstNode = context.cstNodes.get(node);
if (isRootCstNode(node)) {
cstNode.fullText = node.fullText;
} else {
cstNode.grammarSource = this.getGrammarElementId(node.grammarSource);
}
cstNode.hidden = node.hidden;
cstNode.astNode = context.astNodes.get(node.astNode);
if (isCompositeCstNode(node)) {
cstNode.content = node.content.map((child) => this.dehydrateCstNode(child, context));
} else if (isLeafCstNode(node)) {
cstNode.tokenType = node.tokenType.name;
cstNode.offset = node.offset;
cstNode.length = node.length;
cstNode.startLine = node.range.start.line;
cstNode.startColumn = node.range.start.character;
cstNode.endLine = node.range.end.line;
cstNode.endColumn = node.range.end.character;
}
return cstNode;
}
hydrate(result) {
const node = result.value;
const context = this.createHydrationContext(node);
if ("$cstNode" in node) {
this.hydrateCstNode(node.$cstNode, context);
}
return {
lexerErrors: result.lexerErrors,
lexerReport: result.lexerReport,
parserErrors: result.parserErrors,
value: this.hydrateAstNode(node, context)
};
}
createHydrationContext(node) {
const astNodes = /* @__PURE__ */ new Map();
const cstNodes = /* @__PURE__ */ new Map();
for (const astNode of streamAst(node)) {
astNodes.set(astNode, {});
}
let root3;
if (node.$cstNode) {
for (const cstNode of streamCst(node.$cstNode)) {
let cst;
if ("fullText" in cstNode) {
cst = new RootCstNodeImpl(cstNode.fullText);
root3 = cst;
} else if ("content" in cstNode) {
cst = new CompositeCstNodeImpl();
} else if ("tokenType" in cstNode) {
cst = this.hydrateCstLeafNode(cstNode);
}
if (cst) {
cstNodes.set(cstNode, cst);
cst.root = root3;
}
}
}
return {
astNodes,
cstNodes
};
}
hydrateAstNode(node, context) {
const astNode = context.astNodes.get(node);
astNode.$type = node.$type;
astNode.$containerIndex = node.$containerIndex;
astNode.$containerProperty = node.$containerProperty;
if (node.$cstNode) {
astNode.$cstNode = context.cstNodes.get(node.$cstNode);
}
for (const [name, value] of Object.entries(node)) {
if (name.startsWith("$")) {
continue;
}
if (Array.isArray(value)) {
const arr = [];
astNode[name] = arr;
for (const item of value) {
if (isAstNode(item)) {
arr.push(this.setParent(this.hydrateAstNode(item, context), astNode));
} else if (isReference(item)) {
arr.push(this.hydrateReference(item, astNode, name, context));
} else {
arr.push(item);
}
}
} else if (isAstNode(value)) {
astNode[name] = this.setParent(this.hydrateAstNode(value, context), astNode);
} else if (isReference(value)) {
astNode[name] = this.hydrateReference(value, astNode, name, context);
} else if (value !== void 0) {
astNode[name] = value;
}
}
return astNode;
}
setParent(node, parent) {
node.$container = parent;
return node;
}
hydrateReference(reference, node, name, context) {
return this.linker.buildReference(node, name, context.cstNodes.get(reference.$refNode), reference.$refText);
}
hydrateCstNode(cstNode, context, num = 0) {
const cstNodeObj = context.cstNodes.get(cstNode);
if (typeof cstNode.grammarSource === "number") {
cstNodeObj.grammarSource = this.getGrammarElement(cstNode.grammarSource);
}
cstNodeObj.astNode = context.astNodes.get(cstNode.astNode);
if (isCompositeCstNode(cstNodeObj)) {
for (const child of cstNode.content) {
const hydrated = this.hydrateCstNode(child, context, num++);
cstNodeObj.content.push(hydrated);
}
}
return cstNodeObj;
}
hydrateCstLeafNode(cstNode) {
const tokenType = this.getTokenType(cstNode.tokenType);
const offset = cstNode.offset;
const length = cstNode.length;
const startLine = cstNode.startLine;
const startColumn = cstNode.startColumn;
const endLine = cstNode.endLine;
const endColumn = cstNode.endColumn;
const hidden = cstNode.hidden;
const node = new LeafCstNodeImpl(offset, length, {
start: {
line: startLine,
character: startColumn
},
end: {
line: endLine,
character: endColumn
}
}, tokenType, hidden);
return node;
}
getTokenType(name) {
return this.lexer.definition[name];
}
getGrammarElementId(node) {
if (!node) {
return void 0;
}
if (this.grammarElementIdMap.size === 0) {
this.createGrammarElementIdMap();
}
return this.grammarElementIdMap.get(node);
}
getGrammarElement(id) {
if (this.grammarElementIdMap.size === 0) {
this.createGrammarElementIdMap();
}
const element = this.grammarElementIdMap.getKey(id);
return element;
}
createGrammarElementIdMap() {
let id = 0;
for (const element of streamAst(this.grammar)) {
if (isAbstractElement(element)) {
this.grammarElementIdMap.set(element, id++);
}
}
}
};
function createDefaultCoreModule(context) {
return {
documentation: {
CommentProvider: /* @__PURE__ */ __name2((services) => new DefaultCommentProvider(services), "CommentProvider"),
DocumentationProvider: /* @__PURE__ */ __name2((services) => new JSDocDocumentationProvider(services), "DocumentationProvider")
},
parser: {
AsyncParser: /* @__PURE__ */ __name2((services) => new DefaultAsyncParser(services), "AsyncParser"),
GrammarConfig: /* @__PURE__ */ __name2((services) => createGrammarConfig(services), "GrammarConfig"),
LangiumParser: /* @__PURE__ */ __name2((services) => createLangiumParser(services), "LangiumParser"),
CompletionParser: /* @__PURE__ */ __name2((services) => createCompletionParser(services), "CompletionParser"),
ValueConverter: /* @__PURE__ */ __name2(() => new DefaultValueConverter(), "ValueConverter"),
TokenBuilder: /* @__PURE__ */ __name2(() => new DefaultTokenBuilder(), "TokenBuilder"),
Lexer: /* @__PURE__ */ __name2((services) => new DefaultLexer(services), "Lexer"),
ParserErrorMessageProvider: /* @__PURE__ */ __name2(() => new LangiumParserErrorMessageProvider(), "ParserErrorMessageProvider"),
LexerErrorMessageProvider: /* @__PURE__ */ __name2(() => new DefaultLexerErrorMessageProvider(), "LexerErrorMessageProvider")
},
workspace: {
AstNodeLocator: /* @__PURE__ */ __name2(() => new DefaultAstNodeLocator(), "AstNodeLocator"),
AstNodeDescriptionProvider: /* @__PURE__ */ __name2((services) => new DefaultAstNodeDescriptionProvider(services), "AstNodeDescriptionProvider"),
ReferenceDescriptionProvider: /* @__PURE__ */ __name2((services) => new DefaultReferenceDescriptionProvider(services), "ReferenceDescriptionProvider")
},
references: {
Linker: /* @__PURE__ */ __name2((services) => new DefaultLinker(services), "Linker"),
NameProvider: /* @__PURE__ */ __name2(() => new DefaultNameProvider(), "NameProvider"),
ScopeProvider: /* @__PURE__ */ __name2((services) => new DefaultScopeProvider(services), "ScopeProvider"),
ScopeComputation: /* @__PURE__ */ __name2((services) => new DefaultScopeComputation(services), "ScopeComputation"),
References: /* @__PURE__ */ __name2((services) => new DefaultReferences(services), "References")
},
serializer: {
Hydrator: /* @__PURE__ */ __name2((services) => new DefaultHydrator(services), "Hydrator"),
JsonSerializer: /* @__PURE__ */ __name2((services) => new DefaultJsonSerializer(services), "JsonSerializer")
},
validation: {
DocumentValidator: /* @__PURE__ */ __name2((services) => new DefaultDocumentValidator(services), "DocumentValidator"),
ValidationRegistry: /* @__PURE__ */ __name2((services) => new ValidationRegistry(services), "ValidationRegistry")
},
shared: /* @__PURE__ */ __name2(() => context.shared, "shared")
};
}
__name(createDefaultCoreModule, "createDefaultCoreModule");
__name2(createDefaultCoreModule, "createDefaultCoreModule");
function createDefaultSharedCoreModule(context) {
return {
ServiceRegistry: /* @__PURE__ */ __name2((services) => new DefaultServiceRegistry(services), "ServiceRegistry"),
workspace: {
LangiumDocuments: /* @__PURE__ */ __name2((services) => new DefaultLangiumDocuments(services), "LangiumDocuments"),
LangiumDocumentFactory: /* @__PURE__ */ __name2((services) => new DefaultLangiumDocumentFactory(services), "LangiumDocumentFactory"),
DocumentBuilder: /* @__PURE__ */ __name2((services) => new DefaultDocumentBuilder(services), "DocumentBuilder"),
IndexManager: /* @__PURE__ */ __name2((services) => new DefaultIndexManager(services), "IndexManager"),
WorkspaceManager: /* @__PURE__ */ __name2((services) => new DefaultWorkspaceManager(services), "WorkspaceManager"),
FileSystemProvider: /* @__PURE__ */ __name2((services) => context.fileSystemProvider(services), "FileSystemProvider"),
WorkspaceLock: /* @__PURE__ */ __name2(() => new DefaultWorkspaceLock(), "WorkspaceLock"),
ConfigurationProvider: /* @__PURE__ */ __name2((services) => new DefaultConfigurationProvider(services), "ConfigurationProvider")
},
profilers: {}
};
}
__name(createDefaultSharedCoreModule, "createDefaultSharedCoreModule");
__name2(createDefaultSharedCoreModule, "createDefaultSharedCoreModule");
var Module;
(function(Module2) {
Module2.merge = (m1, m2) => _merge(_merge({}, m1), m2);
})(Module || (Module = {}));
function inject(module1, module2, module3, module4, module5, module6, module7, module8, module9) {
const module10 = [module1, module2, module3, module4, module5, module6, module7, module8, module9].reduce(_merge, {});
return _inject(module10);
}
__name(inject, "inject");
__name2(inject, "inject");
var isProxy = Symbol("isProxy");
function eagerLoad(item) {
if (item && item[isProxy]) {
for (const value of Object.values(item)) {
eagerLoad(value);
}
}
return item;
}
__name(eagerLoad, "eagerLoad");
__name2(eagerLoad, "eagerLoad");
function _inject(module2, injector) {
const proxy = new Proxy({}, {
deleteProperty: /* @__PURE__ */ __name2(() => false, "deleteProperty"),
set: /* @__PURE__ */ __name2(() => {
throw new Error("Cannot set property on injected service container");
}, "set"),
get: /* @__PURE__ */ __name2((obj, prop) => {
if (prop === isProxy) {
return true;
} else {
return _resolve(obj, prop, module2, injector || proxy);
}
}, "get"),
getOwnPropertyDescriptor: /* @__PURE__ */ __name2((obj, prop) => (_resolve(obj, prop, module2, injector || proxy), Object.getOwnPropertyDescriptor(obj, prop)), "getOwnPropertyDescriptor"),
// used by for..in
has: /* @__PURE__ */ __name2((_, prop) => prop in module2, "has"),
// used by ..in..
ownKeys: /* @__PURE__ */ __name2(() => [...Object.getOwnPropertyNames(module2)], "ownKeys")
// used by for..in
});
return proxy;
}
__name(_inject, "_inject");
__name2(_inject, "_inject");
var __requested__ = Symbol();
function _resolve(obj, prop, module2, injector) {
if (prop in obj) {
if (obj[prop] instanceof Error) {
throw new Error("Construction failure. Please make sure that your dependencies are constructable. Cause: " + obj[prop]);
}
if (obj[prop] === __requested__) {
throw new Error('Cycle detected. Please make "' + String(prop) + '" lazy. Visit https://langium.org/docs/reference/configuration-services/#resolving-cyclic-dependencies');
}
return obj[prop];
} else if (prop in module2) {
const value = module2[prop];
obj[prop] = __requested__;
try {
obj[prop] = typeof value === "function" ? value(injector) : _inject(value, injector);
} catch (error) {
obj[prop] = error instanceof Error ? error : void 0;
throw error;
}
return obj[prop];
} else {
return void 0;
}
}
__name(_resolve, "_resolve");
__name2(_resolve, "_resolve");
function _merge(target, source) {
if (source) {
for (const [key, sourceValue] of Object.entries(source)) {
if (sourceValue !== void 0 && sourceValue !== null) {
if (typeof sourceValue === "object") {
const targetValue = target[key];
if (typeof targetValue === "object" && targetValue !== null) {
target[key] = _merge(targetValue, sourceValue);
} else {
target[key] = _merge({}, sourceValue);
}
} else {
target[key] = sourceValue;
}
}
}
}
return target;
}
__name(_merge, "_merge");
__name2(_merge, "_merge");
var indentationBuilderDefaultOptions = {
indentTokenName: "INDENT",
dedentTokenName: "DEDENT",
whitespaceTokenName: "WS",
ignoreIndentationDelimiters: []
};
var LexingMode;
(function(LexingMode2) {
LexingMode2["REGULAR"] = "indentation-sensitive";
LexingMode2["IGNORE_INDENTATION"] = "ignore-indentation";
})(LexingMode || (LexingMode = {}));
var IndentationAwareTokenBuilder = class extends DefaultTokenBuilder {
static {
__name(this, "IndentationAwareTokenBuilder");
}
static {
__name2(this, "IndentationAwareTokenBuilder");
}
constructor(options = indentationBuilderDefaultOptions) {
super();
this.indentationStack = [0];
this.whitespaceRegExp = /[ \t]+/y;
this.options = {
...indentationBuilderDefaultOptions,
...options
};
this.indentTokenType = createToken({
name: this.options.indentTokenName,
pattern: this.indentMatcher.bind(this),
line_breaks: false
});
this.dedentTokenType = createToken({
name: this.options.dedentTokenName,
pattern: this.dedentMatcher.bind(this),
line_breaks: false
});
}
buildTokens(grammar, options) {
const tokenTypes = super.buildTokens(grammar, options);
if (!isTokenTypeArray(tokenTypes)) {
throw new Error("Invalid tokens built by default builder");
}
const { indentTokenName, dedentTokenName, whitespaceTokenName, ignoreIndentationDelimiters } = this.options;
let dedent;
let indent;
let ws;
const otherTokens = [];
for (const tokenType of tokenTypes) {
for (const [begin, end] of ignoreIndentationDelimiters) {
if (tokenType.name === begin) {
tokenType.PUSH_MODE = LexingMode.IGNORE_INDENTATION;
} else if (tokenType.name === end) {
tokenType.POP_MODE = true;
}
}
if (tokenType.name === dedentTokenName) {
dedent = tokenType;
} else if (tokenType.name === indentTokenName) {
indent = tokenType;
} else if (tokenType.name === whitespaceTokenName) {
ws = tokenType;
} else {
otherTokens.push(tokenType);
}
}
if (!dedent || !indent || !ws) {
throw new Error("Some indentation/whitespace tokens not found!");
}
if (ignoreIndentationDelimiters.length > 0) {
const multiModeLexerDef = {
modes: {
[LexingMode.REGULAR]: [dedent, indent, ...otherTokens, ws],
[LexingMode.IGNORE_INDENTATION]: [...otherTokens, ws]
},
defaultMode: LexingMode.REGULAR
};
return multiModeLexerDef;
} else {
return [dedent, indent, ws, ...otherTokens];
}
}
flushLexingReport(text) {
const result = super.flushLexingReport(text);
return {
...result,
remainingDedents: this.flushRemainingDedents(text)
};
}
/**
* Helper function to check if the current position is the start of a new line.
*
* @param text The full input string.
* @param offset The current position at which to check
* @returns Whether the current position is the start of a new line
*/
isStartOfLine(text, offset) {
return offset === 0 || "\r\n".includes(text[offset - 1]);
}
/**
* A helper function used in matching both indents and dedents.
*
* @param text The full input string.
* @param offset The current position at which to attempt a match
* @param tokens Previously scanned tokens
* @param groups Token Groups
* @returns The current and previous indentation levels and the matched whitespace
*/
// eslint-disable-next-line @typescript-eslint/no-unused-vars
matchWhitespace(text, offset, tokens, groups) {
this.whitespaceRegExp.lastIndex = offset;
const match = this.whitespaceRegExp.exec(text);
return {
currIndentLevel: match?.[0].length ?? 0,
prevIndentLevel: this.indentationStack.at(-1),
match
};
}
/**
* Helper function to create an instance of an indentation token.
*
* @param tokenType Indent or dedent token type
* @param text Full input string, used to calculate the line number
* @param image The original image of the token (tabs or spaces)
* @param offset Current position in the input string
* @returns The indentation token instance
*/
createIndentationTokenInstance(tokenType, text, image, offset) {
const lineNumber = this.getLineNumber(text, offset);
return createTokenInstance(tokenType, image, offset, offset + image.length, lineNumber, lineNumber, 1, image.length);
}
/**
* Helper function to get the line number at a given offset.
*
* @param text Full input string, used to calculate the line number
* @param offset Current position in the input string
* @returns The line number at the given offset
*/
getLineNumber(text, offset) {
return text.substring(0, offset).split(/\r\n|\r|\n/).length;
}
/**
* A custom pattern for matching indents
*
* @param text The full input string.
* @param offset The offset at which to attempt a match
* @param tokens Previously scanned tokens
* @param groups Token Groups
*/
indentMatcher(text, offset, tokens, groups) {
if (!this.isStartOfLine(text, offset)) {
return null;
}
const { currIndentLevel, prevIndentLevel, match } = this.matchWhitespace(text, offset, tokens, groups);
if (currIndentLevel <= prevIndentLevel) {
return null;
}
this.indentationStack.push(currIndentLevel);
return match;
}
/**
* A custom pattern for matching dedents
*
* @param text The full input string.
* @param offset The offset at which to attempt a match
* @param tokens Previously scanned tokens
* @param groups Token Groups
*/
dedentMatcher(text, offset, tokens, groups) {
if (!this.isStartOfLine(text, offset)) {
return null;
}
const { currIndentLevel, prevIndentLevel, match } = this.matchWhitespace(text, offset, tokens, groups);
if (currIndentLevel >= prevIndentLevel) {
return null;
}
const matchIndentIndex = this.indentationStack.lastIndexOf(currIndentLevel);
if (matchIndentIndex === -1) {
this.diagnostics.push({
severity: "error",
message: `Invalid dedent level ${currIndentLevel} at offset: ${offset}. Current indentation stack: ${this.indentationStack}`,
offset,
length: match?.[0]?.length ?? 0,
line: this.getLineNumber(text, offset),
column: 1
});
return null;
}
const numberOfDedents = this.indentationStack.length - matchIndentIndex - 1;
const newlinesBeforeDedent = text.substring(0, offset).match(/[\r\n]+$/)?.[0].length ?? 1;
for (let i = 0; i < numberOfDedents; i++) {
const token = this.createIndentationTokenInstance(
this.dedentTokenType,
text,
"",
// Dedents are 0-width tokens
offset - (newlinesBeforeDedent - 1)
);
tokens.push(token);
this.indentationStack.pop();
}
return null;
}
buildTerminalToken(terminal) {
const tokenType = super.buildTerminalToken(terminal);
const { indentTokenName, dedentTokenName, whitespaceTokenName } = this.options;
if (tokenType.name === indentTokenName) {
return this.indentTokenType;
} else if (tokenType.name === dedentTokenName) {
return this.dedentTokenType;
} else if (tokenType.name === whitespaceTokenName) {
return createToken({
name: whitespaceTokenName,
pattern: this.whitespaceRegExp,
group: Lexer.SKIPPED
});
}
return tokenType;
}
/**
* Resets the indentation stack between different runs of the lexer
*
* @param text Full text that was tokenized
* @returns Remaining dedent tokens to match all previous indents at the end of the file
*/
flushRemainingDedents(text) {
const remainingDedents = [];
while (this.indentationStack.length > 1) {
remainingDedents.push(this.createIndentationTokenInstance(this.dedentTokenType, text, "", text.length));
this.indentationStack.pop();
}
this.indentationStack = [0];
return remainingDedents;
}
};
var IndentationAwareLexer = class extends DefaultLexer {
static {
__name(this, "IndentationAwareLexer");
}
static {
__name2(this, "IndentationAwareLexer");
}
constructor(services) {
super(services);
if (services.parser.TokenBuilder instanceof IndentationAwareTokenBuilder) {
this.indentationTokenBuilder = services.parser.TokenBuilder;
} else {
throw new Error("IndentationAwareLexer requires an accompanying IndentationAwareTokenBuilder");
}
}
tokenize(text, options = DEFAULT_TOKENIZE_OPTIONS) {
const result = super.tokenize(text);
const report = result.report;
if (options?.mode === "full") {
result.tokens.push(...report.remainingDedents);
}
report.remainingDedents = [];
const { indentTokenType, dedentTokenType } = this.indentationTokenBuilder;
const indentTokenIdx = indentTokenType.tokenTypeIdx;
const dedentTokenIdx = dedentTokenType.tokenTypeIdx;
const cleanTokens = [];
const length = result.tokens.length - 1;
for (let i = 0; i < length; i++) {
const token = result.tokens[i];
const nextToken = result.tokens[i + 1];
if (token.tokenTypeIdx === indentTokenIdx && nextToken.tokenTypeIdx === dedentTokenIdx) {
i++;
continue;
}
cleanTokens.push(token);
}
if (length >= 0) {
cleanTokens.push(result.tokens[length]);
}
result.tokens = cleanTokens;
return result;
}
};
var utils_exports = {};
__export(utils_exports, {
AstUtils: /* @__PURE__ */ __name(() => ast_utils_exports, "AstUtils"),
BiMap: /* @__PURE__ */ __name(() => BiMap, "BiMap"),
Cancellation: /* @__PURE__ */ __name(() => cancellation_exports, "Cancellation"),
ContextCache: /* @__PURE__ */ __name(() => ContextCache, "ContextCache"),
CstUtils: /* @__PURE__ */ __name(() => cst_utils_exports, "CstUtils"),
DONE_RESULT: /* @__PURE__ */ __name(() => DONE_RESULT, "DONE_RESULT"),
Deferred: /* @__PURE__ */ __name(() => Deferred, "Deferred"),
Disposable: /* @__PURE__ */ __name(() => Disposable, "Disposable"),
DisposableCache: /* @__PURE__ */ __name(() => DisposableCache, "DisposableCache"),
DocumentCache: /* @__PURE__ */ __name(() => DocumentCache, "DocumentCache"),
EMPTY_STREAM: /* @__PURE__ */ __name(() => EMPTY_STREAM, "EMPTY_STREAM"),
ErrorWithLocation: /* @__PURE__ */ __name(() => ErrorWithLocation, "ErrorWithLocation"),
GrammarUtils: /* @__PURE__ */ __name(() => grammar_utils_exports, "GrammarUtils"),
MultiMap: /* @__PURE__ */ __name(() => MultiMap, "MultiMap"),
OperationCancelled: /* @__PURE__ */ __name(() => OperationCancelled, "OperationCancelled"),
Reduction: /* @__PURE__ */ __name(() => Reduction, "Reduction"),
RegExpUtils: /* @__PURE__ */ __name(() => regexp_utils_exports, "RegExpUtils"),
SimpleCache: /* @__PURE__ */ __name(() => SimpleCache, "SimpleCache"),
StreamImpl: /* @__PURE__ */ __name(() => StreamImpl, "StreamImpl"),
TreeStreamImpl: /* @__PURE__ */ __name(() => TreeStreamImpl, "TreeStreamImpl"),
URI: /* @__PURE__ */ __name(() => URI2, "URI"),
UriTrie: /* @__PURE__ */ __name(() => UriTrie, "UriTrie"),
UriUtils: /* @__PURE__ */ __name(() => UriUtils, "UriUtils"),
WorkspaceCache: /* @__PURE__ */ __name(() => WorkspaceCache, "WorkspaceCache"),
assertCondition: /* @__PURE__ */ __name(() => assertCondition, "assertCondition"),
assertUnreachable: /* @__PURE__ */ __name(() => assertUnreachable, "assertUnreachable"),
delayNextTick: /* @__PURE__ */ __name(() => delayNextTick, "delayNextTick"),
interruptAndCheck: /* @__PURE__ */ __name(() => interruptAndCheck, "interruptAndCheck"),
isOperationCancelled: /* @__PURE__ */ __name(() => isOperationCancelled, "isOperationCancelled"),
loadGrammarFromJson: /* @__PURE__ */ __name(() => loadGrammarFromJson, "loadGrammarFromJson"),
setInterruptionPeriod: /* @__PURE__ */ __name(() => setInterruptionPeriod, "setInterruptionPeriod"),
startCancelableOperation: /* @__PURE__ */ __name(() => startCancelableOperation, "startCancelableOperation"),
stream: /* @__PURE__ */ __name(() => stream, "stream")
});
__reExport(utils_exports, event_exports);
var EmptyFileSystemProvider = class {
static {
__name(this, "EmptyFileSystemProvider");
}
static {
__name2(this, "EmptyFileSystemProvider");
}
stat(_uri) {
throw new Error("No file system is available.");
}
statSync(_uri) {
throw new Error("No file system is available.");
}
async exists() {
return false;
}
existsSync() {
return false;
}
readBinary() {
throw new Error("No file system is available.");
}
readBinarySync() {
throw new Error("No file system is available.");
}
readFile() {
throw new Error("No file system is available.");
}
readFileSync() {
throw new Error("No file system is available.");
}
async readDirectory() {
return [];
}
readDirectorySync() {
return [];
}
};
var EmptyFileSystem = {
fileSystemProvider: /* @__PURE__ */ __name2(() => new EmptyFileSystemProvider(), "fileSystemProvider")
};
var minimalGrammarModule = {
Grammar: /* @__PURE__ */ __name2(() => void 0, "Grammar"),
LanguageMetaData: /* @__PURE__ */ __name2(() => ({
caseInsensitive: false,
fileExtensions: [".langium"],
languageId: "langium"
}), "LanguageMetaData")
};
var minimalSharedGrammarModule = {
AstReflection: /* @__PURE__ */ __name2(() => new LangiumGrammarAstReflection(), "AstReflection")
};
function createMinimalGrammarServices() {
const shared = inject(createDefaultSharedCoreModule(EmptyFileSystem), minimalSharedGrammarModule);
const grammar = inject(createDefaultCoreModule({ shared }), minimalGrammarModule);
shared.ServiceRegistry.register(grammar);
return grammar;
}
__name(createMinimalGrammarServices, "createMinimalGrammarServices");
__name2(createMinimalGrammarServices, "createMinimalGrammarServices");
function loadGrammarFromJson(json) {
const services = createMinimalGrammarServices();
const astNode = services.serializer.JsonSerializer.deserialize(json);
services.shared.workspace.LangiumDocumentFactory.fromModel(astNode, URI2.parse(`memory:/${astNode.name ?? "grammar"}.langium`));
return astNode;
}
__name(loadGrammarFromJson, "loadGrammarFromJson");
__name2(loadGrammarFromJson, "loadGrammarFromJson");
__reExport(lib_exports, utils_exports);
var DefaultLangiumProfiler = class {
static {
__name(this, "DefaultLangiumProfiler");
}
static {
__name2(this, "DefaultLangiumProfiler");
}
constructor(activeCategories) {
this.activeCategories = /* @__PURE__ */ new Set();
this.allCategories = /* @__PURE__ */ new Set(["validating", "parsing", "linking"]);
this.activeCategories = activeCategories ?? new Set(this.allCategories);
this.records = new MultiMap();
}
isActive(category) {
return this.activeCategories.has(category);
}
start(...categories) {
if (!categories) {
this.activeCategories = new Set(this.allCategories);
} else {
categories.forEach((category) => this.activeCategories.add(category));
}
}
stop(...categories) {
if (!categories) {
this.activeCategories.clear();
} else {
categories.forEach((category) => this.activeCategories.delete(category));
}
}
createTask(category, taskId) {
if (!this.isActive(category)) {
throw new Error(`Category "${category}" is not active.`);
}
console.log(`Creating profiling task for '${category}.${taskId}'.`);
return new ProfilingTask((record) => this.records.add(category, this.dumpRecord(category, record)), taskId);
}
dumpRecord(category, record) {
console.info(`Task ${category}.${record.identifier} executed in ${record.duration.toFixed(2)}ms and ended at ${record.date.toISOString()}`);
const result = [];
for (const key of record.entries.keys()) {
const values2 = record.entries.get(key);
const duration = values2.reduce((p, c) => p + c);
result.push({ name: `${record.identifier}.${key}`, count: values2.length, duration });
}
const taskInternalDuration = record.duration - result.map((r) => r.duration).reduce((a, b) => a + b, 0);
result.push({ name: record.identifier, count: 1, duration: taskInternalDuration });
result.sort((a, b) => b.duration - a.duration);
function Round(value) {
return Math.round(100 * value) / 100;
}
__name(Round, "Round");
__name2(Round, "Round");
console.table(result.map((e) => {
return { Element: e.name, Count: e.count, "Self %": Round(100 * e.duration / record.duration), "Time (ms)": Round(e.duration) };
}));
return record;
}
getRecords(...categories) {
if (categories.length === 0) {
return this.records.values();
} else {
return this.records.entries().filter((e) => categories.some((c) => c === e[0])).flatMap((e) => e[1]);
}
}
};
var ProfilingTask = class {
static {
__name(this, "ProfilingTask");
}
static {
__name2(this, "ProfilingTask");
}
constructor(addRecord, identifier) {
this.stack = [];
this.entries = new MultiMap();
this.addRecord = addRecord;
this.identifier = identifier;
}
start() {
if (this.startTime !== void 0) {
throw new Error(`Task "${this.identifier}" is already started.`);
}
this.startTime = performance.now();
}
stop() {
if (this.startTime === void 0) {
throw new Error(`Task "${this.identifier}" was not started.`);
}
if (this.stack.length !== 0) {
throw new Error(`Task "${this.identifier}" cannot be stopped before sub-task(s): ${this.stack.map((s) => s.id).join(", ")}.`);
}
const record = {
identifier: this.identifier,
date: /* @__PURE__ */ new Date(),
duration: performance.now() - this.startTime,
entries: this.entries
};
this.addRecord(record);
this.startTime = void 0;
this.entries.clear();
}
startSubTask(subTaskId) {
this.stack.push({ id: subTaskId, start: performance.now(), content: 0 });
}
stopSubTask(subTaskId) {
const subStack = this.stack.pop();
if (!subStack) {
throw new Error(`Task "${this.identifier}.${subTaskId}" was not started.`);
}
if (subStack.id !== subTaskId) {
throw new Error(`Sub-Task "${subStack.id}" is not already stopped.`);
}
const duration = performance.now() - subStack.start;
if (this.stack.at(-1) !== void 0) {
this.stack[this.stack.length - 1].content += duration;
}
const selfDuration = duration - subStack.content;
this.entries.add(subTaskId, selfDuration);
}
};
var ArchitectureGrammar;
((ArchitectureGrammar2) => {
ArchitectureGrammar2.Terminals = {
ARROW_DIRECTION: /L|R|T|B/,
ARROW_GROUP: /\{group\}/,
ARROW_INTO: /<|>/,
ACC_DESCR: /[\t ]*accDescr(?:[\t ]*:([^\n\r]*?(?=%%)|[^\n\r]*)|\s*{([^}]*)})/,
ACC_TITLE: /[\t ]*accTitle[\t ]*:(?:[^\n\r]*?(?=%%)|[^\n\r]*)/,
TITLE: /[\t ]*title(?:[\t ][^\n\r]*?(?=%%)|[\t ][^\n\r]*|)/,
STRING: /"([^"\\]|\\.)*"|'([^'\\]|\\.)*'/,
ID: /[\w]([-\w]*\w)?/,
NEWLINE: /\r?\n/,
WHITESPACE: /[\t ]+/,
YAML: /---[\t ]*\r?\n(?:[\S\s]*?\r?\n)?---(?:\r?\n|(?!\S))/,
DIRECTIVE: /[\t ]*%%{[\S\s]*?}%%(?:\r?\n|(?!\S))/,
SINGLE_LINE_COMMENT: /[\t ]*%%[^\n\r]*/,
ARCH_ICON: /\([\w-:]+\)/,
ARCH_TITLE: /\[(?:"([^"\\]|\\.)*"|'([^'\\]|\\.)*'|[^\[\]\r\n]+)\]/
};
})(ArchitectureGrammar || (ArchitectureGrammar = {}));
var CynefinGrammar;
((CynefinGrammar2) => {
CynefinGrammar2.Terminals = {
DOMAIN_NAME: /complex|complicated|clear|chaotic|confusion/,
ACC_DESCR: /[\t ]*accDescr(?:[\t ]*:([^\n\r]*?(?=%%)|[^\n\r]*)|\s*{([^}]*)})/,
ACC_TITLE: /[\t ]*accTitle[\t ]*:(?:[^\n\r]*?(?=%%)|[^\n\r]*)/,
TITLE: /[\t ]*title(?:[\t ][^\n\r]*?(?=%%)|[\t ][^\n\r]*|)/,
STRING: /"([^"\\]|\\.)*"|'([^'\\]|\\.)*'/,
NEWLINE: /\r?\n/,
WHITESPACE: /[\t ]+/,
YAML: /---[\t ]*\r?\n(?:[\S\s]*?\r?\n)?---(?:\r?\n|(?!\S))/,
DIRECTIVE: /[\t ]*%%{[\S\s]*?}%%(?:\r?\n|(?!\S))/,
SINGLE_LINE_COMMENT: /[\t ]*%%[^\n\r]*/
};
})(CynefinGrammar || (CynefinGrammar = {}));
var EventModeling;
((EventModeling2) => {
EventModeling2.Terminals = {
EM_ID: /[_a-zA-Z][\w_]*/,
EM_FID: /\d{1,3}/,
EM_DATA_INLINE: /\{(.*)\}|"(.*)"|'(.*)'/,
EM_DATA_BLOCK: /\{[\t ]*\r?\n(?:[\S\s]*?\r?\n)?\}(?:\r?\n|(?!\S))/,
EM_ACC_DESCR: /[\t ]*accDescr(?:[\t ]*:([^\n\r]*?(?=%%)|[^\n\r]*)|\s*{([^}]*)})/,
EM_ACC_TITLE: /[\t ]*accTitle[\t ]*:(?:[^\n\r]*?(?=%%)|[^\n\r]*)/,
EM_TITLE: /[\t ]*title(?:[\t ][^\n\r]*?(?=%%)|[\t ][^\n\r]*|)/,
EM_WS: /\s+/,
EM_YAML: /---[\t ]*\r?\n(?:[\S\s]*?\r?\n)?---(?:\r?\n|(?!\S))/,
EM_DIRECTIVE: /[\t ]*%%{[\S\s]*?}%%(?:\r?\n|(?!\S))/,
EM_SINGLE_LINE_COMMENT: /[\t ]*%%[^\n\r]*/,
EM_ML_COMMENT: /\/\*[\s\S]*?\*\//,
EM_SL_COMMENT: /\/\/[^\n\r]*/
};
})(EventModeling || (EventModeling = {}));
var GitGraphGrammar;
((GitGraphGrammar2) => {
GitGraphGrammar2.Terminals = {
ACC_DESCR: /[\t ]*accDescr(?:[\t ]*:([^\n\r]*?(?=%%)|[^\n\r]*)|\s*{([^}]*)})/,
ACC_TITLE: /[\t ]*accTitle[\t ]*:(?:[^\n\r]*?(?=%%)|[^\n\r]*)/,
TITLE: /[\t ]*title(?:[\t ][^\n\r]*?(?=%%)|[\t ][^\n\r]*|)/,
INT: /0|[1-9][0-9]*(?!\.)/,
STRING: /"([^"\\]|\\.)*"|'([^'\\]|\\.)*'/,
NEWLINE: /\r?\n/,
WHITESPACE: /[\t ]+/,
YAML: /---[\t ]*\r?\n(?:[\S\s]*?\r?\n)?---(?:\r?\n|(?!\S))/,
DIRECTIVE: /[\t ]*%%{[\S\s]*?}%%(?:\r?\n|(?!\S))/,
SINGLE_LINE_COMMENT: /[\t ]*%%[^\n\r]*/,
REFERENCE: /\w([-\./\w]*[-\w])?/
};
})(GitGraphGrammar || (GitGraphGrammar = {}));
var InfoGrammar;
((InfoGrammar2) => {
InfoGrammar2.Terminals = {
ACC_DESCR: /[\t ]*accDescr(?:[\t ]*:([^\n\r]*?(?=%%)|[^\n\r]*)|\s*{([^}]*)})/,
ACC_TITLE: /[\t ]*accTitle[\t ]*:(?:[^\n\r]*?(?=%%)|[^\n\r]*)/,
TITLE: /[\t ]*title(?:[\t ][^\n\r]*?(?=%%)|[\t ][^\n\r]*|)/,
NEWLINE: /\r?\n/,
WHITESPACE: /[\t ]+/,
YAML: /---[\t ]*\r?\n(?:[\S\s]*?\r?\n)?---(?:\r?\n|(?!\S))/,
DIRECTIVE: /[\t ]*%%{[\S\s]*?}%%(?:\r?\n|(?!\S))/,
SINGLE_LINE_COMMENT: /[\t ]*%%[^\n\r]*/
};
})(InfoGrammar || (InfoGrammar = {}));
var PacketGrammar;
((PacketGrammar2) => {
PacketGrammar2.Terminals = {
ACC_DESCR: /[\t ]*accDescr(?:[\t ]*:([^\n\r]*?(?=%%)|[^\n\r]*)|\s*{([^}]*)})/,
ACC_TITLE: /[\t ]*accTitle[\t ]*:(?:[^\n\r]*?(?=%%)|[^\n\r]*)/,
TITLE: /[\t ]*title(?:[\t ][^\n\r]*?(?=%%)|[\t ][^\n\r]*|)/,
INT: /0|[1-9][0-9]*(?!\.)/,
STRING: /"([^"\\]|\\.)*"|'([^'\\]|\\.)*'/,
NEWLINE: /\r?\n/,
WHITESPACE: /[\t ]+/,
YAML: /---[\t ]*\r?\n(?:[\S\s]*?\r?\n)?---(?:\r?\n|(?!\S))/,
DIRECTIVE: /[\t ]*%%{[\S\s]*?}%%(?:\r?\n|(?!\S))/,
SINGLE_LINE_COMMENT: /[\t ]*%%[^\n\r]*/
};
})(PacketGrammar || (PacketGrammar = {}));
var PieGrammar;
((PieGrammar2) => {
PieGrammar2.Terminals = {
NUMBER_PIE: /(?:-?[0-9]+\.[0-9]+(?!\.))|(?:-?(0|[1-9][0-9]*)(?!\.))/,
ACC_DESCR: /[\t ]*accDescr(?:[\t ]*:([^\n\r]*?(?=%%)|[^\n\r]*)|\s*{([^}]*)})/,
ACC_TITLE: /[\t ]*accTitle[\t ]*:(?:[^\n\r]*?(?=%%)|[^\n\r]*)/,
TITLE: /[\t ]*title(?:[\t ][^\n\r]*?(?=%%)|[\t ][^\n\r]*|)/,
STRING: /"([^"\\]|\\.)*"|'([^'\\]|\\.)*'/,
NEWLINE: /\r?\n/,
WHITESPACE: /[\t ]+/,
YAML: /---[\t ]*\r?\n(?:[\S\s]*?\r?\n)?---(?:\r?\n|(?!\S))/,
DIRECTIVE: /[\t ]*%%{[\S\s]*?}%%(?:\r?\n|(?!\S))/,
SINGLE_LINE_COMMENT: /[\t ]*%%[^\n\r]*/
};
})(PieGrammar || (PieGrammar = {}));
var RadarGrammar;
((RadarGrammar2) => {
RadarGrammar2.Terminals = {
GRATICULE: /circle|polygon/,
BOOLEAN: /true|false/,
ACC_DESCR: /[\t ]*accDescr(?:[\t ]*:([^\n\r]*?(?=%%)|[^\n\r]*)|\s*{([^}]*)})/,
ACC_TITLE: /[\t ]*accTitle[\t ]*:(?:[^\n\r]*?(?=%%)|[^\n\r]*)/,
TITLE: /[\t ]*title(?:[\t ][^\n\r]*?(?=%%)|[\t ][^\n\r]*|)/,
NUMBER: /(?:[0-9]+\.[0-9]+(?!\.))|(?:0|[1-9][0-9]*(?!\.))/,
STRING: /"([^"\\]|\\.)*"|'([^'\\]|\\.)*'/,
ID: /[\w]([-\w]*\w)?/,
NEWLINE: /\r?\n/,
WHITESPACE: /[\t ]+/,
YAML: /---[\t ]*\r?\n(?:[\S\s]*?\r?\n)?---(?:\r?\n|(?!\S))/,
DIRECTIVE: /[\t ]*%%{[\S\s]*?}%%(?:\r?\n|(?!\S))/,
SINGLE_LINE_COMMENT: /[\t ]*%%[^\n\r]*/
};
})(RadarGrammar || (RadarGrammar = {}));
var RailroadAbnfGrammar;
((RailroadAbnfGrammar2) => {
RailroadAbnfGrammar2.Terminals = {
TITLE: /title(?:[\t ][^\n\r]*?(?=%%)|[\t ][^\n\r]*|)/,
ACC_TITLE: /accTitle[\t ]*:(?:[^\n\r]*?(?=%%)|[^\n\r]*)/,
ACC_DESCR: /accDescr(?:[\t ]*:([^\n\r]*?(?=%%)|[^\n\r]*)|\s*{([^}]*)})/,
ABNF_RULENAME: /[A-Za-z][A-Za-z0-9-]*/,
ABNF_STRING: /"[^"]*"/,
ABNF_NUMVAL: /%[xXdDbB][0-9A-Fa-f]+(?:-[0-9A-Fa-f]+|\.[0-9A-Fa-f]+)*/,
ABNF_REPEAT: /[0-9]*\*[0-9]*/,
ABNF_EXACT_REPEAT: /[0-9]+/,
ABNF_WHITESPACE: /[\t \r\n]+/,
ABNF_YAML: /---[\t ]*\r?\n(?:[\S\s]*?\r?\n)?---(?:\r?\n|(?!\S))/,
ABNF_DIRECTIVE: /[\t ]*%%{[\S\s]*?}%%(?:\r?\n|(?!\S))/,
ABNF_SINGLE_LINE_COMMENT: /[\t ]*%%[^\n\r]*/,
ABNF_COMMENT: /;[^\n\r]*/
};
})(RailroadAbnfGrammar || (RailroadAbnfGrammar = {}));
var RailroadEbnfGrammar;
((RailroadEbnfGrammar2) => {
RailroadEbnfGrammar2.Terminals = {
TITLE: /title(?:[\t ][^\n\r]*?(?=%%)|[\t ][^\n\r]*|)/,
ACC_TITLE: /accTitle[\t ]*:(?:[^\n\r]*?(?=%%)|[^\n\r]*)/,
ACC_DESCR: /accDescr(?:[\t ]*:([^\n\r]*?(?=%%)|[^\n\r]*)|\s*{([^}]*)})/,
EBNF_ID: /[A-Z_a-z][\w-]*/,
EBNF_STRING: /"([^"\\]|\\.)*"|'([^'\\]|\\.)*'/,
EBNF_SPECIAL_SEQUENCE: /\?(?=[^?;]*[^?\s;][^?;]*\?)[^?;]*\?/,
EBNF_WHITESPACE: /[\t \r\n]+/,
EBNF_YAML: /---[\t ]*\r?\n(?:[\S\s]*?\r?\n)?---(?:\r?\n|(?!\S))/,
EBNF_DIRECTIVE: /[\t ]*%%{[\S\s]*?}%%(?:\r?\n|(?!\S))/,
EBNF_SINGLE_LINE_COMMENT: /[\t ]*%%[^\n\r]*/,
EBNF_BLOCK_COMMENT: /\/\*[\s\S]*?\*\//,
EBNF_ISO_COMMENT: /\(\*[\s\S]*?\*\)/
};
})(RailroadEbnfGrammar || (RailroadEbnfGrammar = {}));
var RailroadGrammar;
((RailroadGrammar2) => {
RailroadGrammar2.Terminals = {
TITLE: /title(?:[\t ][^\n\r]*?(?=%%)|[\t ][^\n\r]*|)/,
ACC_TITLE: /accTitle[\t ]*:(?:[^\n\r]*?(?=%%)|[^\n\r]*)/,
ACC_DESCR: /accDescr(?:[\t ]*:([^\n\r]*?(?=%%)|[^\n\r]*)|\s*{([^}]*)})/,
RR_ID: /[A-Z_a-z][\w-]*/,
RR_STRING: /"([^"\\]|\\.)*"|'([^'\\]|\\.)*'/,
RR_WHITESPACE: /[\t \r\n]+/,
RR_YAML: /---[\t ]*\r?\n(?:[\S\s]*?\r?\n)?---(?:\r?\n|(?!\S))/,
RR_DIRECTIVE: /[\t ]*%%{[\S\s]*?}%%(?:\r?\n|(?!\S))/,
RR_SINGLE_LINE_COMMENT: /[\t ]*%%[^\n\r]*/,
RR_BLOCK_COMMENT: /\/\*[\s\S]*?\*\//
};
})(RailroadGrammar || (RailroadGrammar = {}));
var RailroadPegGrammar;
((RailroadPegGrammar2) => {
RailroadPegGrammar2.Terminals = {
TITLE: /title(?:[\t ][^\n\r]*?(?=%%)|[\t ][^\n\r]*|)/,
ACC_TITLE: /accTitle[\t ]*:(?:[^\n\r]*?(?=%%)|[^\n\r]*)/,
ACC_DESCR: /accDescr(?:[\t ]*:([^\n\r]*?(?=%%)|[^\n\r]*)|\s*{([^}]*)})/,
PEG_ID: /[A-Z_a-z][\w-]*/,
PEG_STRING: /"([^"\\]|\\.)*"|'([^'\\]|\\.)*'/,
PEG_WHITESPACE: /[\t \r\n]+/,
PEG_YAML: /---[\t ]*\r?\n(?:[\S\s]*?\r?\n)?---(?:\r?\n|(?!\S))/,
PEG_DIRECTIVE: /[\t ]*%%{[\S\s]*?}%%(?:\r?\n|(?!\S))/,
PEG_SINGLE_LINE_COMMENT: /[\t ]*%%[^\n\r]*/,
PEG_LINE_COMMENT: /#[^\n\r]*/
};
})(RailroadPegGrammar || (RailroadPegGrammar = {}));
var TreemapGrammar;
((TreemapGrammar2) => {
TreemapGrammar2.Terminals = {
ACC_DESCR: /[\t ]*accDescr(?:[\t ]*:([^\n\r]*?(?=%%)|[^\n\r]*)|\s*{([^}]*)})/,
ACC_TITLE: /[\t ]*accTitle[\t ]*:(?:[^\n\r]*?(?=%%)|[^\n\r]*)/,
TITLE: /[\t ]*title(?:[\t ][^\n\r]*?(?=%%)|[\t ][^\n\r]*|)/,
TREEMAP_KEYWORD: /treemap-beta|treemap/,
CLASS_DEF: /classDef\s+([a-zA-Z_][a-zA-Z0-9_]+)(?:\s+([^;\r\n]*))?(?:;)?/,
STYLE_SEPARATOR: /:::/,
SEPARATOR: /:/,
COMMA: /,/,
INDENTATION: /[ \t]{1,}/,
WS: /[ \t]+/,
ML_COMMENT: /\%\%[^\n]*/,
NL: /\r?\n/,
ID2: /[a-zA-Z_][a-zA-Z0-9_]*/,
NUMBER2: /[0-9_\.\,]+/,
STRING2: /"[^"]*"|'[^']*'/
};
})(TreemapGrammar || (TreemapGrammar = {}));
var TreeViewGrammar;
((TreeViewGrammar2) => {
TreeViewGrammar2.Terminals = {
ACC_DESCR: /[\t ]*accDescr(?:[\t ]*:([^\n\r]*?(?=%%)|[^\n\r]*)|\s*{([^}]*)})/,
ACC_TITLE: /[\t ]*accTitle[\t ]*:(?:[^\n\r]*?(?=%%)|[^\n\r]*)/,
TITLE: /[\t ]*title(?:[\t ][^\n\r]*?(?=%%)|[\t ][^\n\r]*|)/,
CLASS_ANNOTATION: /[ \t]+:::[ \t]*[A-Za-z_][\w-]*/,
ICON_ANNOTATION: /[ \t]+icon\([\w-]*(?::[\w-]+)?\)/,
DESC_ANNOTATION: /[ \t]+##[^\n\r]*/,
INDENTATION: /[ \t]{1,}/,
QUOTED_NAME: /"[^"]*"|'[^']*'/,
WS: /[ \t]+/,
ML_COMMENT: /\%\%[^\n]*/,
NL: /\r?\n/,
BARE_NAME: /(?!:::|icon\(|##)[^ \t\n\r"'](?:(?![ \t]+:::[ \t]*[A-Za-z_]|[ \t]+icon\(|[ \t]+##)[^\n\r])*/
};
})(TreeViewGrammar || (TreeViewGrammar = {}));
var WardleyGrammar;
((WardleyGrammar2) => {
WardleyGrammar2.Terminals = {
WARDLEY_NUMBER: /[0-9]+\.[0-9]+/,
ARROW: /->/,
LINK_PORT: /\+<>|\+>|\+</,
LINK_ARROW: /-->|-\.->|>|\+'[^']*'<>|\+'[^']*'<|\+'[^']*'>/,
LINK_LABEL: /;[^\n\r]+/,
STRATEGY: /build|buy|outsource|market/,
KW_WARDLEY: /wardley-beta/,
KW_SIZE: /size/,
KW_EVOLUTION: /evolution/,
KW_ANCHOR: /anchor/,
KW_COMPONENT: /component/,
KW_LABEL: /label/,
KW_INERTIA: /inertia/,
KW_EVOLVE: /evolve/,
KW_PIPELINE: /pipeline/,
KW_NOTE: /note/,
KW_ANNOTATIONS: /annotations/,
KW_ANNOTATION: /annotation/,
KW_ACCELERATOR: /accelerator/,
KW_DEACCELERATOR: /deaccelerator/,
NAME_WITH_SPACES: /(?!title\s|accTitle|accDescr)[A-Za-z](?:[A-Za-z0-9_()&]|-(?!>))*(?:[ \t]+[A-Za-z(](?:[A-Za-z0-9_()&]|-(?!>))*)*/,
WS: /[ \t]+/,
ACC_DESCR: /[\t ]*accDescr(?:[\t ]*:([^\n\r]*?(?=%%)|[^\n\r]*)|\s*{([^}]*)})/,
ACC_TITLE: /[\t ]*accTitle[\t ]*:(?:[^\n\r]*?(?=%%)|[^\n\r]*)/,
TITLE: /[\t ]*title(?:[\t ][^\n\r]*?(?=%%)|[\t ][^\n\r]*|)/,
INT: /0|[1-9][0-9]*(?!\.)/,
STRING: /"([^"\\]|\\.)*"|'([^'\\]|\\.)*'/,
ID: /[\w]([-\w]*\w)?/,
NEWLINE: /\r?\n/,
WHITESPACE: /[\t ]+/,
YAML: /---[\t ]*\r?\n(?:[\S\s]*?\r?\n)?---(?:\r?\n|(?!\S))/,
DIRECTIVE: /[\t ]*%%{[\S\s]*?}%%(?:\r?\n|(?!\S))/,
SINGLE_LINE_COMMENT: /[\t ]*%%[^\n\r]*/
};
})(WardleyGrammar || (WardleyGrammar = {}));
var MermaidTerminals = {
...ArchitectureGrammar.Terminals,
...CynefinGrammar.Terminals,
...EventModeling.Terminals,
...GitGraphGrammar.Terminals,
...InfoGrammar.Terminals,
...PacketGrammar.Terminals,
...PieGrammar.Terminals,
...RadarGrammar.Terminals,
...RailroadAbnfGrammar.Terminals,
...RailroadEbnfGrammar.Terminals,
...RailroadGrammar.Terminals,
...RailroadPegGrammar.Terminals,
...TreeViewGrammar.Terminals,
...TreemapGrammar.Terminals,
...WardleyGrammar.Terminals
};
var AbnfAlternation = {
$type: "AbnfAlternation",
alternatives: "alternatives"
};
var AbnfConcatenation = {
$type: "AbnfConcatenation",
elements: "elements"
};
var AbnfElement = {
$type: "AbnfElement",
primary: "primary",
repeat: "repeat"
};
var AbnfGroup = {
$type: "AbnfGroup",
element: "element"
};
var AbnfNumVal = {
$type: "AbnfNumVal",
value: "value"
};
var AbnfOptionalGroup = {
$type: "AbnfOptionalGroup",
element: "element"
};
var AbnfPrimary = {
$type: "AbnfPrimary"
};
var AbnfRule = {
$type: "AbnfRule",
definition: "definition",
name: "name"
};
var AbnfRuleName = {
$type: "AbnfRuleName",
name: "name"
};
var AbnfStringLiteral = {
$type: "AbnfStringLiteral",
value: "value"
};
var Accelerator = {
$type: "Accelerator",
name: "name",
x: "x",
y: "y"
};
var Alignment = {
$type: "Alignment",
direction: "direction",
members: "members"
};
var Anchor = {
$type: "Anchor",
evolution: "evolution",
name: "name",
visibility: "visibility"
};
var Annotation = {
$type: "Annotation",
number: "number",
text: "text",
x: "x",
y: "y"
};
var Annotations = {
$type: "Annotations",
x: "x",
y: "y"
};
var Architecture = {
$type: "Architecture",
accDescr: "accDescr",
accTitle: "accTitle",
alignments: "alignments",
edges: "edges",
groups: "groups",
junctions: "junctions",
services: "services",
title: "title"
};
function isArchitecture(item) {
return reflection2.isInstance(item, Architecture.$type);
}
__name(isArchitecture, "isArchitecture");
__name2(isArchitecture, "isArchitecture");
var Axis = {
$type: "Axis",
label: "label",
name: "name"
};
var Branch = {
$type: "Branch",
name: "name",
order: "order"
};
function isBranch(item) {
return reflection2.isInstance(item, Branch.$type);
}
__name(isBranch, "isBranch");
__name2(isBranch, "isBranch");
var Checkout = {
$type: "Checkout",
branch: "branch"
};
var CherryPicking = {
$type: "CherryPicking",
id: "id",
parent: "parent",
tags: "tags"
};
var ClassDefStatement = {
$type: "ClassDefStatement",
className: "className",
styleText: "styleText"
};
var Commit = {
$type: "Commit",
id: "id",
message: "message",
tags: "tags",
type: "type"
};
function isCommit(item) {
return reflection2.isInstance(item, Commit.$type);
}
__name(isCommit, "isCommit");
__name2(isCommit, "isCommit");
var Common = {
$type: "Common",
accDescr: "accDescr",
accTitle: "accTitle",
title: "title"
};
var Component = {
$type: "Component",
decorator: "decorator",
evolution: "evolution",
inertia: "inertia",
label: "label",
name: "name",
visibility: "visibility"
};
var Curve = {
$type: "Curve",
entries: "entries",
label: "label",
name: "name"
};
var Cynefin = {
$type: "Cynefin",
accDescr: "accDescr",
accTitle: "accTitle",
domains: "domains",
title: "title",
transitions: "transitions"
};
function isCynefin(item) {
return reflection2.isInstance(item, Cynefin.$type);
}
__name(isCynefin, "isCynefin");
__name2(isCynefin, "isCynefin");
var Deaccelerator = {
$type: "Deaccelerator",
name: "name",
x: "x",
y: "y"
};
var Decorator = {
$type: "Decorator",
strategy: "strategy"
};
var Direction = {
$type: "Direction",
accDescr: "accDescr",
accTitle: "accTitle",
dir: "dir",
statements: "statements",
title: "title"
};
var DomainBlock = {
$type: "DomainBlock",
domain: "domain",
items: "items"
};
function isDomainBlock(item) {
return reflection2.isInstance(item, DomainBlock.$type);
}
__name(isDomainBlock, "isDomainBlock");
__name2(isDomainBlock, "isDomainBlock");
var DomainItem = {
$type: "DomainItem",
label: "label"
};
function isDomainItem(item) {
return reflection2.isInstance(item, DomainItem.$type);
}
__name(isDomainItem, "isDomainItem");
__name2(isDomainItem, "isDomainItem");
var EbnfChoice = {
$type: "EbnfChoice",
alternatives: "alternatives"
};
var EbnfExceptionPostfix = {
$type: "EbnfExceptionPostfix",
except: "except"
};
var EbnfGroup = {
$type: "EbnfGroup",
element: "element"
};
var EbnfNonTerminal = {
$type: "EbnfNonTerminal",
name: "name"
};
var EbnfOneOrMorePostfix = {
$type: "EbnfOneOrMorePostfix",
operator: "operator"
};
var EbnfOptional = {
$type: "EbnfOptional",
element: "element"
};
var EbnfOptionalPostfix = {
$type: "EbnfOptionalPostfix",
operator: "operator"
};
var EbnfPostfix = {
$type: "EbnfPostfix"
};
var EbnfPrimary = {
$type: "EbnfPrimary"
};
var EbnfRepetition = {
$type: "EbnfRepetition",
element: "element"
};
var EbnfRule = {
$type: "EbnfRule",
definition: "definition",
name: "name"
};
var EbnfSequence = {
$type: "EbnfSequence",
elements: "elements"
};
var EbnfSpecial = {
$type: "EbnfSpecial",
text: "text"
};
var EbnfTerm = {
$type: "EbnfTerm",
base: "base",
postfixes: "postfixes"
};
var EbnfTerminal = {
$type: "EbnfTerminal",
value: "value"
};
var EbnfZeroOrMorePostfix = {
$type: "EbnfZeroOrMorePostfix",
operator: "operator"
};
var Edge = {
$type: "Edge",
lhsDir: "lhsDir",
lhsGroup: "lhsGroup",
lhsId: "lhsId",
lhsInto: "lhsInto",
rhsDir: "rhsDir",
rhsGroup: "rhsGroup",
rhsId: "rhsId",
rhsInto: "rhsInto",
title: "title"
};
var EmDataEntity = {
$type: "EmDataEntity",
dataBlockValue: "dataBlockValue",
dataType: "dataType",
name: "name"
};
var EmFrame = {
$type: "EmFrame"
};
var EmGwt = {
$type: "EmGwt",
givenStatements: "givenStatements",
sourceFrame: "sourceFrame",
thenStatements: "thenStatements",
whenStatements: "whenStatements"
};
var EmGwtStatement = {
$type: "EmGwtStatement",
entityIdentifier: "entityIdentifier"
};
var EmModelEntity = {
$type: "EmModelEntity",
name: "name"
};
function isEmModelEntityType(item) {
return item === "rmo" || item === "readmodel" || item === "ui" || item === "cmd" || item === "command" || item === "evt" || item === "event" || item === "pcr" || item === "processor";
}
__name(isEmModelEntityType, "isEmModelEntityType");
__name2(isEmModelEntityType, "isEmModelEntityType");
var EmNoteEntity = {
$type: "EmNoteEntity",
dataBlockValue: "dataBlockValue",
dataType: "dataType",
sourceFrame: "sourceFrame"
};
var EmResetFrame = {
$type: "EmResetFrame",
dataInlineValue: "dataInlineValue",
dataReference: "dataReference",
dataType: "dataType",
entityIdentifier: "entityIdentifier",
modelEntityType: "modelEntityType",
name: "name",
sourceFrames: "sourceFrames"
};
function isEmResetFrame(item) {
return reflection2.isInstance(item, EmResetFrame.$type);
}
__name(isEmResetFrame, "isEmResetFrame");
__name2(isEmResetFrame, "isEmResetFrame");
var EmTimeFrame = {
$type: "EmTimeFrame",
dataInlineValue: "dataInlineValue",
dataReference: "dataReference",
dataType: "dataType",
entityIdentifier: "entityIdentifier",
modelEntityType: "modelEntityType",
name: "name",
sourceFrames: "sourceFrames"
};
var Entry = {
$type: "Entry",
axis: "axis",
value: "value"
};
var EventModel = {
$type: "EventModel",
accDescr: "accDescr",
accTitle: "accTitle",
dataEntities: "dataEntities",
frames: "frames",
gwtEntities: "gwtEntities",
modelEntities: "modelEntities",
noteEntities: "noteEntities",
title: "title"
};
var Evolution = {
$type: "Evolution",
stages: "stages"
};
var EvolutionStage = {
$type: "EvolutionStage",
boundary: "boundary",
name: "name",
secondName: "secondName"
};
var Evolve = {
$type: "Evolve",
component: "component",
target: "target"
};
var GitGraph = {
$type: "GitGraph",
accDescr: "accDescr",
accTitle: "accTitle",
statements: "statements",
title: "title"
};
function isGitGraph(item) {
return reflection2.isInstance(item, GitGraph.$type);
}
__name(isGitGraph, "isGitGraph");
__name2(isGitGraph, "isGitGraph");
var Group2 = {
$type: "Group",
icon: "icon",
id: "id",
in: "in",
title: "title"
};
var Info = {
$type: "Info",
accDescr: "accDescr",
accTitle: "accTitle",
title: "title"
};
function isInfo(item) {
return reflection2.isInstance(item, Info.$type);
}
__name(isInfo, "isInfo");
__name2(isInfo, "isInfo");
var Item = {
$type: "Item",
classSelector: "classSelector",
name: "name"
};
var Junction = {
$type: "Junction",
id: "id",
in: "in"
};
var Label = {
$type: "Label",
negX: "negX",
negY: "negY",
offsetX: "offsetX",
offsetY: "offsetY"
};
var Leaf = {
$type: "Leaf",
classSelector: "classSelector",
name: "name",
value: "value"
};
var Link = {
$type: "Link",
arrow: "arrow",
from: "from",
fromPort: "fromPort",
linkLabel: "linkLabel",
to: "to",
toPort: "toPort"
};
var Merge = {
$type: "Merge",
branch: "branch",
id: "id",
tags: "tags",
type: "type"
};
function isMerge(item) {
return reflection2.isInstance(item, Merge.$type);
}
__name(isMerge, "isMerge");
__name2(isMerge, "isMerge");
var Note = {
$type: "Note",
evolution: "evolution",
text: "text",
visibility: "visibility"
};
var Option2 = {
$type: "Option",
name: "name",
value: "value"
};
var Packet = {
$type: "Packet",
accDescr: "accDescr",
accTitle: "accTitle",
blocks: "blocks",
title: "title"
};
function isPacket(item) {
return reflection2.isInstance(item, Packet.$type);
}
__name(isPacket, "isPacket");
__name2(isPacket, "isPacket");
var PacketBlock = {
$type: "PacketBlock",
bits: "bits",
end: "end",
label: "label",
start: "start"
};
function isPacketBlock(item) {
return reflection2.isInstance(item, PacketBlock.$type);
}
__name(isPacketBlock, "isPacketBlock");
__name2(isPacketBlock, "isPacketBlock");
var PegAny = {
$type: "PegAny",
dot: "dot"
};
var PegGroup = {
$type: "PegGroup",
element: "element"
};
var PegIdentifier = {
$type: "PegIdentifier",
name: "name"
};
var PegLiteral = {
$type: "PegLiteral",
value: "value"
};
var PegOrderedChoice = {
$type: "PegOrderedChoice",
alternatives: "alternatives"
};
var PegPrefix = {
$type: "PegPrefix",
operator: "operator",
suffix: "suffix"
};
var PegPrimary = {
$type: "PegPrimary"
};
var PegRule = {
$type: "PegRule",
definition: "definition",
name: "name"
};
var PegSequence = {
$type: "PegSequence",
elements: "elements"
};
var PegSuffix = {
$type: "PegSuffix",
operator: "operator",
primary: "primary"
};
var Pie = {
$type: "Pie",
accDescr: "accDescr",
accTitle: "accTitle",
sections: "sections",
showData: "showData",
title: "title"
};
function isPie(item) {
return reflection2.isInstance(item, Pie.$type);
}
__name(isPie, "isPie");
__name2(isPie, "isPie");
var PieSection = {
$type: "PieSection",
label: "label",
value: "value"
};
function isPieSection(item) {
return reflection2.isInstance(item, PieSection.$type);
}
__name(isPieSection, "isPieSection");
__name2(isPieSection, "isPieSection");
var Pipeline = {
$type: "Pipeline",
components: "components",
parent: "parent"
};
var PipelineComponent = {
$type: "PipelineComponent",
evolution: "evolution",
label: "label",
name: "name"
};
var Radar = {
$type: "Radar",
accDescr: "accDescr",
accTitle: "accTitle",
axes: "axes",
curves: "curves",
options: "options",
title: "title"
};
var Railroad = {
$type: "Railroad",
accDescr: "accDescr",
accTitle: "accTitle",
rules: "rules",
title: "title"
};
function isRailroad(item) {
return reflection2.isInstance(item, Railroad.$type);
}
__name(isRailroad, "isRailroad");
__name2(isRailroad, "isRailroad");
var RailroadAbnf = {
$type: "RailroadAbnf",
accDescr: "accDescr",
accTitle: "accTitle",
rules: "rules",
title: "title"
};
function isRailroadAbnf(item) {
return reflection2.isInstance(item, RailroadAbnf.$type);
}
__name(isRailroadAbnf, "isRailroadAbnf");
__name2(isRailroadAbnf, "isRailroadAbnf");
var RailroadChoiceExpr = {
$type: "RailroadChoiceExpr",
alternatives: "alternatives"
};
var RailroadEbnf = {
$type: "RailroadEbnf",
accDescr: "accDescr",
accTitle: "accTitle",
rules: "rules",
title: "title"
};
function isRailroadEbnf(item) {
return reflection2.isInstance(item, RailroadEbnf.$type);
}
__name(isRailroadEbnf, "isRailroadEbnf");
__name2(isRailroadEbnf, "isRailroadEbnf");
var RailroadExpression = {
$type: "RailroadExpression"
};
var RailroadNonTerminalExpr = {
$type: "RailroadNonTerminalExpr",
name: "name"
};
var RailroadOneOrMoreExpr = {
$type: "RailroadOneOrMoreExpr",
element: "element"
};
var RailroadOptionalExpr = {
$type: "RailroadOptionalExpr",
element: "element"
};
var RailroadPeg = {
$type: "RailroadPeg",
accDescr: "accDescr",
accTitle: "accTitle",
rules: "rules",
title: "title"
};
function isRailroadPeg(item) {
return reflection2.isInstance(item, RailroadPeg.$type);
}
__name(isRailroadPeg, "isRailroadPeg");
__name2(isRailroadPeg, "isRailroadPeg");
var RailroadRule = {
$type: "RailroadRule",
definition: "definition",
name: "name"
};
var RailroadSequenceExpr = {
$type: "RailroadSequenceExpr",
elements: "elements"
};
var RailroadSpecialExpr = {
$type: "RailroadSpecialExpr",
text: "text"
};
var RailroadTerminalExpr = {
$type: "RailroadTerminalExpr",
value: "value"
};
var RailroadZeroOrMoreExpr = {
$type: "RailroadZeroOrMoreExpr",
element: "element"
};
var Section = {
$type: "Section",
classSelector: "classSelector",
name: "name"
};
var Service = {
$type: "Service",
icon: "icon",
iconText: "iconText",
id: "id",
in: "in",
title: "title"
};
var Size = {
$type: "Size",
height: "height",
width: "width"
};
var Statement = {
$type: "Statement"
};
var Transition = {
$type: "Transition",
from: "from",
label: "label",
to: "to"
};
function isTransition(item) {
return reflection2.isInstance(item, Transition.$type);
}
__name(isTransition, "isTransition");
__name2(isTransition, "isTransition");
var Treemap = {
$type: "Treemap",
accDescr: "accDescr",
accTitle: "accTitle",
title: "title",
TreemapRows: "TreemapRows"
};
function isTreemap(item) {
return reflection2.isInstance(item, Treemap.$type);
}
__name(isTreemap, "isTreemap");
__name2(isTreemap, "isTreemap");
var TreemapRow = {
$type: "TreemapRow",
indent: "indent",
item: "item"
};
var TreeNode = {
$type: "TreeNode",
classAnnotation: "classAnnotation",
descAnnotation: "descAnnotation",
iconAnnotation: "iconAnnotation",
indent: "indent",
name: "name"
};
var TreeView = {
$type: "TreeView",
accDescr: "accDescr",
accTitle: "accTitle",
nodes: "nodes",
title: "title"
};
var Wardley = {
$type: "Wardley",
accDescr: "accDescr",
accelerators: "accelerators",
accTitle: "accTitle",
anchors: "anchors",
annotation: "annotation",
annotations: "annotations",
components: "components",
deaccelerators: "deaccelerators",
evolution: "evolution",
evolves: "evolves",
links: "links",
notes: "notes",
pipelines: "pipelines",
size: "size",
title: "title"
};
function isWardley(item) {
return reflection2.isInstance(item, Wardley.$type);
}
__name(isWardley, "isWardley");
__name2(isWardley, "isWardley");
var MermaidAstReflection = class extends AbstractAstReflection {
static {
__name(this, "MermaidAstReflection");
}
constructor() {
super(...arguments);
this.types = {
AbnfAlternation: {
name: AbnfAlternation.$type,
properties: {
alternatives: {
name: AbnfAlternation.alternatives,
defaultValue: []
}
},
superTypes: []
},
AbnfConcatenation: {
name: AbnfConcatenation.$type,
properties: {
elements: {
name: AbnfConcatenation.elements,
defaultValue: []
}
},
superTypes: []
},
AbnfElement: {
name: AbnfElement.$type,
properties: {
primary: {
name: AbnfElement.primary
},
repeat: {
name: AbnfElement.repeat
}
},
superTypes: []
},
AbnfGroup: {
name: AbnfGroup.$type,
properties: {
element: {
name: AbnfGroup.element
}
},
superTypes: [AbnfPrimary.$type]
},
AbnfNumVal: {
name: AbnfNumVal.$type,
properties: {
value: {
name: AbnfNumVal.value
}
},
superTypes: [AbnfPrimary.$type]
},
AbnfOptionalGroup: {
name: AbnfOptionalGroup.$type,
properties: {
element: {
name: AbnfOptionalGroup.element
}
},
superTypes: [AbnfPrimary.$type]
},
AbnfPrimary: {
name: AbnfPrimary.$type,
properties: {},
superTypes: []
},
AbnfRule: {
name: AbnfRule.$type,
properties: {
definition: {
name: AbnfRule.definition
},
name: {
name: AbnfRule.name
}
},
superTypes: []
},
AbnfRuleName: {
name: AbnfRuleName.$type,
properties: {
name: {
name: AbnfRuleName.name
}
},
superTypes: [AbnfPrimary.$type]
},
AbnfStringLiteral: {
name: AbnfStringLiteral.$type,
properties: {
value: {
name: AbnfStringLiteral.value
}
},
superTypes: [AbnfPrimary.$type]
},
Accelerator: {
name: Accelerator.$type,
properties: {
name: {
name: Accelerator.name
},
x: {
name: Accelerator.x
},
y: {
name: Accelerator.y
}
},
superTypes: []
},
Alignment: {
name: Alignment.$type,
properties: {
direction: {
name: Alignment.direction
},
members: {
name: Alignment.members,
defaultValue: []
}
},
superTypes: []
},
Anchor: {
name: Anchor.$type,
properties: {
evolution: {
name: Anchor.evolution
},
name: {
name: Anchor.name
},
visibility: {
name: Anchor.visibility
}
},
superTypes: []
},
Annotation: {
name: Annotation.$type,
properties: {
number: {
name: Annotation.number
},
text: {
name: Annotation.text
},
x: {
name: Annotation.x
},
y: {
name: Annotation.y
}
},
superTypes: []
},
Annotations: {
name: Annotations.$type,
properties: {
x: {
name: Annotations.x
},
y: {
name: Annotations.y
}
},
superTypes: []
},
Architecture: {
name: Architecture.$type,
properties: {
accDescr: {
name: Architecture.accDescr
},
accTitle: {
name: Architecture.accTitle
},
alignments: {
name: Architecture.alignments,
defaultValue: []
},
edges: {
name: Architecture.edges,
defaultValue: []
},
groups: {
name: Architecture.groups,
defaultValue: []
},
junctions: {
name: Architecture.junctions,
defaultValue: []
},
services: {
name: Architecture.services,
defaultValue: []
},
title: {
name: Architecture.title
}
},
superTypes: []
},
Axis: {
name: Axis.$type,
properties: {
label: {
name: Axis.label
},
name: {
name: Axis.name
}
},
superTypes: []
},
Branch: {
name: Branch.$type,
properties: {
name: {
name: Branch.name
},
order: {
name: Branch.order
}
},
superTypes: [Statement.$type]
},
Checkout: {
name: Checkout.$type,
properties: {
branch: {
name: Checkout.branch
}
},
superTypes: [Statement.$type]
},
CherryPicking: {
name: CherryPicking.$type,
properties: {
id: {
name: CherryPicking.id
},
parent: {
name: CherryPicking.parent
},
tags: {
name: CherryPicking.tags,
defaultValue: []
}
},
superTypes: [Statement.$type]
},
ClassDefStatement: {
name: ClassDefStatement.$type,
properties: {
className: {
name: ClassDefStatement.className
},
styleText: {
name: ClassDefStatement.styleText
}
},
superTypes: []
},
Commit: {
name: Commit.$type,
properties: {
id: {
name: Commit.id
},
message: {
name: Commit.message
},
tags: {
name: Commit.tags,
defaultValue: []
},
type: {
name: Commit.type
}
},
superTypes: [Statement.$type]
},
Common: {
name: Common.$type,
properties: {
accDescr: {
name: Common.accDescr
},
accTitle: {
name: Common.accTitle
},
title: {
name: Common.title
}
},
superTypes: []
},
Component: {
name: Component.$type,
properties: {
decorator: {
name: Component.decorator
},
evolution: {
name: Component.evolution
},
inertia: {
name: Component.inertia,
defaultValue: false
},
label: {
name: Component.label
},
name: {
name: Component.name
},
visibility: {
name: Component.visibility
}
},
superTypes: []
},
Curve: {
name: Curve.$type,
properties: {
entries: {
name: Curve.entries,
defaultValue: []
},
label: {
name: Curve.label
},
name: {
name: Curve.name
}
},
superTypes: []
},
Cynefin: {
name: Cynefin.$type,
properties: {
accDescr: {
name: Cynefin.accDescr
},
accTitle: {
name: Cynefin.accTitle
},
domains: {
name: Cynefin.domains,
defaultValue: []
},
title: {
name: Cynefin.title
},
transitions: {
name: Cynefin.transitions,
defaultValue: []
}
},
superTypes: []
},
Deaccelerator: {
name: Deaccelerator.$type,
properties: {
name: {
name: Deaccelerator.name
},
x: {
name: Deaccelerator.x
},
y: {
name: Deaccelerator.y
}
},
superTypes: []
},
Decorator: {
name: Decorator.$type,
properties: {
strategy: {
name: Decorator.strategy
}
},
superTypes: []
},
Direction: {
name: Direction.$type,
properties: {
accDescr: {
name: Direction.accDescr
},
accTitle: {
name: Direction.accTitle
},
dir: {
name: Direction.dir
},
statements: {
name: Direction.statements,
defaultValue: []
},
title: {
name: Direction.title
}
},
superTypes: [GitGraph.$type]
},
DomainBlock: {
name: DomainBlock.$type,
properties: {
domain: {
name: DomainBlock.domain
},
items: {
name: DomainBlock.items,
defaultValue: []
}
},
superTypes: []
},
DomainItem: {
name: DomainItem.$type,
properties: {
label: {
name: DomainItem.label
}
},
superTypes: []
},
EbnfChoice: {
name: EbnfChoice.$type,
properties: {
alternatives: {
name: EbnfChoice.alternatives,
defaultValue: []
}
},
superTypes: []
},
EbnfExceptionPostfix: {
name: EbnfExceptionPostfix.$type,
properties: {
except: {
name: EbnfExceptionPostfix.except
}
},
superTypes: [EbnfPostfix.$type]
},
EbnfGroup: {
name: EbnfGroup.$type,
properties: {
element: {
name: EbnfGroup.element
}
},
superTypes: [EbnfPrimary.$type]
},
EbnfNonTerminal: {
name: EbnfNonTerminal.$type,
properties: {
name: {
name: EbnfNonTerminal.name
}
},
superTypes: [EbnfPrimary.$type]
},
EbnfOneOrMorePostfix: {
name: EbnfOneOrMorePostfix.$type,
properties: {
operator: {
name: EbnfOneOrMorePostfix.operator
}
},
superTypes: [EbnfPostfix.$type]
},
EbnfOptional: {
name: EbnfOptional.$type,
properties: {
element: {
name: EbnfOptional.element
}
},
superTypes: [EbnfPrimary.$type]
},
EbnfOptionalPostfix: {
name: EbnfOptionalPostfix.$type,
properties: {
operator: {
name: EbnfOptionalPostfix.operator
}
},
superTypes: [EbnfPostfix.$type]
},
EbnfPostfix: {
name: EbnfPostfix.$type,
properties: {},
superTypes: []
},
EbnfPrimary: {
name: EbnfPrimary.$type,
properties: {},
superTypes: []
},
EbnfRepetition: {
name: EbnfRepetition.$type,
properties: {
element: {
name: EbnfRepetition.element
}
},
superTypes: [EbnfPrimary.$type]
},
EbnfRule: {
name: EbnfRule.$type,
properties: {
definition: {
name: EbnfRule.definition
},
name: {
name: EbnfRule.name
}
},
superTypes: []
},
EbnfSequence: {
name: EbnfSequence.$type,
properties: {
elements: {
name: EbnfSequence.elements,
defaultValue: []
}
},
superTypes: []
},
EbnfSpecial: {
name: EbnfSpecial.$type,
properties: {
text: {
name: EbnfSpecial.text
}
},
superTypes: [EbnfPrimary.$type]
},
EbnfTerm: {
name: EbnfTerm.$type,
properties: {
base: {
name: EbnfTerm.base
},
postfixes: {
name: EbnfTerm.postfixes,
defaultValue: []
}
},
superTypes: []
},
EbnfTerminal: {
name: EbnfTerminal.$type,
properties: {
value: {
name: EbnfTerminal.value
}
},
superTypes: [EbnfPrimary.$type]
},
EbnfZeroOrMorePostfix: {
name: EbnfZeroOrMorePostfix.$type,
properties: {
operator: {
name: EbnfZeroOrMorePostfix.operator
}
},
superTypes: [EbnfPostfix.$type]
},
Edge: {
name: Edge.$type,
properties: {
lhsDir: {
name: Edge.lhsDir
},
lhsGroup: {
name: Edge.lhsGroup,
defaultValue: false
},
lhsId: {
name: Edge.lhsId
},
lhsInto: {
name: Edge.lhsInto,
defaultValue: false
},
rhsDir: {
name: Edge.rhsDir
},
rhsGroup: {
name: Edge.rhsGroup,
defaultValue: false
},
rhsId: {
name: Edge.rhsId
},
rhsInto: {
name: Edge.rhsInto,
defaultValue: false
},
title: {
name: Edge.title
}
},
superTypes: []
},
EmDataEntity: {
name: EmDataEntity.$type,
properties: {
dataBlockValue: {
name: EmDataEntity.dataBlockValue
},
dataType: {
name: EmDataEntity.dataType
},
name: {
name: EmDataEntity.name
}
},
superTypes: []
},
EmFrame: {
name: EmFrame.$type,
properties: {},
superTypes: []
},
EmGwt: {
name: EmGwt.$type,
properties: {
givenStatements: {
name: EmGwt.givenStatements,
defaultValue: []
},
sourceFrame: {
name: EmGwt.sourceFrame,
referenceType: EmFrame.$type
},
thenStatements: {
name: EmGwt.thenStatements,
defaultValue: []
},
whenStatements: {
name: EmGwt.whenStatements,
defaultValue: []
}
},
superTypes: []
},
EmGwtStatement: {
name: EmGwtStatement.$type,
properties: {
entityIdentifier: {
name: EmGwtStatement.entityIdentifier,
referenceType: EmModelEntity.$type
}
},
superTypes: []
},
EmModelEntity: {
name: EmModelEntity.$type,
properties: {
name: {
name: EmModelEntity.name
}
},
superTypes: []
},
EmNoteEntity: {
name: EmNoteEntity.$type,
properties: {
dataBlockValue: {
name: EmNoteEntity.dataBlockValue
},
dataType: {
name: EmNoteEntity.dataType
},
sourceFrame: {
name: EmNoteEntity.sourceFrame,
referenceType: EmFrame.$type
}
},
superTypes: []
},
EmResetFrame: {
name: EmResetFrame.$type,
properties: {
dataInlineValue: {
name: EmResetFrame.dataInlineValue
},
dataReference: {
name: EmResetFrame.dataReference,
referenceType: EmDataEntity.$type
},
dataType: {
name: EmResetFrame.dataType
},
entityIdentifier: {
name: EmResetFrame.entityIdentifier
},
modelEntityType: {
name: EmResetFrame.modelEntityType
},
name: {
name: EmResetFrame.name
},
sourceFrames: {
name: EmResetFrame.sourceFrames,
defaultValue: [],
referenceType: EmFrame.$type
}
},
superTypes: [EmFrame.$type]
},
EmTimeFrame: {
name: EmTimeFrame.$type,
properties: {
dataInlineValue: {
name: EmTimeFrame.dataInlineValue
},
dataReference: {
name: EmTimeFrame.dataReference,
referenceType: EmDataEntity.$type
},
dataType: {
name: EmTimeFrame.dataType
},
entityIdentifier: {
name: EmTimeFrame.entityIdentifier
},
modelEntityType: {
name: EmTimeFrame.modelEntityType
},
name: {
name: EmTimeFrame.name
},
sourceFrames: {
name: EmTimeFrame.sourceFrames,
defaultValue: [],
referenceType: EmFrame.$type
}
},
superTypes: [EmFrame.$type]
},
Entry: {
name: Entry.$type,
properties: {
axis: {
name: Entry.axis,
referenceType: Axis.$type
},
value: {
name: Entry.value
}
},
superTypes: []
},
EventModel: {
name: EventModel.$type,
properties: {
accDescr: {
name: EventModel.accDescr
},
accTitle: {
name: EventModel.accTitle
},
dataEntities: {
name: EventModel.dataEntities,
defaultValue: []
},
frames: {
name: EventModel.frames,
defaultValue: []
},
gwtEntities: {
name: EventModel.gwtEntities,
defaultValue: []
},
modelEntities: {
name: EventModel.modelEntities,
defaultValue: []
},
noteEntities: {
name: EventModel.noteEntities,
defaultValue: []
},
title: {
name: EventModel.title
}
},
superTypes: []
},
Evolution: {
name: Evolution.$type,
properties: {
stages: {
name: Evolution.stages,
defaultValue: []
}
},
superTypes: []
},
EvolutionStage: {
name: EvolutionStage.$type,
properties: {
boundary: {
name: EvolutionStage.boundary
},
name: {
name: EvolutionStage.name
},
secondName: {
name: EvolutionStage.secondName
}
},
superTypes: []
},
Evolve: {
name: Evolve.$type,
properties: {
component: {
name: Evolve.component
},
target: {
name: Evolve.target
}
},
superTypes: []
},
GitGraph: {
name: GitGraph.$type,
properties: {
accDescr: {
name: GitGraph.accDescr
},
accTitle: {
name: GitGraph.accTitle
},
statements: {
name: GitGraph.statements,
defaultValue: []
},
title: {
name: GitGraph.title
}
},
superTypes: []
},
Group: {
name: Group2.$type,
properties: {
icon: {
name: Group2.icon
},
id: {
name: Group2.id
},
in: {
name: Group2.in
},
title: {
name: Group2.title
}
},
superTypes: []
},
Info: {
name: Info.$type,
properties: {
accDescr: {
name: Info.accDescr
},
accTitle: {
name: Info.accTitle
},
title: {
name: Info.title
}
},
superTypes: []
},
Item: {
name: Item.$type,
properties: {
classSelector: {
name: Item.classSelector
},
name: {
name: Item.name
}
},
superTypes: []
},
Junction: {
name: Junction.$type,
properties: {
id: {
name: Junction.id
},
in: {
name: Junction.in
}
},
superTypes: []
},
Label: {
name: Label.$type,
properties: {
negX: {
name: Label.negX,
defaultValue: false
},
negY: {
name: Label.negY,
defaultValue: false
},
offsetX: {
name: Label.offsetX
},
offsetY: {
name: Label.offsetY
}
},
superTypes: []
},
Leaf: {
name: Leaf.$type,
properties: {
classSelector: {
name: Leaf.classSelector
},
name: {
name: Leaf.name
},
value: {
name: Leaf.value
}
},
superTypes: [Item.$type]
},
Link: {
name: Link.$type,
properties: {
arrow: {
name: Link.arrow
},
from: {
name: Link.from
},
fromPort: {
name: Link.fromPort
},
linkLabel: {
name: Link.linkLabel
},
to: {
name: Link.to
},
toPort: {
name: Link.toPort
}
},
superTypes: []
},
Merge: {
name: Merge.$type,
properties: {
branch: {
name: Merge.branch
},
id: {
name: Merge.id
},
tags: {
name: Merge.tags,
defaultValue: []
},
type: {
name: Merge.type
}
},
superTypes: [Statement.$type]
},
Note: {
name: Note.$type,
properties: {
evolution: {
name: Note.evolution
},
text: {
name: Note.text
},
visibility: {
name: Note.visibility
}
},
superTypes: []
},
Option: {
name: Option2.$type,
properties: {
name: {
name: Option2.name
},
value: {
name: Option2.value,
defaultValue: false
}
},
superTypes: []
},
Packet: {
name: Packet.$type,
properties: {
accDescr: {
name: Packet.accDescr
},
accTitle: {
name: Packet.accTitle
},
blocks: {
name: Packet.blocks,
defaultValue: []
},
title: {
name: Packet.title
}
},
superTypes: []
},
PacketBlock: {
name: PacketBlock.$type,
properties: {
bits: {
name: PacketBlock.bits
},
end: {
name: PacketBlock.end
},
label: {
name: PacketBlock.label
},
start: {
name: PacketBlock.start
}
},
superTypes: []
},
PegAny: {
name: PegAny.$type,
properties: {
dot: {
name: PegAny.dot
}
},
superTypes: [PegPrimary.$type]
},
PegGroup: {
name: PegGroup.$type,
properties: {
element: {
name: PegGroup.element
}
},
superTypes: [PegPrimary.$type]
},
PegIdentifier: {
name: PegIdentifier.$type,
properties: {
name: {
name: PegIdentifier.name
}
},
superTypes: [PegPrimary.$type]
},
PegLiteral: {
name: PegLiteral.$type,
properties: {
value: {
name: PegLiteral.value
}
},
superTypes: [PegPrimary.$type]
},
PegOrderedChoice: {
name: PegOrderedChoice.$type,
properties: {
alternatives: {
name: PegOrderedChoice.alternatives,
defaultValue: []
}
},
superTypes: []
},
PegPrefix: {
name: PegPrefix.$type,
properties: {
operator: {
name: PegPrefix.operator
},
suffix: {
name: PegPrefix.suffix
}
},
superTypes: []
},
PegPrimary: {
name: PegPrimary.$type,
properties: {},
superTypes: []
},
PegRule: {
name: PegRule.$type,
properties: {
definition: {
name: PegRule.definition
},
name: {
name: PegRule.name
}
},
superTypes: []
},
PegSequence: {
name: PegSequence.$type,
properties: {
elements: {
name: PegSequence.elements,
defaultValue: []
}
},
superTypes: []
},
PegSuffix: {
name: PegSuffix.$type,
properties: {
operator: {
name: PegSuffix.operator
},
primary: {
name: PegSuffix.primary
}
},
superTypes: []
},
Pie: {
name: Pie.$type,
properties: {
accDescr: {
name: Pie.accDescr
},
accTitle: {
name: Pie.accTitle
},
sections: {
name: Pie.sections,
defaultValue: []
},
showData: {
name: Pie.showData,
defaultValue: false
},
title: {
name: Pie.title
}
},
superTypes: []
},
PieSection: {
name: PieSection.$type,
properties: {
label: {
name: PieSection.label
},
value: {
name: PieSection.value
}
},
superTypes: []
},
Pipeline: {
name: Pipeline.$type,
properties: {
components: {
name: Pipeline.components,
defaultValue: []
},
parent: {
name: Pipeline.parent
}
},
superTypes: []
},
PipelineComponent: {
name: PipelineComponent.$type,
properties: {
evolution: {
name: PipelineComponent.evolution
},
label: {
name: PipelineComponent.label
},
name: {
name: PipelineComponent.name
}
},
superTypes: []
},
Radar: {
name: Radar.$type,
properties: {
accDescr: {
name: Radar.accDescr
},
accTitle: {
name: Radar.accTitle
},
axes: {
name: Radar.axes,
defaultValue: []
},
curves: {
name: Radar.curves,
defaultValue: []
},
options: {
name: Radar.options,
defaultValue: []
},
title: {
name: Radar.title
}
},
superTypes: []
},
Railroad: {
name: Railroad.$type,
properties: {
accDescr: {
name: Railroad.accDescr
},
accTitle: {
name: Railroad.accTitle
},
rules: {
name: Railroad.rules,
defaultValue: []
},
title: {
name: Railroad.title
}
},
superTypes: []
},
RailroadAbnf: {
name: RailroadAbnf.$type,
properties: {
accDescr: {
name: RailroadAbnf.accDescr
},
accTitle: {
name: RailroadAbnf.accTitle
},
rules: {
name: RailroadAbnf.rules,
defaultValue: []
},
title: {
name: RailroadAbnf.title
}
},
superTypes: []
},
RailroadChoiceExpr: {
name: RailroadChoiceExpr.$type,
properties: {
alternatives: {
name: RailroadChoiceExpr.alternatives,
defaultValue: []
}
},
superTypes: [RailroadExpression.$type]
},
RailroadEbnf: {
name: RailroadEbnf.$type,
properties: {
accDescr: {
name: RailroadEbnf.accDescr
},
accTitle: {
name: RailroadEbnf.accTitle
},
rules: {
name: RailroadEbnf.rules,
defaultValue: []
},
title: {
name: RailroadEbnf.title
}
},
superTypes: []
},
RailroadExpression: {
name: RailroadExpression.$type,
properties: {},
superTypes: []
},
RailroadNonTerminalExpr: {
name: RailroadNonTerminalExpr.$type,
properties: {
name: {
name: RailroadNonTerminalExpr.name
}
},
superTypes: [RailroadExpression.$type]
},
RailroadOneOrMoreExpr: {
name: RailroadOneOrMoreExpr.$type,
properties: {
element: {
name: RailroadOneOrMoreExpr.element
}
},
superTypes: [RailroadExpression.$type]
},
RailroadOptionalExpr: {
name: RailroadOptionalExpr.$type,
properties: {
element: {
name: RailroadOptionalExpr.element
}
},
superTypes: [RailroadExpression.$type]
},
RailroadPeg: {
name: RailroadPeg.$type,
properties: {
accDescr: {
name: RailroadPeg.accDescr
},
accTitle: {
name: RailroadPeg.accTitle
},
rules: {
name: RailroadPeg.rules,
defaultValue: []
},
title: {
name: RailroadPeg.title
}
},
superTypes: []
},
RailroadRule: {
name: RailroadRule.$type,
properties: {
definition: {
name: RailroadRule.definition
},
name: {
name: RailroadRule.name
}
},
superTypes: []
},
RailroadSequenceExpr: {
name: RailroadSequenceExpr.$type,
properties: {
elements: {
name: RailroadSequenceExpr.elements,
defaultValue: []
}
},
superTypes: [RailroadExpression.$type]
},
RailroadSpecialExpr: {
name: RailroadSpecialExpr.$type,
properties: {
text: {
name: RailroadSpecialExpr.text
}
},
superTypes: [RailroadExpression.$type]
},
RailroadTerminalExpr: {
name: RailroadTerminalExpr.$type,
properties: {
value: {
name: RailroadTerminalExpr.value
}
},
superTypes: [RailroadExpression.$type]
},
RailroadZeroOrMoreExpr: {
name: RailroadZeroOrMoreExpr.$type,
properties: {
element: {
name: RailroadZeroOrMoreExpr.element
}
},
superTypes: [RailroadExpression.$type]
},
Section: {
name: Section.$type,
properties: {
classSelector: {
name: Section.classSelector
},
name: {
name: Section.name
}
},
superTypes: [Item.$type]
},
Service: {
name: Service.$type,
properties: {
icon: {
name: Service.icon
},
iconText: {
name: Service.iconText
},
id: {
name: Service.id
},
in: {
name: Service.in
},
title: {
name: Service.title
}
},
superTypes: []
},
Size: {
name: Size.$type,
properties: {
height: {
name: Size.height
},
width: {
name: Size.width
}
},
superTypes: []
},
Statement: {
name: Statement.$type,
properties: {},
superTypes: []
},
Transition: {
name: Transition.$type,
properties: {
from: {
name: Transition.from
},
label: {
name: Transition.label
},
to: {
name: Transition.to
}
},
superTypes: []
},
TreeNode: {
name: TreeNode.$type,
properties: {
classAnnotation: {
name: TreeNode.classAnnotation
},
descAnnotation: {
name: TreeNode.descAnnotation
},
iconAnnotation: {
name: TreeNode.iconAnnotation
},
indent: {
name: TreeNode.indent
},
name: {
name: TreeNode.name
}
},
superTypes: []
},
TreeView: {
name: TreeView.$type,
properties: {
accDescr: {
name: TreeView.accDescr
},
accTitle: {
name: TreeView.accTitle
},
nodes: {
name: TreeView.nodes,
defaultValue: []
},
title: {
name: TreeView.title
}
},
superTypes: []
},
Treemap: {
name: Treemap.$type,
properties: {
accDescr: {
name: Treemap.accDescr
},
accTitle: {
name: Treemap.accTitle
},
title: {
name: Treemap.title
},
TreemapRows: {
name: Treemap.TreemapRows,
defaultValue: []
}
},
superTypes: []
},
TreemapRow: {
name: TreemapRow.$type,
properties: {
indent: {
name: TreemapRow.indent
},
item: {
name: TreemapRow.item
}
},
superTypes: []
},
Wardley: {
name: Wardley.$type,
properties: {
accDescr: {
name: Wardley.accDescr
},
accelerators: {
name: Wardley.accelerators,
defaultValue: []
},
accTitle: {
name: Wardley.accTitle
},
anchors: {
name: Wardley.anchors,
defaultValue: []
},
annotation: {
name: Wardley.annotation,
defaultValue: []
},
annotations: {
name: Wardley.annotations,
defaultValue: []
},
components: {
name: Wardley.components,
defaultValue: []
},
deaccelerators: {
name: Wardley.deaccelerators,
defaultValue: []
},
evolution: {
name: Wardley.evolution
},
evolves: {
name: Wardley.evolves,
defaultValue: []
},
links: {
name: Wardley.links,
defaultValue: []
},
notes: {
name: Wardley.notes,
defaultValue: []
},
pipelines: {
name: Wardley.pipelines,
defaultValue: []
},
size: {
name: Wardley.size
},
title: {
name: Wardley.title
}
},
superTypes: []
}
};
}
static {
__name2(this, "MermaidAstReflection");
}
};
var reflection2 = new MermaidAstReflection();
var loadedArchitectureGrammarGrammar;
var ArchitectureGrammarGrammar = /* @__PURE__ */ __name2(() => loadedArchitectureGrammarGrammar ?? (loadedArchitectureGrammarGrammar = loadGrammarFromJson(`{"$type":"Grammar","isDeclared":true,"name":"ArchitectureGrammar","imports":[],"rules":[{"$type":"ParserRule","entry":true,"name":"Architecture","definition":{"$type":"Group","elements":[{"$type":"RuleCall","rule":{"$ref":"#/rules@24"},"arguments":[],"cardinality":"*"},{"$type":"Keyword","value":"architecture-beta"},{"$type":"Alternatives","elements":[{"$type":"RuleCall","rule":{"$ref":"#/rules@24"},"arguments":[]},{"$type":"RuleCall","rule":{"$ref":"#/rules@14"},"arguments":[]},{"$type":"RuleCall","rule":{"$ref":"#/rules@1"},"arguments":[]}],"cardinality":"*"}]},"fragment":false,"parameters":[]},{"$type":"ParserRule","fragment":true,"name":"Statement","definition":{"$type":"Alternatives","elements":[{"$type":"Assignment","feature":"groups","operator":"+=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@5"},"arguments":[]}},{"$type":"Assignment","feature":"services","operator":"+=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@6"},"arguments":[]}},{"$type":"Assignment","feature":"junctions","operator":"+=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@7"},"arguments":[]}},{"$type":"Assignment","feature":"edges","operator":"+=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@8"},"arguments":[]}},{"$type":"Assignment","feature":"alignments","operator":"+=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@9"},"arguments":[]}}]},"entry":false,"parameters":[]},{"$type":"ParserRule","fragment":true,"name":"LeftPort","definition":{"$type":"Group","elements":[{"$type":"Keyword","value":":"},{"$type":"Assignment","feature":"lhsDir","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@10"},"arguments":[]}}]},"entry":false,"parameters":[]},{"$type":"ParserRule","fragment":true,"name":"RightPort","definition":{"$type":"Group","elements":[{"$type":"Assignment","feature":"rhsDir","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@10"},"arguments":[]}},{"$type":"Keyword","value":":"}]},"entry":false,"parameters":[]},{"$type":"ParserRule","fragment":true,"name":"Arrow","definition":{"$type":"Group","elements":[{"$type":"RuleCall","rule":{"$ref":"#/rules@2"},"arguments":[]},{"$type":"Assignment","feature":"lhsInto","operator":"?=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@12"},"arguments":[]},"cardinality":"?"},{"$type":"Alternatives","elements":[{"$type":"Keyword","value":"--"},{"$type":"Group","elements":[{"$type":"Keyword","value":"-"},{"$type":"Assignment","feature":"title","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@30"},"arguments":[]}},{"$type":"Keyword","value":"-"}]}]},{"$type":"Assignment","feature":"rhsInto","operator":"?=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@12"},"arguments":[]},"cardinality":"?"},{"$type":"RuleCall","rule":{"$ref":"#/rules@3"},"arguments":[]}]},"entry":false,"parameters":[]},{"$type":"ParserRule","name":"Group","definition":{"$type":"Group","elements":[{"$type":"Keyword","value":"group"},{"$type":"Assignment","feature":"id","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@23"},"arguments":[]}},{"$type":"Assignment","feature":"icon","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@29"},"arguments":[]},"cardinality":"?"},{"$type":"Assignment","feature":"title","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@30"},"arguments":[]},"cardinality":"?"},{"$type":"Group","elements":[{"$type":"Keyword","value":"in"},{"$type":"Assignment","feature":"in","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@23"},"arguments":[]}}],"cardinality":"?"},{"$type":"RuleCall","rule":{"$ref":"#/rules@13"},"arguments":[]}]},"entry":false,"fragment":false,"parameters":[]},{"$type":"ParserRule","name":"Service","definition":{"$type":"Group","elements":[{"$type":"Keyword","value":"service"},{"$type":"Assignment","feature":"id","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@23"},"arguments":[]}},{"$type":"Alternatives","elements":[{"$type":"Assignment","feature":"iconText","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@22"},"arguments":[]}},{"$type":"Assignment","feature":"icon","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@29"},"arguments":[]}}],"cardinality":"?"},{"$type":"Assignment","feature":"title","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@30"},"arguments":[]},"cardinality":"?"},{"$type":"Group","elements":[{"$type":"Keyword","value":"in"},{"$type":"Assignment","feature":"in","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@23"},"arguments":[]}}],"cardinality":"?"},{"$type":"RuleCall","rule":{"$ref":"#/rules@13"},"arguments":[]}]},"entry":false,"fragment":false,"parameters":[]},{"$type":"ParserRule","name":"Junction","definition":{"$type":"Group","elements":[{"$type":"Keyword","value":"junction"},{"$type":"Assignment","feature":"id","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@23"},"arguments":[]}},{"$type":"Group","elements":[{"$type":"Keyword","value":"in"},{"$type":"Assignment","feature":"in","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@23"},"arguments":[]}}],"cardinality":"?"},{"$type":"RuleCall","rule":{"$ref":"#/rules@13"},"arguments":[]}]},"entry":false,"fragment":false,"parameters":[]},{"$type":"ParserRule","name":"Edge","definition":{"$type":"Group","elements":[{"$type":"Assignment","feature":"lhsId","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@23"},"arguments":[]}},{"$type":"Assignment","feature":"lhsGroup","operator":"?=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@11"},"arguments":[]},"cardinality":"?"},{"$type":"RuleCall","rule":{"$ref":"#/rules@4"},"arguments":[]},{"$type":"Assignment","feature":"rhsId","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@23"},"arguments":[]}},{"$type":"Assignment","feature":"rhsGroup","operator":"?=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@11"},"arguments":[]},"cardinality":"?"},{"$type":"RuleCall","rule":{"$ref":"#/rules@13"},"arguments":[]}]},"entry":false,"fragment":false,"parameters":[]},{"$type":"ParserRule","name":"Alignment","definition":{"$type":"Group","elements":[{"$type":"Keyword","value":"align"},{"$type":"Assignment","feature":"direction","operator":"=","terminal":{"$type":"Alternatives","elements":[{"$type":"Keyword","value":"row"},{"$type":"Keyword","value":"column"}]}},{"$type":"Assignment","feature":"members","operator":"+=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@23"},"arguments":[]}},{"$type":"Assignment","feature":"members","operator":"+=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@23"},"arguments":[]},"cardinality":"+"},{"$type":"RuleCall","rule":{"$ref":"#/rules@13"},"arguments":[]}]},"entry":false,"fragment":false,"parameters":[]},{"$type":"TerminalRule","name":"ARROW_DIRECTION","definition":{"$type":"TerminalAlternatives","elements":[{"$type":"TerminalAlternatives","elements":[{"$type":"TerminalAlternatives","elements":[{"$type":"CharacterRange","left":{"$type":"Keyword","value":"L"},"parenthesized":false},{"$type":"CharacterRange","left":{"$type":"Keyword","value":"R"},"parenthesized":false}],"parenthesized":false},{"$type":"CharacterRange","left":{"$type":"Keyword","value":"T"},"parenthesized":false}],"parenthesized":false},{"$type":"CharacterRange","left":{"$type":"Keyword","value":"B"},"parenthesized":false}],"parenthesized":false},"fragment":false,"hidden":false},{"$type":"TerminalRule","name":"ARROW_GROUP","definition":{"$type":"RegexToken","regex":"/\\\\{group\\\\}/","parenthesized":false},"fragment":false,"hidden":false},{"$type":"TerminalRule","name":"ARROW_INTO","definition":{"$type":"RegexToken","regex":"/<|>/","parenthesized":false},"fragment":false,"hidden":false},{"$type":"ParserRule","name":"EOL","dataType":"string","definition":{"$type":"Alternatives","elements":[{"$type":"RuleCall","rule":{"$ref":"#/rules@24"},"arguments":[],"cardinality":"+"},{"$type":"EndOfFile"}]},"entry":false,"fragment":false,"parameters":[]},{"$type":"ParserRule","fragment":true,"name":"TitleAndAccessibilities","definition":{"$type":"Group","elements":[{"$type":"Alternatives","elements":[{"$type":"Assignment","feature":"accDescr","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@16"},"arguments":[]}},{"$type":"Assignment","feature":"accTitle","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@17"},"arguments":[]}},{"$type":"Assignment","feature":"title","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@18"},"arguments":[]}}]},{"$type":"RuleCall","rule":{"$ref":"#/rules@13"},"arguments":[]}],"cardinality":"+"},"entry":false,"parameters":[]},{"$type":"TerminalRule","name":"BOOLEAN","type":{"$type":"ReturnType","name":"boolean"},"definition":{"$type":"TerminalAlternatives","elements":[{"$type":"CharacterRange","left":{"$type":"Keyword","value":"true"},"parenthesized":false},{"$type":"CharacterRange","left":{"$type":"Keyword","value":"false"},"parenthesized":false}],"parenthesized":false},"fragment":false,"hidden":false},{"$type":"TerminalRule","name":"ACC_DESCR","definition":{"$type":"RegexToken","regex":"/[\\\\t ]*accDescr(?:[\\\\t ]*:([^\\\\n\\\\r]*?(?=%%)|[^\\\\n\\\\r]*)|\\\\s*{([^}]*)})/","parenthesized":false},"fragment":false,"hidden":false},{"$type":"TerminalRule","name":"ACC_TITLE","definition":{"$type":"RegexToken","regex":"/[\\\\t ]*accTitle[\\\\t ]*:(?:[^\\\\n\\\\r]*?(?=%%)|[^\\\\n\\\\r]*)/","parenthesized":false},"fragment":false,"hidden":false},{"$type":"TerminalRule","name":"TITLE","definition":{"$type":"RegexToken","regex":"/[\\\\t ]*title(?:[\\\\t ][^\\\\n\\\\r]*?(?=%%)|[\\\\t ][^\\\\n\\\\r]*|)/","parenthesized":false},"fragment":false,"hidden":false},{"$type":"TerminalRule","name":"FLOAT","type":{"$type":"ReturnType","name":"number"},"definition":{"$type":"RegexToken","regex":"/[0-9]+\\\\.[0-9]+(?!\\\\.)/","parenthesized":false},"fragment":false,"hidden":false},{"$type":"TerminalRule","name":"INT","type":{"$type":"ReturnType","name":"number"},"definition":{"$type":"RegexToken","regex":"/0|[1-9][0-9]*(?!\\\\.)/","parenthesized":false},"fragment":false,"hidden":false},{"$type":"TerminalRule","name":"NUMBER","type":{"$type":"ReturnType","name":"number"},"definition":{"$type":"TerminalAlternatives","elements":[{"$type":"TerminalRuleCall","rule":{"$ref":"#/rules@19"},"parenthesized":false},{"$type":"TerminalRuleCall","rule":{"$ref":"#/rules@20"},"parenthesized":false}],"parenthesized":false},"fragment":false,"hidden":false},{"$type":"TerminalRule","name":"STRING","type":{"$type":"ReturnType","name":"string"},"definition":{"$type":"RegexToken","regex":"/\\"([^\\"\\\\\\\\]|\\\\\\\\.)*\\"|'([^'\\\\\\\\]|\\\\\\\\.)*'/","parenthesized":false},"fragment":false,"hidden":false},{"$type":"TerminalRule","name":"ID","type":{"$type":"ReturnType","name":"string"},"definition":{"$type":"RegexToken","regex":"/[\\\\w]([-\\\\w]*\\\\w)?/","parenthesized":false},"fragment":false,"hidden":false},{"$type":"TerminalRule","name":"NEWLINE","definition":{"$type":"RegexToken","regex":"/\\\\r?\\\\n/","parenthesized":false},"fragment":false,"hidden":false},{"$type":"TerminalRule","hidden":true,"name":"WHITESPACE","definition":{"$type":"RegexToken","regex":"/[\\\\t ]+/","parenthesized":false},"fragment":false},{"$type":"TerminalRule","hidden":true,"name":"YAML","definition":{"$type":"RegexToken","regex":"/---[\\\\t ]*\\\\r?\\\\n(?:[\\\\S\\\\s]*?\\\\r?\\\\n)?---(?:\\\\r?\\\\n|(?!\\\\S))/","parenthesized":false},"fragment":false},{"$type":"TerminalRule","hidden":true,"name":"DIRECTIVE","definition":{"$type":"RegexToken","regex":"/[\\\\t ]*%%{[\\\\S\\\\s]*?}%%(?:\\\\r?\\\\n|(?!\\\\S))/","parenthesized":false},"fragment":false},{"$type":"TerminalRule","hidden":true,"name":"SINGLE_LINE_COMMENT","definition":{"$type":"RegexToken","regex":"/[\\\\t ]*%%[^\\\\n\\\\r]*/","parenthesized":false},"fragment":false},{"$type":"TerminalRule","name":"ARCH_ICON","definition":{"$type":"RegexToken","regex":"/\\\\([\\\\w-:]+\\\\)/","parenthesized":false},"fragment":false,"hidden":false},{"$type":"TerminalRule","name":"ARCH_TITLE","definition":{"$type":"RegexToken","regex":"/\\\\[(?:\\"([^\\"\\\\\\\\]|\\\\\\\\.)*\\"|'([^'\\\\\\\\]|\\\\\\\\.)*'|[^\\\\[\\\\]\\\\r\\\\n]+)\\\\]/","parenthesized":false},"fragment":false,"hidden":false}],"interfaces":[],"types":[]}`)), "ArchitectureGrammarGrammar");
var loadedCynefinGrammarGrammar;
var CynefinGrammarGrammar = /* @__PURE__ */ __name2(() => loadedCynefinGrammarGrammar ?? (loadedCynefinGrammarGrammar = loadGrammarFromJson(`{"$type":"Grammar","isDeclared":true,"name":"CynefinGrammar","imports":[],"rules":[{"$type":"ParserRule","entry":true,"name":"Cynefin","definition":{"$type":"Group","elements":[{"$type":"RuleCall","rule":{"$ref":"#/rules@16"},"arguments":[],"cardinality":"*"},{"$type":"Alternatives","elements":[{"$type":"Keyword","value":"cynefin-beta"},{"$type":"Keyword","value":"cynefin-beta:"}]},{"$type":"RuleCall","rule":{"$ref":"#/rules@16"},"arguments":[],"cardinality":"*"},{"$type":"Alternatives","elements":[{"$type":"RuleCall","rule":{"$ref":"#/rules@6"},"arguments":[]},{"$type":"Assignment","feature":"domains","operator":"+=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@1"},"arguments":[]}},{"$type":"Assignment","feature":"transitions","operator":"+=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@3"},"arguments":[]}},{"$type":"RuleCall","rule":{"$ref":"#/rules@16"},"arguments":[]}],"cardinality":"*"}]},"fragment":false,"parameters":[]},{"$type":"ParserRule","name":"DomainBlock","definition":{"$type":"Group","elements":[{"$type":"Assignment","feature":"domain","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@4"},"arguments":[]}},{"$type":"RuleCall","rule":{"$ref":"#/rules@16"},"arguments":[],"cardinality":"*"},{"$type":"Group","elements":[{"$type":"Assignment","feature":"items","operator":"+=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@2"},"arguments":[]}},{"$type":"RuleCall","rule":{"$ref":"#/rules@16"},"arguments":[],"cardinality":"*"}],"cardinality":"*"}]},"entry":false,"fragment":false,"parameters":[]},{"$type":"ParserRule","name":"DomainItem","definition":{"$type":"Assignment","feature":"label","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@14"},"arguments":[]}},"entry":false,"fragment":false,"parameters":[]},{"$type":"ParserRule","name":"Transition","definition":{"$type":"Group","elements":[{"$type":"Assignment","feature":"from","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@4"},"arguments":[]}},{"$type":"Keyword","value":"-->"},{"$type":"Assignment","feature":"to","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@4"},"arguments":[]}},{"$type":"Group","elements":[{"$type":"Keyword","value":":"},{"$type":"Assignment","feature":"label","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@14"},"arguments":[]}}],"cardinality":"?"},{"$type":"RuleCall","rule":{"$ref":"#/rules@5"},"arguments":[]}]},"entry":false,"fragment":false,"parameters":[]},{"$type":"TerminalRule","name":"DOMAIN_NAME","type":{"$type":"ReturnType","name":"string"},"definition":{"$type":"TerminalAlternatives","elements":[{"$type":"TerminalAlternatives","elements":[{"$type":"TerminalAlternatives","elements":[{"$type":"TerminalAlternatives","elements":[{"$type":"CharacterRange","left":{"$type":"Keyword","value":"complex"},"parenthesized":false},{"$type":"CharacterRange","left":{"$type":"Keyword","value":"complicated"},"parenthesized":false}],"parenthesized":false},{"$type":"CharacterRange","left":{"$type":"Keyword","value":"clear"},"parenthesized":false}],"parenthesized":false},{"$type":"CharacterRange","left":{"$type":"Keyword","value":"chaotic"},"parenthesized":false}],"parenthesized":false},{"$type":"CharacterRange","left":{"$type":"Keyword","value":"confusion"},"parenthesized":false}],"parenthesized":false},"fragment":false,"hidden":false},{"$type":"ParserRule","name":"EOL","dataType":"string","definition":{"$type":"Alternatives","elements":[{"$type":"RuleCall","rule":{"$ref":"#/rules@16"},"arguments":[],"cardinality":"+"},{"$type":"EndOfFile"}]},"entry":false,"fragment":false,"parameters":[]},{"$type":"ParserRule","fragment":true,"name":"TitleAndAccessibilities","definition":{"$type":"Group","elements":[{"$type":"Alternatives","elements":[{"$type":"Assignment","feature":"accDescr","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@8"},"arguments":[]}},{"$type":"Assignment","feature":"accTitle","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@9"},"arguments":[]}},{"$type":"Assignment","feature":"title","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@10"},"arguments":[]}}]},{"$type":"RuleCall","rule":{"$ref":"#/rules@5"},"arguments":[]}],"cardinality":"+"},"entry":false,"parameters":[]},{"$type":"TerminalRule","name":"BOOLEAN","type":{"$type":"ReturnType","name":"boolean"},"definition":{"$type":"TerminalAlternatives","elements":[{"$type":"CharacterRange","left":{"$type":"Keyword","value":"true"},"parenthesized":false},{"$type":"CharacterRange","left":{"$type":"Keyword","value":"false"},"parenthesized":false}],"parenthesized":false},"fragment":false,"hidden":false},{"$type":"TerminalRule","name":"ACC_DESCR","definition":{"$type":"RegexToken","regex":"/[\\\\t ]*accDescr(?:[\\\\t ]*:([^\\\\n\\\\r]*?(?=%%)|[^\\\\n\\\\r]*)|\\\\s*{([^}]*)})/","parenthesized":false},"fragment":false,"hidden":false},{"$type":"TerminalRule","name":"ACC_TITLE","definition":{"$type":"RegexToken","regex":"/[\\\\t ]*accTitle[\\\\t ]*:(?:[^\\\\n\\\\r]*?(?=%%)|[^\\\\n\\\\r]*)/","parenthesized":false},"fragment":false,"hidden":false},{"$type":"TerminalRule","name":"TITLE","definition":{"$type":"RegexToken","regex":"/[\\\\t ]*title(?:[\\\\t ][^\\\\n\\\\r]*?(?=%%)|[\\\\t ][^\\\\n\\\\r]*|)/","parenthesized":false},"fragment":false,"hidden":false},{"$type":"TerminalRule","name":"FLOAT","type":{"$type":"ReturnType","name":"number"},"definition":{"$type":"RegexToken","regex":"/[0-9]+\\\\.[0-9]+(?!\\\\.)/","parenthesized":false},"fragment":false,"hidden":false},{"$type":"TerminalRule","name":"INT","type":{"$type":"ReturnType","name":"number"},"definition":{"$type":"RegexToken","regex":"/0|[1-9][0-9]*(?!\\\\.)/","parenthesized":false},"fragment":false,"hidden":false},{"$type":"TerminalRule","name":"NUMBER","type":{"$type":"ReturnType","name":"number"},"definition":{"$type":"TerminalAlternatives","elements":[{"$type":"TerminalRuleCall","rule":{"$ref":"#/rules@11"},"parenthesized":false},{"$type":"TerminalRuleCall","rule":{"$ref":"#/rules@12"},"parenthesized":false}],"parenthesized":false},"fragment":false,"hidden":false},{"$type":"TerminalRule","name":"STRING","type":{"$type":"ReturnType","name":"string"},"definition":{"$type":"RegexToken","regex":"/\\"([^\\"\\\\\\\\]|\\\\\\\\.)*\\"|'([^'\\\\\\\\]|\\\\\\\\.)*'/","parenthesized":false},"fragment":false,"hidden":false},{"$type":"TerminalRule","name":"ID","type":{"$type":"ReturnType","name":"string"},"definition":{"$type":"RegexToken","regex":"/[\\\\w]([-\\\\w]*\\\\w)?/","parenthesized":false},"fragment":false,"hidden":false},{"$type":"TerminalRule","name":"NEWLINE","definition":{"$type":"RegexToken","regex":"/\\\\r?\\\\n/","parenthesized":false},"fragment":false,"hidden":false},{"$type":"TerminalRule","hidden":true,"name":"WHITESPACE","definition":{"$type":"RegexToken","regex":"/[\\\\t ]+/","parenthesized":false},"fragment":false},{"$type":"TerminalRule","hidden":true,"name":"YAML","definition":{"$type":"RegexToken","regex":"/---[\\\\t ]*\\\\r?\\\\n(?:[\\\\S\\\\s]*?\\\\r?\\\\n)?---(?:\\\\r?\\\\n|(?!\\\\S))/","parenthesized":false},"fragment":false},{"$type":"TerminalRule","hidden":true,"name":"DIRECTIVE","definition":{"$type":"RegexToken","regex":"/[\\\\t ]*%%{[\\\\S\\\\s]*?}%%(?:\\\\r?\\\\n|(?!\\\\S))/","parenthesized":false},"fragment":false},{"$type":"TerminalRule","hidden":true,"name":"SINGLE_LINE_COMMENT","definition":{"$type":"RegexToken","regex":"/[\\\\t ]*%%[^\\\\n\\\\r]*/","parenthesized":false},"fragment":false}],"interfaces":[],"types":[]}`)), "CynefinGrammarGrammar");
var loadedEventModelingGrammar;
var EventModelingGrammar = /* @__PURE__ */ __name2(() => loadedEventModelingGrammar ?? (loadedEventModelingGrammar = loadGrammarFromJson('{"$type":"Grammar","isDeclared":true,"name":"EventModeling","interfaces":[{"$type":"Interface","name":"Common","attributes":[{"$type":"TypeAttribute","name":"accDescr","isOptional":true,"type":{"$type":"SimpleType","primitiveType":"string"}},{"$type":"TypeAttribute","name":"accTitle","isOptional":true,"type":{"$type":"SimpleType","primitiveType":"string"}},{"$type":"TypeAttribute","name":"title","isOptional":true,"type":{"$type":"SimpleType","primitiveType":"string"}}],"superTypes":[]}],"rules":[{"$type":"ParserRule","entry":true,"name":"EventModel","definition":{"$type":"Group","elements":[{"$type":"Keyword","value":"eventmodeling"},{"$type":"Alternatives","elements":[{"$type":"Assignment","feature":"accDescr","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@20"},"arguments":[]}},{"$type":"Assignment","feature":"accTitle","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@21"},"arguments":[]}},{"$type":"Assignment","feature":"title","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@22"},"arguments":[]}},{"$type":"Assignment","feature":"modelEntities","operator":"+=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@9"},"arguments":[]}},{"$type":"Assignment","feature":"frames","operator":"+=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@8"},"arguments":[]}},{"$type":"Assignment","feature":"dataEntities","operator":"+=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@10"},"arguments":[]}},{"$type":"Assignment","feature":"noteEntities","operator":"+=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@11"},"arguments":[]}},{"$type":"Assignment","feature":"gwtEntities","operator":"+=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@12"},"arguments":[]}}],"cardinality":"*"}]},"fragment":false,"parameters":[]},{"$type":"ParserRule","name":"EmModelEntityType","dataType":"string","definition":{"$type":"Alternatives","elements":[{"$type":"Keyword","value":"rmo"},{"$type":"Keyword","value":"readmodel"},{"$type":"Keyword","value":"ui"},{"$type":"Keyword","value":"cmd"},{"$type":"Keyword","value":"command"},{"$type":"Keyword","value":"evt"},{"$type":"Keyword","value":"event"},{"$type":"Keyword","value":"pcr"},{"$type":"Keyword","value":"processor"}]},"entry":false,"fragment":false,"parameters":[]},{"$type":"ParserRule","name":"EmDataType","dataType":"string","definition":{"$type":"Alternatives","elements":[{"$type":"Keyword","value":"json"},{"$type":"Keyword","value":"jsobj"},{"$type":"Keyword","value":"figma"},{"$type":"Keyword","value":"salt"},{"$type":"Keyword","value":"uri"},{"$type":"Keyword","value":"md"},{"$type":"Keyword","value":"html"},{"$type":"Keyword","value":"text"}]},"entry":false,"fragment":false,"parameters":[]},{"$type":"ParserRule","fragment":true,"name":"EmDataInline","definition":{"$type":"Group","elements":[{"$type":"Group","elements":[{"$type":"Keyword","value":"`"},{"$type":"Assignment","feature":"dataType","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@2"},"arguments":[]}},{"$type":"Keyword","value":"`"}],"cardinality":"?"},{"$type":"Assignment","feature":"dataInlineValue","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@18"},"arguments":[]}}]},"entry":false,"parameters":[]},{"$type":"ParserRule","fragment":true,"name":"EmDataBlock","definition":{"$type":"Group","elements":[{"$type":"Group","elements":[{"$type":"Keyword","value":"`"},{"$type":"Assignment","feature":"dataType","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@2"},"arguments":[]}},{"$type":"Keyword","value":"`"}],"cardinality":"?"},{"$type":"Assignment","feature":"dataBlockValue","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@19"},"arguments":[]}}]},"entry":false,"parameters":[]},{"$type":"ParserRule","name":"QualifiedName","dataType":"string","definition":{"$type":"Group","elements":[{"$type":"RuleCall","rule":{"$ref":"#/rules@14"},"arguments":[]},{"$type":"Group","elements":[{"$type":"Keyword","value":"."},{"$type":"RuleCall","rule":{"$ref":"#/rules@14"},"arguments":[]}],"cardinality":"*"}]},"entry":false,"fragment":false,"parameters":[]},{"$type":"ParserRule","name":"EmTimeFrame","definition":{"$type":"Group","elements":[{"$type":"Alternatives","elements":[{"$type":"Keyword","value":"tf"},{"$type":"Keyword","value":"timeframe"}]},{"$type":"Assignment","feature":"name","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@15"},"arguments":[]}},{"$type":"Assignment","feature":"modelEntityType","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@1"},"arguments":[]}},{"$type":"Assignment","feature":"entityIdentifier","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@5"},"arguments":[]}},{"$type":"Group","elements":[{"$type":"Keyword","value":"->>"},{"$type":"Assignment","feature":"sourceFrames","operator":"+=","terminal":{"$type":"CrossReference","type":{"$ref":"#/rules@8"},"terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@15"},"arguments":[]},"deprecatedSyntax":false,"isMulti":false}}],"cardinality":"*"},{"$type":"Group","elements":[{"$type":"Keyword","value":"[["},{"$type":"Assignment","feature":"dataReference","operator":"=","terminal":{"$type":"CrossReference","type":{"$ref":"#/rules@10"},"terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@14"},"arguments":[]},"deprecatedSyntax":false,"isMulti":false}},{"$type":"Keyword","value":"]]"}],"cardinality":"?"},{"$type":"RuleCall","rule":{"$ref":"#/rules@3"},"arguments":[],"cardinality":"?"}]},"entry":false,"fragment":false,"parameters":[]},{"$type":"ParserRule","name":"EmResetFrame","definition":{"$type":"Group","elements":[{"$type":"Alternatives","elements":[{"$type":"Keyword","value":"rf"},{"$type":"Keyword","value":"resetframe"}]},{"$type":"Assignment","feature":"name","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@15"},"arguments":[]}},{"$type":"Assignment","feature":"modelEntityType","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@1"},"arguments":[]}},{"$type":"Assignment","feature":"entityIdentifier","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@5"},"arguments":[]}},{"$type":"Group","elements":[{"$type":"Keyword","value":"->>"},{"$type":"Assignment","feature":"sourceFrames","operator":"+=","terminal":{"$type":"CrossReference","type":{"$ref":"#/rules@8"},"terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@15"},"arguments":[]},"deprecatedSyntax":false,"isMulti":false}}],"cardinality":"*"},{"$type":"Group","elements":[{"$type":"Keyword","value":"[["},{"$type":"Assignment","feature":"dataReference","operator":"=","terminal":{"$type":"CrossReference","type":{"$ref":"#/rules@10"},"terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@14"},"arguments":[]},"deprecatedSyntax":false,"isMulti":false}},{"$type":"Keyword","value":"]]"}],"cardinality":"?"},{"$type":"RuleCall","rule":{"$ref":"#/rules@3"},"arguments":[],"cardinality":"?"}]},"entry":false,"fragment":false,"parameters":[]},{"$type":"ParserRule","name":"EmFrame","definition":{"$type":"Alternatives","elements":[{"$type":"RuleCall","rule":{"$ref":"#/rules@6"},"arguments":[]},{"$type":"RuleCall","rule":{"$ref":"#/rules@7"},"arguments":[]}]},"entry":false,"fragment":false,"parameters":[]},{"$type":"ParserRule","name":"EmModelEntity","definition":{"$type":"Group","elements":[{"$type":"Keyword","value":"entity"},{"$type":"Assignment","feature":"name","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@5"},"arguments":[]}}]},"entry":false,"fragment":false,"parameters":[]},{"$type":"ParserRule","name":"EmDataEntity","definition":{"$type":"Group","elements":[{"$type":"Keyword","value":"data"},{"$type":"Assignment","feature":"name","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@14"},"arguments":[]}},{"$type":"RuleCall","rule":{"$ref":"#/rules@4"},"arguments":[]}]},"entry":false,"fragment":false,"parameters":[]},{"$type":"ParserRule","name":"EmNoteEntity","definition":{"$type":"Group","elements":[{"$type":"Keyword","value":"note"},{"$type":"Assignment","feature":"sourceFrame","operator":"=","terminal":{"$type":"CrossReference","type":{"$ref":"#/rules@8"},"terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@15"},"arguments":[]},"deprecatedSyntax":false,"isMulti":false}},{"$type":"RuleCall","rule":{"$ref":"#/rules@4"},"arguments":[]}]},"entry":false,"fragment":false,"parameters":[]},{"$type":"ParserRule","name":"EmGwt","definition":{"$type":"Group","elements":[{"$type":"Keyword","value":"gwt"},{"$type":"Assignment","feature":"sourceFrame","operator":"=","terminal":{"$type":"CrossReference","type":{"$ref":"#/rules@8"},"terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@15"},"arguments":[]},"deprecatedSyntax":false,"isMulti":false}},{"$type":"Keyword","value":"given"},{"$type":"Assignment","feature":"givenStatements","operator":"+=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@13"},"arguments":[]},"cardinality":"+"},{"$type":"Group","elements":[{"$type":"Keyword","value":"when"},{"$type":"Assignment","feature":"whenStatements","operator":"+=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@13"},"arguments":[]},"cardinality":"+"}],"cardinality":"?"},{"$type":"Keyword","value":"then"},{"$type":"Assignment","feature":"thenStatements","operator":"+=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@13"},"arguments":[]},"cardinality":"+"}]},"entry":false,"fragment":false,"parameters":[]},{"$type":"ParserRule","name":"EmGwtStatement","definition":{"$type":"Group","elements":[{"$type":"RuleCall","rule":{"$ref":"#/rules@1"},"arguments":[]},{"$type":"Assignment","feature":"entityIdentifier","operator":"=","terminal":{"$type":"CrossReference","type":{"$ref":"#/rules@9"},"terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@14"},"arguments":[]},"deprecatedSyntax":false,"isMulti":false}}]},"entry":false,"fragment":false,"parameters":[]},{"$type":"ParserRule","name":"EM_EID","dataType":"string","definition":{"$type":"RuleCall","rule":{"$ref":"#/rules@16"},"arguments":[]},"entry":false,"fragment":false,"parameters":[]},{"$type":"ParserRule","name":"EM_FI","dataType":"string","definition":{"$type":"RuleCall","rule":{"$ref":"#/rules@17"},"arguments":[]},"entry":false,"fragment":false,"parameters":[]},{"$type":"TerminalRule","name":"EM_ID","definition":{"$type":"RegexToken","regex":"/[_a-zA-Z][\\\\w_]*/","parenthesized":false},"fragment":false,"hidden":false},{"$type":"TerminalRule","name":"EM_FID","definition":{"$type":"RegexToken","regex":"/\\\\d{1,3}/","parenthesized":false},"fragment":false,"hidden":false},{"$type":"TerminalRule","name":"EM_DATA_INLINE","definition":{"$type":"RegexToken","regex":"/\\\\{(.*)\\\\}|\\"(.*)\\"|\'(.*)\'/","parenthesized":false},"fragment":false,"hidden":false},{"$type":"TerminalRule","name":"EM_DATA_BLOCK","definition":{"$type":"RegexToken","regex":"/\\\\{[\\\\t ]*\\\\r?\\\\n(?:[\\\\S\\\\s]*?\\\\r?\\\\n)?\\\\}(?:\\\\r?\\\\n|(?!\\\\S))/","parenthesized":false},"fragment":false,"hidden":false},{"$type":"TerminalRule","name":"EM_ACC_DESCR","definition":{"$type":"RegexToken","regex":"/[\\\\t ]*accDescr(?:[\\\\t ]*:([^\\\\n\\\\r]*?(?=%%)|[^\\\\n\\\\r]*)|\\\\s*{([^}]*)})/","parenthesized":false},"fragment":false,"hidden":false},{"$type":"TerminalRule","name":"EM_ACC_TITLE","definition":{"$type":"RegexToken","regex":"/[\\\\t ]*accTitle[\\\\t ]*:(?:[^\\\\n\\\\r]*?(?=%%)|[^\\\\n\\\\r]*)/","parenthesized":false},"fragment":false,"hidden":false},{"$type":"TerminalRule","name":"EM_TITLE","definition":{"$type":"RegexToken","regex":"/[\\\\t ]*title(?:[\\\\t ][^\\\\n\\\\r]*?(?=%%)|[\\\\t ][^\\\\n\\\\r]*|)/","parenthesized":false},"fragment":false,"hidden":false},{"$type":"TerminalRule","hidden":true,"name":"EM_WS","definition":{"$type":"RegexToken","regex":"/\\\\s+/","parenthesized":false},"fragment":false},{"$type":"TerminalRule","hidden":true,"name":"EM_YAML","definition":{"$type":"RegexToken","regex":"/---[\\\\t ]*\\\\r?\\\\n(?:[\\\\S\\\\s]*?\\\\r?\\\\n)?---(?:\\\\r?\\\\n|(?!\\\\S))/","parenthesized":false},"fragment":false},{"$type":"TerminalRule","hidden":true,"name":"EM_DIRECTIVE","definition":{"$type":"RegexToken","regex":"/[\\\\t ]*%%{[\\\\S\\\\s]*?}%%(?:\\\\r?\\\\n|(?!\\\\S))/","parenthesized":false},"fragment":false},{"$type":"TerminalRule","hidden":true,"name":"EM_SINGLE_LINE_COMMENT","definition":{"$type":"RegexToken","regex":"/[\\\\t ]*%%[^\\\\n\\\\r]*/","parenthesized":false},"fragment":false},{"$type":"TerminalRule","hidden":true,"name":"EM_ML_COMMENT","definition":{"$type":"RegexToken","regex":"/\\\\/\\\\*[\\\\s\\\\S]*?\\\\*\\\\//","parenthesized":false},"fragment":false},{"$type":"TerminalRule","hidden":true,"name":"EM_SL_COMMENT","definition":{"$type":"RegexToken","regex":"/\\\\/\\\\/[^\\\\n\\\\r]*/","parenthesized":false},"fragment":false}],"imports":[],"types":[]}')), "EventModelingGrammar");
var loadedGitGraphGrammarGrammar;
var GitGraphGrammarGrammar = /* @__PURE__ */ __name2(() => loadedGitGraphGrammarGrammar ?? (loadedGitGraphGrammarGrammar = loadGrammarFromJson(`{"$type":"Grammar","isDeclared":true,"name":"GitGraphGrammar","imports":[],"rules":[{"$type":"ParserRule","entry":true,"name":"GitGraph","definition":{"$type":"Group","elements":[{"$type":"RuleCall","rule":{"$ref":"#/rules@19"},"arguments":[],"cardinality":"*"},{"$type":"Alternatives","elements":[{"$type":"Keyword","value":"gitGraph"},{"$type":"Group","elements":[{"$type":"Keyword","value":"gitGraph"},{"$type":"Keyword","value":":"}]},{"$type":"Keyword","value":"gitGraph:"},{"$type":"Group","elements":[{"$type":"Keyword","value":"gitGraph"},{"$type":"RuleCall","rule":{"$ref":"#/rules@2"},"arguments":[]},{"$type":"Keyword","value":":"}]}]},{"$type":"Alternatives","elements":[{"$type":"RuleCall","rule":{"$ref":"#/rules@19"},"arguments":[]},{"$type":"RuleCall","rule":{"$ref":"#/rules@9"},"arguments":[]},{"$type":"Assignment","feature":"statements","operator":"+=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@1"},"arguments":[]}}],"cardinality":"*"}]},"fragment":false,"parameters":[]},{"$type":"ParserRule","name":"Statement","definition":{"$type":"Alternatives","elements":[{"$type":"RuleCall","rule":{"$ref":"#/rules@3"},"arguments":[]},{"$type":"RuleCall","rule":{"$ref":"#/rules@4"},"arguments":[]},{"$type":"RuleCall","rule":{"$ref":"#/rules@5"},"arguments":[]},{"$type":"RuleCall","rule":{"$ref":"#/rules@6"},"arguments":[]},{"$type":"RuleCall","rule":{"$ref":"#/rules@7"},"arguments":[]}]},"entry":false,"fragment":false,"parameters":[]},{"$type":"ParserRule","name":"Direction","definition":{"$type":"Assignment","feature":"dir","operator":"=","terminal":{"$type":"Alternatives","elements":[{"$type":"Keyword","value":"LR"},{"$type":"Keyword","value":"TB"},{"$type":"Keyword","value":"BT"}]}},"entry":false,"fragment":false,"parameters":[]},{"$type":"ParserRule","name":"Commit","definition":{"$type":"Group","elements":[{"$type":"Keyword","value":"commit"},{"$type":"Alternatives","elements":[{"$type":"Group","elements":[{"$type":"Keyword","value":"id:"},{"$type":"Assignment","feature":"id","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@17"},"arguments":[]}}]},{"$type":"Group","elements":[{"$type":"Keyword","value":"msg:","cardinality":"?"},{"$type":"Assignment","feature":"message","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@17"},"arguments":[]}}]},{"$type":"Group","elements":[{"$type":"Keyword","value":"tag:"},{"$type":"Assignment","feature":"tags","operator":"+=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@17"},"arguments":[]}}]},{"$type":"Group","elements":[{"$type":"Keyword","value":"type:"},{"$type":"Assignment","feature":"type","operator":"=","terminal":{"$type":"Alternatives","elements":[{"$type":"Keyword","value":"NORMAL"},{"$type":"Keyword","value":"REVERSE"},{"$type":"Keyword","value":"HIGHLIGHT"}]}}]}],"cardinality":"*"},{"$type":"RuleCall","rule":{"$ref":"#/rules@8"},"arguments":[]}]},"entry":false,"fragment":false,"parameters":[]},{"$type":"ParserRule","name":"Branch","definition":{"$type":"Group","elements":[{"$type":"Keyword","value":"branch"},{"$type":"Assignment","feature":"name","operator":"=","terminal":{"$type":"Alternatives","elements":[{"$type":"RuleCall","rule":{"$ref":"#/rules@24"},"arguments":[]},{"$type":"RuleCall","rule":{"$ref":"#/rules@17"},"arguments":[]}]}},{"$type":"Group","elements":[{"$type":"Keyword","value":"order:"},{"$type":"Assignment","feature":"order","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@15"},"arguments":[]}}],"cardinality":"?"},{"$type":"RuleCall","rule":{"$ref":"#/rules@8"},"arguments":[]}]},"entry":false,"fragment":false,"parameters":[]},{"$type":"ParserRule","name":"Merge","definition":{"$type":"Group","elements":[{"$type":"Keyword","value":"merge"},{"$type":"Assignment","feature":"branch","operator":"=","terminal":{"$type":"Alternatives","elements":[{"$type":"RuleCall","rule":{"$ref":"#/rules@24"},"arguments":[]},{"$type":"RuleCall","rule":{"$ref":"#/rules@17"},"arguments":[]}]}},{"$type":"Alternatives","elements":[{"$type":"Group","elements":[{"$type":"Keyword","value":"id:"},{"$type":"Assignment","feature":"id","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@17"},"arguments":[]}}]},{"$type":"Group","elements":[{"$type":"Keyword","value":"tag:"},{"$type":"Assignment","feature":"tags","operator":"+=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@17"},"arguments":[]}}]},{"$type":"Group","elements":[{"$type":"Keyword","value":"type:"},{"$type":"Assignment","feature":"type","operator":"=","terminal":{"$type":"Alternatives","elements":[{"$type":"Keyword","value":"NORMAL"},{"$type":"Keyword","value":"REVERSE"},{"$type":"Keyword","value":"HIGHLIGHT"}]}}]}],"cardinality":"*"},{"$type":"RuleCall","rule":{"$ref":"#/rules@8"},"arguments":[]}]},"entry":false,"fragment":false,"parameters":[]},{"$type":"ParserRule","name":"Checkout","definition":{"$type":"Group","elements":[{"$type":"Alternatives","elements":[{"$type":"Keyword","value":"checkout"},{"$type":"Keyword","value":"switch"}]},{"$type":"Assignment","feature":"branch","operator":"=","terminal":{"$type":"Alternatives","elements":[{"$type":"RuleCall","rule":{"$ref":"#/rules@24"},"arguments":[]},{"$type":"RuleCall","rule":{"$ref":"#/rules@17"},"arguments":[]}]}},{"$type":"RuleCall","rule":{"$ref":"#/rules@8"},"arguments":[]}]},"entry":false,"fragment":false,"parameters":[]},{"$type":"ParserRule","name":"CherryPicking","definition":{"$type":"Group","elements":[{"$type":"Keyword","value":"cherry-pick"},{"$type":"Alternatives","elements":[{"$type":"Group","elements":[{"$type":"Keyword","value":"id:"},{"$type":"Assignment","feature":"id","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@17"},"arguments":[]}}]},{"$type":"Group","elements":[{"$type":"Keyword","value":"tag:"},{"$type":"Assignment","feature":"tags","operator":"+=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@17"},"arguments":[]}}]},{"$type":"Group","elements":[{"$type":"Keyword","value":"parent:"},{"$type":"Assignment","feature":"parent","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@17"},"arguments":[]}}]}],"cardinality":"*"},{"$type":"RuleCall","rule":{"$ref":"#/rules@8"},"arguments":[]}]},"entry":false,"fragment":false,"parameters":[]},{"$type":"ParserRule","name":"EOL","dataType":"string","definition":{"$type":"Alternatives","elements":[{"$type":"RuleCall","rule":{"$ref":"#/rules@19"},"arguments":[],"cardinality":"+"},{"$type":"EndOfFile"}]},"entry":false,"fragment":false,"parameters":[]},{"$type":"ParserRule","fragment":true,"name":"TitleAndAccessibilities","definition":{"$type":"Group","elements":[{"$type":"Alternatives","elements":[{"$type":"Assignment","feature":"accDescr","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@11"},"arguments":[]}},{"$type":"Assignment","feature":"accTitle","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@12"},"arguments":[]}},{"$type":"Assignment","feature":"title","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@13"},"arguments":[]}}]},{"$type":"RuleCall","rule":{"$ref":"#/rules@8"},"arguments":[]}],"cardinality":"+"},"entry":false,"parameters":[]},{"$type":"TerminalRule","name":"BOOLEAN","type":{"$type":"ReturnType","name":"boolean"},"definition":{"$type":"TerminalAlternatives","elements":[{"$type":"CharacterRange","left":{"$type":"Keyword","value":"true"},"parenthesized":false},{"$type":"CharacterRange","left":{"$type":"Keyword","value":"false"},"parenthesized":false}],"parenthesized":false},"fragment":false,"hidden":false},{"$type":"TerminalRule","name":"ACC_DESCR","definition":{"$type":"RegexToken","regex":"/[\\\\t ]*accDescr(?:[\\\\t ]*:([^\\\\n\\\\r]*?(?=%%)|[^\\\\n\\\\r]*)|\\\\s*{([^}]*)})/","parenthesized":false},"fragment":false,"hidden":false},{"$type":"TerminalRule","name":"ACC_TITLE","definition":{"$type":"RegexToken","regex":"/[\\\\t ]*accTitle[\\\\t ]*:(?:[^\\\\n\\\\r]*?(?=%%)|[^\\\\n\\\\r]*)/","parenthesized":false},"fragment":false,"hidden":false},{"$type":"TerminalRule","name":"TITLE","definition":{"$type":"RegexToken","regex":"/[\\\\t ]*title(?:[\\\\t ][^\\\\n\\\\r]*?(?=%%)|[\\\\t ][^\\\\n\\\\r]*|)/","parenthesized":false},"fragment":false,"hidden":false},{"$type":"TerminalRule","name":"FLOAT","type":{"$type":"ReturnType","name":"number"},"definition":{"$type":"RegexToken","regex":"/[0-9]+\\\\.[0-9]+(?!\\\\.)/","parenthesized":false},"fragment":false,"hidden":false},{"$type":"TerminalRule","name":"INT","type":{"$type":"ReturnType","name":"number"},"definition":{"$type":"RegexToken","regex":"/0|[1-9][0-9]*(?!\\\\.)/","parenthesized":false},"fragment":false,"hidden":false},{"$type":"TerminalRule","name":"NUMBER","type":{"$type":"ReturnType","name":"number"},"definition":{"$type":"TerminalAlternatives","elements":[{"$type":"TerminalRuleCall","rule":{"$ref":"#/rules@14"},"parenthesized":false},{"$type":"TerminalRuleCall","rule":{"$ref":"#/rules@15"},"parenthesized":false}],"parenthesized":false},"fragment":false,"hidden":false},{"$type":"TerminalRule","name":"STRING","type":{"$type":"ReturnType","name":"string"},"definition":{"$type":"RegexToken","regex":"/\\"([^\\"\\\\\\\\]|\\\\\\\\.)*\\"|'([^'\\\\\\\\]|\\\\\\\\.)*'/","parenthesized":false},"fragment":false,"hidden":false},{"$type":"TerminalRule","name":"ID","type":{"$type":"ReturnType","name":"string"},"definition":{"$type":"RegexToken","regex":"/[\\\\w]([-\\\\w]*\\\\w)?/","parenthesized":false},"fragment":false,"hidden":false},{"$type":"TerminalRule","name":"NEWLINE","definition":{"$type":"RegexToken","regex":"/\\\\r?\\\\n/","parenthesized":false},"fragment":false,"hidden":false},{"$type":"TerminalRule","hidden":true,"name":"WHITESPACE","definition":{"$type":"RegexToken","regex":"/[\\\\t ]+/","parenthesized":false},"fragment":false},{"$type":"TerminalRule","hidden":true,"name":"YAML","definition":{"$type":"RegexToken","regex":"/---[\\\\t ]*\\\\r?\\\\n(?:[\\\\S\\\\s]*?\\\\r?\\\\n)?---(?:\\\\r?\\\\n|(?!\\\\S))/","parenthesized":false},"fragment":false},{"$type":"TerminalRule","hidden":true,"name":"DIRECTIVE","definition":{"$type":"RegexToken","regex":"/[\\\\t ]*%%{[\\\\S\\\\s]*?}%%(?:\\\\r?\\\\n|(?!\\\\S))/","parenthesized":false},"fragment":false},{"$type":"TerminalRule","hidden":true,"name":"SINGLE_LINE_COMMENT","definition":{"$type":"RegexToken","regex":"/[\\\\t ]*%%[^\\\\n\\\\r]*/","parenthesized":false},"fragment":false},{"$type":"TerminalRule","name":"REFERENCE","type":{"$type":"ReturnType","name":"string"},"definition":{"$type":"RegexToken","regex":"/\\\\w([-\\\\./\\\\w]*[-\\\\w])?/","parenthesized":false},"fragment":false,"hidden":false}],"interfaces":[],"types":[]}`)), "GitGraphGrammarGrammar");
var loadedInfoGrammarGrammar;
var InfoGrammarGrammar = /* @__PURE__ */ __name2(() => loadedInfoGrammarGrammar ?? (loadedInfoGrammarGrammar = loadGrammarFromJson(`{"$type":"Grammar","isDeclared":true,"name":"InfoGrammar","imports":[],"rules":[{"$type":"ParserRule","entry":true,"name":"Info","definition":{"$type":"Group","elements":[{"$type":"RuleCall","rule":{"$ref":"#/rules@12"},"arguments":[],"cardinality":"*"},{"$type":"Keyword","value":"info"},{"$type":"RuleCall","rule":{"$ref":"#/rules@12"},"arguments":[],"cardinality":"*"},{"$type":"Group","elements":[{"$type":"Keyword","value":"showInfo"},{"$type":"RuleCall","rule":{"$ref":"#/rules@12"},"arguments":[],"cardinality":"*"}],"cardinality":"?"},{"$type":"RuleCall","rule":{"$ref":"#/rules@2"},"arguments":[],"cardinality":"?"}]},"fragment":false,"parameters":[]},{"$type":"ParserRule","name":"EOL","dataType":"string","definition":{"$type":"Alternatives","elements":[{"$type":"RuleCall","rule":{"$ref":"#/rules@12"},"arguments":[],"cardinality":"+"},{"$type":"EndOfFile"}]},"entry":false,"fragment":false,"parameters":[]},{"$type":"ParserRule","fragment":true,"name":"TitleAndAccessibilities","definition":{"$type":"Group","elements":[{"$type":"Alternatives","elements":[{"$type":"Assignment","feature":"accDescr","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@4"},"arguments":[]}},{"$type":"Assignment","feature":"accTitle","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@5"},"arguments":[]}},{"$type":"Assignment","feature":"title","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@6"},"arguments":[]}}]},{"$type":"RuleCall","rule":{"$ref":"#/rules@1"},"arguments":[]}],"cardinality":"+"},"entry":false,"parameters":[]},{"$type":"TerminalRule","name":"BOOLEAN","type":{"$type":"ReturnType","name":"boolean"},"definition":{"$type":"TerminalAlternatives","elements":[{"$type":"CharacterRange","left":{"$type":"Keyword","value":"true"},"parenthesized":false},{"$type":"CharacterRange","left":{"$type":"Keyword","value":"false"},"parenthesized":false}],"parenthesized":false},"fragment":false,"hidden":false},{"$type":"TerminalRule","name":"ACC_DESCR","definition":{"$type":"RegexToken","regex":"/[\\\\t ]*accDescr(?:[\\\\t ]*:([^\\\\n\\\\r]*?(?=%%)|[^\\\\n\\\\r]*)|\\\\s*{([^}]*)})/","parenthesized":false},"fragment":false,"hidden":false},{"$type":"TerminalRule","name":"ACC_TITLE","definition":{"$type":"RegexToken","regex":"/[\\\\t ]*accTitle[\\\\t ]*:(?:[^\\\\n\\\\r]*?(?=%%)|[^\\\\n\\\\r]*)/","parenthesized":false},"fragment":false,"hidden":false},{"$type":"TerminalRule","name":"TITLE","definition":{"$type":"RegexToken","regex":"/[\\\\t ]*title(?:[\\\\t ][^\\\\n\\\\r]*?(?=%%)|[\\\\t ][^\\\\n\\\\r]*|)/","parenthesized":false},"fragment":false,"hidden":false},{"$type":"TerminalRule","name":"FLOAT","type":{"$type":"ReturnType","name":"number"},"definition":{"$type":"RegexToken","regex":"/[0-9]+\\\\.[0-9]+(?!\\\\.)/","parenthesized":false},"fragment":false,"hidden":false},{"$type":"TerminalRule","name":"INT","type":{"$type":"ReturnType","name":"number"},"definition":{"$type":"RegexToken","regex":"/0|[1-9][0-9]*(?!\\\\.)/","parenthesized":false},"fragment":false,"hidden":false},{"$type":"TerminalRule","name":"NUMBER","type":{"$type":"ReturnType","name":"number"},"definition":{"$type":"TerminalAlternatives","elements":[{"$type":"TerminalRuleCall","rule":{"$ref":"#/rules@7"},"parenthesized":false},{"$type":"TerminalRuleCall","rule":{"$ref":"#/rules@8"},"parenthesized":false}],"parenthesized":false},"fragment":false,"hidden":false},{"$type":"TerminalRule","name":"STRING","type":{"$type":"ReturnType","name":"string"},"definition":{"$type":"RegexToken","regex":"/\\"([^\\"\\\\\\\\]|\\\\\\\\.)*\\"|'([^'\\\\\\\\]|\\\\\\\\.)*'/","parenthesized":false},"fragment":false,"hidden":false},{"$type":"TerminalRule","name":"ID","type":{"$type":"ReturnType","name":"string"},"definition":{"$type":"RegexToken","regex":"/[\\\\w]([-\\\\w]*\\\\w)?/","parenthesized":false},"fragment":false,"hidden":false},{"$type":"TerminalRule","name":"NEWLINE","definition":{"$type":"RegexToken","regex":"/\\\\r?\\\\n/","parenthesized":false},"fragment":false,"hidden":false},{"$type":"TerminalRule","hidden":true,"name":"WHITESPACE","definition":{"$type":"RegexToken","regex":"/[\\\\t ]+/","parenthesized":false},"fragment":false},{"$type":"TerminalRule","hidden":true,"name":"YAML","definition":{"$type":"RegexToken","regex":"/---[\\\\t ]*\\\\r?\\\\n(?:[\\\\S\\\\s]*?\\\\r?\\\\n)?---(?:\\\\r?\\\\n|(?!\\\\S))/","parenthesized":false},"fragment":false},{"$type":"TerminalRule","hidden":true,"name":"DIRECTIVE","definition":{"$type":"RegexToken","regex":"/[\\\\t ]*%%{[\\\\S\\\\s]*?}%%(?:\\\\r?\\\\n|(?!\\\\S))/","parenthesized":false},"fragment":false},{"$type":"TerminalRule","hidden":true,"name":"SINGLE_LINE_COMMENT","definition":{"$type":"RegexToken","regex":"/[\\\\t ]*%%[^\\\\n\\\\r]*/","parenthesized":false},"fragment":false}],"interfaces":[],"types":[]}`)), "InfoGrammarGrammar");
var loadedPacketGrammarGrammar;
var PacketGrammarGrammar = /* @__PURE__ */ __name2(() => loadedPacketGrammarGrammar ?? (loadedPacketGrammarGrammar = loadGrammarFromJson(`{"$type":"Grammar","isDeclared":true,"name":"PacketGrammar","imports":[],"rules":[{"$type":"ParserRule","entry":true,"name":"Packet","definition":{"$type":"Group","elements":[{"$type":"RuleCall","rule":{"$ref":"#/rules@13"},"arguments":[],"cardinality":"*"},{"$type":"Alternatives","elements":[{"$type":"Keyword","value":"packet"},{"$type":"Keyword","value":"packet-beta"}]},{"$type":"Alternatives","elements":[{"$type":"RuleCall","rule":{"$ref":"#/rules@3"},"arguments":[]},{"$type":"Assignment","feature":"blocks","operator":"+=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@1"},"arguments":[]}},{"$type":"RuleCall","rule":{"$ref":"#/rules@13"},"arguments":[]}],"cardinality":"*"}]},"fragment":false,"parameters":[]},{"$type":"ParserRule","name":"PacketBlock","definition":{"$type":"Group","elements":[{"$type":"Alternatives","elements":[{"$type":"Group","elements":[{"$type":"Assignment","feature":"start","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@9"},"arguments":[]}},{"$type":"Group","elements":[{"$type":"Keyword","value":"-"},{"$type":"Assignment","feature":"end","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@9"},"arguments":[]}}],"cardinality":"?"}]},{"$type":"Group","elements":[{"$type":"Keyword","value":"+"},{"$type":"Assignment","feature":"bits","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@9"},"arguments":[]}}]}]},{"$type":"Keyword","value":":"},{"$type":"Assignment","feature":"label","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@11"},"arguments":[]}},{"$type":"RuleCall","rule":{"$ref":"#/rules@2"},"arguments":[]}]},"entry":false,"fragment":false,"parameters":[]},{"$type":"ParserRule","name":"EOL","dataType":"string","definition":{"$type":"Alternatives","elements":[{"$type":"RuleCall","rule":{"$ref":"#/rules@13"},"arguments":[],"cardinality":"+"},{"$type":"EndOfFile"}]},"entry":false,"fragment":false,"parameters":[]},{"$type":"ParserRule","fragment":true,"name":"TitleAndAccessibilities","definition":{"$type":"Group","elements":[{"$type":"Alternatives","elements":[{"$type":"Assignment","feature":"accDescr","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@5"},"arguments":[]}},{"$type":"Assignment","feature":"accTitle","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@6"},"arguments":[]}},{"$type":"Assignment","feature":"title","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@7"},"arguments":[]}}]},{"$type":"RuleCall","rule":{"$ref":"#/rules@2"},"arguments":[]}],"cardinality":"+"},"entry":false,"parameters":[]},{"$type":"TerminalRule","name":"BOOLEAN","type":{"$type":"ReturnType","name":"boolean"},"definition":{"$type":"TerminalAlternatives","elements":[{"$type":"CharacterRange","left":{"$type":"Keyword","value":"true"},"parenthesized":false},{"$type":"CharacterRange","left":{"$type":"Keyword","value":"false"},"parenthesized":false}],"parenthesized":false},"fragment":false,"hidden":false},{"$type":"TerminalRule","name":"ACC_DESCR","definition":{"$type":"RegexToken","regex":"/[\\\\t ]*accDescr(?:[\\\\t ]*:([^\\\\n\\\\r]*?(?=%%)|[^\\\\n\\\\r]*)|\\\\s*{([^}]*)})/","parenthesized":false},"fragment":false,"hidden":false},{"$type":"TerminalRule","name":"ACC_TITLE","definition":{"$type":"RegexToken","regex":"/[\\\\t ]*accTitle[\\\\t ]*:(?:[^\\\\n\\\\r]*?(?=%%)|[^\\\\n\\\\r]*)/","parenthesized":false},"fragment":false,"hidden":false},{"$type":"TerminalRule","name":"TITLE","definition":{"$type":"RegexToken","regex":"/[\\\\t ]*title(?:[\\\\t ][^\\\\n\\\\r]*?(?=%%)|[\\\\t ][^\\\\n\\\\r]*|)/","parenthesized":false},"fragment":false,"hidden":false},{"$type":"TerminalRule","name":"FLOAT","type":{"$type":"ReturnType","name":"number"},"definition":{"$type":"RegexToken","regex":"/[0-9]+\\\\.[0-9]+(?!\\\\.)/","parenthesized":false},"fragment":false,"hidden":false},{"$type":"TerminalRule","name":"INT","type":{"$type":"ReturnType","name":"number"},"definition":{"$type":"RegexToken","regex":"/0|[1-9][0-9]*(?!\\\\.)/","parenthesized":false},"fragment":false,"hidden":false},{"$type":"TerminalRule","name":"NUMBER","type":{"$type":"ReturnType","name":"number"},"definition":{"$type":"TerminalAlternatives","elements":[{"$type":"TerminalRuleCall","rule":{"$ref":"#/rules@8"},"parenthesized":false},{"$type":"TerminalRuleCall","rule":{"$ref":"#/rules@9"},"parenthesized":false}],"parenthesized":false},"fragment":false,"hidden":false},{"$type":"TerminalRule","name":"STRING","type":{"$type":"ReturnType","name":"string"},"definition":{"$type":"RegexToken","regex":"/\\"([^\\"\\\\\\\\]|\\\\\\\\.)*\\"|'([^'\\\\\\\\]|\\\\\\\\.)*'/","parenthesized":false},"fragment":false,"hidden":false},{"$type":"TerminalRule","name":"ID","type":{"$type":"ReturnType","name":"string"},"definition":{"$type":"RegexToken","regex":"/[\\\\w]([-\\\\w]*\\\\w)?/","parenthesized":false},"fragment":false,"hidden":false},{"$type":"TerminalRule","name":"NEWLINE","definition":{"$type":"RegexToken","regex":"/\\\\r?\\\\n/","parenthesized":false},"fragment":false,"hidden":false},{"$type":"TerminalRule","hidden":true,"name":"WHITESPACE","definition":{"$type":"RegexToken","regex":"/[\\\\t ]+/","parenthesized":false},"fragment":false},{"$type":"TerminalRule","hidden":true,"name":"YAML","definition":{"$type":"RegexToken","regex":"/---[\\\\t ]*\\\\r?\\\\n(?:[\\\\S\\\\s]*?\\\\r?\\\\n)?---(?:\\\\r?\\\\n|(?!\\\\S))/","parenthesized":false},"fragment":false},{"$type":"TerminalRule","hidden":true,"name":"DIRECTIVE","definition":{"$type":"RegexToken","regex":"/[\\\\t ]*%%{[\\\\S\\\\s]*?}%%(?:\\\\r?\\\\n|(?!\\\\S))/","parenthesized":false},"fragment":false},{"$type":"TerminalRule","hidden":true,"name":"SINGLE_LINE_COMMENT","definition":{"$type":"RegexToken","regex":"/[\\\\t ]*%%[^\\\\n\\\\r]*/","parenthesized":false},"fragment":false}],"interfaces":[],"types":[]}`)), "PacketGrammarGrammar");
var loadedPieGrammarGrammar;
var PieGrammarGrammar = /* @__PURE__ */ __name2(() => loadedPieGrammarGrammar ?? (loadedPieGrammarGrammar = loadGrammarFromJson(`{"$type":"Grammar","isDeclared":true,"name":"PieGrammar","imports":[],"rules":[{"$type":"ParserRule","entry":true,"name":"Pie","definition":{"$type":"Group","elements":[{"$type":"RuleCall","rule":{"$ref":"#/rules@16"},"arguments":[],"cardinality":"*"},{"$type":"Keyword","value":"pie"},{"$type":"Assignment","feature":"showData","operator":"?=","terminal":{"$type":"Keyword","value":"showData"},"cardinality":"?"},{"$type":"Alternatives","elements":[{"$type":"RuleCall","rule":{"$ref":"#/rules@6"},"arguments":[]},{"$type":"Assignment","feature":"sections","operator":"+=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@1"},"arguments":[]}},{"$type":"RuleCall","rule":{"$ref":"#/rules@16"},"arguments":[]}],"cardinality":"*"}]},"fragment":false,"parameters":[]},{"$type":"ParserRule","name":"PieSection","definition":{"$type":"Group","elements":[{"$type":"Assignment","feature":"label","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@14"},"arguments":[]}},{"$type":"Keyword","value":":"},{"$type":"Assignment","feature":"value","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@4"},"arguments":[]}},{"$type":"RuleCall","rule":{"$ref":"#/rules@5"},"arguments":[]}]},"entry":false,"fragment":false,"parameters":[]},{"$type":"TerminalRule","name":"FLOAT_PIE","type":{"$type":"ReturnType","name":"number"},"definition":{"$type":"RegexToken","regex":"/-?[0-9]+\\\\.[0-9]+(?!\\\\.)/","parenthesized":false},"fragment":false,"hidden":false},{"$type":"TerminalRule","name":"INT_PIE","type":{"$type":"ReturnType","name":"number"},"definition":{"$type":"RegexToken","regex":"/-?(0|[1-9][0-9]*)(?!\\\\.)/","parenthesized":false},"fragment":false,"hidden":false},{"$type":"TerminalRule","name":"NUMBER_PIE","type":{"$type":"ReturnType","name":"number"},"definition":{"$type":"TerminalAlternatives","elements":[{"$type":"TerminalRuleCall","rule":{"$ref":"#/rules@2"},"parenthesized":false},{"$type":"TerminalRuleCall","rule":{"$ref":"#/rules@3"},"parenthesized":false}],"parenthesized":false},"fragment":false,"hidden":false},{"$type":"ParserRule","name":"EOL","dataType":"string","definition":{"$type":"Alternatives","elements":[{"$type":"RuleCall","rule":{"$ref":"#/rules@16"},"arguments":[],"cardinality":"+"},{"$type":"EndOfFile"}]},"entry":false,"fragment":false,"parameters":[]},{"$type":"ParserRule","fragment":true,"name":"TitleAndAccessibilities","definition":{"$type":"Group","elements":[{"$type":"Alternatives","elements":[{"$type":"Assignment","feature":"accDescr","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@8"},"arguments":[]}},{"$type":"Assignment","feature":"accTitle","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@9"},"arguments":[]}},{"$type":"Assignment","feature":"title","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@10"},"arguments":[]}}]},{"$type":"RuleCall","rule":{"$ref":"#/rules@5"},"arguments":[]}],"cardinality":"+"},"entry":false,"parameters":[]},{"$type":"TerminalRule","name":"BOOLEAN","type":{"$type":"ReturnType","name":"boolean"},"definition":{"$type":"TerminalAlternatives","elements":[{"$type":"CharacterRange","left":{"$type":"Keyword","value":"true"},"parenthesized":false},{"$type":"CharacterRange","left":{"$type":"Keyword","value":"false"},"parenthesized":false}],"parenthesized":false},"fragment":false,"hidden":false},{"$type":"TerminalRule","name":"ACC_DESCR","definition":{"$type":"RegexToken","regex":"/[\\\\t ]*accDescr(?:[\\\\t ]*:([^\\\\n\\\\r]*?(?=%%)|[^\\\\n\\\\r]*)|\\\\s*{([^}]*)})/","parenthesized":false},"fragment":false,"hidden":false},{"$type":"TerminalRule","name":"ACC_TITLE","definition":{"$type":"RegexToken","regex":"/[\\\\t ]*accTitle[\\\\t ]*:(?:[^\\\\n\\\\r]*?(?=%%)|[^\\\\n\\\\r]*)/","parenthesized":false},"fragment":false,"hidden":false},{"$type":"TerminalRule","name":"TITLE","definition":{"$type":"RegexToken","regex":"/[\\\\t ]*title(?:[\\\\t ][^\\\\n\\\\r]*?(?=%%)|[\\\\t ][^\\\\n\\\\r]*|)/","parenthesized":false},"fragment":false,"hidden":false},{"$type":"TerminalRule","name":"FLOAT","type":{"$type":"ReturnType","name":"number"},"definition":{"$type":"RegexToken","regex":"/[0-9]+\\\\.[0-9]+(?!\\\\.)/","parenthesized":false},"fragment":false,"hidden":false},{"$type":"TerminalRule","name":"INT","type":{"$type":"ReturnType","name":"number"},"definition":{"$type":"RegexToken","regex":"/0|[1-9][0-9]*(?!\\\\.)/","parenthesized":false},"fragment":false,"hidden":false},{"$type":"TerminalRule","name":"NUMBER","type":{"$type":"ReturnType","name":"number"},"definition":{"$type":"TerminalAlternatives","elements":[{"$type":"TerminalRuleCall","rule":{"$ref":"#/rules@11"},"parenthesized":false},{"$type":"TerminalRuleCall","rule":{"$ref":"#/rules@12"},"parenthesized":false}],"parenthesized":false},"fragment":false,"hidden":false},{"$type":"TerminalRule","name":"STRING","type":{"$type":"ReturnType","name":"string"},"definition":{"$type":"RegexToken","regex":"/\\"([^\\"\\\\\\\\]|\\\\\\\\.)*\\"|'([^'\\\\\\\\]|\\\\\\\\.)*'/","parenthesized":false},"fragment":false,"hidden":false},{"$type":"TerminalRule","name":"ID","type":{"$type":"ReturnType","name":"string"},"definition":{"$type":"RegexToken","regex":"/[\\\\w]([-\\\\w]*\\\\w)?/","parenthesized":false},"fragment":false,"hidden":false},{"$type":"TerminalRule","name":"NEWLINE","definition":{"$type":"RegexToken","regex":"/\\\\r?\\\\n/","parenthesized":false},"fragment":false,"hidden":false},{"$type":"TerminalRule","hidden":true,"name":"WHITESPACE","definition":{"$type":"RegexToken","regex":"/[\\\\t ]+/","parenthesized":false},"fragment":false},{"$type":"TerminalRule","hidden":true,"name":"YAML","definition":{"$type":"RegexToken","regex":"/---[\\\\t ]*\\\\r?\\\\n(?:[\\\\S\\\\s]*?\\\\r?\\\\n)?---(?:\\\\r?\\\\n|(?!\\\\S))/","parenthesized":false},"fragment":false},{"$type":"TerminalRule","hidden":true,"name":"DIRECTIVE","definition":{"$type":"RegexToken","regex":"/[\\\\t ]*%%{[\\\\S\\\\s]*?}%%(?:\\\\r?\\\\n|(?!\\\\S))/","parenthesized":false},"fragment":false},{"$type":"TerminalRule","hidden":true,"name":"SINGLE_LINE_COMMENT","definition":{"$type":"RegexToken","regex":"/[\\\\t ]*%%[^\\\\n\\\\r]*/","parenthesized":false},"fragment":false}],"interfaces":[],"types":[]}`)), "PieGrammarGrammar");
var loadedRadarGrammarGrammar;
var RadarGrammarGrammar = /* @__PURE__ */ __name2(() => loadedRadarGrammarGrammar ?? (loadedRadarGrammarGrammar = loadGrammarFromJson(`{"$type":"Grammar","isDeclared":true,"name":"RadarGrammar","imports":[],"rules":[{"$type":"ParserRule","entry":true,"name":"Radar","definition":{"$type":"Group","elements":[{"$type":"RuleCall","rule":{"$ref":"#/rules@20"},"arguments":[],"cardinality":"*"},{"$type":"Alternatives","elements":[{"$type":"Keyword","value":"radar-beta"},{"$type":"Keyword","value":"radar-beta:"},{"$type":"Group","elements":[{"$type":"Keyword","value":"radar-beta"},{"$type":"Keyword","value":":"}]}]},{"$type":"RuleCall","rule":{"$ref":"#/rules@20"},"arguments":[],"cardinality":"*"},{"$type":"Alternatives","elements":[{"$type":"RuleCall","rule":{"$ref":"#/rules@10"},"arguments":[]},{"$type":"Group","elements":[{"$type":"Keyword","value":"axis"},{"$type":"Assignment","feature":"axes","operator":"+=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@2"},"arguments":[]}},{"$type":"Group","elements":[{"$type":"Keyword","value":","},{"$type":"Assignment","feature":"axes","operator":"+=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@2"},"arguments":[]}}],"cardinality":"*"}]},{"$type":"Group","elements":[{"$type":"Keyword","value":"curve"},{"$type":"Assignment","feature":"curves","operator":"+=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@3"},"arguments":[]}},{"$type":"Group","elements":[{"$type":"Keyword","value":","},{"$type":"Assignment","feature":"curves","operator":"+=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@3"},"arguments":[]}}],"cardinality":"*"}]},{"$type":"Group","elements":[{"$type":"Assignment","feature":"options","operator":"+=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@7"},"arguments":[]}},{"$type":"Group","elements":[{"$type":"Keyword","value":","},{"$type":"Assignment","feature":"options","operator":"+=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@7"},"arguments":[]}}],"cardinality":"*"}]},{"$type":"RuleCall","rule":{"$ref":"#/rules@20"},"arguments":[]}],"cardinality":"*"}]},"fragment":false,"parameters":[]},{"$type":"ParserRule","fragment":true,"name":"Label","definition":{"$type":"Group","elements":[{"$type":"Keyword","value":"["},{"$type":"Assignment","feature":"label","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@18"},"arguments":[]}},{"$type":"Keyword","value":"]"}]},"entry":false,"parameters":[]},{"$type":"ParserRule","name":"Axis","definition":{"$type":"Group","elements":[{"$type":"Assignment","feature":"name","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@19"},"arguments":[]}},{"$type":"RuleCall","rule":{"$ref":"#/rules@1"},"arguments":[],"cardinality":"?"}]},"entry":false,"fragment":false,"parameters":[]},{"$type":"ParserRule","name":"Curve","definition":{"$type":"Group","elements":[{"$type":"Assignment","feature":"name","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@19"},"arguments":[]}},{"$type":"RuleCall","rule":{"$ref":"#/rules@1"},"arguments":[],"cardinality":"?"},{"$type":"Keyword","value":"{"},{"$type":"RuleCall","rule":{"$ref":"#/rules@4"},"arguments":[]},{"$type":"Keyword","value":"}"}]},"entry":false,"fragment":false,"parameters":[]},{"$type":"ParserRule","fragment":true,"name":"Entries","definition":{"$type":"Alternatives","elements":[{"$type":"Group","elements":[{"$type":"RuleCall","rule":{"$ref":"#/rules@20"},"arguments":[],"cardinality":"*"},{"$type":"Assignment","feature":"entries","operator":"+=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@6"},"arguments":[]}},{"$type":"Group","elements":[{"$type":"Keyword","value":","},{"$type":"RuleCall","rule":{"$ref":"#/rules@20"},"arguments":[],"cardinality":"*"},{"$type":"Assignment","feature":"entries","operator":"+=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@6"},"arguments":[]}}],"cardinality":"*"},{"$type":"RuleCall","rule":{"$ref":"#/rules@20"},"arguments":[],"cardinality":"*"}]},{"$type":"Group","elements":[{"$type":"RuleCall","rule":{"$ref":"#/rules@20"},"arguments":[],"cardinality":"*"},{"$type":"Assignment","feature":"entries","operator":"+=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@5"},"arguments":[]}},{"$type":"Group","elements":[{"$type":"Keyword","value":","},{"$type":"RuleCall","rule":{"$ref":"#/rules@20"},"arguments":[],"cardinality":"*"},{"$type":"Assignment","feature":"entries","operator":"+=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@5"},"arguments":[]}}],"cardinality":"*"},{"$type":"RuleCall","rule":{"$ref":"#/rules@20"},"arguments":[],"cardinality":"*"}]}]},"entry":false,"parameters":[]},{"$type":"ParserRule","name":"DetailedEntry","returnType":{"$ref":"#/interfaces@0"},"definition":{"$type":"Group","elements":[{"$type":"Assignment","feature":"axis","operator":"=","terminal":{"$type":"CrossReference","type":{"$ref":"#/rules@2"},"terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@19"},"arguments":[]},"deprecatedSyntax":false,"isMulti":false}},{"$type":"Keyword","value":":","cardinality":"?"},{"$type":"Assignment","feature":"value","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@17"},"arguments":[]}}]},"entry":false,"fragment":false,"parameters":[]},{"$type":"ParserRule","name":"NumberEntry","returnType":{"$ref":"#/interfaces@0"},"definition":{"$type":"Assignment","feature":"value","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@17"},"arguments":[]}},"entry":false,"fragment":false,"parameters":[]},{"$type":"ParserRule","name":"Option","definition":{"$type":"Alternatives","elements":[{"$type":"Group","elements":[{"$type":"Assignment","feature":"name","operator":"=","terminal":{"$type":"Keyword","value":"showLegend"}},{"$type":"Assignment","feature":"value","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@11"},"arguments":[]}}]},{"$type":"Group","elements":[{"$type":"Assignment","feature":"name","operator":"=","terminal":{"$type":"Keyword","value":"ticks"}},{"$type":"Assignment","feature":"value","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@17"},"arguments":[]}}]},{"$type":"Group","elements":[{"$type":"Assignment","feature":"name","operator":"=","terminal":{"$type":"Keyword","value":"max"}},{"$type":"Assignment","feature":"value","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@17"},"arguments":[]}}]},{"$type":"Group","elements":[{"$type":"Assignment","feature":"name","operator":"=","terminal":{"$type":"Keyword","value":"min"}},{"$type":"Assignment","feature":"value","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@17"},"arguments":[]}}]},{"$type":"Group","elements":[{"$type":"Assignment","feature":"name","operator":"=","terminal":{"$type":"Keyword","value":"graticule"}},{"$type":"Assignment","feature":"value","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@8"},"arguments":[]}}]}]},"entry":false,"fragment":false,"parameters":[]},{"$type":"TerminalRule","name":"GRATICULE","type":{"$type":"ReturnType","name":"string"},"definition":{"$type":"TerminalAlternatives","elements":[{"$type":"CharacterRange","left":{"$type":"Keyword","value":"circle"},"parenthesized":false},{"$type":"CharacterRange","left":{"$type":"Keyword","value":"polygon"},"parenthesized":false}],"parenthesized":false},"fragment":false,"hidden":false},{"$type":"ParserRule","name":"EOL","dataType":"string","definition":{"$type":"Alternatives","elements":[{"$type":"RuleCall","rule":{"$ref":"#/rules@20"},"arguments":[],"cardinality":"+"},{"$type":"EndOfFile"}]},"entry":false,"fragment":false,"parameters":[]},{"$type":"ParserRule","fragment":true,"name":"TitleAndAccessibilities","definition":{"$type":"Group","elements":[{"$type":"Alternatives","elements":[{"$type":"Assignment","feature":"accDescr","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@12"},"arguments":[]}},{"$type":"Assignment","feature":"accTitle","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@13"},"arguments":[]}},{"$type":"Assignment","feature":"title","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@14"},"arguments":[]}}]},{"$type":"RuleCall","rule":{"$ref":"#/rules@9"},"arguments":[]}],"cardinality":"+"},"entry":false,"parameters":[]},{"$type":"TerminalRule","name":"BOOLEAN","type":{"$type":"ReturnType","name":"boolean"},"definition":{"$type":"TerminalAlternatives","elements":[{"$type":"CharacterRange","left":{"$type":"Keyword","value":"true"},"parenthesized":false},{"$type":"CharacterRange","left":{"$type":"Keyword","value":"false"},"parenthesized":false}],"parenthesized":false},"fragment":false,"hidden":false},{"$type":"TerminalRule","name":"ACC_DESCR","definition":{"$type":"RegexToken","regex":"/[\\\\t ]*accDescr(?:[\\\\t ]*:([^\\\\n\\\\r]*?(?=%%)|[^\\\\n\\\\r]*)|\\\\s*{([^}]*)})/","parenthesized":false},"fragment":false,"hidden":false},{"$type":"TerminalRule","name":"ACC_TITLE","definition":{"$type":"RegexToken","regex":"/[\\\\t ]*accTitle[\\\\t ]*:(?:[^\\\\n\\\\r]*?(?=%%)|[^\\\\n\\\\r]*)/","parenthesized":false},"fragment":false,"hidden":false},{"$type":"TerminalRule","name":"TITLE","definition":{"$type":"RegexToken","regex":"/[\\\\t ]*title(?:[\\\\t ][^\\\\n\\\\r]*?(?=%%)|[\\\\t ][^\\\\n\\\\r]*|)/","parenthesized":false},"fragment":false,"hidden":false},{"$type":"TerminalRule","name":"FLOAT","type":{"$type":"ReturnType","name":"number"},"definition":{"$type":"RegexToken","regex":"/[0-9]+\\\\.[0-9]+(?!\\\\.)/","parenthesized":false},"fragment":false,"hidden":false},{"$type":"TerminalRule","name":"INT","type":{"$type":"ReturnType","name":"number"},"definition":{"$type":"RegexToken","regex":"/0|[1-9][0-9]*(?!\\\\.)/","parenthesized":false},"fragment":false,"hidden":false},{"$type":"TerminalRule","name":"NUMBER","type":{"$type":"ReturnType","name":"number"},"definition":{"$type":"TerminalAlternatives","elements":[{"$type":"TerminalRuleCall","rule":{"$ref":"#/rules@15"},"parenthesized":false},{"$type":"TerminalRuleCall","rule":{"$ref":"#/rules@16"},"parenthesized":false}],"parenthesized":false},"fragment":false,"hidden":false},{"$type":"TerminalRule","name":"STRING","type":{"$type":"ReturnType","name":"string"},"definition":{"$type":"RegexToken","regex":"/\\"([^\\"\\\\\\\\]|\\\\\\\\.)*\\"|'([^'\\\\\\\\]|\\\\\\\\.)*'/","parenthesized":false},"fragment":false,"hidden":false},{"$type":"TerminalRule","name":"ID","type":{"$type":"ReturnType","name":"string"},"definition":{"$type":"RegexToken","regex":"/[\\\\w]([-\\\\w]*\\\\w)?/","parenthesized":false},"fragment":false,"hidden":false},{"$type":"TerminalRule","name":"NEWLINE","definition":{"$type":"RegexToken","regex":"/\\\\r?\\\\n/","parenthesized":false},"fragment":false,"hidden":false},{"$type":"TerminalRule","hidden":true,"name":"WHITESPACE","definition":{"$type":"RegexToken","regex":"/[\\\\t ]+/","parenthesized":false},"fragment":false},{"$type":"TerminalRule","hidden":true,"name":"YAML","definition":{"$type":"RegexToken","regex":"/---[\\\\t ]*\\\\r?\\\\n(?:[\\\\S\\\\s]*?\\\\r?\\\\n)?---(?:\\\\r?\\\\n|(?!\\\\S))/","parenthesized":false},"fragment":false},{"$type":"TerminalRule","hidden":true,"name":"DIRECTIVE","definition":{"$type":"RegexToken","regex":"/[\\\\t ]*%%{[\\\\S\\\\s]*?}%%(?:\\\\r?\\\\n|(?!\\\\S))/","parenthesized":false},"fragment":false},{"$type":"TerminalRule","hidden":true,"name":"SINGLE_LINE_COMMENT","definition":{"$type":"RegexToken","regex":"/[\\\\t ]*%%[^\\\\n\\\\r]*/","parenthesized":false},"fragment":false}],"interfaces":[{"$type":"Interface","name":"Entry","attributes":[{"$type":"TypeAttribute","name":"axis","isOptional":true,"type":{"$type":"ReferenceType","referenceType":{"$type":"SimpleType","typeRef":{"$ref":"#/rules@2"}},"isMulti":false}},{"$type":"TypeAttribute","name":"value","type":{"$type":"SimpleType","primitiveType":"number"},"isOptional":false}],"superTypes":[]}],"types":[]}`)), "RadarGrammarGrammar");
var loadedRailroadAbnfGrammarGrammar;
var RailroadAbnfGrammarGrammar = /* @__PURE__ */ __name2(() => loadedRailroadAbnfGrammarGrammar ?? (loadedRailroadAbnfGrammarGrammar = loadGrammarFromJson('{"$type":"Grammar","isDeclared":true,"name":"RailroadAbnfGrammar","rules":[{"$type":"TerminalRule","name":"TITLE","definition":{"$type":"RegexToken","regex":"/title(?:[\\\\t ][^\\\\n\\\\r]*?(?=%%)|[\\\\t ][^\\\\n\\\\r]*|)/","parenthesized":false},"fragment":false,"hidden":false},{"$type":"TerminalRule","name":"ACC_TITLE","definition":{"$type":"RegexToken","regex":"/accTitle[\\\\t ]*:(?:[^\\\\n\\\\r]*?(?=%%)|[^\\\\n\\\\r]*)/","parenthesized":false},"fragment":false,"hidden":false},{"$type":"TerminalRule","name":"ACC_DESCR","definition":{"$type":"RegexToken","regex":"/accDescr(?:[\\\\t ]*:([^\\\\n\\\\r]*?(?=%%)|[^\\\\n\\\\r]*)|\\\\s*{([^}]*)})/","parenthesized":false},"fragment":false,"hidden":false},{"$type":"TerminalRule","name":"ABNF_RULENAME","type":{"$type":"ReturnType","name":"string"},"definition":{"$type":"RegexToken","regex":"/[A-Za-z][A-Za-z0-9-]*/","parenthesized":false},"fragment":false,"hidden":false},{"$type":"TerminalRule","name":"ABNF_STRING","type":{"$type":"ReturnType","name":"string"},"definition":{"$type":"RegexToken","regex":"/\\"[^\\"]*\\"/","parenthesized":false},"fragment":false,"hidden":false},{"$type":"TerminalRule","name":"ABNF_NUMVAL","type":{"$type":"ReturnType","name":"string"},"definition":{"$type":"RegexToken","regex":"/%[xXdDbB][0-9A-Fa-f]+(?:-[0-9A-Fa-f]+|\\\\.[0-9A-Fa-f]+)*/","parenthesized":false},"fragment":false,"hidden":false},{"$type":"TerminalRule","name":"ABNF_REPEAT","type":{"$type":"ReturnType","name":"string"},"definition":{"$type":"RegexToken","regex":"/[0-9]*\\\\*[0-9]*/","parenthesized":false},"fragment":false,"hidden":false},{"$type":"TerminalRule","name":"ABNF_EXACT_REPEAT","type":{"$type":"ReturnType","name":"string"},"definition":{"$type":"RegexToken","regex":"/[0-9]+/","parenthesized":false},"fragment":false,"hidden":false},{"$type":"TerminalRule","hidden":true,"name":"ABNF_WHITESPACE","definition":{"$type":"RegexToken","regex":"/[\\\\t \\\\r\\\\n]+/","parenthesized":false},"fragment":false},{"$type":"TerminalRule","hidden":true,"name":"ABNF_YAML","definition":{"$type":"RegexToken","regex":"/---[\\\\t ]*\\\\r?\\\\n(?:[\\\\S\\\\s]*?\\\\r?\\\\n)?---(?:\\\\r?\\\\n|(?!\\\\S))/","parenthesized":false},"fragment":false},{"$type":"TerminalRule","hidden":true,"name":"ABNF_DIRECTIVE","definition":{"$type":"RegexToken","regex":"/[\\\\t ]*%%{[\\\\S\\\\s]*?}%%(?:\\\\r?\\\\n|(?!\\\\S))/","parenthesized":false},"fragment":false},{"$type":"TerminalRule","hidden":true,"name":"ABNF_SINGLE_LINE_COMMENT","definition":{"$type":"RegexToken","regex":"/[\\\\t ]*%%[^\\\\n\\\\r]*/","parenthesized":false},"fragment":false},{"$type":"TerminalRule","hidden":true,"name":"ABNF_COMMENT","definition":{"$type":"RegexToken","regex":"/;[^\\\\n\\\\r]*/","parenthesized":false},"fragment":false},{"$type":"ParserRule","entry":true,"name":"RailroadAbnf","returnType":{"$ref":"#/interfaces@0"},"definition":{"$type":"Group","elements":[{"$type":"Keyword","value":"railroad-abnf-beta"},{"$type":"Alternatives","elements":[{"$type":"Assignment","feature":"title","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@0"},"arguments":[]}},{"$type":"Assignment","feature":"accTitle","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@1"},"arguments":[]}},{"$type":"Assignment","feature":"accDescr","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@2"},"arguments":[]}}],"cardinality":"*"},{"$type":"Assignment","feature":"rules","operator":"+=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@14"},"arguments":[]},"cardinality":"*"}]},"fragment":false,"parameters":[]},{"$type":"ParserRule","name":"AbnfRule","returnType":{"$ref":"#/interfaces@1"},"definition":{"$type":"Group","elements":[{"$type":"Assignment","feature":"name","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@3"},"arguments":[]}},{"$type":"Keyword","value":"="},{"$type":"Assignment","feature":"definition","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@15"},"arguments":[]}},{"$type":"Keyword","value":";"}]},"entry":false,"fragment":false,"parameters":[]},{"$type":"ParserRule","name":"AbnfAlternation","returnType":{"$ref":"#/interfaces@2"},"definition":{"$type":"Group","elements":[{"$type":"Assignment","feature":"alternatives","operator":"+=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@16"},"arguments":[]}},{"$type":"Group","elements":[{"$type":"Keyword","value":"/"},{"$type":"Assignment","feature":"alternatives","operator":"+=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@16"},"arguments":[]}}],"cardinality":"*"}]},"entry":false,"fragment":false,"parameters":[]},{"$type":"ParserRule","name":"AbnfConcatenation","returnType":{"$ref":"#/interfaces@3"},"definition":{"$type":"Assignment","feature":"elements","operator":"+=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@17"},"arguments":[]},"cardinality":"+"},"entry":false,"fragment":false,"parameters":[]},{"$type":"ParserRule","name":"AbnfElement","returnType":{"$ref":"#/interfaces@4"},"definition":{"$type":"Group","elements":[{"$type":"Alternatives","elements":[{"$type":"Assignment","feature":"repeat","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@6"},"arguments":[]}},{"$type":"Assignment","feature":"repeat","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@7"},"arguments":[]}}],"cardinality":"?"},{"$type":"Assignment","feature":"primary","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@18"},"arguments":[]}}]},"entry":false,"fragment":false,"parameters":[]},{"$type":"ParserRule","name":"AbnfPrimary","returnType":{"$ref":"#/interfaces@5"},"definition":{"$type":"Alternatives","elements":[{"$type":"RuleCall","rule":{"$ref":"#/rules@19"},"arguments":[]},{"$type":"RuleCall","rule":{"$ref":"#/rules@20"},"arguments":[]},{"$type":"RuleCall","rule":{"$ref":"#/rules@21"},"arguments":[]},{"$type":"RuleCall","rule":{"$ref":"#/rules@22"},"arguments":[]},{"$type":"RuleCall","rule":{"$ref":"#/rules@23"},"arguments":[]}]},"entry":false,"fragment":false,"parameters":[]},{"$type":"ParserRule","name":"AbnfStringLiteral","returnType":{"$ref":"#/interfaces@6"},"definition":{"$type":"Assignment","feature":"value","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@4"},"arguments":[]}},"entry":false,"fragment":false,"parameters":[]},{"$type":"ParserRule","name":"AbnfNumVal","returnType":{"$ref":"#/interfaces@7"},"definition":{"$type":"Assignment","feature":"value","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@5"},"arguments":[]}},"entry":false,"fragment":false,"parameters":[]},{"$type":"ParserRule","name":"AbnfRuleName","returnType":{"$ref":"#/interfaces@8"},"definition":{"$type":"Assignment","feature":"name","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@3"},"arguments":[]}},"entry":false,"fragment":false,"parameters":[]},{"$type":"ParserRule","name":"AbnfGroup","returnType":{"$ref":"#/interfaces@9"},"definition":{"$type":"Group","elements":[{"$type":"Keyword","value":"("},{"$type":"Assignment","feature":"element","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@15"},"arguments":[]}},{"$type":"Keyword","value":")"}]},"entry":false,"fragment":false,"parameters":[]},{"$type":"ParserRule","name":"AbnfOptionalGroup","returnType":{"$ref":"#/interfaces@10"},"definition":{"$type":"Group","elements":[{"$type":"Keyword","value":"["},{"$type":"Assignment","feature":"element","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@15"},"arguments":[]}},{"$type":"Keyword","value":"]"}]},"entry":false,"fragment":false,"parameters":[]}],"interfaces":[{"$type":"Interface","name":"RailroadAbnf","attributes":[{"$type":"TypeAttribute","name":"title","isOptional":true,"type":{"$type":"SimpleType","primitiveType":"string"}},{"$type":"TypeAttribute","name":"accTitle","isOptional":true,"type":{"$type":"SimpleType","primitiveType":"string"}},{"$type":"TypeAttribute","name":"accDescr","isOptional":true,"type":{"$type":"SimpleType","primitiveType":"string"}},{"$type":"TypeAttribute","name":"rules","type":{"$type":"ArrayType","elementType":{"$type":"SimpleType","typeRef":{"$ref":"#/interfaces@1"}}},"isOptional":false}],"superTypes":[]},{"$type":"Interface","name":"AbnfRule","attributes":[{"$type":"TypeAttribute","name":"name","type":{"$type":"SimpleType","primitiveType":"string"},"isOptional":false},{"$type":"TypeAttribute","name":"definition","type":{"$type":"SimpleType","typeRef":{"$ref":"#/interfaces@2"}},"isOptional":false}],"superTypes":[]},{"$type":"Interface","name":"AbnfAlternation","attributes":[{"$type":"TypeAttribute","name":"alternatives","type":{"$type":"ArrayType","elementType":{"$type":"SimpleType","typeRef":{"$ref":"#/interfaces@3"}}},"isOptional":false}],"superTypes":[]},{"$type":"Interface","name":"AbnfConcatenation","attributes":[{"$type":"TypeAttribute","name":"elements","type":{"$type":"ArrayType","elementType":{"$type":"SimpleType","typeRef":{"$ref":"#/interfaces@4"}}},"isOptional":false}],"superTypes":[]},{"$type":"Interface","name":"AbnfElement","attributes":[{"$type":"TypeAttribute","name":"repeat","isOptional":true,"type":{"$type":"SimpleType","primitiveType":"string"}},{"$type":"TypeAttribute","name":"primary","type":{"$type":"SimpleType","typeRef":{"$ref":"#/interfaces@5"}},"isOptional":false}],"superTypes":[]},{"$type":"Interface","name":"AbnfPrimary","attributes":[],"superTypes":[]},{"$type":"Interface","name":"AbnfStringLiteral","superTypes":[{"$ref":"#/interfaces@5"}],"attributes":[{"$type":"TypeAttribute","name":"value","type":{"$type":"SimpleType","primitiveType":"string"},"isOptional":false}]},{"$type":"Interface","name":"AbnfNumVal","superTypes":[{"$ref":"#/interfaces@5"}],"attributes":[{"$type":"TypeAttribute","name":"value","type":{"$type":"SimpleType","primitiveType":"string"},"isOptional":false}]},{"$type":"Interface","name":"AbnfRuleName","superTypes":[{"$ref":"#/interfaces@5"}],"attributes":[{"$type":"TypeAttribute","name":"name","type":{"$type":"SimpleType","primitiveType":"string"},"isOptional":false}]},{"$type":"Interface","name":"AbnfGroup","superTypes":[{"$ref":"#/interfaces@5"}],"attributes":[{"$type":"TypeAttribute","name":"element","type":{"$type":"SimpleType","typeRef":{"$ref":"#/interfaces@2"}},"isOptional":false}]},{"$type":"Interface","name":"AbnfOptionalGroup","superTypes":[{"$ref":"#/interfaces@5"}],"attributes":[{"$type":"TypeAttribute","name":"element","type":{"$type":"SimpleType","typeRef":{"$ref":"#/interfaces@2"}},"isOptional":false}]}],"imports":[],"types":[]}')), "RailroadAbnfGrammarGrammar");
var loadedRailroadEbnfGrammarGrammar;
var RailroadEbnfGrammarGrammar = /* @__PURE__ */ __name2(() => loadedRailroadEbnfGrammarGrammar ?? (loadedRailroadEbnfGrammarGrammar = loadGrammarFromJson(`{"$type":"Grammar","isDeclared":true,"name":"RailroadEbnfGrammar","rules":[{"$type":"TerminalRule","name":"TITLE","definition":{"$type":"RegexToken","regex":"/title(?:[\\\\t ][^\\\\n\\\\r]*?(?=%%)|[\\\\t ][^\\\\n\\\\r]*|)/","parenthesized":false},"fragment":false,"hidden":false},{"$type":"TerminalRule","name":"ACC_TITLE","definition":{"$type":"RegexToken","regex":"/accTitle[\\\\t ]*:(?:[^\\\\n\\\\r]*?(?=%%)|[^\\\\n\\\\r]*)/","parenthesized":false},"fragment":false,"hidden":false},{"$type":"TerminalRule","name":"ACC_DESCR","definition":{"$type":"RegexToken","regex":"/accDescr(?:[\\\\t ]*:([^\\\\n\\\\r]*?(?=%%)|[^\\\\n\\\\r]*)|\\\\s*{([^}]*)})/","parenthesized":false},"fragment":false,"hidden":false},{"$type":"TerminalRule","name":"EBNF_ID","type":{"$type":"ReturnType","name":"string"},"definition":{"$type":"RegexToken","regex":"/[A-Z_a-z][\\\\w-]*/","parenthesized":false},"fragment":false,"hidden":false},{"$type":"TerminalRule","name":"EBNF_STRING","type":{"$type":"ReturnType","name":"string"},"definition":{"$type":"RegexToken","regex":"/\\"([^\\"\\\\\\\\]|\\\\\\\\.)*\\"|'([^'\\\\\\\\]|\\\\\\\\.)*'/","parenthesized":false},"fragment":false,"hidden":false},{"$type":"TerminalRule","name":"EBNF_SPECIAL_SEQUENCE","type":{"$type":"ReturnType","name":"string"},"definition":{"$type":"RegexToken","regex":"/\\\\?(?=[^?;]*[^?\\\\s;][^?;]*\\\\?)[^?;]*\\\\?/","parenthesized":false},"fragment":false,"hidden":false},{"$type":"TerminalRule","hidden":true,"name":"EBNF_WHITESPACE","definition":{"$type":"RegexToken","regex":"/[\\\\t \\\\r\\\\n]+/","parenthesized":false},"fragment":false},{"$type":"TerminalRule","hidden":true,"name":"EBNF_YAML","definition":{"$type":"RegexToken","regex":"/---[\\\\t ]*\\\\r?\\\\n(?:[\\\\S\\\\s]*?\\\\r?\\\\n)?---(?:\\\\r?\\\\n|(?!\\\\S))/","parenthesized":false},"fragment":false},{"$type":"TerminalRule","hidden":true,"name":"EBNF_DIRECTIVE","definition":{"$type":"RegexToken","regex":"/[\\\\t ]*%%{[\\\\S\\\\s]*?}%%(?:\\\\r?\\\\n|(?!\\\\S))/","parenthesized":false},"fragment":false},{"$type":"TerminalRule","hidden":true,"name":"EBNF_SINGLE_LINE_COMMENT","definition":{"$type":"RegexToken","regex":"/[\\\\t ]*%%[^\\\\n\\\\r]*/","parenthesized":false},"fragment":false},{"$type":"TerminalRule","hidden":true,"name":"EBNF_BLOCK_COMMENT","definition":{"$type":"RegexToken","regex":"/\\\\/\\\\*[\\\\s\\\\S]*?\\\\*\\\\//","parenthesized":false},"fragment":false},{"$type":"TerminalRule","hidden":true,"name":"EBNF_ISO_COMMENT","definition":{"$type":"RegexToken","regex":"/\\\\(\\\\*[\\\\s\\\\S]*?\\\\*\\\\)/","parenthesized":false},"fragment":false},{"$type":"ParserRule","entry":true,"name":"RailroadEbnf","returnType":{"$ref":"#/interfaces@0"},"definition":{"$type":"Group","elements":[{"$type":"Keyword","value":"railroad-ebnf-beta"},{"$type":"Alternatives","elements":[{"$type":"Assignment","feature":"title","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@0"},"arguments":[]}},{"$type":"Assignment","feature":"accTitle","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@1"},"arguments":[]}},{"$type":"Assignment","feature":"accDescr","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@2"},"arguments":[]}}],"cardinality":"*"},{"$type":"Assignment","feature":"rules","operator":"+=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@13"},"arguments":[]},"cardinality":"*"}]},"fragment":false,"parameters":[]},{"$type":"ParserRule","name":"EbnfRule","returnType":{"$ref":"#/interfaces@1"},"definition":{"$type":"Group","elements":[{"$type":"Assignment","feature":"name","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@3"},"arguments":[]}},{"$type":"Alternatives","elements":[{"$type":"Keyword","value":"="},{"$type":"Keyword","value":"::="}]},{"$type":"Assignment","feature":"definition","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@14"},"arguments":[]}},{"$type":"Keyword","value":";"}]},"entry":false,"fragment":false,"parameters":[]},{"$type":"ParserRule","name":"EbnfChoice","returnType":{"$ref":"#/interfaces@2"},"definition":{"$type":"Group","elements":[{"$type":"Assignment","feature":"alternatives","operator":"+=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@15"},"arguments":[]}},{"$type":"Group","elements":[{"$type":"Keyword","value":"|"},{"$type":"Assignment","feature":"alternatives","operator":"+=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@15"},"arguments":[]}}],"cardinality":"*"}]},"entry":false,"fragment":false,"parameters":[]},{"$type":"ParserRule","name":"EbnfSequence","returnType":{"$ref":"#/interfaces@3"},"definition":{"$type":"Group","elements":[{"$type":"Assignment","feature":"elements","operator":"+=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@16"},"arguments":[]}},{"$type":"Group","elements":[{"$type":"Keyword","value":",","cardinality":"?"},{"$type":"Assignment","feature":"elements","operator":"+=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@16"},"arguments":[]}}],"cardinality":"*"}]},"entry":false,"fragment":false,"parameters":[]},{"$type":"ParserRule","name":"EbnfTerm","returnType":{"$ref":"#/interfaces@4"},"definition":{"$type":"Group","elements":[{"$type":"Assignment","feature":"base","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@17"},"arguments":[]}},{"$type":"Assignment","feature":"postfixes","operator":"+=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@24"},"arguments":[]},"cardinality":"*"}]},"entry":false,"fragment":false,"parameters":[]},{"$type":"ParserRule","name":"EbnfPrimary","returnType":{"$ref":"#/interfaces@5"},"definition":{"$type":"Alternatives","elements":[{"$type":"RuleCall","rule":{"$ref":"#/rules@18"},"arguments":[]},{"$type":"RuleCall","rule":{"$ref":"#/rules@20"},"arguments":[]},{"$type":"RuleCall","rule":{"$ref":"#/rules@19"},"arguments":[]},{"$type":"RuleCall","rule":{"$ref":"#/rules@21"},"arguments":[]},{"$type":"RuleCall","rule":{"$ref":"#/rules@22"},"arguments":[]},{"$type":"RuleCall","rule":{"$ref":"#/rules@23"},"arguments":[]}]},"entry":false,"fragment":false,"parameters":[]},{"$type":"ParserRule","name":"EbnfTerminal","returnType":{"$ref":"#/interfaces@7"},"definition":{"$type":"Assignment","feature":"value","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@4"},"arguments":[]}},"entry":false,"fragment":false,"parameters":[]},{"$type":"ParserRule","name":"EbnfNonTerminal","returnType":{"$ref":"#/interfaces@8"},"definition":{"$type":"Assignment","feature":"name","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@3"},"arguments":[]}},"entry":false,"fragment":false,"parameters":[]},{"$type":"ParserRule","name":"EbnfSpecial","returnType":{"$ref":"#/interfaces@9"},"definition":{"$type":"Assignment","feature":"text","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@5"},"arguments":[]}},"entry":false,"fragment":false,"parameters":[]},{"$type":"ParserRule","name":"EbnfGroup","returnType":{"$ref":"#/interfaces@10"},"definition":{"$type":"Group","elements":[{"$type":"Keyword","value":"("},{"$type":"Assignment","feature":"element","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@14"},"arguments":[]}},{"$type":"Keyword","value":")"}]},"entry":false,"fragment":false,"parameters":[]},{"$type":"ParserRule","name":"EbnfOptional","returnType":{"$ref":"#/interfaces@11"},"definition":{"$type":"Group","elements":[{"$type":"Keyword","value":"["},{"$type":"Assignment","feature":"element","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@14"},"arguments":[]}},{"$type":"Keyword","value":"]"}]},"entry":false,"fragment":false,"parameters":[]},{"$type":"ParserRule","name":"EbnfRepetition","returnType":{"$ref":"#/interfaces@12"},"definition":{"$type":"Group","elements":[{"$type":"Keyword","value":"{"},{"$type":"Assignment","feature":"element","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@14"},"arguments":[]}},{"$type":"Keyword","value":"}"}]},"entry":false,"fragment":false,"parameters":[]},{"$type":"ParserRule","name":"EbnfPostfix","returnType":{"$ref":"#/interfaces@6"},"definition":{"$type":"Alternatives","elements":[{"$type":"RuleCall","rule":{"$ref":"#/rules@25"},"arguments":[]},{"$type":"RuleCall","rule":{"$ref":"#/rules@26"},"arguments":[]},{"$type":"RuleCall","rule":{"$ref":"#/rules@27"},"arguments":[]},{"$type":"RuleCall","rule":{"$ref":"#/rules@28"},"arguments":[]}]},"entry":false,"fragment":false,"parameters":[]},{"$type":"ParserRule","name":"EbnfOptionalPostfix","returnType":{"$ref":"#/interfaces@13"},"definition":{"$type":"Assignment","feature":"operator","operator":"=","terminal":{"$type":"Keyword","value":"?"}},"entry":false,"fragment":false,"parameters":[]},{"$type":"ParserRule","name":"EbnfZeroOrMorePostfix","returnType":{"$ref":"#/interfaces@14"},"definition":{"$type":"Assignment","feature":"operator","operator":"=","terminal":{"$type":"Keyword","value":"*"}},"entry":false,"fragment":false,"parameters":[]},{"$type":"ParserRule","name":"EbnfOneOrMorePostfix","returnType":{"$ref":"#/interfaces@15"},"definition":{"$type":"Assignment","feature":"operator","operator":"=","terminal":{"$type":"Keyword","value":"+"}},"entry":false,"fragment":false,"parameters":[]},{"$type":"ParserRule","name":"EbnfExceptionPostfix","returnType":{"$ref":"#/interfaces@16"},"definition":{"$type":"Group","elements":[{"$type":"Keyword","value":"-"},{"$type":"Assignment","feature":"except","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@17"},"arguments":[]}}]},"entry":false,"fragment":false,"parameters":[]}],"interfaces":[{"$type":"Interface","name":"RailroadEbnf","attributes":[{"$type":"TypeAttribute","name":"title","isOptional":true,"type":{"$type":"SimpleType","primitiveType":"string"}},{"$type":"TypeAttribute","name":"accTitle","isOptional":true,"type":{"$type":"SimpleType","primitiveType":"string"}},{"$type":"TypeAttribute","name":"accDescr","isOptional":true,"type":{"$type":"SimpleType","primitiveType":"string"}},{"$type":"TypeAttribute","name":"rules","type":{"$type":"ArrayType","elementType":{"$type":"SimpleType","typeRef":{"$ref":"#/interfaces@1"}}},"isOptional":false}],"superTypes":[]},{"$type":"Interface","name":"EbnfRule","attributes":[{"$type":"TypeAttribute","name":"name","type":{"$type":"SimpleType","primitiveType":"string"},"isOptional":false},{"$type":"TypeAttribute","name":"definition","type":{"$type":"SimpleType","typeRef":{"$ref":"#/interfaces@2"}},"isOptional":false}],"superTypes":[]},{"$type":"Interface","name":"EbnfChoice","attributes":[{"$type":"TypeAttribute","name":"alternatives","type":{"$type":"ArrayType","elementType":{"$type":"SimpleType","typeRef":{"$ref":"#/interfaces@3"}}},"isOptional":false}],"superTypes":[]},{"$type":"Interface","name":"EbnfSequence","attributes":[{"$type":"TypeAttribute","name":"elements","type":{"$type":"ArrayType","elementType":{"$type":"SimpleType","typeRef":{"$ref":"#/interfaces@4"}}},"isOptional":false}],"superTypes":[]},{"$type":"Interface","name":"EbnfTerm","attributes":[{"$type":"TypeAttribute","name":"base","type":{"$type":"SimpleType","typeRef":{"$ref":"#/interfaces@5"}},"isOptional":false},{"$type":"TypeAttribute","name":"postfixes","type":{"$type":"ArrayType","elementType":{"$type":"SimpleType","typeRef":{"$ref":"#/interfaces@6"}}},"isOptional":false}],"superTypes":[]},{"$type":"Interface","name":"EbnfPrimary","attributes":[],"superTypes":[]},{"$type":"Interface","name":"EbnfPostfix","attributes":[],"superTypes":[]},{"$type":"Interface","name":"EbnfTerminal","superTypes":[{"$ref":"#/interfaces@5"}],"attributes":[{"$type":"TypeAttribute","name":"value","type":{"$type":"SimpleType","primitiveType":"string"},"isOptional":false}]},{"$type":"Interface","name":"EbnfNonTerminal","superTypes":[{"$ref":"#/interfaces@5"}],"attributes":[{"$type":"TypeAttribute","name":"name","type":{"$type":"SimpleType","primitiveType":"string"},"isOptional":false}]},{"$type":"Interface","name":"EbnfSpecial","superTypes":[{"$ref":"#/interfaces@5"}],"attributes":[{"$type":"TypeAttribute","name":"text","type":{"$type":"SimpleType","primitiveType":"string"},"isOptional":false}]},{"$type":"Interface","name":"EbnfGroup","superTypes":[{"$ref":"#/interfaces@5"}],"attributes":[{"$type":"TypeAttribute","name":"element","type":{"$type":"SimpleType","typeRef":{"$ref":"#/interfaces@2"}},"isOptional":false}]},{"$type":"Interface","name":"EbnfOptional","superTypes":[{"$ref":"#/interfaces@5"}],"attributes":[{"$type":"TypeAttribute","name":"element","type":{"$type":"SimpleType","typeRef":{"$ref":"#/interfaces@2"}},"isOptional":false}]},{"$type":"Interface","name":"EbnfRepetition","superTypes":[{"$ref":"#/interfaces@5"}],"attributes":[{"$type":"TypeAttribute","name":"element","type":{"$type":"SimpleType","typeRef":{"$ref":"#/interfaces@2"}},"isOptional":false}]},{"$type":"Interface","name":"EbnfOptionalPostfix","superTypes":[{"$ref":"#/interfaces@6"}],"attributes":[{"$type":"TypeAttribute","name":"operator","type":{"$type":"SimpleType","primitiveType":"string"},"isOptional":false}]},{"$type":"Interface","name":"EbnfZeroOrMorePostfix","superTypes":[{"$ref":"#/interfaces@6"}],"attributes":[{"$type":"TypeAttribute","name":"operator","type":{"$type":"SimpleType","primitiveType":"string"},"isOptional":false}]},{"$type":"Interface","name":"EbnfOneOrMorePostfix","superTypes":[{"$ref":"#/interfaces@6"}],"attributes":[{"$type":"TypeAttribute","name":"operator","type":{"$type":"SimpleType","primitiveType":"string"},"isOptional":false}]},{"$type":"Interface","name":"EbnfExceptionPostfix","superTypes":[{"$ref":"#/interfaces@6"}],"attributes":[{"$type":"TypeAttribute","name":"except","type":{"$type":"SimpleType","typeRef":{"$ref":"#/interfaces@5"}},"isOptional":false}]}],"imports":[],"types":[]}`)), "RailroadEbnfGrammarGrammar");
var loadedRailroadGrammarGrammar;
var RailroadGrammarGrammar = /* @__PURE__ */ __name2(() => loadedRailroadGrammarGrammar ?? (loadedRailroadGrammarGrammar = loadGrammarFromJson(`{"$type":"Grammar","isDeclared":true,"name":"RailroadGrammar","rules":[{"$type":"TerminalRule","name":"TITLE","definition":{"$type":"RegexToken","regex":"/title(?:[\\\\t ][^\\\\n\\\\r]*?(?=%%)|[\\\\t ][^\\\\n\\\\r]*|)/","parenthesized":false},"fragment":false,"hidden":false},{"$type":"TerminalRule","name":"ACC_TITLE","definition":{"$type":"RegexToken","regex":"/accTitle[\\\\t ]*:(?:[^\\\\n\\\\r]*?(?=%%)|[^\\\\n\\\\r]*)/","parenthesized":false},"fragment":false,"hidden":false},{"$type":"TerminalRule","name":"ACC_DESCR","definition":{"$type":"RegexToken","regex":"/accDescr(?:[\\\\t ]*:([^\\\\n\\\\r]*?(?=%%)|[^\\\\n\\\\r]*)|\\\\s*{([^}]*)})/","parenthesized":false},"fragment":false,"hidden":false},{"$type":"TerminalRule","name":"RR_ID","type":{"$type":"ReturnType","name":"string"},"definition":{"$type":"RegexToken","regex":"/[A-Z_a-z][\\\\w-]*/","parenthesized":false},"fragment":false,"hidden":false},{"$type":"TerminalRule","name":"RR_STRING","type":{"$type":"ReturnType","name":"string"},"definition":{"$type":"RegexToken","regex":"/\\"([^\\"\\\\\\\\]|\\\\\\\\.)*\\"|'([^'\\\\\\\\]|\\\\\\\\.)*'/","parenthesized":false},"fragment":false,"hidden":false},{"$type":"TerminalRule","hidden":true,"name":"RR_WHITESPACE","definition":{"$type":"RegexToken","regex":"/[\\\\t \\\\r\\\\n]+/","parenthesized":false},"fragment":false},{"$type":"TerminalRule","hidden":true,"name":"RR_YAML","definition":{"$type":"RegexToken","regex":"/---[\\\\t ]*\\\\r?\\\\n(?:[\\\\S\\\\s]*?\\\\r?\\\\n)?---(?:\\\\r?\\\\n|(?!\\\\S))/","parenthesized":false},"fragment":false},{"$type":"TerminalRule","hidden":true,"name":"RR_DIRECTIVE","definition":{"$type":"RegexToken","regex":"/[\\\\t ]*%%{[\\\\S\\\\s]*?}%%(?:\\\\r?\\\\n|(?!\\\\S))/","parenthesized":false},"fragment":false},{"$type":"TerminalRule","hidden":true,"name":"RR_SINGLE_LINE_COMMENT","definition":{"$type":"RegexToken","regex":"/[\\\\t ]*%%[^\\\\n\\\\r]*/","parenthesized":false},"fragment":false},{"$type":"TerminalRule","hidden":true,"name":"RR_BLOCK_COMMENT","definition":{"$type":"RegexToken","regex":"/\\\\/\\\\*[\\\\s\\\\S]*?\\\\*\\\\//","parenthesized":false},"fragment":false},{"$type":"ParserRule","entry":true,"name":"Railroad","returnType":{"$ref":"#/interfaces@0"},"definition":{"$type":"Group","elements":[{"$type":"Keyword","value":"railroad-beta"},{"$type":"Alternatives","elements":[{"$type":"Assignment","feature":"title","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@0"},"arguments":[]}},{"$type":"Assignment","feature":"accTitle","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@1"},"arguments":[]}},{"$type":"Assignment","feature":"accDescr","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@2"},"arguments":[]}}],"cardinality":"*"},{"$type":"Assignment","feature":"rules","operator":"+=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@11"},"arguments":[]},"cardinality":"*"}]},"fragment":false,"parameters":[]},{"$type":"ParserRule","name":"RailroadRule","returnType":{"$ref":"#/interfaces@1"},"definition":{"$type":"Group","elements":[{"$type":"Assignment","feature":"name","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@3"},"arguments":[]}},{"$type":"Keyword","value":"="},{"$type":"Assignment","feature":"definition","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@12"},"arguments":[]}},{"$type":"Keyword","value":";"}]},"entry":false,"fragment":false,"parameters":[]},{"$type":"ParserRule","name":"RailroadExpression","returnType":{"$ref":"#/interfaces@2"},"definition":{"$type":"Alternatives","elements":[{"$type":"RuleCall","rule":{"$ref":"#/rules@13"},"arguments":[]},{"$type":"RuleCall","rule":{"$ref":"#/rules@14"},"arguments":[]},{"$type":"RuleCall","rule":{"$ref":"#/rules@15"},"arguments":[]},{"$type":"RuleCall","rule":{"$ref":"#/rules@16"},"arguments":[]},{"$type":"RuleCall","rule":{"$ref":"#/rules@17"},"arguments":[]},{"$type":"RuleCall","rule":{"$ref":"#/rules@18"},"arguments":[]},{"$type":"RuleCall","rule":{"$ref":"#/rules@19"},"arguments":[]},{"$type":"RuleCall","rule":{"$ref":"#/rules@20"},"arguments":[]}]},"entry":false,"fragment":false,"parameters":[]},{"$type":"ParserRule","name":"RailroadSequenceExpr","returnType":{"$ref":"#/interfaces@3"},"definition":{"$type":"Group","elements":[{"$type":"Keyword","value":"sequence"},{"$type":"Keyword","value":"("},{"$type":"Assignment","feature":"elements","operator":"+=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@12"},"arguments":[]}},{"$type":"Group","elements":[{"$type":"Keyword","value":","},{"$type":"Assignment","feature":"elements","operator":"+=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@12"},"arguments":[]}}],"cardinality":"*"},{"$type":"Keyword","value":")"}]},"entry":false,"fragment":false,"parameters":[]},{"$type":"ParserRule","name":"RailroadChoiceExpr","returnType":{"$ref":"#/interfaces@4"},"definition":{"$type":"Group","elements":[{"$type":"Keyword","value":"choice"},{"$type":"Keyword","value":"("},{"$type":"Assignment","feature":"alternatives","operator":"+=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@12"},"arguments":[]}},{"$type":"Group","elements":[{"$type":"Keyword","value":","},{"$type":"Assignment","feature":"alternatives","operator":"+=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@12"},"arguments":[]}}],"cardinality":"*"},{"$type":"Keyword","value":")"}]},"entry":false,"fragment":false,"parameters":[]},{"$type":"ParserRule","name":"RailroadOptionalExpr","returnType":{"$ref":"#/interfaces@5"},"definition":{"$type":"Group","elements":[{"$type":"Keyword","value":"optional"},{"$type":"Keyword","value":"("},{"$type":"Assignment","feature":"element","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@12"},"arguments":[]}},{"$type":"Keyword","value":")"}]},"entry":false,"fragment":false,"parameters":[]},{"$type":"ParserRule","name":"RailroadOneOrMoreExpr","returnType":{"$ref":"#/interfaces@6"},"definition":{"$type":"Group","elements":[{"$type":"Keyword","value":"oneOrMore"},{"$type":"Keyword","value":"("},{"$type":"Assignment","feature":"element","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@12"},"arguments":[]}},{"$type":"Keyword","value":")"}]},"entry":false,"fragment":false,"parameters":[]},{"$type":"ParserRule","name":"RailroadZeroOrMoreExpr","returnType":{"$ref":"#/interfaces@7"},"definition":{"$type":"Group","elements":[{"$type":"Keyword","value":"zeroOrMore"},{"$type":"Keyword","value":"("},{"$type":"Assignment","feature":"element","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@12"},"arguments":[]}},{"$type":"Keyword","value":")"}]},"entry":false,"fragment":false,"parameters":[]},{"$type":"ParserRule","name":"RailroadTerminalExpr","returnType":{"$ref":"#/interfaces@8"},"definition":{"$type":"Group","elements":[{"$type":"Keyword","value":"terminal"},{"$type":"Keyword","value":"("},{"$type":"Assignment","feature":"value","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@4"},"arguments":[]}},{"$type":"Keyword","value":")"}]},"entry":false,"fragment":false,"parameters":[]},{"$type":"ParserRule","name":"RailroadNonTerminalExpr","returnType":{"$ref":"#/interfaces@9"},"definition":{"$type":"Group","elements":[{"$type":"Keyword","value":"nonterminal"},{"$type":"Keyword","value":"("},{"$type":"Assignment","feature":"name","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@4"},"arguments":[]}},{"$type":"Keyword","value":")"}]},"entry":false,"fragment":false,"parameters":[]},{"$type":"ParserRule","name":"RailroadSpecialExpr","returnType":{"$ref":"#/interfaces@10"},"definition":{"$type":"Group","elements":[{"$type":"Keyword","value":"special"},{"$type":"Keyword","value":"("},{"$type":"Assignment","feature":"text","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@4"},"arguments":[]}},{"$type":"Keyword","value":")"}]},"entry":false,"fragment":false,"parameters":[]}],"interfaces":[{"$type":"Interface","name":"Railroad","attributes":[{"$type":"TypeAttribute","name":"title","isOptional":true,"type":{"$type":"SimpleType","primitiveType":"string"}},{"$type":"TypeAttribute","name":"accTitle","isOptional":true,"type":{"$type":"SimpleType","primitiveType":"string"}},{"$type":"TypeAttribute","name":"accDescr","isOptional":true,"type":{"$type":"SimpleType","primitiveType":"string"}},{"$type":"TypeAttribute","name":"rules","type":{"$type":"ArrayType","elementType":{"$type":"SimpleType","typeRef":{"$ref":"#/interfaces@1"}}},"isOptional":false}],"superTypes":[]},{"$type":"Interface","name":"RailroadRule","attributes":[{"$type":"TypeAttribute","name":"name","type":{"$type":"SimpleType","primitiveType":"string"},"isOptional":false},{"$type":"TypeAttribute","name":"definition","type":{"$type":"SimpleType","typeRef":{"$ref":"#/interfaces@2"}},"isOptional":false}],"superTypes":[]},{"$type":"Interface","name":"RailroadExpression","attributes":[],"superTypes":[]},{"$type":"Interface","name":"RailroadSequenceExpr","superTypes":[{"$ref":"#/interfaces@2"}],"attributes":[{"$type":"TypeAttribute","name":"elements","type":{"$type":"ArrayType","elementType":{"$type":"SimpleType","typeRef":{"$ref":"#/interfaces@2"}}},"isOptional":false}]},{"$type":"Interface","name":"RailroadChoiceExpr","superTypes":[{"$ref":"#/interfaces@2"}],"attributes":[{"$type":"TypeAttribute","name":"alternatives","type":{"$type":"ArrayType","elementType":{"$type":"SimpleType","typeRef":{"$ref":"#/interfaces@2"}}},"isOptional":false}]},{"$type":"Interface","name":"RailroadOptionalExpr","superTypes":[{"$ref":"#/interfaces@2"}],"attributes":[{"$type":"TypeAttribute","name":"element","type":{"$type":"SimpleType","typeRef":{"$ref":"#/interfaces@2"}},"isOptional":false}]},{"$type":"Interface","name":"RailroadOneOrMoreExpr","superTypes":[{"$ref":"#/interfaces@2"}],"attributes":[{"$type":"TypeAttribute","name":"element","type":{"$type":"SimpleType","typeRef":{"$ref":"#/interfaces@2"}},"isOptional":false}]},{"$type":"Interface","name":"RailroadZeroOrMoreExpr","superTypes":[{"$ref":"#/interfaces@2"}],"attributes":[{"$type":"TypeAttribute","name":"element","type":{"$type":"SimpleType","typeRef":{"$ref":"#/interfaces@2"}},"isOptional":false}]},{"$type":"Interface","name":"RailroadTerminalExpr","superTypes":[{"$ref":"#/interfaces@2"}],"attributes":[{"$type":"TypeAttribute","name":"value","type":{"$type":"SimpleType","primitiveType":"string"},"isOptional":false}]},{"$type":"Interface","name":"RailroadNonTerminalExpr","superTypes":[{"$ref":"#/interfaces@2"}],"attributes":[{"$type":"TypeAttribute","name":"name","type":{"$type":"SimpleType","primitiveType":"string"},"isOptional":false}]},{"$type":"Interface","name":"RailroadSpecialExpr","superTypes":[{"$ref":"#/interfaces@2"}],"attributes":[{"$type":"TypeAttribute","name":"text","type":{"$type":"SimpleType","primitiveType":"string"},"isOptional":false}]}],"imports":[],"types":[]}`)), "RailroadGrammarGrammar");
var loadedRailroadPegGrammarGrammar;
var RailroadPegGrammarGrammar = /* @__PURE__ */ __name2(() => loadedRailroadPegGrammarGrammar ?? (loadedRailroadPegGrammarGrammar = loadGrammarFromJson(`{"$type":"Grammar","isDeclared":true,"name":"RailroadPegGrammar","rules":[{"$type":"TerminalRule","name":"TITLE","definition":{"$type":"RegexToken","regex":"/title(?:[\\\\t ][^\\\\n\\\\r]*?(?=%%)|[\\\\t ][^\\\\n\\\\r]*|)/","parenthesized":false},"fragment":false,"hidden":false},{"$type":"TerminalRule","name":"ACC_TITLE","definition":{"$type":"RegexToken","regex":"/accTitle[\\\\t ]*:(?:[^\\\\n\\\\r]*?(?=%%)|[^\\\\n\\\\r]*)/","parenthesized":false},"fragment":false,"hidden":false},{"$type":"TerminalRule","name":"ACC_DESCR","definition":{"$type":"RegexToken","regex":"/accDescr(?:[\\\\t ]*:([^\\\\n\\\\r]*?(?=%%)|[^\\\\n\\\\r]*)|\\\\s*{([^}]*)})/","parenthesized":false},"fragment":false,"hidden":false},{"$type":"TerminalRule","name":"PEG_ID","type":{"$type":"ReturnType","name":"string"},"definition":{"$type":"RegexToken","regex":"/[A-Z_a-z][\\\\w-]*/","parenthesized":false},"fragment":false,"hidden":false},{"$type":"TerminalRule","name":"PEG_STRING","type":{"$type":"ReturnType","name":"string"},"definition":{"$type":"RegexToken","regex":"/\\"([^\\"\\\\\\\\]|\\\\\\\\.)*\\"|'([^'\\\\\\\\]|\\\\\\\\.)*'/","parenthesized":false},"fragment":false,"hidden":false},{"$type":"TerminalRule","hidden":true,"name":"PEG_WHITESPACE","definition":{"$type":"RegexToken","regex":"/[\\\\t \\\\r\\\\n]+/","parenthesized":false},"fragment":false},{"$type":"TerminalRule","hidden":true,"name":"PEG_YAML","definition":{"$type":"RegexToken","regex":"/---[\\\\t ]*\\\\r?\\\\n(?:[\\\\S\\\\s]*?\\\\r?\\\\n)?---(?:\\\\r?\\\\n|(?!\\\\S))/","parenthesized":false},"fragment":false},{"$type":"TerminalRule","hidden":true,"name":"PEG_DIRECTIVE","definition":{"$type":"RegexToken","regex":"/[\\\\t ]*%%{[\\\\S\\\\s]*?}%%(?:\\\\r?\\\\n|(?!\\\\S))/","parenthesized":false},"fragment":false},{"$type":"TerminalRule","hidden":true,"name":"PEG_SINGLE_LINE_COMMENT","definition":{"$type":"RegexToken","regex":"/[\\\\t ]*%%[^\\\\n\\\\r]*/","parenthesized":false},"fragment":false},{"$type":"TerminalRule","hidden":true,"name":"PEG_LINE_COMMENT","definition":{"$type":"RegexToken","regex":"/#[^\\\\n\\\\r]*/","parenthesized":false},"fragment":false},{"$type":"ParserRule","entry":true,"name":"RailroadPeg","returnType":{"$ref":"#/interfaces@0"},"definition":{"$type":"Group","elements":[{"$type":"Keyword","value":"railroad-peg-beta"},{"$type":"Alternatives","elements":[{"$type":"Assignment","feature":"title","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@0"},"arguments":[]}},{"$type":"Assignment","feature":"accTitle","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@1"},"arguments":[]}},{"$type":"Assignment","feature":"accDescr","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@2"},"arguments":[]}}],"cardinality":"*"},{"$type":"Assignment","feature":"rules","operator":"+=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@11"},"arguments":[]},"cardinality":"*"}]},"fragment":false,"parameters":[]},{"$type":"ParserRule","name":"PegRule","returnType":{"$ref":"#/interfaces@1"},"definition":{"$type":"Group","elements":[{"$type":"Assignment","feature":"name","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@3"},"arguments":[]}},{"$type":"Keyword","value":"<-"},{"$type":"Assignment","feature":"definition","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@12"},"arguments":[]}},{"$type":"Keyword","value":";"}]},"entry":false,"fragment":false,"parameters":[]},{"$type":"ParserRule","name":"PegOrderedChoice","returnType":{"$ref":"#/interfaces@2"},"definition":{"$type":"Group","elements":[{"$type":"Assignment","feature":"alternatives","operator":"+=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@13"},"arguments":[]}},{"$type":"Group","elements":[{"$type":"Keyword","value":"/"},{"$type":"Assignment","feature":"alternatives","operator":"+=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@13"},"arguments":[]}}],"cardinality":"*"}]},"entry":false,"fragment":false,"parameters":[]},{"$type":"ParserRule","name":"PegSequence","returnType":{"$ref":"#/interfaces@3"},"definition":{"$type":"Assignment","feature":"elements","operator":"+=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@14"},"arguments":[]},"cardinality":"+"},"entry":false,"fragment":false,"parameters":[]},{"$type":"ParserRule","name":"PegPrefix","returnType":{"$ref":"#/interfaces@4"},"definition":{"$type":"Group","elements":[{"$type":"Alternatives","elements":[{"$type":"Assignment","feature":"operator","operator":"=","terminal":{"$type":"Keyword","value":"&"}},{"$type":"Assignment","feature":"operator","operator":"=","terminal":{"$type":"Keyword","value":"!"}}],"cardinality":"?"},{"$type":"Assignment","feature":"suffix","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@15"},"arguments":[]}}]},"entry":false,"fragment":false,"parameters":[]},{"$type":"ParserRule","name":"PegSuffix","returnType":{"$ref":"#/interfaces@5"},"definition":{"$type":"Group","elements":[{"$type":"Assignment","feature":"primary","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@16"},"arguments":[]}},{"$type":"Alternatives","elements":[{"$type":"Assignment","feature":"operator","operator":"=","terminal":{"$type":"Keyword","value":"?"}},{"$type":"Assignment","feature":"operator","operator":"=","terminal":{"$type":"Keyword","value":"*"}},{"$type":"Assignment","feature":"operator","operator":"=","terminal":{"$type":"Keyword","value":"+"}}],"cardinality":"?"}]},"entry":false,"fragment":false,"parameters":[]},{"$type":"ParserRule","name":"PegPrimary","returnType":{"$ref":"#/interfaces@6"},"definition":{"$type":"Alternatives","elements":[{"$type":"RuleCall","rule":{"$ref":"#/rules@17"},"arguments":[]},{"$type":"RuleCall","rule":{"$ref":"#/rules@18"},"arguments":[]},{"$type":"RuleCall","rule":{"$ref":"#/rules@19"},"arguments":[]},{"$type":"RuleCall","rule":{"$ref":"#/rules@20"},"arguments":[]}]},"entry":false,"fragment":false,"parameters":[]},{"$type":"ParserRule","name":"PegLiteral","returnType":{"$ref":"#/interfaces@7"},"definition":{"$type":"Assignment","feature":"value","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@4"},"arguments":[]}},"entry":false,"fragment":false,"parameters":[]},{"$type":"ParserRule","name":"PegIdentifier","returnType":{"$ref":"#/interfaces@8"},"definition":{"$type":"Assignment","feature":"name","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@3"},"arguments":[]}},"entry":false,"fragment":false,"parameters":[]},{"$type":"ParserRule","name":"PegGroup","returnType":{"$ref":"#/interfaces@9"},"definition":{"$type":"Group","elements":[{"$type":"Keyword","value":"("},{"$type":"Assignment","feature":"element","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@12"},"arguments":[]}},{"$type":"Keyword","value":")"}]},"entry":false,"fragment":false,"parameters":[]},{"$type":"ParserRule","name":"PegAny","returnType":{"$ref":"#/interfaces@10"},"definition":{"$type":"Assignment","feature":"dot","operator":"=","terminal":{"$type":"Keyword","value":"."}},"entry":false,"fragment":false,"parameters":[]}],"interfaces":[{"$type":"Interface","name":"RailroadPeg","attributes":[{"$type":"TypeAttribute","name":"title","isOptional":true,"type":{"$type":"SimpleType","primitiveType":"string"}},{"$type":"TypeAttribute","name":"accTitle","isOptional":true,"type":{"$type":"SimpleType","primitiveType":"string"}},{"$type":"TypeAttribute","name":"accDescr","isOptional":true,"type":{"$type":"SimpleType","primitiveType":"string"}},{"$type":"TypeAttribute","name":"rules","type":{"$type":"ArrayType","elementType":{"$type":"SimpleType","typeRef":{"$ref":"#/interfaces@1"}}},"isOptional":false}],"superTypes":[]},{"$type":"Interface","name":"PegRule","attributes":[{"$type":"TypeAttribute","name":"name","type":{"$type":"SimpleType","primitiveType":"string"},"isOptional":false},{"$type":"TypeAttribute","name":"definition","type":{"$type":"SimpleType","typeRef":{"$ref":"#/interfaces@2"}},"isOptional":false}],"superTypes":[]},{"$type":"Interface","name":"PegOrderedChoice","attributes":[{"$type":"TypeAttribute","name":"alternatives","type":{"$type":"ArrayType","elementType":{"$type":"SimpleType","typeRef":{"$ref":"#/interfaces@3"}}},"isOptional":false}],"superTypes":[]},{"$type":"Interface","name":"PegSequence","attributes":[{"$type":"TypeAttribute","name":"elements","type":{"$type":"ArrayType","elementType":{"$type":"SimpleType","typeRef":{"$ref":"#/interfaces@4"}}},"isOptional":false}],"superTypes":[]},{"$type":"Interface","name":"PegPrefix","attributes":[{"$type":"TypeAttribute","name":"operator","isOptional":true,"type":{"$type":"SimpleType","primitiveType":"string"}},{"$type":"TypeAttribute","name":"suffix","type":{"$type":"SimpleType","typeRef":{"$ref":"#/interfaces@5"}},"isOptional":false}],"superTypes":[]},{"$type":"Interface","name":"PegSuffix","attributes":[{"$type":"TypeAttribute","name":"primary","type":{"$type":"SimpleType","typeRef":{"$ref":"#/interfaces@6"}},"isOptional":false},{"$type":"TypeAttribute","name":"operator","isOptional":true,"type":{"$type":"SimpleType","primitiveType":"string"}}],"superTypes":[]},{"$type":"Interface","name":"PegPrimary","attributes":[],"superTypes":[]},{"$type":"Interface","name":"PegLiteral","superTypes":[{"$ref":"#/interfaces@6"}],"attributes":[{"$type":"TypeAttribute","name":"value","type":{"$type":"SimpleType","primitiveType":"string"},"isOptional":false}]},{"$type":"Interface","name":"PegIdentifier","superTypes":[{"$ref":"#/interfaces@6"}],"attributes":[{"$type":"TypeAttribute","name":"name","type":{"$type":"SimpleType","primitiveType":"string"},"isOptional":false}]},{"$type":"Interface","name":"PegGroup","superTypes":[{"$ref":"#/interfaces@6"}],"attributes":[{"$type":"TypeAttribute","name":"element","type":{"$type":"SimpleType","typeRef":{"$ref":"#/interfaces@2"}},"isOptional":false}]},{"$type":"Interface","name":"PegAny","superTypes":[{"$ref":"#/interfaces@6"}],"attributes":[{"$type":"TypeAttribute","name":"dot","type":{"$type":"SimpleType","primitiveType":"string"},"isOptional":false}]}],"imports":[],"types":[]}`)), "RailroadPegGrammarGrammar");
var loadedTreemapGrammarGrammar;
var TreemapGrammarGrammar = /* @__PURE__ */ __name2(() => loadedTreemapGrammarGrammar ?? (loadedTreemapGrammarGrammar = loadGrammarFromJson(`{"$type":"Grammar","isDeclared":true,"name":"TreemapGrammar","rules":[{"$type":"ParserRule","fragment":true,"name":"TitleAndAccessibilities","definition":{"$type":"Alternatives","elements":[{"$type":"Assignment","feature":"accDescr","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@2"},"arguments":[]}},{"$type":"Assignment","feature":"accTitle","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@3"},"arguments":[]}},{"$type":"Assignment","feature":"title","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@4"},"arguments":[]}}],"cardinality":"+"},"entry":false,"parameters":[]},{"$type":"TerminalRule","name":"BOOLEAN","type":{"$type":"ReturnType","name":"boolean"},"definition":{"$type":"TerminalAlternatives","elements":[{"$type":"CharacterRange","left":{"$type":"Keyword","value":"true"},"parenthesized":false},{"$type":"CharacterRange","left":{"$type":"Keyword","value":"false"},"parenthesized":false}],"parenthesized":false},"fragment":false,"hidden":false},{"$type":"TerminalRule","name":"ACC_DESCR","definition":{"$type":"RegexToken","regex":"/[\\\\t ]*accDescr(?:[\\\\t ]*:([^\\\\n\\\\r]*?(?=%%)|[^\\\\n\\\\r]*)|\\\\s*{([^}]*)})/","parenthesized":false},"fragment":false,"hidden":false},{"$type":"TerminalRule","name":"ACC_TITLE","definition":{"$type":"RegexToken","regex":"/[\\\\t ]*accTitle[\\\\t ]*:(?:[^\\\\n\\\\r]*?(?=%%)|[^\\\\n\\\\r]*)/","parenthesized":false},"fragment":false,"hidden":false},{"$type":"TerminalRule","name":"TITLE","definition":{"$type":"RegexToken","regex":"/[\\\\t ]*title(?:[\\\\t ][^\\\\n\\\\r]*?(?=%%)|[\\\\t ][^\\\\n\\\\r]*|)/","parenthesized":false},"fragment":false,"hidden":false},{"$type":"ParserRule","entry":true,"name":"Treemap","returnType":{"$ref":"#/interfaces@4"},"definition":{"$type":"Group","elements":[{"$type":"RuleCall","rule":{"$ref":"#/rules@6"},"arguments":[]},{"$type":"Alternatives","elements":[{"$type":"RuleCall","rule":{"$ref":"#/rules@0"},"arguments":[]},{"$type":"Assignment","feature":"TreemapRows","operator":"+=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@15"},"arguments":[]}}],"cardinality":"*"}]},"fragment":false,"parameters":[]},{"$type":"TerminalRule","name":"TREEMAP_KEYWORD","definition":{"$type":"TerminalAlternatives","elements":[{"$type":"CharacterRange","left":{"$type":"Keyword","value":"treemap-beta"},"parenthesized":false},{"$type":"CharacterRange","left":{"$type":"Keyword","value":"treemap"},"parenthesized":false}],"parenthesized":false},"fragment":false,"hidden":false},{"$type":"TerminalRule","name":"CLASS_DEF","definition":{"$type":"RegexToken","regex":"/classDef\\\\s+([a-zA-Z_][a-zA-Z0-9_]+)(?:\\\\s+([^;\\\\r\\\\n]*))?(?:;)?/","parenthesized":false},"fragment":false,"hidden":false},{"$type":"TerminalRule","name":"STYLE_SEPARATOR","definition":{"$type":"CharacterRange","left":{"$type":"Keyword","value":":::"},"parenthesized":false},"fragment":false,"hidden":false},{"$type":"TerminalRule","name":"SEPARATOR","definition":{"$type":"CharacterRange","left":{"$type":"Keyword","value":":"},"parenthesized":false},"fragment":false,"hidden":false},{"$type":"TerminalRule","name":"COMMA","definition":{"$type":"CharacterRange","left":{"$type":"Keyword","value":","},"parenthesized":false},"fragment":false,"hidden":false},{"$type":"TerminalRule","name":"INDENTATION","definition":{"$type":"RegexToken","regex":"/[ \\\\t]{1,}/","parenthesized":false},"fragment":false,"hidden":false},{"$type":"TerminalRule","hidden":true,"name":"WS","definition":{"$type":"RegexToken","regex":"/[ \\\\t]+/","parenthesized":false},"fragment":false},{"$type":"TerminalRule","hidden":true,"name":"ML_COMMENT","definition":{"$type":"RegexToken","regex":"/\\\\%\\\\%[^\\\\n]*/","parenthesized":false},"fragment":false},{"$type":"TerminalRule","hidden":true,"name":"NL","definition":{"$type":"RegexToken","regex":"/\\\\r?\\\\n/","parenthesized":false},"fragment":false},{"$type":"ParserRule","name":"TreemapRow","definition":{"$type":"Group","elements":[{"$type":"Assignment","feature":"indent","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@11"},"arguments":[]},"cardinality":"?"},{"$type":"Alternatives","elements":[{"$type":"Assignment","feature":"item","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@17"},"arguments":[]}},{"$type":"RuleCall","rule":{"$ref":"#/rules@16"},"arguments":[]}]}]},"entry":false,"fragment":false,"parameters":[]},{"$type":"ParserRule","name":"ClassDef","dataType":"string","definition":{"$type":"RuleCall","rule":{"$ref":"#/rules@7"},"arguments":[]},"entry":false,"fragment":false,"parameters":[]},{"$type":"ParserRule","name":"Item","returnType":{"$ref":"#/interfaces@0"},"definition":{"$type":"Alternatives","elements":[{"$type":"RuleCall","rule":{"$ref":"#/rules@19"},"arguments":[]},{"$type":"RuleCall","rule":{"$ref":"#/rules@18"},"arguments":[]}]},"entry":false,"fragment":false,"parameters":[]},{"$type":"ParserRule","name":"Section","returnType":{"$ref":"#/interfaces@1"},"definition":{"$type":"Group","elements":[{"$type":"Assignment","feature":"name","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@23"},"arguments":[]}},{"$type":"Group","elements":[{"$type":"RuleCall","rule":{"$ref":"#/rules@8"},"arguments":[]},{"$type":"Assignment","feature":"classSelector","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@20"},"arguments":[]}}],"cardinality":"?"}]},"entry":false,"fragment":false,"parameters":[]},{"$type":"ParserRule","name":"Leaf","returnType":{"$ref":"#/interfaces@2"},"definition":{"$type":"Group","elements":[{"$type":"Assignment","feature":"name","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@23"},"arguments":[]}},{"$type":"RuleCall","rule":{"$ref":"#/rules@11"},"arguments":[],"cardinality":"?"},{"$type":"Alternatives","elements":[{"$type":"RuleCall","rule":{"$ref":"#/rules@9"},"arguments":[]},{"$type":"RuleCall","rule":{"$ref":"#/rules@10"},"arguments":[]}]},{"$type":"RuleCall","rule":{"$ref":"#/rules@11"},"arguments":[],"cardinality":"?"},{"$type":"Assignment","feature":"value","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@22"},"arguments":[]}},{"$type":"Group","elements":[{"$type":"RuleCall","rule":{"$ref":"#/rules@8"},"arguments":[]},{"$type":"Assignment","feature":"classSelector","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@20"},"arguments":[]}}],"cardinality":"?"}]},"entry":false,"fragment":false,"parameters":[]},{"$type":"TerminalRule","name":"ID2","definition":{"$type":"RegexToken","regex":"/[a-zA-Z_][a-zA-Z0-9_]*/","parenthesized":false},"fragment":false,"hidden":false},{"$type":"TerminalRule","name":"NUMBER2","definition":{"$type":"RegexToken","regex":"/[0-9_\\\\.\\\\,]+/","parenthesized":false},"fragment":false,"hidden":false},{"$type":"ParserRule","name":"MyNumber","dataType":"number","definition":{"$type":"RuleCall","rule":{"$ref":"#/rules@21"},"arguments":[]},"entry":false,"fragment":false,"parameters":[]},{"$type":"TerminalRule","name":"STRING2","definition":{"$type":"RegexToken","regex":"/\\"[^\\"]*\\"|'[^']*'/","parenthesized":false},"fragment":false,"hidden":false}],"interfaces":[{"$type":"Interface","name":"Item","attributes":[{"$type":"TypeAttribute","name":"name","type":{"$type":"SimpleType","primitiveType":"string"},"isOptional":false},{"$type":"TypeAttribute","name":"classSelector","isOptional":true,"type":{"$type":"SimpleType","primitiveType":"string"}}],"superTypes":[]},{"$type":"Interface","name":"Section","superTypes":[{"$ref":"#/interfaces@0"}],"attributes":[]},{"$type":"Interface","name":"Leaf","superTypes":[{"$ref":"#/interfaces@0"}],"attributes":[{"$type":"TypeAttribute","name":"value","type":{"$type":"SimpleType","primitiveType":"number"},"isOptional":false}]},{"$type":"Interface","name":"ClassDefStatement","attributes":[{"$type":"TypeAttribute","name":"className","type":{"$type":"SimpleType","primitiveType":"string"},"isOptional":false},{"$type":"TypeAttribute","name":"styleText","type":{"$type":"SimpleType","primitiveType":"string"},"isOptional":false}],"superTypes":[]},{"$type":"Interface","name":"Treemap","attributes":[{"$type":"TypeAttribute","name":"TreemapRows","type":{"$type":"ArrayType","elementType":{"$type":"SimpleType","typeRef":{"$ref":"#/rules@15"}}},"isOptional":false},{"$type":"TypeAttribute","name":"title","isOptional":true,"type":{"$type":"SimpleType","primitiveType":"string"}},{"$type":"TypeAttribute","name":"accTitle","isOptional":true,"type":{"$type":"SimpleType","primitiveType":"string"}},{"$type":"TypeAttribute","name":"accDescr","isOptional":true,"type":{"$type":"SimpleType","primitiveType":"string"}}],"superTypes":[]}],"imports":[],"types":[],"$comment":"/**\\n * Treemap grammar for Langium\\n * Converted from mindmap grammar\\n *\\n * The ML_COMMENT and NL hidden terminals handle whitespace, comments, and newlines\\n * before the treemap keyword, allowing for empty lines and comments before the\\n * treemap declaration.\\n */"}`)), "TreemapGrammarGrammar");
var loadedTreeViewGrammarGrammar;
var TreeViewGrammarGrammar = /* @__PURE__ */ __name2(() => loadedTreeViewGrammarGrammar ?? (loadedTreeViewGrammarGrammar = loadGrammarFromJson(`{"$type":"Grammar","isDeclared":true,"name":"TreeViewGrammar","rules":[{"$type":"TerminalRule","name":"ACC_DESCR","definition":{"$type":"RegexToken","regex":"/[\\\\t ]*accDescr(?:[\\\\t ]*:([^\\\\n\\\\r]*?(?=%%)|[^\\\\n\\\\r]*)|\\\\s*{([^}]*)})/","parenthesized":false},"fragment":false,"hidden":false},{"$type":"TerminalRule","name":"ACC_TITLE","definition":{"$type":"RegexToken","regex":"/[\\\\t ]*accTitle[\\\\t ]*:(?:[^\\\\n\\\\r]*?(?=%%)|[^\\\\n\\\\r]*)/","parenthesized":false},"fragment":false,"hidden":false},{"$type":"TerminalRule","name":"TITLE","definition":{"$type":"RegexToken","regex":"/[\\\\t ]*title(?:[\\\\t ][^\\\\n\\\\r]*?(?=%%)|[\\\\t ][^\\\\n\\\\r]*|)/","parenthesized":false},"fragment":false,"hidden":false},{"$type":"ParserRule","entry":true,"name":"TreeView","returnType":{"$ref":"#/interfaces@0"},"definition":{"$type":"Group","elements":[{"$type":"Keyword","value":"treeView-beta"},{"$type":"RuleCall","rule":{"$ref":"#/rules@4"},"arguments":[],"cardinality":"?"},{"$type":"Assignment","feature":"nodes","operator":"+=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@14"},"arguments":[]},"cardinality":"*"}]},"fragment":false,"parameters":[]},{"$type":"ParserRule","fragment":true,"name":"TitleAndAccessibilities","definition":{"$type":"Alternatives","elements":[{"$type":"Assignment","feature":"accDescr","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@0"},"arguments":[]}},{"$type":"Assignment","feature":"accTitle","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@1"},"arguments":[]}},{"$type":"Assignment","feature":"title","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@2"},"arguments":[]}}],"cardinality":"+"},"entry":false,"parameters":[]},{"$type":"TerminalRule","name":"CLASS_ANNOTATION","definition":{"$type":"RegexToken","regex":"/[ \\\\t]+:::[ \\\\t]*[A-Za-z_][\\\\w-]*/","parenthesized":false},"fragment":false,"hidden":false},{"$type":"TerminalRule","name":"ICON_ANNOTATION","definition":{"$type":"RegexToken","regex":"/[ \\\\t]+icon\\\\([\\\\w-]*(?::[\\\\w-]+)?\\\\)/","parenthesized":false},"fragment":false,"hidden":false},{"$type":"TerminalRule","name":"DESC_ANNOTATION","definition":{"$type":"RegexToken","regex":"/[ \\\\t]+##[^\\\\n\\\\r]*/","parenthesized":false},"fragment":false,"hidden":false},{"$type":"TerminalRule","name":"INDENTATION","definition":{"$type":"RegexToken","regex":"/[ \\\\t]{1,}/","parenthesized":false},"fragment":false,"hidden":false},{"$type":"TerminalRule","name":"QUOTED_NAME","definition":{"$type":"RegexToken","regex":"/\\"[^\\"]*\\"|'[^']*'/","parenthesized":false},"fragment":false,"hidden":false},{"$type":"TerminalRule","hidden":true,"name":"WS","definition":{"$type":"RegexToken","regex":"/[ \\\\t]+/","parenthesized":false},"fragment":false},{"$type":"TerminalRule","hidden":true,"name":"ML_COMMENT","definition":{"$type":"RegexToken","regex":"/\\\\%\\\\%[^\\\\n]*/","parenthesized":false},"fragment":false},{"$type":"TerminalRule","hidden":true,"name":"NL","definition":{"$type":"RegexToken","regex":"/\\\\r?\\\\n/","parenthesized":false},"fragment":false},{"$type":"TerminalRule","name":"BARE_NAME","definition":{"$type":"RegexToken","regex":"/(?!:::|icon\\\\(|##)[^ \\\\t\\\\n\\\\r\\"'](?:(?![ \\\\t]+:::[ \\\\t]*[A-Za-z_]|[ \\\\t]+icon\\\\(|[ \\\\t]+##)[^\\\\n\\\\r])*/","parenthesized":false},"fragment":false,"hidden":false},{"$type":"ParserRule","name":"TreeNode","definition":{"$type":"Group","elements":[{"$type":"Assignment","feature":"indent","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@8"},"arguments":[]},"cardinality":"?"},{"$type":"Alternatives","elements":[{"$type":"Assignment","feature":"name","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@9"},"arguments":[]}},{"$type":"Assignment","feature":"name","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@13"},"arguments":[]}}]},{"$type":"Alternatives","elements":[{"$type":"Assignment","feature":"classAnnotation","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@5"},"arguments":[]}},{"$type":"Assignment","feature":"iconAnnotation","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@6"},"arguments":[]}},{"$type":"Assignment","feature":"descAnnotation","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@7"},"arguments":[]}}],"cardinality":"*"}]},"entry":false,"fragment":false,"parameters":[]}],"interfaces":[{"$type":"Interface","name":"TreeView","attributes":[{"$type":"TypeAttribute","name":"nodes","type":{"$type":"ArrayType","elementType":{"$type":"SimpleType","typeRef":{"$ref":"#/rules@14"}}},"isOptional":false},{"$type":"TypeAttribute","name":"title","isOptional":true,"type":{"$type":"SimpleType","primitiveType":"string"}},{"$type":"TypeAttribute","name":"accTitle","isOptional":true,"type":{"$type":"SimpleType","primitiveType":"string"}},{"$type":"TypeAttribute","name":"accDescr","isOptional":true,"type":{"$type":"SimpleType","primitiveType":"string"}}],"superTypes":[]}],"imports":[],"types":[],"$comment":"/**\\n * TreeView grammar for Langium\\n *\\n * Supports both quoted labels (\\"my file\\") and bare labels (index.js).\\n * Annotations (:::class, icon(), ## description) are parsed directly into\\n * AST fields by the grammar. Value conversion for stripping quotes, extracting\\n * class names, icon names, and description text happens in valueConverter.ts.\\n *\\n * The ML_COMMENT and NL hidden terminals handle whitespace, comments, and newlines\\n * before the treeView keyword, allowing for empty lines and comments before the\\n * treeView declaration.\\n */"}`)), "TreeViewGrammarGrammar");
var loadedWardleyGrammarGrammar;
var WardleyGrammarGrammar = /* @__PURE__ */ __name2(() => loadedWardleyGrammarGrammar ?? (loadedWardleyGrammarGrammar = loadGrammarFromJson(`{"$type":"Grammar","isDeclared":true,"name":"WardleyGrammar","imports":[],"rules":[{"$type":"ParserRule","entry":true,"name":"Wardley","definition":{"$type":"Group","elements":[{"$type":"RuleCall","rule":{"$ref":"#/rules@52"},"arguments":[],"cardinality":"*"},{"$type":"RuleCall","rule":{"$ref":"#/rules@25"},"arguments":[]},{"$type":"Alternatives","elements":[{"$type":"RuleCall","rule":{"$ref":"#/rules@52"},"arguments":[]},{"$type":"RuleCall","rule":{"$ref":"#/rules@42"},"arguments":[]},{"$type":"RuleCall","rule":{"$ref":"#/rules@1"},"arguments":[]}],"cardinality":"*"}]},"fragment":false,"parameters":[]},{"$type":"ParserRule","fragment":true,"name":"Statement","definition":{"$type":"Alternatives","elements":[{"$type":"Assignment","feature":"size","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@2"},"arguments":[]}},{"$type":"Assignment","feature":"evolution","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@3"},"arguments":[]}},{"$type":"Assignment","feature":"anchors","operator":"+=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@5"},"arguments":[]}},{"$type":"Assignment","feature":"components","operator":"+=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@6"},"arguments":[]}},{"$type":"Assignment","feature":"links","operator":"+=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@9"},"arguments":[]}},{"$type":"Assignment","feature":"evolves","operator":"+=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@10"},"arguments":[]}},{"$type":"Assignment","feature":"pipelines","operator":"+=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@11"},"arguments":[]}},{"$type":"Assignment","feature":"notes","operator":"+=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@13"},"arguments":[]}},{"$type":"Assignment","feature":"annotations","operator":"+=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@14"},"arguments":[]}},{"$type":"Assignment","feature":"annotation","operator":"+=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@15"},"arguments":[]}},{"$type":"Assignment","feature":"accelerators","operator":"+=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@17"},"arguments":[]}},{"$type":"Assignment","feature":"deaccelerators","operator":"+=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@18"},"arguments":[]}}]},"entry":false,"parameters":[]},{"$type":"ParserRule","name":"Size","definition":{"$type":"Group","elements":[{"$type":"RuleCall","rule":{"$ref":"#/rules@26"},"arguments":[]},{"$type":"Keyword","value":"["},{"$type":"Assignment","feature":"width","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@48"},"arguments":[]}},{"$type":"Keyword","value":","},{"$type":"Assignment","feature":"height","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@48"},"arguments":[]}},{"$type":"Keyword","value":"]"},{"$type":"RuleCall","rule":{"$ref":"#/rules@41"},"arguments":[]}]},"entry":false,"fragment":false,"parameters":[]},{"$type":"ParserRule","name":"Evolution","definition":{"$type":"Group","elements":[{"$type":"RuleCall","rule":{"$ref":"#/rules@27"},"arguments":[]},{"$type":"Assignment","feature":"stages","operator":"+=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@4"},"arguments":[]}},{"$type":"Group","elements":[{"$type":"RuleCall","rule":{"$ref":"#/rules@20"},"arguments":[]},{"$type":"Assignment","feature":"stages","operator":"+=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@4"},"arguments":[]}}],"cardinality":"+"},{"$type":"RuleCall","rule":{"$ref":"#/rules@41"},"arguments":[]}]},"entry":false,"fragment":false,"parameters":[]},{"$type":"ParserRule","name":"EvolutionStage","definition":{"$type":"Group","elements":[{"$type":"Assignment","feature":"name","operator":"=","terminal":{"$type":"Alternatives","elements":[{"$type":"RuleCall","rule":{"$ref":"#/rules@51"},"arguments":[]},{"$type":"RuleCall","rule":{"$ref":"#/rules@50"},"arguments":[]},{"$type":"RuleCall","rule":{"$ref":"#/rules@39"},"arguments":[]}]}},{"$type":"Group","elements":[{"$type":"Keyword","value":"@"},{"$type":"Assignment","feature":"boundary","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@19"},"arguments":[]}}],"cardinality":"?"},{"$type":"Group","elements":[{"$type":"Keyword","value":"/"},{"$type":"Assignment","feature":"secondName","operator":"=","terminal":{"$type":"Alternatives","elements":[{"$type":"RuleCall","rule":{"$ref":"#/rules@51"},"arguments":[]},{"$type":"RuleCall","rule":{"$ref":"#/rules@50"},"arguments":[]},{"$type":"RuleCall","rule":{"$ref":"#/rules@39"},"arguments":[]}]}}],"cardinality":"?"}]},"entry":false,"fragment":false,"parameters":[]},{"$type":"ParserRule","name":"Anchor","definition":{"$type":"Group","elements":[{"$type":"RuleCall","rule":{"$ref":"#/rules@28"},"arguments":[]},{"$type":"Assignment","feature":"name","operator":"=","terminal":{"$type":"Alternatives","elements":[{"$type":"RuleCall","rule":{"$ref":"#/rules@50"},"arguments":[]},{"$type":"RuleCall","rule":{"$ref":"#/rules@51"},"arguments":[]},{"$type":"RuleCall","rule":{"$ref":"#/rules@39"},"arguments":[]}]}},{"$type":"Keyword","value":"["},{"$type":"Assignment","feature":"visibility","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@19"},"arguments":[]}},{"$type":"Keyword","value":","},{"$type":"Assignment","feature":"evolution","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@19"},"arguments":[]}},{"$type":"Keyword","value":"]"},{"$type":"RuleCall","rule":{"$ref":"#/rules@41"},"arguments":[]}]},"entry":false,"fragment":false,"parameters":[]},{"$type":"ParserRule","name":"Component","definition":{"$type":"Group","elements":[{"$type":"RuleCall","rule":{"$ref":"#/rules@29"},"arguments":[]},{"$type":"Assignment","feature":"name","operator":"=","terminal":{"$type":"Alternatives","elements":[{"$type":"RuleCall","rule":{"$ref":"#/rules@50"},"arguments":[]},{"$type":"RuleCall","rule":{"$ref":"#/rules@51"},"arguments":[]},{"$type":"RuleCall","rule":{"$ref":"#/rules@39"},"arguments":[]}]}},{"$type":"Keyword","value":"["},{"$type":"Assignment","feature":"visibility","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@19"},"arguments":[]}},{"$type":"Keyword","value":","},{"$type":"Assignment","feature":"evolution","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@19"},"arguments":[]}},{"$type":"Keyword","value":"]"},{"$type":"Assignment","feature":"label","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@7"},"arguments":[]},"cardinality":"?"},{"$type":"Assignment","feature":"decorator","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@8"},"arguments":[]},"cardinality":"?"},{"$type":"Alternatives","elements":[{"$type":"Assignment","feature":"inertia","operator":"?=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@31"},"arguments":[]}},{"$type":"Group","elements":[{"$type":"Keyword","value":"("},{"$type":"Assignment","feature":"inertia","operator":"?=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@31"},"arguments":[]}},{"$type":"Keyword","value":")"}]}],"cardinality":"?"},{"$type":"RuleCall","rule":{"$ref":"#/rules@41"},"arguments":[]}]},"entry":false,"fragment":false,"parameters":[]},{"$type":"ParserRule","name":"Label","definition":{"$type":"Group","elements":[{"$type":"RuleCall","rule":{"$ref":"#/rules@30"},"arguments":[]},{"$type":"Keyword","value":"["},{"$type":"Assignment","feature":"negX","operator":"?=","terminal":{"$type":"Keyword","value":"-"},"cardinality":"?"},{"$type":"Assignment","feature":"offsetX","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@48"},"arguments":[]}},{"$type":"Keyword","value":","},{"$type":"Assignment","feature":"negY","operator":"?=","terminal":{"$type":"Keyword","value":"-"},"cardinality":"?"},{"$type":"Assignment","feature":"offsetY","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@48"},"arguments":[]}},{"$type":"Keyword","value":"]"}]},"entry":false,"fragment":false,"parameters":[]},{"$type":"ParserRule","name":"Decorator","definition":{"$type":"Group","elements":[{"$type":"Keyword","value":"("},{"$type":"Assignment","feature":"strategy","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@24"},"arguments":[]}},{"$type":"Keyword","value":")"}]},"entry":false,"fragment":false,"parameters":[]},{"$type":"ParserRule","name":"Link","definition":{"$type":"Group","elements":[{"$type":"Assignment","feature":"from","operator":"=","terminal":{"$type":"Alternatives","elements":[{"$type":"RuleCall","rule":{"$ref":"#/rules@50"},"arguments":[]},{"$type":"RuleCall","rule":{"$ref":"#/rules@51"},"arguments":[]},{"$type":"RuleCall","rule":{"$ref":"#/rules@39"},"arguments":[]}]}},{"$type":"Assignment","feature":"fromPort","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@21"},"arguments":[]},"cardinality":"?"},{"$type":"Assignment","feature":"arrow","operator":"=","terminal":{"$type":"Alternatives","elements":[{"$type":"RuleCall","rule":{"$ref":"#/rules@22"},"arguments":[]},{"$type":"RuleCall","rule":{"$ref":"#/rules@20"},"arguments":[]}]},"cardinality":"?"},{"$type":"Assignment","feature":"to","operator":"=","terminal":{"$type":"Alternatives","elements":[{"$type":"RuleCall","rule":{"$ref":"#/rules@50"},"arguments":[]},{"$type":"RuleCall","rule":{"$ref":"#/rules@51"},"arguments":[]},{"$type":"RuleCall","rule":{"$ref":"#/rules@39"},"arguments":[]}]}},{"$type":"Assignment","feature":"toPort","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@21"},"arguments":[]},"cardinality":"?"},{"$type":"Assignment","feature":"linkLabel","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@23"},"arguments":[]},"cardinality":"?"},{"$type":"RuleCall","rule":{"$ref":"#/rules@41"},"arguments":[]}]},"entry":false,"fragment":false,"parameters":[]},{"$type":"ParserRule","name":"Evolve","definition":{"$type":"Group","elements":[{"$type":"RuleCall","rule":{"$ref":"#/rules@32"},"arguments":[]},{"$type":"Assignment","feature":"component","operator":"=","terminal":{"$type":"Alternatives","elements":[{"$type":"RuleCall","rule":{"$ref":"#/rules@50"},"arguments":[]},{"$type":"RuleCall","rule":{"$ref":"#/rules@51"},"arguments":[]},{"$type":"RuleCall","rule":{"$ref":"#/rules@39"},"arguments":[]}]}},{"$type":"Assignment","feature":"target","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@19"},"arguments":[]}},{"$type":"RuleCall","rule":{"$ref":"#/rules@41"},"arguments":[]}]},"entry":false,"fragment":false,"parameters":[]},{"$type":"ParserRule","name":"Pipeline","definition":{"$type":"Group","elements":[{"$type":"RuleCall","rule":{"$ref":"#/rules@33"},"arguments":[]},{"$type":"Assignment","feature":"parent","operator":"=","terminal":{"$type":"Alternatives","elements":[{"$type":"RuleCall","rule":{"$ref":"#/rules@50"},"arguments":[]},{"$type":"RuleCall","rule":{"$ref":"#/rules@51"},"arguments":[]},{"$type":"RuleCall","rule":{"$ref":"#/rules@39"},"arguments":[]}]}},{"$type":"Keyword","value":"{"},{"$type":"RuleCall","rule":{"$ref":"#/rules@52"},"arguments":[],"cardinality":"+"},{"$type":"Assignment","feature":"components","operator":"+=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@12"},"arguments":[]},"cardinality":"+"},{"$type":"Keyword","value":"}"},{"$type":"RuleCall","rule":{"$ref":"#/rules@41"},"arguments":[]}]},"entry":false,"fragment":false,"parameters":[]},{"$type":"ParserRule","name":"PipelineComponent","definition":{"$type":"Group","elements":[{"$type":"RuleCall","rule":{"$ref":"#/rules@29"},"arguments":[]},{"$type":"Assignment","feature":"name","operator":"=","terminal":{"$type":"Alternatives","elements":[{"$type":"RuleCall","rule":{"$ref":"#/rules@50"},"arguments":[]},{"$type":"RuleCall","rule":{"$ref":"#/rules@51"},"arguments":[]},{"$type":"RuleCall","rule":{"$ref":"#/rules@39"},"arguments":[]}]}},{"$type":"Keyword","value":"["},{"$type":"Assignment","feature":"evolution","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@19"},"arguments":[]}},{"$type":"Keyword","value":"]"},{"$type":"Assignment","feature":"label","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@7"},"arguments":[]},"cardinality":"?"},{"$type":"RuleCall","rule":{"$ref":"#/rules@41"},"arguments":[]}]},"entry":false,"fragment":false,"parameters":[]},{"$type":"ParserRule","name":"Note","definition":{"$type":"Group","elements":[{"$type":"RuleCall","rule":{"$ref":"#/rules@34"},"arguments":[]},{"$type":"Assignment","feature":"text","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@50"},"arguments":[]}},{"$type":"Keyword","value":"["},{"$type":"Assignment","feature":"visibility","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@19"},"arguments":[]}},{"$type":"Keyword","value":","},{"$type":"Assignment","feature":"evolution","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@19"},"arguments":[]}},{"$type":"Keyword","value":"]"},{"$type":"RuleCall","rule":{"$ref":"#/rules@41"},"arguments":[]}]},"entry":false,"fragment":false,"parameters":[]},{"$type":"ParserRule","name":"Annotations","definition":{"$type":"Group","elements":[{"$type":"RuleCall","rule":{"$ref":"#/rules@35"},"arguments":[]},{"$type":"Keyword","value":"["},{"$type":"Assignment","feature":"x","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@16"},"arguments":[]}},{"$type":"Keyword","value":","},{"$type":"Assignment","feature":"y","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@16"},"arguments":[]}},{"$type":"Keyword","value":"]"},{"$type":"RuleCall","rule":{"$ref":"#/rules@41"},"arguments":[]}]},"entry":false,"fragment":false,"parameters":[]},{"$type":"ParserRule","name":"Annotation","definition":{"$type":"Group","elements":[{"$type":"RuleCall","rule":{"$ref":"#/rules@36"},"arguments":[]},{"$type":"Assignment","feature":"number","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@48"},"arguments":[]}},{"$type":"Keyword","value":","},{"$type":"Keyword","value":"["},{"$type":"Assignment","feature":"x","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@16"},"arguments":[]}},{"$type":"Keyword","value":","},{"$type":"Assignment","feature":"y","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@16"},"arguments":[]}},{"$type":"Keyword","value":"]"},{"$type":"Assignment","feature":"text","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@50"},"arguments":[]}},{"$type":"RuleCall","rule":{"$ref":"#/rules@41"},"arguments":[]}]},"entry":false,"fragment":false,"parameters":[]},{"$type":"ParserRule","name":"CoordinateValue","dataType":"number","definition":{"$type":"Alternatives","elements":[{"$type":"RuleCall","rule":{"$ref":"#/rules@19"},"arguments":[]},{"$type":"RuleCall","rule":{"$ref":"#/rules@48"},"arguments":[]}]},"entry":false,"fragment":false,"parameters":[]},{"$type":"ParserRule","name":"Accelerator","definition":{"$type":"Group","elements":[{"$type":"RuleCall","rule":{"$ref":"#/rules@37"},"arguments":[]},{"$type":"Assignment","feature":"name","operator":"=","terminal":{"$type":"Alternatives","elements":[{"$type":"RuleCall","rule":{"$ref":"#/rules@50"},"arguments":[]},{"$type":"RuleCall","rule":{"$ref":"#/rules@51"},"arguments":[]},{"$type":"RuleCall","rule":{"$ref":"#/rules@39"},"arguments":[]}]}},{"$type":"Keyword","value":"["},{"$type":"Assignment","feature":"x","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@19"},"arguments":[]}},{"$type":"Keyword","value":","},{"$type":"Assignment","feature":"y","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@19"},"arguments":[]}},{"$type":"Keyword","value":"]"},{"$type":"RuleCall","rule":{"$ref":"#/rules@41"},"arguments":[]}]},"entry":false,"fragment":false,"parameters":[]},{"$type":"ParserRule","name":"Deaccelerator","definition":{"$type":"Group","elements":[{"$type":"RuleCall","rule":{"$ref":"#/rules@38"},"arguments":[]},{"$type":"Assignment","feature":"name","operator":"=","terminal":{"$type":"Alternatives","elements":[{"$type":"RuleCall","rule":{"$ref":"#/rules@50"},"arguments":[]},{"$type":"RuleCall","rule":{"$ref":"#/rules@51"},"arguments":[]},{"$type":"RuleCall","rule":{"$ref":"#/rules@39"},"arguments":[]}]}},{"$type":"Keyword","value":"["},{"$type":"Assignment","feature":"x","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@19"},"arguments":[]}},{"$type":"Keyword","value":","},{"$type":"Assignment","feature":"y","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@19"},"arguments":[]}},{"$type":"Keyword","value":"]"},{"$type":"RuleCall","rule":{"$ref":"#/rules@41"},"arguments":[]}]},"entry":false,"fragment":false,"parameters":[]},{"$type":"TerminalRule","name":"WARDLEY_NUMBER","type":{"$type":"ReturnType","name":"number"},"definition":{"$type":"RegexToken","regex":"/[0-9]+\\\\.[0-9]+/","parenthesized":false},"fragment":false,"hidden":false},{"$type":"TerminalRule","name":"ARROW","definition":{"$type":"CharacterRange","left":{"$type":"Keyword","value":"->"},"parenthesized":false},"fragment":false,"hidden":false},{"$type":"TerminalRule","name":"LINK_PORT","definition":{"$type":"TerminalAlternatives","elements":[{"$type":"TerminalAlternatives","elements":[{"$type":"CharacterRange","left":{"$type":"Keyword","value":"+<>"},"parenthesized":false},{"$type":"CharacterRange","left":{"$type":"Keyword","value":"+>"},"parenthesized":false}],"parenthesized":false},{"$type":"CharacterRange","left":{"$type":"Keyword","value":"+<"},"parenthesized":false}],"parenthesized":false},"fragment":false,"hidden":false},{"$type":"TerminalRule","name":"LINK_ARROW","definition":{"$type":"TerminalAlternatives","elements":[{"$type":"TerminalAlternatives","elements":[{"$type":"TerminalAlternatives","elements":[{"$type":"TerminalAlternatives","elements":[{"$type":"TerminalAlternatives","elements":[{"$type":"CharacterRange","left":{"$type":"Keyword","value":"-->"},"parenthesized":false},{"$type":"CharacterRange","left":{"$type":"Keyword","value":"-.->"},"parenthesized":false}],"parenthesized":false},{"$type":"CharacterRange","left":{"$type":"Keyword","value":">"},"parenthesized":false}],"parenthesized":false},{"$type":"RegexToken","regex":"/\\\\+'[^']*'<>/","parenthesized":false}],"parenthesized":false},{"$type":"RegexToken","regex":"/\\\\+'[^']*'</","parenthesized":false}],"parenthesized":false},{"$type":"RegexToken","regex":"/\\\\+'[^']*'>/","parenthesized":false}],"parenthesized":false},"fragment":false,"hidden":false},{"$type":"TerminalRule","name":"LINK_LABEL","definition":{"$type":"RegexToken","regex":"/;[^\\\\n\\\\r]+/","parenthesized":false},"fragment":false,"hidden":false},{"$type":"TerminalRule","name":"STRATEGY","definition":{"$type":"TerminalAlternatives","elements":[{"$type":"TerminalAlternatives","elements":[{"$type":"TerminalAlternatives","elements":[{"$type":"CharacterRange","left":{"$type":"Keyword","value":"build"},"parenthesized":false},{"$type":"CharacterRange","left":{"$type":"Keyword","value":"buy"},"parenthesized":false}],"parenthesized":false},{"$type":"CharacterRange","left":{"$type":"Keyword","value":"outsource"},"parenthesized":false}],"parenthesized":false},{"$type":"CharacterRange","left":{"$type":"Keyword","value":"market"},"parenthesized":false}],"parenthesized":false},"fragment":false,"hidden":false},{"$type":"TerminalRule","name":"KW_WARDLEY","definition":{"$type":"CharacterRange","left":{"$type":"Keyword","value":"wardley-beta"},"parenthesized":false},"fragment":false,"hidden":false},{"$type":"TerminalRule","name":"KW_SIZE","definition":{"$type":"CharacterRange","left":{"$type":"Keyword","value":"size"},"parenthesized":false},"fragment":false,"hidden":false},{"$type":"TerminalRule","name":"KW_EVOLUTION","definition":{"$type":"CharacterRange","left":{"$type":"Keyword","value":"evolution"},"parenthesized":false},"fragment":false,"hidden":false},{"$type":"TerminalRule","name":"KW_ANCHOR","definition":{"$type":"CharacterRange","left":{"$type":"Keyword","value":"anchor"},"parenthesized":false},"fragment":false,"hidden":false},{"$type":"TerminalRule","name":"KW_COMPONENT","definition":{"$type":"CharacterRange","left":{"$type":"Keyword","value":"component"},"parenthesized":false},"fragment":false,"hidden":false},{"$type":"TerminalRule","name":"KW_LABEL","definition":{"$type":"CharacterRange","left":{"$type":"Keyword","value":"label"},"parenthesized":false},"fragment":false,"hidden":false},{"$type":"TerminalRule","name":"KW_INERTIA","definition":{"$type":"CharacterRange","left":{"$type":"Keyword","value":"inertia"},"parenthesized":false},"fragment":false,"hidden":false},{"$type":"TerminalRule","name":"KW_EVOLVE","definition":{"$type":"CharacterRange","left":{"$type":"Keyword","value":"evolve"},"parenthesized":false},"fragment":false,"hidden":false},{"$type":"TerminalRule","name":"KW_PIPELINE","definition":{"$type":"CharacterRange","left":{"$type":"Keyword","value":"pipeline"},"parenthesized":false},"fragment":false,"hidden":false},{"$type":"TerminalRule","name":"KW_NOTE","definition":{"$type":"CharacterRange","left":{"$type":"Keyword","value":"note"},"parenthesized":false},"fragment":false,"hidden":false},{"$type":"TerminalRule","name":"KW_ANNOTATIONS","definition":{"$type":"CharacterRange","left":{"$type":"Keyword","value":"annotations"},"parenthesized":false},"fragment":false,"hidden":false},{"$type":"TerminalRule","name":"KW_ANNOTATION","definition":{"$type":"CharacterRange","left":{"$type":"Keyword","value":"annotation"},"parenthesized":false},"fragment":false,"hidden":false},{"$type":"TerminalRule","name":"KW_ACCELERATOR","definition":{"$type":"CharacterRange","left":{"$type":"Keyword","value":"accelerator"},"parenthesized":false},"fragment":false,"hidden":false},{"$type":"TerminalRule","name":"KW_DEACCELERATOR","definition":{"$type":"CharacterRange","left":{"$type":"Keyword","value":"deaccelerator"},"parenthesized":false},"fragment":false,"hidden":false},{"$type":"TerminalRule","name":"NAME_WITH_SPACES","definition":{"$type":"RegexToken","regex":"/(?!title\\\\s|accTitle|accDescr)[A-Za-z](?:[A-Za-z0-9_()&]|-(?!>))*(?:[ \\\\t]+[A-Za-z(](?:[A-Za-z0-9_()&]|-(?!>))*)*/","parenthesized":false},"fragment":false,"hidden":false},{"$type":"TerminalRule","hidden":true,"name":"WS","definition":{"$type":"RegexToken","regex":"/[ \\\\t]+/","parenthesized":false},"fragment":false},{"$type":"ParserRule","name":"EOL","dataType":"string","definition":{"$type":"Alternatives","elements":[{"$type":"RuleCall","rule":{"$ref":"#/rules@52"},"arguments":[],"cardinality":"+"},{"$type":"EndOfFile"}]},"entry":false,"fragment":false,"parameters":[]},{"$type":"ParserRule","fragment":true,"name":"TitleAndAccessibilities","definition":{"$type":"Group","elements":[{"$type":"Alternatives","elements":[{"$type":"Assignment","feature":"accDescr","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@44"},"arguments":[]}},{"$type":"Assignment","feature":"accTitle","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@45"},"arguments":[]}},{"$type":"Assignment","feature":"title","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@46"},"arguments":[]}}]},{"$type":"RuleCall","rule":{"$ref":"#/rules@41"},"arguments":[]}],"cardinality":"+"},"entry":false,"parameters":[]},{"$type":"TerminalRule","name":"BOOLEAN","type":{"$type":"ReturnType","name":"boolean"},"definition":{"$type":"TerminalAlternatives","elements":[{"$type":"CharacterRange","left":{"$type":"Keyword","value":"true"},"parenthesized":false},{"$type":"CharacterRange","left":{"$type":"Keyword","value":"false"},"parenthesized":false}],"parenthesized":false},"fragment":false,"hidden":false},{"$type":"TerminalRule","name":"ACC_DESCR","definition":{"$type":"RegexToken","regex":"/[\\\\t ]*accDescr(?:[\\\\t ]*:([^\\\\n\\\\r]*?(?=%%)|[^\\\\n\\\\r]*)|\\\\s*{([^}]*)})/","parenthesized":false},"fragment":false,"hidden":false},{"$type":"TerminalRule","name":"ACC_TITLE","definition":{"$type":"RegexToken","regex":"/[\\\\t ]*accTitle[\\\\t ]*:(?:[^\\\\n\\\\r]*?(?=%%)|[^\\\\n\\\\r]*)/","parenthesized":false},"fragment":false,"hidden":false},{"$type":"TerminalRule","name":"TITLE","definition":{"$type":"RegexToken","regex":"/[\\\\t ]*title(?:[\\\\t ][^\\\\n\\\\r]*?(?=%%)|[\\\\t ][^\\\\n\\\\r]*|)/","parenthesized":false},"fragment":false,"hidden":false},{"$type":"TerminalRule","name":"FLOAT","type":{"$type":"ReturnType","name":"number"},"definition":{"$type":"RegexToken","regex":"/[0-9]+\\\\.[0-9]+(?!\\\\.)/","parenthesized":false},"fragment":false,"hidden":false},{"$type":"TerminalRule","name":"INT","type":{"$type":"ReturnType","name":"number"},"definition":{"$type":"RegexToken","regex":"/0|[1-9][0-9]*(?!\\\\.)/","parenthesized":false},"fragment":false,"hidden":false},{"$type":"TerminalRule","name":"NUMBER","type":{"$type":"ReturnType","name":"number"},"definition":{"$type":"TerminalAlternatives","elements":[{"$type":"TerminalRuleCall","rule":{"$ref":"#/rules@47"},"parenthesized":false},{"$type":"TerminalRuleCall","rule":{"$ref":"#/rules@48"},"parenthesized":false}],"parenthesized":false},"fragment":false,"hidden":false},{"$type":"TerminalRule","name":"STRING","type":{"$type":"ReturnType","name":"string"},"definition":{"$type":"RegexToken","regex":"/\\"([^\\"\\\\\\\\]|\\\\\\\\.)*\\"|'([^'\\\\\\\\]|\\\\\\\\.)*'/","parenthesized":false},"fragment":false,"hidden":false},{"$type":"TerminalRule","name":"ID","type":{"$type":"ReturnType","name":"string"},"definition":{"$type":"RegexToken","regex":"/[\\\\w]([-\\\\w]*\\\\w)?/","parenthesized":false},"fragment":false,"hidden":false},{"$type":"TerminalRule","name":"NEWLINE","definition":{"$type":"RegexToken","regex":"/\\\\r?\\\\n/","parenthesized":false},"fragment":false,"hidden":false},{"$type":"TerminalRule","hidden":true,"name":"WHITESPACE","definition":{"$type":"RegexToken","regex":"/[\\\\t ]+/","parenthesized":false},"fragment":false},{"$type":"TerminalRule","hidden":true,"name":"YAML","definition":{"$type":"RegexToken","regex":"/---[\\\\t ]*\\\\r?\\\\n(?:[\\\\S\\\\s]*?\\\\r?\\\\n)?---(?:\\\\r?\\\\n|(?!\\\\S))/","parenthesized":false},"fragment":false},{"$type":"TerminalRule","hidden":true,"name":"DIRECTIVE","definition":{"$type":"RegexToken","regex":"/[\\\\t ]*%%{[\\\\S\\\\s]*?}%%(?:\\\\r?\\\\n|(?!\\\\S))/","parenthesized":false},"fragment":false},{"$type":"TerminalRule","hidden":true,"name":"SINGLE_LINE_COMMENT","definition":{"$type":"RegexToken","regex":"/[\\\\t ]*%%[^\\\\n\\\\r]*/","parenthesized":false},"fragment":false}],"interfaces":[],"types":[]}`)), "WardleyGrammarGrammar");
var ArchitectureGrammarLanguageMetaData = {
languageId: "architecture",
fileExtensions: [".mmd", ".mermaid"],
caseInsensitive: false,
mode: "production"
};
var CynefinGrammarLanguageMetaData = {
languageId: "cynefin",
fileExtensions: [".mmd", ".mermaid"],
caseInsensitive: false,
mode: "production"
};
var EventModelingLanguageMetaData = {
languageId: "eventmodeling",
fileExtensions: [".mmd", ".mermaid"],
caseInsensitive: false,
mode: "production"
};
var GitGraphGrammarLanguageMetaData = {
languageId: "gitGraph",
fileExtensions: [".mmd", ".mermaid"],
caseInsensitive: false,
mode: "production"
};
var InfoGrammarLanguageMetaData = {
languageId: "info",
fileExtensions: [".mmd", ".mermaid"],
caseInsensitive: false,
mode: "production"
};
var PacketGrammarLanguageMetaData = {
languageId: "packet",
fileExtensions: [".mmd", ".mermaid"],
caseInsensitive: false,
mode: "production"
};
var PieGrammarLanguageMetaData = {
languageId: "pie",
fileExtensions: [".mmd", ".mermaid"],
caseInsensitive: false,
mode: "production"
};
var RadarGrammarLanguageMetaData = {
languageId: "radar",
fileExtensions: [".mmd", ".mermaid"],
caseInsensitive: false,
mode: "production"
};
var RailroadAbnfGrammarLanguageMetaData = {
languageId: "railroadAbnf",
fileExtensions: [".mmd", ".mermaid"],
caseInsensitive: false,
mode: "production"
};
var RailroadEbnfGrammarLanguageMetaData = {
languageId: "railroadEbnf",
fileExtensions: [".mmd", ".mermaid"],
caseInsensitive: false,
mode: "production"
};
var RailroadGrammarLanguageMetaData = {
languageId: "railroad",
fileExtensions: [".mmd", ".mermaid"],
caseInsensitive: false,
mode: "production"
};
var RailroadPegGrammarLanguageMetaData = {
languageId: "railroadPeg",
fileExtensions: [".mmd", ".mermaid"],
caseInsensitive: false,
mode: "production"
};
var TreemapGrammarLanguageMetaData = {
languageId: "treemap",
fileExtensions: [".mmd", ".mermaid"],
caseInsensitive: false,
mode: "production"
};
var TreeViewGrammarLanguageMetaData = {
languageId: "treeView",
fileExtensions: [".mmd", ".mermaid"],
caseInsensitive: false,
mode: "production"
};
var WardleyGrammarLanguageMetaData = {
languageId: "wardley",
fileExtensions: [".mmd", ".mermaid"],
caseInsensitive: false,
mode: "production"
};
var MermaidGeneratedSharedModule = {
AstReflection: /* @__PURE__ */ __name2(() => new MermaidAstReflection(), "AstReflection")
};
var ArchitectureGrammarGeneratedModule = {
Grammar: /* @__PURE__ */ __name2(() => ArchitectureGrammarGrammar(), "Grammar"),
LanguageMetaData: /* @__PURE__ */ __name2(() => ArchitectureGrammarLanguageMetaData, "LanguageMetaData"),
parser: {}
};
var CynefinGrammarGeneratedModule = {
Grammar: /* @__PURE__ */ __name2(() => CynefinGrammarGrammar(), "Grammar"),
LanguageMetaData: /* @__PURE__ */ __name2(() => CynefinGrammarLanguageMetaData, "LanguageMetaData"),
parser: {}
};
var EventModelingGeneratedModule = {
Grammar: /* @__PURE__ */ __name2(() => EventModelingGrammar(), "Grammar"),
LanguageMetaData: /* @__PURE__ */ __name2(() => EventModelingLanguageMetaData, "LanguageMetaData"),
parser: {}
};
var GitGraphGrammarGeneratedModule = {
Grammar: /* @__PURE__ */ __name2(() => GitGraphGrammarGrammar(), "Grammar"),
LanguageMetaData: /* @__PURE__ */ __name2(() => GitGraphGrammarLanguageMetaData, "LanguageMetaData"),
parser: {}
};
var InfoGrammarGeneratedModule = {
Grammar: /* @__PURE__ */ __name2(() => InfoGrammarGrammar(), "Grammar"),
LanguageMetaData: /* @__PURE__ */ __name2(() => InfoGrammarLanguageMetaData, "LanguageMetaData"),
parser: {}
};
var PacketGrammarGeneratedModule = {
Grammar: /* @__PURE__ */ __name2(() => PacketGrammarGrammar(), "Grammar"),
LanguageMetaData: /* @__PURE__ */ __name2(() => PacketGrammarLanguageMetaData, "LanguageMetaData"),
parser: {}
};
var PieGrammarGeneratedModule = {
Grammar: /* @__PURE__ */ __name2(() => PieGrammarGrammar(), "Grammar"),
LanguageMetaData: /* @__PURE__ */ __name2(() => PieGrammarLanguageMetaData, "LanguageMetaData"),
parser: {}
};
var RadarGrammarGeneratedModule = {
Grammar: /* @__PURE__ */ __name2(() => RadarGrammarGrammar(), "Grammar"),
LanguageMetaData: /* @__PURE__ */ __name2(() => RadarGrammarLanguageMetaData, "LanguageMetaData"),
parser: {}
};
var RailroadAbnfGrammarGeneratedModule = {
Grammar: /* @__PURE__ */ __name2(() => RailroadAbnfGrammarGrammar(), "Grammar"),
LanguageMetaData: /* @__PURE__ */ __name2(() => RailroadAbnfGrammarLanguageMetaData, "LanguageMetaData"),
parser: {}
};
var RailroadEbnfGrammarGeneratedModule = {
Grammar: /* @__PURE__ */ __name2(() => RailroadEbnfGrammarGrammar(), "Grammar"),
LanguageMetaData: /* @__PURE__ */ __name2(() => RailroadEbnfGrammarLanguageMetaData, "LanguageMetaData"),
parser: {}
};
var RailroadGrammarGeneratedModule = {
Grammar: /* @__PURE__ */ __name2(() => RailroadGrammarGrammar(), "Grammar"),
LanguageMetaData: /* @__PURE__ */ __name2(() => RailroadGrammarLanguageMetaData, "LanguageMetaData"),
parser: {}
};
var RailroadPegGrammarGeneratedModule = {
Grammar: /* @__PURE__ */ __name2(() => RailroadPegGrammarGrammar(), "Grammar"),
LanguageMetaData: /* @__PURE__ */ __name2(() => RailroadPegGrammarLanguageMetaData, "LanguageMetaData"),
parser: {}
};
var TreemapGrammarGeneratedModule = {
Grammar: /* @__PURE__ */ __name2(() => TreemapGrammarGrammar(), "Grammar"),
LanguageMetaData: /* @__PURE__ */ __name2(() => TreemapGrammarLanguageMetaData, "LanguageMetaData"),
parser: {}
};
var TreeViewGrammarGeneratedModule = {
Grammar: /* @__PURE__ */ __name2(() => TreeViewGrammarGrammar(), "Grammar"),
LanguageMetaData: /* @__PURE__ */ __name2(() => TreeViewGrammarLanguageMetaData, "LanguageMetaData"),
parser: {}
};
var WardleyGrammarGeneratedModule = {
Grammar: /* @__PURE__ */ __name2(() => WardleyGrammarGrammar(), "Grammar"),
LanguageMetaData: /* @__PURE__ */ __name2(() => WardleyGrammarLanguageMetaData, "LanguageMetaData"),
parser: {}
};
var accessibilityDescrRegex = /accDescr(?:[\t ]*:([^\n\r]*)|\s*{([^}]*)})/;
var accessibilityTitleRegex = /accTitle[\t ]*:([^\n\r]*)/;
var titleRegex = /title([\t ][^\n\r]*|)/;
var rulesRegexes = {
ACC_DESCR: accessibilityDescrRegex,
ACC_TITLE: accessibilityTitleRegex,
TITLE: titleRegex
};
var AbstractMermaidValueConverter = class extends DefaultValueConverter {
static {
__name(this, "AbstractMermaidValueConverter");
}
static {
__name2(this, "AbstractMermaidValueConverter");
}
runConverter(rule, input, cstNode) {
let value = this.runCommonConverter(rule, input, cstNode);
if (value === void 0) {
value = this.runCustomConverter(rule, input, cstNode);
}
if (value === void 0) {
return super.runConverter(rule, input, cstNode);
}
return value;
}
runCommonConverter(rule, input, _cstNode) {
const regex = rulesRegexes[rule.name];
if (regex === void 0) {
return void 0;
}
const match = regex.exec(input);
if (match === null) {
return void 0;
}
if (match[1] !== void 0) {
return match[1].trim().replace(/[\t ]{2,}/gm, " ");
}
if (match[2] !== void 0) {
return match[2].replace(/^\s*/gm, "").replace(/\s+$/gm, "").replace(/[\t ]{2,}/gm, " ").replace(/[\n\r]{2,}/gm, "\n");
}
return void 0;
}
};
var CommonValueConverter = class extends AbstractMermaidValueConverter {
static {
__name(this, "CommonValueConverter");
}
static {
__name2(this, "CommonValueConverter");
}
runCustomConverter(_rule, _input, _cstNode) {
return void 0;
}
};
var AbstractMermaidTokenBuilder = class extends DefaultTokenBuilder {
static {
__name(this, "AbstractMermaidTokenBuilder");
}
static {
__name2(this, "AbstractMermaidTokenBuilder");
}
constructor(keywords) {
super();
this.keywords = new Set(keywords);
}
buildKeywordTokens(rules, terminalTokens, options) {
const tokenTypes = super.buildKeywordTokens(rules, terminalTokens, options);
tokenTypes.forEach((tokenType) => {
if (this.keywords.has(tokenType.name) && tokenType.PATTERN !== void 0) {
tokenType.PATTERN = new RegExp(tokenType.PATTERN.toString() + "(?:(?=%%)|(?!\\S))");
}
});
return tokenTypes;
}
};
var CommonTokenBuilder = class extends AbstractMermaidTokenBuilder {
static {
__name(this, "CommonTokenBuilder");
}
static {
__name2(this, "CommonTokenBuilder");
}
};
export {
__name2 as __name,
createDefaultCoreModule,
createDefaultSharedCoreModule,
inject,
EmptyFileSystem,
isEmResetFrame,
MermaidGeneratedSharedModule,
ArchitectureGrammarGeneratedModule,
CynefinGrammarGeneratedModule,
EventModelingGeneratedModule,
GitGraphGrammarGeneratedModule,
InfoGrammarGeneratedModule,
PacketGrammarGeneratedModule,
PieGrammarGeneratedModule,
RadarGrammarGeneratedModule,
RailroadAbnfGrammarGeneratedModule,
RailroadEbnfGrammarGeneratedModule,
RailroadGrammarGeneratedModule,
RailroadPegGrammarGeneratedModule,
TreemapGrammarGeneratedModule,
TreeViewGrammarGeneratedModule,
WardleyGrammarGeneratedModule,
AbstractMermaidValueConverter,
CommonValueConverter,
AbstractMermaidTokenBuilder
};
/*! Bundled license information:
lodash-es/lodash.js:
(**
* @license
* Lodash (Custom Build) <https://lodash.com/>
* Build: `lodash modularize exports="es" -o ./`
* Copyright OpenJS Foundation and other contributors <https://openjsf.org/>
* Released under MIT license <https://lodash.com/license>
* Based on Underscore.js 1.8.3 <http://underscorejs.org/LICENSE>
* Copyright Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
*)
*/