@matdata/yasgui-explain-plugin 0.1.0 → 1.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +201 -201
- package/README.md +92 -91
- package/dist/ExplainPlugin.d.ts +64 -0
- package/dist/ExplainPlugin.d.ts.map +1 -0
- package/dist/algebra/print.d.ts +21 -0
- package/dist/algebra/print.d.ts.map +1 -0
- package/dist/algebra/terms.d.ts +18 -0
- package/dist/algebra/terms.d.ts.map +1 -0
- package/dist/algebra/translate.d.ts +19 -0
- package/dist/algebra/translate.d.ts.map +1 -0
- package/dist/engines/blazegraph.d.ts +12 -0
- package/dist/engines/blazegraph.d.ts.map +1 -0
- package/dist/engines/graphdb.d.ts +23 -0
- package/dist/engines/graphdb.d.ts.map +1 -0
- package/dist/engines/index.d.ts +23 -0
- package/dist/engines/index.d.ts.map +1 -0
- package/dist/engines/neptune.d.ts +11 -0
- package/dist/engines/neptune.d.ts.map +1 -0
- package/dist/engines/qlever.d.ts +35 -0
- package/dist/engines/qlever.d.ts.map +1 -0
- package/dist/engines/stardog.d.ts +14 -0
- package/dist/engines/stardog.d.ts.map +1 -0
- package/dist/engines/tripletrail.d.ts +18 -0
- package/dist/engines/tripletrail.d.ts.map +1 -0
- package/dist/host.d.ts +24 -0
- package/dist/host.d.ts.map +1 -0
- package/dist/icons.d.ts +22 -0
- package/dist/icons.d.ts.map +1 -0
- package/dist/index.d.ts +17 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/render.d.ts +46 -0
- package/dist/render.d.ts.map +1 -0
- package/dist/settings.d.ts +11 -0
- package/dist/settings.d.ts.map +1 -0
- package/dist/types.d.ts +141 -0
- package/dist/types.d.ts.map +1 -0
- package/dist/yasgui-explain-plugin.cjs.js +20602 -0
- package/dist/yasgui-explain-plugin.cjs.js.map +7 -0
- package/dist/yasgui-explain-plugin.css +354 -0
- package/dist/yasgui-explain-plugin.esm.js +20596 -0
- package/dist/yasgui-explain-plugin.esm.js.map +7 -0
- package/dist/yasgui-explain-plugin.min.css +1 -0
- package/dist/yasgui-explain-plugin.min.js +147 -0
- package/dist/yasgui-explain-plugin.min.js.map +7 -0
- package/package.json +74 -73
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
{
|
|
2
|
+
"version": 3,
|
|
3
|
+
"sources": ["../node_modules/fast-deep-equal/index.js", "../node_modules/rdf-data-factory/lib/BlankNode.ts", "../node_modules/rdf-data-factory/lib/DefaultGraph.ts", "../node_modules/rdf-data-factory/lib/NamedNode.ts", "../node_modules/rdf-data-factory/lib/Literal.ts", "../node_modules/rdf-data-factory/lib/Quad.ts", "../node_modules/rdf-data-factory/lib/Variable.ts", "../node_modules/rdf-data-factory/lib/DataFactory.ts", "../node_modules/rdf-data-factory/index.ts", "../node_modules/rdf-string/lib/TermUtil.ts", "../node_modules/rdf-string/index.ts", "../src/index.ts", "../src/engines/qlever.ts", "../src/engines/graphdb.ts", "../src/engines/stardog.ts", "../src/engines/blazegraph.ts", "../src/engines/neptune.ts", "../src/engines/tripletrail.ts", "../src/engines/index.ts", "../src/settings.ts", "../src/host.ts", "../node_modules/@traqula/core/lib/AstCoreFactory.ts", "../node_modules/node_modules/chevrotain/src/version.ts", "../node_modules/node_modules/lodash-es/_freeGlobal.js", "../node_modules/node_modules/lodash-es/_root.js", "../node_modules/node_modules/lodash-es/_Symbol.js", "../node_modules/node_modules/lodash-es/_getRawTag.js", "../node_modules/node_modules/lodash-es/_objectToString.js", "../node_modules/node_modules/lodash-es/_baseGetTag.js", "../node_modules/node_modules/lodash-es/isObjectLike.js", "../node_modules/node_modules/lodash-es/isSymbol.js", "../node_modules/node_modules/lodash-es/_arrayMap.js", "../node_modules/node_modules/lodash-es/isArray.js", "../node_modules/node_modules/lodash-es/_baseToString.js", "../node_modules/node_modules/lodash-es/_trimmedEndIndex.js", "../node_modules/node_modules/lodash-es/_baseTrim.js", "../node_modules/node_modules/lodash-es/isObject.js", "../node_modules/node_modules/lodash-es/toNumber.js", "../node_modules/node_modules/lodash-es/toFinite.js", "../node_modules/node_modules/lodash-es/toInteger.js", "../node_modules/node_modules/lodash-es/identity.js", "../node_modules/node_modules/lodash-es/isFunction.js", "../node_modules/node_modules/lodash-es/_coreJsData.js", "../node_modules/node_modules/lodash-es/_isMasked.js", "../node_modules/node_modules/lodash-es/_toSource.js", "../node_modules/node_modules/lodash-es/_baseIsNative.js", "../node_modules/node_modules/lodash-es/_getValue.js", "../node_modules/node_modules/lodash-es/_getNative.js", "../node_modules/node_modules/lodash-es/_WeakMap.js", "../node_modules/node_modules/lodash-es/_baseCreate.js", "../node_modules/node_modules/lodash-es/_apply.js", "../node_modules/node_modules/lodash-es/noop.js", "../node_modules/node_modules/lodash-es/_copyArray.js", "../node_modules/node_modules/lodash-es/_shortOut.js", "../node_modules/node_modules/lodash-es/constant.js", "../node_modules/node_modules/lodash-es/_defineProperty.js", "../node_modules/node_modules/lodash-es/_baseSetToString.js", "../node_modules/node_modules/lodash-es/_setToString.js", "../node_modules/node_modules/lodash-es/_arrayEach.js", "../node_modules/node_modules/lodash-es/_baseFindIndex.js", "../node_modules/node_modules/lodash-es/_baseIsNaN.js", "../node_modules/node_modules/lodash-es/_strictIndexOf.js", "../node_modules/node_modules/lodash-es/_baseIndexOf.js", "../node_modules/node_modules/lodash-es/_arrayIncludes.js", "../node_modules/node_modules/lodash-es/_isIndex.js", "../node_modules/node_modules/lodash-es/_baseAssignValue.js", "../node_modules/node_modules/lodash-es/eq.js", "../node_modules/node_modules/lodash-es/_assignValue.js", "../node_modules/node_modules/lodash-es/_copyObject.js", "../node_modules/node_modules/lodash-es/_overRest.js", "../node_modules/node_modules/lodash-es/_baseRest.js", "../node_modules/node_modules/lodash-es/isLength.js", "../node_modules/node_modules/lodash-es/isArrayLike.js", "../node_modules/node_modules/lodash-es/_isIterateeCall.js", "../node_modules/node_modules/lodash-es/_createAssigner.js", "../node_modules/node_modules/lodash-es/_isPrototype.js", "../node_modules/node_modules/lodash-es/_baseTimes.js", "../node_modules/node_modules/lodash-es/_baseIsArguments.js", "../node_modules/node_modules/lodash-es/isArguments.js", "../node_modules/node_modules/lodash-es/stubFalse.js", "../node_modules/node_modules/lodash-es/isBuffer.js", "../node_modules/node_modules/lodash-es/_baseIsTypedArray.js", "../node_modules/node_modules/lodash-es/_baseUnary.js", "../node_modules/node_modules/lodash-es/_nodeUtil.js", "../node_modules/node_modules/lodash-es/isTypedArray.js", "../node_modules/node_modules/lodash-es/_arrayLikeKeys.js", "../node_modules/node_modules/lodash-es/_overArg.js", "../node_modules/node_modules/lodash-es/_nativeKeys.js", "../node_modules/node_modules/lodash-es/_baseKeys.js", "../node_modules/node_modules/lodash-es/keys.js", "../node_modules/node_modules/lodash-es/assign.js", "../node_modules/node_modules/lodash-es/_nativeKeysIn.js", "../node_modules/node_modules/lodash-es/_baseKeysIn.js", "../node_modules/node_modules/lodash-es/keysIn.js", "../node_modules/node_modules/lodash-es/_isKey.js", "../node_modules/node_modules/lodash-es/_nativeCreate.js", "../node_modules/node_modules/lodash-es/_hashClear.js", "../node_modules/node_modules/lodash-es/_hashDelete.js", "../node_modules/node_modules/lodash-es/_hashGet.js", "../node_modules/node_modules/lodash-es/_hashHas.js", "../node_modules/node_modules/lodash-es/_hashSet.js", "../node_modules/node_modules/lodash-es/_Hash.js", "../node_modules/node_modules/lodash-es/_listCacheClear.js", "../node_modules/node_modules/lodash-es/_assocIndexOf.js", "../node_modules/node_modules/lodash-es/_listCacheDelete.js", "../node_modules/node_modules/lodash-es/_listCacheGet.js", "../node_modules/node_modules/lodash-es/_listCacheHas.js", "../node_modules/node_modules/lodash-es/_listCacheSet.js", "../node_modules/node_modules/lodash-es/_ListCache.js", "../node_modules/node_modules/lodash-es/_Map.js", "../node_modules/node_modules/lodash-es/_mapCacheClear.js", "../node_modules/node_modules/lodash-es/_isKeyable.js", "../node_modules/node_modules/lodash-es/_getMapData.js", "../node_modules/node_modules/lodash-es/_mapCacheDelete.js", "../node_modules/node_modules/lodash-es/_mapCacheGet.js", "../node_modules/node_modules/lodash-es/_mapCacheHas.js", "../node_modules/node_modules/lodash-es/_mapCacheSet.js", "../node_modules/node_modules/lodash-es/_MapCache.js", "../node_modules/node_modules/lodash-es/memoize.js", "../node_modules/node_modules/lodash-es/_memoizeCapped.js", "../node_modules/node_modules/lodash-es/_stringToPath.js", "../node_modules/node_modules/lodash-es/toString.js", "../node_modules/node_modules/lodash-es/_castPath.js", "../node_modules/node_modules/lodash-es/_toKey.js", "../node_modules/node_modules/lodash-es/_baseGet.js", "../node_modules/node_modules/lodash-es/get.js", "../node_modules/node_modules/lodash-es/_arrayPush.js", "../node_modules/node_modules/lodash-es/_isFlattenable.js", "../node_modules/node_modules/lodash-es/_baseFlatten.js", "../node_modules/node_modules/lodash-es/flatten.js", "../node_modules/node_modules/lodash-es/_getPrototype.js", "../node_modules/node_modules/lodash-es/_baseSlice.js", "../node_modules/node_modules/lodash-es/_castSlice.js", "../node_modules/node_modules/lodash-es/_hasUnicode.js", "../node_modules/node_modules/lodash-es/_asciiToArray.js", "../node_modules/node_modules/lodash-es/_unicodeToArray.js", "../node_modules/node_modules/lodash-es/_stringToArray.js", "../node_modules/node_modules/lodash-es/_createCaseFirst.js", "../node_modules/node_modules/lodash-es/upperFirst.js", "../node_modules/node_modules/lodash-es/_arrayReduce.js", "../node_modules/node_modules/lodash-es/_stackClear.js", "../node_modules/node_modules/lodash-es/_stackDelete.js", "../node_modules/node_modules/lodash-es/_stackGet.js", "../node_modules/node_modules/lodash-es/_stackHas.js", "../node_modules/node_modules/lodash-es/_stackSet.js", "../node_modules/node_modules/lodash-es/_Stack.js", "../node_modules/node_modules/lodash-es/_baseAssign.js", "../node_modules/node_modules/lodash-es/_baseAssignIn.js", "../node_modules/node_modules/lodash-es/_cloneBuffer.js", "../node_modules/node_modules/lodash-es/_arrayFilter.js", "../node_modules/node_modules/lodash-es/stubArray.js", "../node_modules/node_modules/lodash-es/_getSymbols.js", "../node_modules/node_modules/lodash-es/_copySymbols.js", "../node_modules/node_modules/lodash-es/_getSymbolsIn.js", "../node_modules/node_modules/lodash-es/_copySymbolsIn.js", "../node_modules/node_modules/lodash-es/_baseGetAllKeys.js", "../node_modules/node_modules/lodash-es/_getAllKeys.js", "../node_modules/node_modules/lodash-es/_getAllKeysIn.js", "../node_modules/node_modules/lodash-es/_DataView.js", "../node_modules/node_modules/lodash-es/_Promise.js", "../node_modules/node_modules/lodash-es/_Set.js", "../node_modules/node_modules/lodash-es/_getTag.js", "../node_modules/node_modules/lodash-es/_initCloneArray.js", "../node_modules/node_modules/lodash-es/_Uint8Array.js", "../node_modules/node_modules/lodash-es/_cloneArrayBuffer.js", "../node_modules/node_modules/lodash-es/_cloneDataView.js", "../node_modules/node_modules/lodash-es/_cloneRegExp.js", "../node_modules/node_modules/lodash-es/_cloneSymbol.js", "../node_modules/node_modules/lodash-es/_cloneTypedArray.js", "../node_modules/node_modules/lodash-es/_initCloneByTag.js", "../node_modules/node_modules/lodash-es/_initCloneObject.js", "../node_modules/node_modules/lodash-es/_baseIsMap.js", "../node_modules/node_modules/lodash-es/isMap.js", "../node_modules/node_modules/lodash-es/_baseIsSet.js", "../node_modules/node_modules/lodash-es/isSet.js", "../node_modules/node_modules/lodash-es/_baseClone.js", "../node_modules/node_modules/lodash-es/clone.js", "../node_modules/node_modules/lodash-es/compact.js", "../node_modules/node_modules/lodash-es/_setCacheAdd.js", "../node_modules/node_modules/lodash-es/_setCacheHas.js", "../node_modules/node_modules/lodash-es/_SetCache.js", "../node_modules/node_modules/lodash-es/_arraySome.js", "../node_modules/node_modules/lodash-es/_cacheHas.js", "../node_modules/node_modules/lodash-es/_equalArrays.js", "../node_modules/node_modules/lodash-es/_mapToArray.js", "../node_modules/node_modules/lodash-es/_setToArray.js", "../node_modules/node_modules/lodash-es/_equalByTag.js", "../node_modules/node_modules/lodash-es/_equalObjects.js", "../node_modules/node_modules/lodash-es/_baseIsEqualDeep.js", "../node_modules/node_modules/lodash-es/_baseIsEqual.js", "../node_modules/node_modules/lodash-es/_baseIsMatch.js", "../node_modules/node_modules/lodash-es/_isStrictComparable.js", "../node_modules/node_modules/lodash-es/_getMatchData.js", "../node_modules/node_modules/lodash-es/_matchesStrictComparable.js", "../node_modules/node_modules/lodash-es/_baseMatches.js", "../node_modules/node_modules/lodash-es/_baseHasIn.js", "../node_modules/node_modules/lodash-es/_hasPath.js", "../node_modules/node_modules/lodash-es/hasIn.js", "../node_modules/node_modules/lodash-es/_baseMatchesProperty.js", "../node_modules/node_modules/lodash-es/_baseProperty.js", "../node_modules/node_modules/lodash-es/_basePropertyDeep.js", "../node_modules/node_modules/lodash-es/property.js", "../node_modules/node_modules/lodash-es/_baseIteratee.js", "../node_modules/node_modules/lodash-es/_arrayAggregator.js", "../node_modules/node_modules/lodash-es/_createBaseFor.js", "../node_modules/node_modules/lodash-es/_baseFor.js", "../node_modules/node_modules/lodash-es/_baseForOwn.js", "../node_modules/node_modules/lodash-es/_createBaseEach.js", "../node_modules/node_modules/lodash-es/_baseEach.js", "../node_modules/node_modules/lodash-es/_baseAggregator.js", "../node_modules/node_modules/lodash-es/_createAggregator.js", "../node_modules/node_modules/lodash-es/defaults.js", "../node_modules/node_modules/lodash-es/isArrayLikeObject.js", "../node_modules/node_modules/lodash-es/_arrayIncludesWith.js", "../node_modules/node_modules/lodash-es/_baseDifference.js", "../node_modules/node_modules/lodash-es/difference.js", "../node_modules/node_modules/lodash-es/last.js", "../node_modules/node_modules/lodash-es/drop.js", "../node_modules/node_modules/lodash-es/dropRight.js", "../node_modules/node_modules/lodash-es/_castFunction.js", "../node_modules/node_modules/lodash-es/forEach.js", "../node_modules/node_modules/lodash-es/_arrayEvery.js", "../node_modules/node_modules/lodash-es/_baseEvery.js", "../node_modules/node_modules/lodash-es/every.js", "../node_modules/node_modules/lodash-es/_baseFilter.js", "../node_modules/node_modules/lodash-es/filter.js", "../node_modules/node_modules/lodash-es/_createFind.js", "../node_modules/node_modules/lodash-es/findIndex.js", "../node_modules/node_modules/lodash-es/find.js", "../node_modules/node_modules/lodash-es/head.js", "../node_modules/node_modules/lodash-es/_baseMap.js", "../node_modules/node_modules/lodash-es/map.js", "../node_modules/node_modules/lodash-es/flatMap.js", "../node_modules/node_modules/lodash-es/groupBy.js", "../node_modules/node_modules/lodash-es/_baseHas.js", "../node_modules/node_modules/lodash-es/has.js", "../node_modules/node_modules/lodash-es/isString.js", "../node_modules/node_modules/lodash-es/_baseValues.js", "../node_modules/node_modules/lodash-es/values.js", "../node_modules/node_modules/lodash-es/includes.js", "../node_modules/node_modules/lodash-es/indexOf.js", "../node_modules/node_modules/lodash-es/isEmpty.js", "../node_modules/node_modules/lodash-es/_baseIsRegExp.js", "../node_modules/node_modules/lodash-es/isRegExp.js", "../node_modules/node_modules/lodash-es/isUndefined.js", "../node_modules/node_modules/lodash-es/negate.js", "../node_modules/node_modules/lodash-es/_baseSet.js", "../node_modules/node_modules/lodash-es/_basePickBy.js", "../node_modules/node_modules/lodash-es/pickBy.js", "../node_modules/node_modules/lodash-es/_baseReduce.js", "../node_modules/node_modules/lodash-es/reduce.js", "../node_modules/node_modules/lodash-es/reject.js", "../node_modules/node_modules/lodash-es/_baseSome.js", "../node_modules/node_modules/lodash-es/some.js", "../node_modules/node_modules/lodash-es/_createSet.js", "../node_modules/node_modules/lodash-es/_baseUniq.js", "../node_modules/node_modules/lodash-es/uniq.js", "../node_modules/node_modules/@chevrotain/utils/src/print.ts", "../node_modules/node_modules/@chevrotain/utils/src/timer.ts", "../node_modules/node_modules/@chevrotain/utils/src/to-fast-properties.ts", "../node_modules/node_modules/@chevrotain/gast/src/model.ts", "../node_modules/node_modules/@chevrotain/gast/src/visitor.ts", "../node_modules/node_modules/@chevrotain/gast/src/helpers.ts", "../node_modules/node_modules/chevrotain/src/parse/grammar/rest.ts", "../node_modules/node_modules/chevrotain/src/parse/grammar/first.ts", "../node_modules/node_modules/chevrotain/src/parse/constants.ts", "../node_modules/node_modules/chevrotain/src/parse/grammar/follow.ts", "../node_modules/node_modules/@chevrotain/regexp-to-ast/src/utils.ts", "../node_modules/node_modules/@chevrotain/regexp-to-ast/src/character-classes.ts", "../node_modules/node_modules/@chevrotain/regexp-to-ast/src/regexp-parser.ts", "../node_modules/node_modules/@chevrotain/regexp-to-ast/src/base-regexp-visitor.ts", "../node_modules/node_modules/chevrotain/src/scan/reg_exp_parser.ts", "../node_modules/node_modules/chevrotain/src/scan/reg_exp.ts", "../node_modules/node_modules/chevrotain/src/scan/lexer.ts", "../node_modules/node_modules/chevrotain/src/scan/tokens.ts", "../node_modules/node_modules/chevrotain/src/scan/lexer_errors_public.ts", "../node_modules/node_modules/chevrotain/src/scan/lexer_public.ts", "../node_modules/node_modules/chevrotain/src/scan/tokens_public.ts", "../node_modules/node_modules/chevrotain/src/parse/errors_public.ts", "../node_modules/node_modules/chevrotain/src/parse/grammar/resolver.ts", "../node_modules/node_modules/chevrotain/src/parse/grammar/interpreter.ts", "../node_modules/node_modules/chevrotain/src/parse/grammar/lookahead.ts", "../node_modules/node_modules/chevrotain/src/parse/grammar/checks.ts", "../node_modules/node_modules/chevrotain/src/parse/grammar/gast/gast_resolver_public.ts", "../node_modules/node_modules/chevrotain/src/parse/exceptions_public.ts", "../node_modules/node_modules/chevrotain/src/parse/parser/traits/recoverable.ts", "../node_modules/node_modules/chevrotain/src/parse/grammar/keys.ts", "../node_modules/node_modules/chevrotain/src/parse/grammar/llk_lookahead.ts", "../node_modules/node_modules/chevrotain/src/parse/parser/traits/looksahead.ts", "../node_modules/node_modules/chevrotain/src/parse/cst/cst.ts", "../node_modules/node_modules/chevrotain/src/lang/lang_extensions.ts", "../node_modules/node_modules/chevrotain/src/parse/cst/cst_visitor.ts", "../node_modules/node_modules/chevrotain/src/parse/parser/traits/tree_builder.ts", "../node_modules/node_modules/chevrotain/src/parse/parser/traits/lexer_adapter.ts", "../node_modules/node_modules/chevrotain/src/parse/parser/traits/recognizer_api.ts", "../node_modules/node_modules/chevrotain/src/parse/parser/traits/recognizer_engine.ts", "../node_modules/node_modules/chevrotain/src/parse/parser/traits/error_handler.ts", "../node_modules/node_modules/chevrotain/src/parse/parser/traits/context_assist.ts", "../node_modules/node_modules/chevrotain/src/parse/parser/traits/gast_recorder.ts", "../node_modules/node_modules/chevrotain/src/parse/parser/traits/perf_tracer.ts", "../node_modules/node_modules/chevrotain/src/parse/parser/utils/apply_mixins.ts", "../node_modules/node_modules/chevrotain/src/parse/parser/parser.ts", "../node_modules/node_modules/@chevrotain/cst-dts-gen/src/model.ts", "../node_modules/node_modules/@chevrotain/cst-dts-gen/src/generate.ts", "../node_modules/node_modules/@chevrotain/cst-dts-gen/src/api.ts", "../node_modules/node_modules/chevrotain/src/diagrams/render_public.ts", "../node_modules/node_modules/chevrotain/src/api.ts", "../node_modules/@traqula/core/lib/utils.ts", "../node_modules/@traqula/core/lib/indirection-builder/helpers.ts", "../node_modules/@traqula/core/lib/indirection-builder/dynamicIndirected.ts", "../node_modules/@traqula/core/lib/indirection-builder/IndirBuilder.ts", "../node_modules/@traqula/core/lib/lexer-builder/LexerBuilder.ts", "../node_modules/@traqula/core/lib/parser-builder/dynamicParser.ts", "../node_modules/@traqula/core/lib/parser-builder/parserBuilder.ts", "../node_modules/@traqula/core/lib/transformers/TransformerObject.ts", "../node_modules/@traqula/core/lib/transformers/TransformerTyped.ts", "../node_modules/@traqula/core/lib/transformers/TransformerSubTyped.ts", "../node_modules/@traqula/rules-sparql-1-1/lib/grammar/index.ts", "../node_modules/@traqula/rules-sparql-1-1/lib/lexer/index.ts", "../node_modules/@traqula/rules-sparql-1-1/lib/lexer/BuiltInCalls.ts", "../node_modules/@traqula/rules-sparql-1-1/lib/lexer/graph.ts", "../node_modules/@traqula/rules-sparql-1-1/lib/lexer/lexerPatterns.ts", "../node_modules/@traqula/rules-sparql-1-1/lib/lexer/symbols.ts", "../node_modules/@traqula/rules-sparql-1-1/lib/lexer/terminals.ts", "../node_modules/@traqula/rules-sparql-1-1/lib/lexer/lexer.ts", "../node_modules/@traqula/rules-sparql-1-1/lib/validation/validators.ts", "../node_modules/@traqula/rules-sparql-1-1/lib/factoryMixins/ContextFactory.ts", "../node_modules/@traqula/rules-sparql-1-1/lib/factoryMixins/ExpressionFactory.ts", "../node_modules/@traqula/rules-sparql-1-1/lib/factoryMixins/GraphRefFactory.ts", "../node_modules/@traqula/rules-sparql-1-1/lib/factoryMixins/mixins.ts", "../node_modules/@traqula/rules-sparql-1-1/lib/factoryMixins/PathFactory.ts", "../node_modules/@traqula/rules-sparql-1-1/lib/factoryMixins/Patternfactory.ts", "../node_modules/@traqula/rules-sparql-1-1/lib/factoryMixins/QueryFactory.ts", "../node_modules/@traqula/rules-sparql-1-1/lib/factoryMixins/SolutionModifiersFactory.ts", "../node_modules/@traqula/rules-sparql-1-1/lib/factoryMixins/TermFactory.ts", "../node_modules/@traqula/rules-sparql-1-1/lib/factoryMixins/UpdateOperationFactory.ts", "../node_modules/@traqula/rules-sparql-1-1/lib/astFactory.ts", "../node_modules/@traqula/rules-sparql-1-1/lib/utils.ts", "../node_modules/@traqula/rules-sparql-1-1/lib/grammar/literals.ts", "../node_modules/@traqula/rules-sparql-1-1/lib/grammar/general.ts", "../node_modules/@traqula/rules-sparql-1-1/lib/grammar/dataSetClause.ts", "../node_modules/@traqula/rules-sparql-1-1/lib/expressionHelpers.ts", "../node_modules/@traqula/rules-sparql-1-1/lib/grammar/builtIn.ts", "../node_modules/@traqula/rules-sparql-1-1/lib/grammar/propertyPaths.ts", "../node_modules/@traqula/rules-sparql-1-1/lib/grammar/tripleBlock.ts", "../node_modules/@traqula/rules-sparql-1-1/lib/grammar/whereClause.ts", "../node_modules/@traqula/rules-sparql-1-1/lib/grammar/expression.ts", "../node_modules/@traqula/rules-sparql-1-1/lib/grammar/solutionModifier.ts", "../node_modules/@traqula/rules-sparql-1-1/lib/grammar/queryUnit.ts", "../node_modules/@traqula/rules-sparql-1-1/lib/grammar/updateUnit.ts", "../node_modules/@traqula/parser-sparql-1-1/lib/expressionParser.ts", "../node_modules/@traqula/parser-sparql-1-1/lib/objectListParser.ts", "../node_modules/@traqula/parser-sparql-1-1/lib/triplesBlockParser.ts", "../node_modules/@traqula/parser-sparql-1-1/lib/subSelectParser.ts", "../node_modules/@traqula/parser-sparql-1-1/lib/triplesTemplateParserBuilder.ts", "../node_modules/@traqula/parser-sparql-1-1/lib/queryUnitParser.ts", "../node_modules/@traqula/parser-sparql-1-1/lib/updateNoModifyParser.ts", "../node_modules/@traqula/parser-sparql-1-1/lib/updateUnitParser.ts", "../node_modules/@traqula/parser-sparql-1-1/lib/Parser.ts", "../node_modules/@traqula/rules-sparql-1-2/lib/validators.ts", "../node_modules/@traqula/rules-sparql-1-2/lib/AstFactory.ts", "../node_modules/@traqula/rules-sparql-1-2/lib/grammar.ts", "../node_modules/@traqula/rules-sparql-1-2/lib/lexer.ts", "../node_modules/@traqula/rules-sparql-1-2/lib/parserUtils.ts", "../node_modules/@traqula/rules-sparql-1-2/lib/index.ts", "../node_modules/@traqula/parser-sparql-1-2/lib/Parser.ts", "../node_modules/@traqula/algebra-transformations-1-1/lib/toAlgebra/aggregate.ts", "../node_modules/@traqula/algebra-transformations-1-1/lib/algebra.ts", "../node_modules/@traqula/algebra-transformations-1-1/lib/util.ts", "../node_modules/@traqula/algebra-transformations-1-1/lib/toAlgebra/general.ts", "../node_modules/@traqula/algebra-transformations-1-1/lib/toAlgebra/core.ts", "../node_modules/@traqula/algebra-transformations-1-1/lib/algebraFactory.ts", "../node_modules/@traqula/algebra-transformations-1-1/lib/toAlgebra/path.ts", "../node_modules/@traqula/algebra-transformations-1-1/lib/toAlgebra/tripleAndQuad.ts", "../node_modules/@traqula/algebra-transformations-1-1/lib/toAlgebra/updates.ts", "../node_modules/@traqula/algebra-transformations-1-1/lib/toAlgebra/toAlgebra.ts", "../node_modules/@traqula/algebra-transformations-1-1/lib/toAlgebra/patterns.ts", "../node_modules/@traqula/algebra-sparql-1-1/lib/toAlgebra.ts", "../node_modules/@traqula/algebra-transformations-1-2/lib/toAlgebra12.ts", "../node_modules/@traqula/algebra-transformations-1-2/lib/types.ts", "../node_modules/@traqula/algebra-sparql-1-2/lib/toAlgebra12.ts", "../src/algebra/translate.ts", "../src/algebra/terms.ts", "../src/algebra/print.ts", "../src/icons.ts", "../src/render.ts", "../src/ExplainPlugin.ts"],
|
|
4
|
+
"sourcesContent": ["'use strict';\n\n// do not edit .js files directly - edit src/index.jst\n\n\n\nmodule.exports = function equal(a, b) {\n if (a === b) return true;\n\n if (a && b && typeof a == 'object' && typeof b == 'object') {\n if (a.constructor !== b.constructor) return false;\n\n var length, i, keys;\n if (Array.isArray(a)) {\n length = a.length;\n if (length != b.length) return false;\n for (i = length; i-- !== 0;)\n if (!equal(a[i], b[i])) return false;\n return true;\n }\n\n\n\n if (a.constructor === RegExp) return a.source === b.source && a.flags === b.flags;\n if (a.valueOf !== Object.prototype.valueOf) return a.valueOf() === b.valueOf();\n if (a.toString !== Object.prototype.toString) return a.toString() === b.toString();\n\n keys = Object.keys(a);\n length = keys.length;\n if (length !== Object.keys(b).length) return false;\n\n for (i = length; i-- !== 0;)\n if (!Object.prototype.hasOwnProperty.call(b, keys[i])) return false;\n\n for (i = length; i-- !== 0;) {\n var key = keys[i];\n\n if (!equal(a[key], b[key])) return false;\n }\n\n return true;\n }\n\n // true if both NaN, false otherwise\n return a!==a && b!==b;\n};\n", "import type * as RDF from '@rdfjs/types';\n\n/**\n * A term that represents an RDF blank node with a label.\n */\nexport class BlankNode implements RDF.BlankNode {\n public readonly termType = 'BlankNode';\n public readonly value: string;\n\n public constructor(value: string) {\n this.value = value;\n }\n\n public equals(other?: RDF.Term | null): boolean {\n return !!other && other.termType === 'BlankNode' && other.value === this.value;\n }\n}\n", "import type * as RDF from '@rdfjs/types';\n\n/**\n * A singleton term instance that represents the default graph.\n * It's only allowed to assign a DefaultGraph to the .graph property of a Quad.\n */\nexport class DefaultGraph implements RDF.DefaultGraph {\n // eslint-disable-next-line ts/naming-convention\n public static INSTANCE = new DefaultGraph();\n\n public readonly termType = 'DefaultGraph';\n public readonly value = '';\n\n private constructor() {\n // Private constructor\n }\n\n public equals(other?: RDF.Term | null): boolean {\n return !!other && other.termType === 'DefaultGraph';\n }\n}\n", "import type * as RDF from '@rdfjs/types';\n\n/**\n * A term that contains an IRI.\n */\nexport class NamedNode<TIri extends string = string> implements RDF.NamedNode<TIri> {\n public readonly termType = 'NamedNode';\n public readonly value: TIri;\n\n public constructor(value: TIri) {\n this.value = value;\n }\n\n public equals(other?: RDF.Term | null): boolean {\n return !!other && other.termType === 'NamedNode' && other.value === this.value;\n }\n}\n", "import type * as RDF from '@rdfjs/types';\nimport { NamedNode } from './NamedNode';\n\n/**\n * A term that represents an RDF literal,\n * containing a string with an optional language tag and optional direction\n * or datatype.\n */\nexport class Literal implements RDF.Literal {\n public readonly termType = 'Literal';\n public readonly value: string;\n public readonly language: string;\n public readonly datatype: RDF.NamedNode;\n public readonly direction: 'ltr' | 'rtl' | '';\n\n // eslint-disable-next-line ts/naming-convention\n public static readonly RDF_LANGUAGE_STRING: RDF.NamedNode =\n new NamedNode('http://www.w3.org/1999/02/22-rdf-syntax-ns#langString');\n\n // eslint-disable-next-line ts/naming-convention\n public static readonly RDF_DIRECTIONAL_LANGUAGE_STRING: RDF.NamedNode =\n new NamedNode('http://www.w3.org/1999/02/22-rdf-syntax-ns#dirLangString');\n\n // eslint-disable-next-line ts/naming-convention\n public static readonly XSD_STRING: RDF.NamedNode =\n new NamedNode('http://www.w3.org/2001/XMLSchema#string');\n\n public constructor(value: string, languageOrDatatype?: string | RDF.NamedNode | RDF.DirectionalLanguage) {\n this.value = value;\n if (typeof languageOrDatatype === 'string') {\n this.language = languageOrDatatype.toLowerCase();\n this.datatype = Literal.RDF_LANGUAGE_STRING;\n this.direction = '';\n } else if (languageOrDatatype) {\n if ('termType' in languageOrDatatype) {\n this.language = '';\n this.datatype = languageOrDatatype;\n this.direction = '';\n } else {\n this.language = languageOrDatatype.language.toLowerCase();\n this.datatype = languageOrDatatype.direction ?\n Literal.RDF_DIRECTIONAL_LANGUAGE_STRING :\n Literal.RDF_LANGUAGE_STRING;\n this.direction = languageOrDatatype.direction ?? '';\n }\n } else {\n this.language = '';\n this.datatype = Literal.XSD_STRING;\n this.direction = '';\n }\n }\n\n public equals(other?: RDF.Term | null): boolean {\n return !!other && other.termType === 'Literal' && other.value === this.value &&\n other.language === this.language &&\n ((other.direction === this.direction) || (!other.direction && this.direction === '')) &&\n this.datatype.equals(other.datatype);\n }\n}\n", "import type * as RDF from '@rdfjs/types';\n\n/**\n * An instance of DefaultGraph represents the default graph.\n * It's only allowed to assign a DefaultGraph to the .graph property of a Quad.\n */\nexport class Quad implements RDF.BaseQuad {\n public readonly termType = 'Quad';\n public readonly value = '';\n public readonly subject: RDF.Term;\n public readonly predicate: RDF.Term;\n public readonly object: RDF.Term;\n public readonly graph: RDF.Term;\n\n public constructor(\n subject: RDF.Term,\n predicate: RDF.Term,\n object: RDF.Term,\n graph: RDF.Term,\n ) {\n this.subject = subject;\n this.predicate = predicate;\n this.object = object;\n this.graph = graph;\n }\n\n public equals(other?: RDF.Term | null): boolean {\n // `|| !other.termType` is for backwards-compatibility with old factories without RDF* support.\n return !!other && (other.termType === 'Quad' || !other.termType) &&\n this.subject.equals(other.subject) &&\n this.predicate.equals(other.predicate) &&\n this.object.equals(other.object) &&\n this.graph.equals(other.graph);\n }\n}\n", "import type * as RDF from '@rdfjs/types';\n\n/**\n * A term that represents a variable.\n */\nexport class Variable implements RDF.Variable {\n public readonly termType = 'Variable';\n public readonly value: string;\n\n public constructor(value: string) {\n this.value = value;\n }\n\n public equals(other?: RDF.Term | null): boolean {\n return !!other && other.termType === 'Variable' && other.value === this.value;\n }\n}\n", "import type * as RDF from '@rdfjs/types';\nimport { BlankNode } from './BlankNode';\nimport { DefaultGraph } from './DefaultGraph';\nimport { Literal } from './Literal';\nimport { NamedNode } from './NamedNode';\nimport { Quad } from './Quad';\nimport { Variable } from './Variable';\n\nlet dataFactoryCounter = 0;\n\n/**\n * A factory for instantiating RDF terms and quads.\n */\nexport class DataFactory<TQ extends RDF.BaseQuad = RDF.Quad> implements RDF.DataFactory<TQ> {\n private readonly blankNodePrefix: string;\n private blankNodeCounter = 0;\n\n public constructor(options?: IDataFactoryOptions) {\n options = options ?? {};\n this.blankNodePrefix = options.blankNodePrefix ?? `df_${dataFactoryCounter++}_`;\n }\n\n /**\n * @param value The IRI for the named node.\n * @return A new instance of NamedNode.\n * @see NamedNode\n */\n public namedNode<TIri extends string = string>(value: TIri): NamedNode<TIri> {\n return new NamedNode(value);\n }\n\n /**\n * @param value The optional blank node identifier.\n * @return A new instance of BlankNode.\n * If the `value` parameter is undefined a new identifier\n * for the blank node is generated for each call.\n * @see BlankNode\n */\n public blankNode(value?: string): BlankNode {\n return new BlankNode(value ?? `${this.blankNodePrefix}${this.blankNodeCounter++}`);\n }\n\n /**\n * @param value The literal value.\n * @param languageOrDatatype The optional language, datatype, or directional language.\n * If `languageOrDatatype` is a NamedNode,\n * then it is used for the value of `NamedNode.datatype`.\n * If `languageOrDatatype` is a NamedNode, it is used for the value\n * of `NamedNode.language`.\n * Otherwise, it is used as a directional language,\n * from which the language is set to `languageOrDatatype.language`\n * and the direction to `languageOrDatatype.direction`.\n * @return A new instance of Literal.\n * @see Literal\n */\n public literal(value: string, languageOrDatatype?: string | RDF.NamedNode | RDF.DirectionalLanguage): Literal {\n return new Literal(value, languageOrDatatype);\n }\n\n /**\n * This method is optional.\n * @param value The variable name\n * @return A new instance of Variable.\n * @see Variable\n */\n public variable(value: string): Variable {\n return new Variable(value);\n }\n\n /**\n * @return An instance of DefaultGraph.\n */\n public defaultGraph(): DefaultGraph {\n return DefaultGraph.INSTANCE;\n }\n\n /**\n * @param subject The quad subject term.\n * @param predicate The quad predicate term.\n * @param object The quad object term.\n * @param graph The quad graph term.\n * @return A new instance of Quad.\n * @see Quad\n */\n public quad(\n subject: TQ['subject'],\n predicate: TQ['predicate'],\n object: TQ['object'],\n graph?: TQ['graph'],\n ): TQ & Quad {\n return <TQ> new Quad(subject, predicate, object, graph ?? this.defaultGraph());\n }\n\n /**\n * Create a deep copy of the given term using this data factory.\n * @param original An RDF term.\n * @return A deep copy of the given term.\n */\n public fromTerm<T extends RDF.Term>(original: T): T {\n // TODO: remove nasty any casts when this TS bug has been fixed:\n // https://github.com/microsoft/TypeScript/issues/26933\n switch (original.termType) {\n case 'NamedNode':\n // eslint-disable-next-line ts/no-unsafe-return\n return <any> this.namedNode(original.value);\n case 'BlankNode':\n // eslint-disable-next-line ts/no-unsafe-return\n return <any> this.blankNode(original.value);\n case 'Literal':\n if (original.language) {\n // eslint-disable-next-line ts/no-unsafe-return\n return <any> this.literal(original.value, original.language);\n }\n if (!original.datatype.equals(Literal.XSD_STRING)) {\n // eslint-disable-next-line ts/no-unsafe-return\n return <any> this.literal(original.value, this.fromTerm(original.datatype));\n }\n // eslint-disable-next-line ts/no-unsafe-return\n return <any> this.literal(original.value);\n case 'Variable':\n // eslint-disable-next-line ts/no-unsafe-return\n return <any> this.variable(original.value);\n case 'DefaultGraph':\n // eslint-disable-next-line ts/no-unsafe-return\n return <any> this.defaultGraph();\n case 'Quad':\n // eslint-disable-next-line ts/no-unsafe-return\n return <any> this.quad(\n <TQ['subject']> this.fromTerm((<TQ> <unknown> original).subject),\n <TQ['predicate']> this.fromTerm((<TQ> <unknown> original).predicate),\n <TQ['object']> this.fromTerm((<TQ> <unknown> original).object),\n <TQ['graph']> this.fromTerm((<TQ> <unknown> original).graph),\n );\n }\n }\n\n /**\n * Create a deep copy of the given quad using this data factory.\n * @param original An RDF quad.\n * @return A deep copy of the given quad.\n */\n public fromQuad(original: TQ): TQ {\n return this.fromTerm(original);\n }\n\n /**\n * Reset the internal blank node counter.\n */\n public resetBlankNodeCounter(): void {\n this.blankNodeCounter = 0;\n }\n}\n\nexport interface IDataFactoryOptions {\n blankNodePrefix?: string;\n}\n", "export * from './lib/BlankNode';\nexport * from './lib/DataFactory';\nexport * from './lib/DefaultGraph';\nexport * from './lib/Literal';\nexport * from './lib/NamedNode';\nexport * from './lib/Quad';\nexport * from './lib/Variable';\n", "import { DataFactory } from \"rdf-data-factory\";\nimport * as RDF from \"@rdfjs/types\";\n\nconst FACTORY = new DataFactory();\n\n/**\n * Utility methods for converting between string-based RDF representations and RDFJS objects.\n *\n * RDF Terms are represented as follows:\n * * Blank nodes: '_:myBlankNode'\n * * Variables: '?myVariable'\n * * Literals: '\"myString\"', '\"myLanguageString\"@en-us', '\"myLanguageString\"@en-us--ltr', '\"3\"^^xsd:number'\n * * URIs: 'http://example.org'\n *\n * Quads/triples are represented as hashes with 'subject', 'predicate', 'object' and 'graph' (optional)\n * as keys, and string-based RDF terms as values.\n */\n\n/**\n * Convert an RDFJS term to a string-based representation.\n * @param {RDF.Term} term An RDFJS term.\n * @return {string} A string-based term representation.\n */\nexport function termToString<T extends RDF.Term | undefined | null>(term: T): T extends RDF.Term ? string : undefined {\n // TODO: remove nasty any casts when this TS bug has been fixed: https://github.com/microsoft/TypeScript/issues/26933\n if (!term) {\n return <any> undefined;\n }\n switch (term.termType) {\n case 'NamedNode': return <any> term.value;\n case 'BlankNode': return <any> ('_:' + term.value);\n case 'Literal':\n const literalValue: RDF.Literal = <RDF.Literal> term;\n return <any> ('\"' + literalValue.value + '\"' +\n (literalValue.datatype &&\n literalValue.datatype.value !== 'http://www.w3.org/2001/XMLSchema#string' &&\n literalValue.datatype.value !== 'http://www.w3.org/1999/02/22-rdf-syntax-ns#langString' &&\n literalValue.datatype.value !== 'http://www.w3.org/1999/02/22-rdf-syntax-ns#dirLangString'?\n '^^' + literalValue.datatype.value : '') +\n (literalValue.language ? '@' + literalValue.language : '') +\n (literalValue.direction ? '--' + literalValue.direction : ''));\n case 'Quad': return <any> `<<${termToString(term.subject)} ${termToString(term.predicate)} ${termToString(term.object)}${term.graph.termType === 'DefaultGraph' ? '' : ' ' + termToString(term.graph)}>>`;\n case 'Variable': return <any> ('?' + term.value);\n case 'DefaultGraph': return <any> term.value;\n }\n}\n\n/**\n * Get the string value of a literal.\n * @param {string} literalValue An RDF literal enclosed by '\"'.\n * @return {string} The literal value inside the '\"'.\n */\nexport function getLiteralValue(literalValue: string): string {\n const match = /^\"([^]*)\"/.exec(literalValue);\n if (!match) {\n throw new Error(literalValue + ' is not a literal');\n }\n return match[1];\n}\n\n/**\n * Get the datatype of the given literal.\n * @param {string} literalValue An RDF literal.\n * @return {string} The datatype of the literal.\n */\nexport function getLiteralType(literalValue: string): string {\n const match = /^\"[^]*\"(?:\\^\\^([^\"]+)|(@)[^@\"]+)?$/.exec(literalValue);\n if (!match) {\n throw new Error(literalValue + ' is not a literal');\n }\n return match[1] || (match[2]\n ? 'http://www.w3.org/1999/02/22-rdf-syntax-ns#langString' : 'http://www.w3.org/2001/XMLSchema#string');\n}\n\n/**\n * Get the language of the given literal.\n * @param {string} literalValue An RDF literal.\n * @return {string} The language of the literal.\n */\nexport function getLiteralLanguage(literalValue: string): string {\n const match = /^\"[^]*\"(?:@([^@\"]+)|\\^\\^[^\"]+)?$/.exec(literalValue);\n if (!match) {\n throw new Error(literalValue + ' is not a literal');\n }\n if (match[1]) {\n let ret = match[1].toLowerCase();\n\n // Remove everything after --, since this indicates the base direction, which will be parsed later.\n const doubleDashPos = ret.indexOf('--');\n if (doubleDashPos >= 0) {\n ret = ret.slice(0, doubleDashPos);\n }\n\n return ret;\n }\n return '';\n}\n\n/**\n * Get the direction of the given literal.\n * @param {string} literalValue An RDF literal.\n * @return {string} The direction of the literal.\n */\nexport function getLiteralDirection(literalValue: string): 'ltr' | 'rtl' | '' {\n const doubleDashPos = literalValue.indexOf('--', literalValue.lastIndexOf('\"'));\n if (doubleDashPos >= 0) {\n const direction = literalValue.slice(doubleDashPos + 2, literalValue.length);\n if (direction === 'ltr' || direction === 'rtl') {\n return direction;\n }\n throw new Error(literalValue + ' is not a literal with a valid direction');\n }\n return '';\n}\n\n/**\n * Transform a string-based RDF term to an RDFJS term.\n * @param {string} value A string-based RDF-term.\n * @param {RDF.DataFactory} dataFactory An optional datafactory to create terms with.\n * @return {RDF.Term} An RDF-JS term.\n */\nexport function stringToTerm(value: string | undefined, dataFactory?: RDF.DataFactory<RDF.BaseQuad>): RDF.Term {\n dataFactory = dataFactory || FACTORY;\n if (!value || !value.length) {\n return dataFactory.defaultGraph();\n }\n switch (value[0]) {\n case '_': return dataFactory.blankNode(value.substr(2));\n case '?':\n if (!dataFactory.variable) {\n throw new Error(`Missing 'variable()' method on the given DataFactory`);\n }\n return dataFactory.variable(value.substr(1));\n case '\"':\n const language: string = getLiteralLanguage(value);\n const direction = getLiteralDirection(value);\n const type: RDF.NamedNode = dataFactory.namedNode(getLiteralType(value));\n return dataFactory.literal(getLiteralValue(value), language ? { language, direction } : type);\n case '<':\n default:\n if (value[0] === '<' && value.length > 4 && value[1] === '<' && value[value.length - 1] === '>' && value[value.length - 2] === '>') {\n // Iterate character-by-character to detect spaces that are *not* wrapped in <<>>\n const terms = value.slice(2, -2).trim();\n let stringTerms: string[] = [];\n let ignoreTags: number = 0;\n let lastIndex = 0;\n let inQuote = false;\n for (let i = 0; i < terms.length; i++) {\n const char = terms[i];\n if (char === '<') ignoreTags++;\n if (char === '>') {\n if (ignoreTags === 0) {\n throw new Error('Found closing tag without opening tag in ' + value);\n } else {\n ignoreTags--\n }\n }\n if (char === '\"') {\n let escaped = false\n let j = i;\n while (j-- > 0 && terms[j] === '\\\\') {\n escaped = !escaped;\n }\n if (!escaped) {\n // We have reached an unescaped quote\n inQuote = !inQuote;\n }\n }\n if (char === ' ' && !inQuote && ignoreTags === 0) {\n stringTerms.push(terms.slice(lastIndex, i));\n\n while (terms[i + 1] === ' ') {\n i += 1;\n }\n\n lastIndex = i + 1;\n }\n }\n if (ignoreTags !== 0) {\n throw new Error('Found opening tag without closing tag in ' + value);\n }\n stringTerms.push(terms.slice(lastIndex, terms.length));\n\n // We require 3 or 4 components\n if (stringTerms.length !== 3 && stringTerms.length !== 4) {\n throw new Error('Nested quad syntax error ' + value);\n }\n\n stringTerms = stringTerms.map(term => term.startsWith('<') && !term.includes(' ') ? term.slice(1, -1) : term)\n\n return dataFactory.quad(\n stringToTerm(stringTerms[0]),\n stringToTerm(stringTerms[1]),\n stringToTerm(stringTerms[2]),\n stringTerms[3] ? stringToTerm(stringTerms[3]) : undefined,\n );\n }\n return dataFactory.namedNode(value);\n }\n}\n\n/**\n * Convert an RDFJS quad to a string-based quad representation.\n * @param {Quad} q An RDFJS quad.\n * @return {IStringQuad} A hash with string-based quad terms.\n * @template Q The type of quad, defaults to RDF.Quad.\n */\nexport function quadToStringQuad<Q extends RDF.BaseQuad = RDF.Quad>(q: Q): IStringQuad {\n // tslint:disable:object-literal-sort-keys\n return {\n subject: termToString(q.subject),\n predicate: termToString(q.predicate),\n object: termToString(q.object),\n graph: termToString(q.graph),\n };\n // tslint:enable:object-literal-sort-keys\n}\n\n/**\n * Convert a string-based quad representation to an RDFJS quad.\n * @param {IStringQuad} stringQuad A hash with string-based quad terms.\n * @param {RDF.DataFactory} dataFactory An optional datafactory to create terms with.\n * @return {Q} An RDFJS quad.\n * @template Q The type of quad, defaults to RDF.Quad.\n */\nexport function stringQuadToQuad<Q extends RDF.BaseQuad = RDF.Quad>(stringQuad: IStringQuad,\n dataFactory?: RDF.DataFactory<Q>): Q {\n dataFactory = <RDF.DataFactory<Q>> dataFactory || FACTORY;\n return dataFactory.quad(\n stringToTerm(stringQuad.subject, dataFactory),\n stringToTerm(stringQuad.predicate, dataFactory),\n stringToTerm(stringQuad.object, dataFactory),\n stringToTerm(stringQuad.graph, dataFactory),\n );\n}\n\nexport interface IStringQuad {\n subject: string;\n predicate: string;\n object: string;\n graph?: string;\n}\n", "import {\n getLiteralLanguage,\n getLiteralDirection,\n getLiteralType,\n getLiteralValue,\n IStringQuad,\n quadToStringQuad,\n stringQuadToQuad,\n stringToTerm,\n termToString,\n} from './lib/TermUtil';\nexport {\n getLiteralLanguage,\n getLiteralDirection,\n getLiteralType,\n getLiteralValue,\n IStringQuad,\n quadToStringQuad,\n stringQuadToQuad,\n stringToTerm,\n termToString,\n};\n", "import ExplainPlugin from './ExplainPlugin';\n\ndeclare global {\n interface Window {\n Yasgui?: {\n Yasr?: {\n registerPlugin: (name: string, plugin: any) => void;\n };\n };\n }\n}\n\n// Auto-register plugin if Yasgui is available (UMD global)\nif (typeof window !== 'undefined' && window.Yasgui && window.Yasgui.Yasr) {\n window.Yasgui.Yasr.registerPlugin('Explain', ExplainPlugin);\n}\n\nexport default ExplainPlugin;\nexport { ExplainPlugin };\nexport { translate, AlgebraError } from './algebra/translate';\nexport { toSExpression, toTree } from './algebra/print';\nexport { ENGINES, ENGINE_IDS, detectEngine } from './engines';\nexport type { ExplainPluginOptions, EngineId, EngineChoice, Plan, PlanNode, Engine } from './types';\n", "/**\n * QLever (https://github.com/ad-freiburg/qlever)\n *\n * With `Accept: application/qlever-results+json`, QLever returns its results\n * together with `runtimeInformation`: the tree of operations it executed, with\n * the time and the number of rows of each. The plugin re-sends the query with\n * that Accept header once the user's query has completed: QLever answers from\n * its result cache, and cached operations keep their original times in their\n * details.\n */\n\nimport type { Engine, Plan, PlanNode } from '../types';\n\nconst ACCEPT = 'application/qlever-results+json';\n\n/** A node of QLever's `query_execution_tree` (newer) or `runtimeInformation` (older) */\ninterface QleverNode {\n description?: string;\n operation_time?: number;\n total_time?: number;\n result_rows?: number;\n result_cols?: number;\n column_names?: string[];\n cache_status?: string;\n was_cached?: boolean;\n status?: string;\n estimated_size?: number;\n estimated_operation_cost?: number;\n estimated_column_multiplicities?: number[];\n details?: Record<string, unknown>;\n children?: QleverNode[];\n}\n\nfunction isNumber(value: unknown): value is number {\n return typeof value === 'number' && Number.isFinite(value);\n}\n\nfunction formatNumber(value: number): string {\n return value.toLocaleString('en-US');\n}\n\nfunction formatDetail(key: string, value: unknown): string {\n if (value && typeof value === 'object') return `${key}: ${JSON.stringify(value)}`;\n return `${key}: ${String(value)}`;\n}\n\n/** Convert one QLever node (and its children) to a plan node */\nexport function toPlanNode(node: QleverNode): PlanNode {\n const cached =\n node.was_cached === true ||\n (typeof node.cache_status === 'string' &&\n node.cache_status !== 'computed' &&\n node.cache_status !== 'not_cached');\n const details: string[] = [];\n if (typeof node.cache_status === 'string' && node.cache_status !== 'computed') {\n details.push(`cache: ${node.cache_status.replace(/_/g, ' ')}`);\n }\n if (isNumber(node.estimated_size))\n details.push(`estimated size: ${formatNumber(node.estimated_size)}`);\n if (isNumber(node.estimated_operation_cost)) {\n details.push(`estimated cost: ${formatNumber(node.estimated_operation_cost)}`);\n }\n if (\n Array.isArray(node.estimated_column_multiplicities) &&\n node.estimated_column_multiplicities.length\n ) {\n details.push(`estimated multiplicities: ${node.estimated_column_multiplicities.join(', ')}`);\n }\n if (node.details && typeof node.details === 'object') {\n for (const [key, value] of Object.entries(node.details)) {\n if (value === undefined || value === null || value === '') continue;\n details.push(formatDetail(key.replace(/_/g, ' '), value));\n }\n }\n return {\n label: (node.description || 'operation').replace(/\\s+/g, ' ').trim(),\n details,\n rows: isNumber(node.result_rows) ? node.result_rows : undefined,\n columns: Array.isArray(node.column_names) ? node.column_names.map(String) : undefined,\n timeMs: isNumber(node.operation_time) ? node.operation_time : undefined,\n totalMs: isNumber(node.total_time) ? node.total_time : undefined,\n cached,\n status: typeof node.status === 'string' ? node.status : undefined,\n children: Array.isArray(node.children) ? node.children.map(toPlanNode) : [],\n };\n}\n\nfunction formatMs(value: unknown): string | undefined {\n if (isNumber(value)) return `${formatNumber(value)} ms`;\n if (typeof value === 'string') return value;\n return undefined;\n}\n\n/** Parse a `application/qlever-results+json` response into a plan */\nexport function parseQleverResponse(body: string): Plan {\n let json: any;\n try {\n json = JSON.parse(body);\n } catch {\n throw new Error('QLever did not return JSON. Is this endpoint a QLever instance?');\n }\n if (json && typeof json === 'object' && json.status === 'ERROR') {\n throw new Error(`QLever reported an error: ${json.exception || json.error || 'unknown error'}`);\n }\n const info = json?.runtimeInformation;\n if (!info || typeof info !== 'object') {\n throw new Error(\n 'The response carries no runtime information. Is this endpoint a QLever instance?'\n );\n }\n const tree: QleverNode | undefined =\n info.query_execution_tree ?? (info.description ? info : undefined);\n if (!tree) throw new Error('The runtime information holds no query execution tree.');\n\n const summary: string[] = [];\n const meta = info.meta;\n if (meta && typeof meta === 'object') {\n const planning = formatMs(meta.time_query_planning);\n if (planning) summary.push(`Query planning: ${planning}`);\n const computing = formatMs(meta.total_time_computing);\n if (computing) summary.push(`Computing: ${computing}`);\n const total = formatMs(meta.total_time);\n if (total) summary.push(`Total: ${total}`);\n }\n if (json.time && typeof json.time === 'object' && summary.length === 0) {\n const total = formatMs(json.time.total);\n if (total) summary.push(`Total: ${total}`);\n const compute = formatMs(json.time.computeResult);\n if (compute) summary.push(`Computing: ${compute}`);\n }\n if (isNumber(json.resultsize)) summary.push(`Result size: ${formatNumber(json.resultsize)} rows`);\n if (Array.isArray(json.warnings) && json.warnings.length) {\n summary.push(`Warnings: ${json.warnings.map(String).join(' | ')}`);\n }\n return { kind: 'tree', root: toPlanNode(tree), summary };\n}\n\nexport const qlever: Engine = {\n id: 'qlever',\n label: 'QLever',\n description: 'The operations QLever executed, with the time and rows of each.',\n needsRequestOptions: false,\n buildRequest(query) {\n // `send` caps the rows QLever sends back: the plan is what we are after\n return { query, accept: ACCEPT, extraArgs: { send: '1' } };\n },\n parse(body) {\n return parseQleverResponse(body);\n },\n};\n", "/**\n * Ontotext GraphDB\n *\n * GraphDB explains a query when it reads from the pseudo graph\n * `onto:explain` (http://www.ontotext.com/explain): the response is then the\n * plan as text, with the chosen order of the triple patterns and the estimated\n * collection sizes, instead of the results. RDF4J shares the `/repositories/`\n * URL layout but has no explain, so the request fails there.\n */\n\nimport type { Engine, Plan } from '../types';\n\nexport const EXPLAIN_GRAPH = 'http://www.ontotext.com/explain';\n\n/**\n * Add `FROM <onto:explain>` to a query. The clause goes right before the\n * WHERE keyword (or the group graph pattern when WHERE is omitted), skipping\n * comments, strings and IRIs so the words inside them are left alone.\n */\nexport function addExplainGraph(query: string): string {\n const insertAt = findWhereOffset(query);\n if (insertAt < 0)\n throw new Error('Could not find the WHERE clause of the query to add the explain graph to.');\n const clause = `FROM <${EXPLAIN_GRAPH}>`;\n const before = query.slice(0, insertAt);\n const needsSpace = before.length > 0 && !/\\s$/.test(before);\n return `${before}${needsSpace ? ' ' : ''}${clause} ${query.slice(insertAt)}`;\n}\n\n/** Offset of the first WHERE keyword or, without one, of the first `{` after the query form */\nexport function findWhereOffset(query: string): number {\n let i = 0;\n const n = query.length;\n let sawForm = false; // SELECT / CONSTRUCT / DESCRIBE / ASK seen\n let depth = 0; // brace depth, so a CONSTRUCT template is skipped\n let firstBrace = -1;\n let skipGroups = 0; // top-level brace groups that belong to the form (the CONSTRUCT template)\n while (i < n) {\n const ch = query[i];\n if (ch === '#') {\n while (i < n && query[i] !== '\\n') i++;\n continue;\n }\n if (ch === '<') {\n // IRI: no spaces inside, ends at the next '>'\n const end = query.indexOf('>', i + 1);\n if (end > 0 && !/\\s/.test(query.slice(i + 1, end))) {\n i = end + 1;\n continue;\n }\n }\n if (ch === '\"' || ch === \"'\") {\n i = skipString(query, i);\n continue;\n }\n if (ch === '{') {\n if (sawForm && depth === 0 && firstBrace < 0) {\n if (skipGroups > 0) skipGroups--;\n else firstBrace = i;\n }\n depth++;\n i++;\n continue;\n }\n if (ch === '}') {\n depth--;\n i++;\n continue;\n }\n if (/[A-Za-z]/.test(ch)) {\n let j = i;\n while (j < n && /[A-Za-z_]/.test(query[j])) j++;\n const word = query.slice(i, j).toUpperCase();\n if (depth === 0) {\n if (word === 'SELECT' || word === 'CONSTRUCT' || word === 'DESCRIBE' || word === 'ASK') {\n sawForm = true;\n firstBrace = -1;\n skipGroups = word === 'CONSTRUCT' ? 1 : 0;\n } else if (word === 'WHERE' && sawForm) {\n return i;\n }\n }\n i = j;\n continue;\n }\n i++;\n }\n return firstBrace;\n}\n\nfunction skipString(text: string, start: number): number {\n const quote = text[start];\n const long = text.startsWith(quote.repeat(3), start);\n const delimiter = long ? quote.repeat(3) : quote;\n let i = start + delimiter.length;\n while (i < text.length) {\n if (text[i] === '\\\\') {\n i += 2;\n continue;\n }\n if (text.startsWith(delimiter, i)) return i + delimiter.length;\n if (!long && text[i] === '\\n') return i;\n i++;\n }\n return text.length;\n}\n\n/** The plan is text, but some clients get it wrapped in a SPARQL result: unwrap it */\nexport function parseGraphdbResponse(body: string, contentType: string | undefined): Plan {\n const text = body.trim();\n if (!text) throw new Error('GraphDB returned an empty response.');\n if (/json/i.test(contentType || '') || text.startsWith('{')) {\n try {\n const json = JSON.parse(text);\n const bindings = json?.results?.bindings;\n if (Array.isArray(bindings)) {\n const lines: string[] = [];\n for (const binding of bindings) {\n for (const term of Object.values(binding as Record<string, { value?: string }>)) {\n if (term && typeof term.value === 'string') lines.push(term.value);\n }\n }\n if (lines.length === 0) {\n throw new Error(\n 'GraphDB returned results instead of a plan. The onto:explain pseudo graph needs GraphDB; RDF4J does not support it.'\n );\n }\n return { kind: 'text', text: lines.join('\\n') };\n }\n } catch (error) {\n if (error instanceof Error && error.message.startsWith('GraphDB returned')) throw error;\n // not JSON after all: fall through to the text plan\n }\n }\n if (/^<\\?xml|^<sparql/i.test(text)) {\n throw new Error(\n 'GraphDB returned results instead of a plan. The onto:explain pseudo graph needs GraphDB; RDF4J does not support it.'\n );\n }\n return { kind: 'text', text };\n}\n\nexport const graphdb: Engine = {\n id: 'graphdb',\n label: 'GraphDB',\n description:\n 'The plan GraphDB chose, with the order of the patterns and estimated sizes (no timings).',\n needsRequestOptions: false,\n buildRequest(query) {\n return {\n query: addExplainGraph(query),\n accept: 'text/plain, application/sparql-results+json;q=0.9, */*;q=0.1',\n };\n },\n parse(body, contentType) {\n return parseGraphdbResponse(body, contentType);\n },\n};\n", "/**\n * Stardog\n *\n * Stardog explains a query on `GET|POST /{db}/explain` with the same `query`\n * parameter as `/{db}/query`. With `profile=true` the plan carries the actual\n * rows, wall time and memory of each operator; without it only estimates.\n * The response is the plan as text.\n */\n\nimport type { Engine, Plan } from '../types';\n\n/** `https://host:5820/mydb/query` becomes `https://host:5820/mydb/explain` */\nexport function explainUrl(endpoint: string): string {\n const [base, suffix] = splitUrl(endpoint);\n const trimmed = base.replace(/\\/+$/, '');\n if (/\\/(query|update)$/i.test(trimmed))\n return trimmed.replace(/\\/(query|update)$/i, '/explain') + suffix;\n if (/\\/explain$/i.test(trimmed)) return trimmed + suffix;\n return `${trimmed}/explain${suffix}`;\n}\n\nfunction splitUrl(url: string): [string, string] {\n const index = url.search(/[?#]/);\n return index < 0 ? [url, ''] : [url.slice(0, index), url.slice(index)];\n}\n\nexport function parseStardogResponse(body: string): Plan {\n const text = body.trim();\n if (!text) throw new Error('Stardog returned an empty response.');\n if (text.startsWith('{')) {\n try {\n const json = JSON.parse(text);\n if (json && typeof json === 'object' && typeof json.message === 'string') {\n throw new Error(`Stardog reported an error: ${json.message}`);\n }\n if (json && typeof json === 'object' && typeof json.plan === 'string') {\n return { kind: 'text', text: json.plan };\n }\n } catch (error) {\n if (error instanceof Error && error.message.startsWith('Stardog reported')) throw error;\n }\n }\n return { kind: 'text', text };\n}\n\nexport const stardog: Engine = {\n id: 'stardog',\n label: 'Stardog',\n description: 'The profiled plan from Stardog, with rows, wall time and memory of each operator.',\n needsRequestOptions: true,\n buildRequest(query, endpoint) {\n return {\n query,\n accept: 'text/plain, application/json;q=0.5, */*;q=0.1',\n extraArgs: { profile: 'true' },\n endpoint: explainUrl(endpoint),\n };\n },\n parse(body) {\n return parseStardogResponse(body);\n },\n};\n", "/**\n * Blazegraph\n *\n * With the `explain` request parameter, Blazegraph answers with an HTML page\n * instead of the results: the query, its abstract syntax tree, the operator\n * plan and, with `explain=details`, a table of statistics per operator. The\n * plugin shows that page in a sandboxed frame.\n */\n\nimport type { Engine, Plan } from '../types';\n\nexport function parseBlazegraphResponse(body: string, contentType: string | undefined): Plan {\n const text = body.trim();\n if (!text) throw new Error('Blazegraph returned an empty response.');\n if (/html/i.test(contentType || '') || /^<!doctype html|^<html/i.test(text)) {\n return { kind: 'html', html: body };\n }\n if (/^<\\?xml|^<sparql|^\\{/.test(text)) {\n throw new Error(\n 'The endpoint returned results instead of an explain page. Is this a Blazegraph instance?'\n );\n }\n return { kind: 'text', text };\n}\n\nexport const blazegraph: Engine = {\n id: 'blazegraph',\n label: 'Blazegraph',\n description:\n 'The explain page of Blazegraph: abstract syntax tree, operator plan and statistics.',\n needsRequestOptions: true,\n buildRequest(query) {\n return { query, accept: 'text/html, */*;q=0.1', extraArgs: { explain: 'details' } };\n },\n parse(body, contentType) {\n return parseBlazegraphResponse(body, contentType);\n },\n};\n", "/**\n * Amazon Neptune\n *\n * Neptune explains a query with the `explain` request parameter\n * (`explain=details` adds the estimates and the time per operator). The\n * response is a text table, one row per operator.\n */\n\nimport type { Engine, Plan } from '../types';\n\nexport function parseNeptuneResponse(body: string, contentType: string | undefined): Plan {\n const text = body.trim();\n if (!text) throw new Error('Neptune returned an empty response.');\n if (/html/i.test(contentType || '') || /^<!doctype html|^<html/i.test(text)) {\n return { kind: 'html', html: body };\n }\n if (text.startsWith('{')) {\n try {\n const json = JSON.parse(text);\n if (json && typeof json === 'object' && (json.detailedMessage || json.message)) {\n throw new Error(`Neptune reported an error: ${json.detailedMessage || json.message}`);\n }\n if (json?.results?.bindings) {\n throw new Error(\n 'The endpoint returned results instead of an explain table. Is this a Neptune instance?'\n );\n }\n } catch (error) {\n if (error instanceof Error && !(error instanceof SyntaxError)) throw error;\n }\n }\n return { kind: 'text', text };\n}\n\nexport const neptune: Engine = {\n id: 'neptune',\n label: 'Neptune',\n description: 'The explain table of Amazon Neptune, one row per operator with its time.',\n needsRequestOptions: true,\n buildRequest(query) {\n return { query, accept: 'text/plain, */*;q=0.1', extraArgs: { explain: 'details' } };\n },\n parse(body, contentType) {\n return parseNeptuneResponse(body, contentType);\n },\n};\n", "/**\n * TripleTrail\n *\n * TripleTrail explains a query on `GET|POST /{ds}/explain`, beside the\n * dataset's `/{ds}/sparql` and `/{ds}/query`, with the same `query`\n * parameter. It runs the query and answers JSON: the row count, the plan it\n * ran under `plan.plan` (each step with its `name`, `number of results`,\n * `duration in seconds` and `children`), the planning time under\n * `plan[\"planning duration in seconds\"]`, and the decisions of its spatial\n * index under `spatial`. A caller who may read only some graphs gets the row\n * count alone, with `restricted: true`.\n */\n\nimport type { Engine, Plan, PlanNode } from '../types';\n\n/** `https://host/ds/sparql` (or `/query`, `/update`) becomes `https://host/ds/explain` */\nexport function explainUrl(endpoint: string): string {\n const index = endpoint.search(/[?#]/);\n const [base, suffix] =\n index < 0 ? [endpoint, ''] : [endpoint.slice(0, index), endpoint.slice(index)];\n const trimmed = base.replace(/\\/+$/, '');\n if (/\\/(sparql|query|update)$/i.test(trimmed))\n return trimmed.replace(/\\/(sparql|query|update)$/i, '/explain') + suffix;\n if (/\\/explain$/i.test(trimmed)) return trimmed + suffix;\n return `${trimmed}/explain${suffix}`;\n}\n\nconst isNumber = (value: unknown): value is number =>\n typeof value === 'number' && Number.isFinite(value);\n\nconst ms = (seconds: unknown) => (isNumber(seconds) ? seconds * 1000 : undefined);\n\nfunction toNode(step: any): PlanNode {\n return {\n label: String(step?.name || 'step')\n .replace(/\\s+/g, ' ')\n .trim(),\n rows: isNumber(step?.['number of results']) ? step['number of results'] : undefined,\n timeMs: ms(step?.['duration in seconds']),\n children: Array.isArray(step?.children) ? step.children.map(toNode) : [],\n };\n}\n\nexport function parseTripleTrailResponse(body: string): Plan {\n const text = body.trim();\n if (!text) throw new Error('TripleTrail returned an empty response.');\n let json: any;\n try {\n json = JSON.parse(text);\n } catch {\n throw new Error('TripleTrail did not return JSON. Is this endpoint a TripleTrail server?');\n }\n if (!json || typeof json !== 'object' || json.head || json.results || 'boolean' in json)\n throw new Error(\n 'The endpoint returned results instead of a plan. Is this endpoint a TripleTrail server?'\n );\n const summary: string[] = [];\n if (isNumber(json.rows)) summary.push(`Result size: ${json.rows.toLocaleString('en-US')} rows`);\n const planning = ms(json.plan?.['planning duration in seconds']);\n if (planning !== undefined) summary.push(`Query planning: ${planning.toFixed(2)} ms`);\n const spatial = json.spatial && typeof json.spatial === 'object' ? json.spatial : {};\n if (spatial.filters || spatial.joins) {\n const lookup = isNumber(spatial.lookup_ms)\n ? `, index lookup ${spatial.lookup_ms.toFixed(1)} ms`\n : '';\n summary.push(\n `Spatial: ${spatial.filters || 0} filters, ${spatial.joins || 0} joins, ${spatial.candidates || 0} candidates${lookup}`\n );\n }\n if (Array.isArray(spatial.decisions))\n for (const decision of spatial.decisions) summary.push(`Spatial rewrite: ${String(decision)}`);\n const root = json.plan && (json.plan.plan || (json.plan.name ? json.plan : undefined));\n if (root && typeof root === 'object') return { kind: 'tree', root: toNode(root), summary };\n if (json.restricted)\n summary.push(\n 'The plan is left out: you may read only some of the graphs, and the plan is chosen from all of them.'\n );\n return { kind: 'text', text: summary.join('\\n') || 'No plan.' };\n}\n\nexport const tripletrail: Engine = {\n id: 'tripletrail',\n label: 'TripleTrail',\n description: 'The plan TripleTrail ran, with the rows and time of each step.',\n needsRequestOptions: true,\n buildRequest(query, endpoint) {\n return { query, accept: 'application/json', endpoint: explainUrl(endpoint) };\n },\n parse(body) {\n return parseTripleTrailResponse(body);\n },\n};\n", "/**\n * The engines the plugin can ask for an execution plan, and how to tell which\n * one an endpoint runs.\n */\n\nimport type { Engine, EngineChoice, EngineId } from '../types';\nimport { qlever } from './qlever';\nimport { graphdb } from './graphdb';\nimport { stardog } from './stardog';\nimport { blazegraph } from './blazegraph';\nimport { neptune } from './neptune';\nimport { tripletrail } from './tripletrail';\n\nexport const ENGINES: Record<EngineId, Engine> = {\n qlever,\n graphdb,\n stardog,\n blazegraph,\n neptune,\n tripletrail,\n};\n\nexport const ENGINE_IDS: EngineId[] = [\n 'qlever',\n 'graphdb',\n 'stardog',\n 'blazegraph',\n 'neptune',\n 'tripletrail',\n];\n\nexport function isEngineId(value: unknown): value is EngineId {\n return typeof value === 'string' && value in ENGINES;\n}\n\nexport function isEngineChoice(value: unknown): value is EngineChoice {\n return value === 'auto' || value === 'none' || isEngineId(value);\n}\n\n/**\n * Guess the engine behind an endpoint from its URL and, when the host exposes\n * them, the response headers of the last query. Undefined when nothing matches:\n * the user can then pick the engine by hand.\n */\nexport function detectEngine(\n endpoint: string | undefined,\n serverHeader?: string | null\n): EngineId | undefined {\n const server = (serverHeader || '').toLowerCase();\n if (server.includes('qlever')) return 'qlever';\n if (server.includes('graphdb')) return 'graphdb';\n if (server.includes('stardog')) return 'stardog';\n if (server.includes('blazegraph') || server.includes('bigdata')) return 'blazegraph';\n if (server.includes('tripletrail')) return 'tripletrail';\n\n if (!endpoint) return undefined;\n let url: URL | undefined;\n try {\n url = new URL(endpoint);\n } catch {\n return undefined;\n }\n const host = url.hostname.toLowerCase();\n const path = url.pathname.toLowerCase();\n\n if (host.includes('qlever') || path.includes('qlever')) return 'qlever';\n if (host.includes('neptune.amazonaws.com') || host.endsWith('.neptune.amazonaws.com'))\n return 'neptune';\n if (/\\/(bigdata|blazegraph)(\\/|$)/.test(path)) return 'blazegraph';\n // Well-known public endpoints whose URL does not name the engine\n if (host === 'query.wikidata.org') return 'blazegraph';\n if (host === 'lindas.admin.ch' || host === 'ld.admin.ch') return 'stardog';\n if (host.includes('graphdb') || path.includes('graphdb')) return 'graphdb';\n if (/\\/repositories\\/[^/]+\\/?$/.test(path)) return 'graphdb';\n if (host.includes('stardog') || path.includes('stardog') || url.port === '5820') return 'stardog';\n if (/\\/[^/]+\\/query\\/?$/.test(path)) return 'stardog';\n return undefined;\n}\n\n/** How the engine was chosen, for the toolbar */\nexport interface ResolvedEngine {\n engine: Engine | undefined;\n /** \"stored\" when the user picked it, \"detected\" when guessed, \"none\" when neither */\n source: 'stored' | 'detected' | 'forced' | 'none';\n}\n\nexport function resolveEngine(\n choice: EngineChoice,\n endpoint: string | undefined,\n serverHeader?: string | null,\n forced?: EngineChoice\n): ResolvedEngine {\n const effective = forced && forced !== 'auto' ? forced : choice;\n const source = forced && forced !== 'auto' ? 'forced' : 'stored';\n if (effective === 'none') return { engine: undefined, source };\n if (isEngineId(effective)) return { engine: ENGINES[effective], source };\n const detected = detectEngine(endpoint, serverHeader);\n return detected\n ? { engine: ENGINES[detected], source: 'detected' }\n : { engine: undefined, source: 'none' };\n}\n", "/**\n * The engine chosen per endpoint, remembered in localStorage so the choice\n * survives new tabs and reloads. Storage can be unavailable (private windows,\n * blocked site data): every access is guarded.\n */\n\nimport type { EngineChoice } from './types';\nimport { isEngineChoice } from './engines';\n\nconst STORAGE_KEY = 'yasgui-explain-plugin:engines';\n\nfunction readAll(): Record<string, EngineChoice> {\n try {\n const raw = window.localStorage.getItem(STORAGE_KEY);\n if (!raw) return {};\n const parsed = JSON.parse(raw);\n if (!parsed || typeof parsed !== 'object') return {};\n const result: Record<string, EngineChoice> = {};\n for (const [endpoint, choice] of Object.entries(parsed)) {\n if (isEngineChoice(choice)) result[endpoint] = choice;\n }\n return result;\n } catch {\n return {};\n }\n}\n\n/** The stored engine choice of an endpoint, \"auto\" when none was stored */\nexport function getEngineChoice(endpoint: string | undefined): EngineChoice {\n if (!endpoint) return 'auto';\n return readAll()[normalize(endpoint)] ?? 'auto';\n}\n\n/** Remember the engine choice of an endpoint (\"auto\" forgets it) */\nexport function setEngineChoice(endpoint: string | undefined, choice: EngineChoice): void {\n if (!endpoint) return;\n try {\n const all = readAll();\n if (choice === 'auto') delete all[normalize(endpoint)];\n else all[normalize(endpoint)] = choice;\n window.localStorage.setItem(STORAGE_KEY, JSON.stringify(all));\n } catch {\n // storage unavailable: the choice lasts for this view only\n }\n}\n\nfunction normalize(endpoint: string): string {\n return endpoint.trim().replace(/\\/+$/, '');\n}\n", "/**\n * Feature detection for the YASR host API\n *\n * Newer YASR versions (MatGUI) offer a toolbar slot and pass extra request\n * options to background queries. Older ones don't: the plugin then draws its\n * own toolbar and, when a request needs options the host can't pass, sends\n * the request itself without the tab's authentication.\n */\n\nimport type { Yasr } from './types';\n\n/** The host's plugin toolbar slot, or null when the host has none */\nexport function getHostToolbar(yasr: Yasr | null | undefined): HTMLDivElement | null {\n if (!yasr?.hostApi?.toolbar || typeof yasr.getPluginToolbar !== 'function') return null;\n try {\n const slot = yasr.getPluginToolbar();\n return slot instanceof HTMLElement ? (slot as HTMLDivElement) : null;\n } catch (error) {\n console.warn('yasgui-explain-plugin: could not get the plugin toolbar', error);\n return null;\n }\n}\n\n/** True when `yasr.executeQuery` passes `extraArgs` and `endpoint` to the request */\nexport function hasHostRequestOptions(yasr: Yasr | null | undefined): boolean {\n return !!yasr?.hostApi?.queryRequest && typeof yasr.executeQuery === 'function';\n}\n\n/** True when the host runs background queries with the tab's settings */\nexport function hasHostExecuteQuery(yasr: Yasr | null | undefined): boolean {\n return typeof yasr?.executeQuery === 'function';\n}\n\n/**\n * The current query and endpoint, read from the host's plain query link\n * (`endpoint?query=...&default-graph-uri=...`).\n */\nexport function readQueryLink(yasr: Yasr | null | undefined): {\n query?: string;\n endpoint?: string;\n} {\n const getLink = yasr?.config?.getPlainQueryLinkToEndpoint;\n if (typeof getLink !== 'function') return {};\n let link: string | undefined;\n try {\n link = getLink();\n } catch (error) {\n console.warn('yasgui-explain-plugin: could not read the query link', error);\n return {};\n }\n if (!link) return {};\n const queryIndex = link.indexOf('?');\n if (queryIndex < 0) return { endpoint: link };\n const endpoint = link.slice(0, queryIndex);\n const params = new URLSearchParams(link.slice(queryIndex + 1));\n const query = params.get('query') ?? params.get('update') ?? undefined;\n return { query: query ?? undefined, endpoint };\n}\n", "import type { IToken } from '@traqula/chevrotain';\n\nimport type {\n SourceLocation,\n SourceLocationNodeAutoGenerate,\n SourceLocationNodeReplace,\n SourceLocationNoMaterialize,\n SourceLocationSource,\n SourceLocationStringReplace,\n Node,\n Localized,\n Wrap,\n Typed,\n SubTyped,\n SourceLocationInlinedSource,\n} from './types.js';\n\nexport interface AstCoreFactoryArgs {\n /**\n * Whether the AstFactory can track sources, if not, the sourceLocation function returns autoGen. Default true\n */\n tracksSourceLocation: boolean;\n}\n\nexport class AstCoreFactory implements AstCoreFactoryArgs {\n /**\n * Whether this AstFactory will track source location. Default: true.\n * In case source location is not tracked,\n * each generated node using this factory will be {@link SourceLocationNodeAutoGenerate}\n */\n public tracksSourceLocation: boolean;\n\n public constructor(args: Partial<AstCoreFactoryArgs> = {}) {\n this.tracksSourceLocation = args.tracksSourceLocation ?? true;\n }\n\n /**\n * Wrap any type into an object that tracks the source location of tha value.\n * @param val the value to wrap\n * @param loc the source location for that value\n */\n public wrap<T>(val: T, loc: SourceLocation): Wrap<T> {\n return { val, loc };\n }\n\n /**\n * Whether the provided value is an object that tracks source location.\n * @param obj\n */\n public isLocalized(obj: unknown): obj is Localized {\n return typeof obj === 'object' && obj !== null && 'loc' in obj &&\n typeof obj.loc === 'object' && obj.loc !== null && 'sourceLocationType' in obj.loc;\n }\n\n /**\n * Compute the source location of an element based on the elements it contains.\n * The provided arguments should be in order of occurrence in the string.\n */\n public sourceLocation(...elements: (undefined | IToken | Localized)[]): SourceLocation {\n if (!this.tracksSourceLocation) {\n return this.gen();\n }\n\n const pureElements = elements.filter(x => x !== undefined);\n if (pureElements.length === 0) {\n return this.sourceLocationNoMaterialize();\n }\n\n const filtered = pureElements.filter(element =>\n !this.isLocalized(element) || this.isSourceLocationSource(element.loc) ||\n this.isSourceLocationStringReplace(element.loc) || this.isSourceLocationNodeReplace(element.loc));\n if (filtered.length === 0) {\n return this.gen();\n }\n const first = filtered.at(0)!;\n const last = filtered.at(-1)!;\n return {\n sourceLocationType: 'source',\n start: this.isLocalized(first) ?\n (<SourceLocationSource | SourceLocationStringReplace> first.loc).start :\n first.startOffset,\n end: this.isLocalized(last) ?\n (<SourceLocationSource | SourceLocationStringReplace> last.loc).end :\n (last.endOffset! + 1),\n };\n }\n\n /**\n * Generate a source location indicating the no materialization.\n */\n public sourceLocationNoMaterialize(): SourceLocation {\n if (!this.tracksSourceLocation) {\n return this.gen();\n }\n return { sourceLocationType: 'noMaterialize' };\n }\n\n /**\n * Returns a copy of the argument that is not materialized\n */\n public dematerialized<T extends Node>(arg: T): T {\n return { ...arg, loc: this.sourceLocationNoMaterialize() };\n }\n\n /**\n * Given a value and some mapper from objects to objects,\n * map all containing items in case it is an array,\n * otherwise map the provided value in case it is an object, finally, do nothing.\n * @param value the value to map\n * @param mapper the function mapping an object to another object.\n */\n public safeObjectTransform(value: unknown, mapper: (some: object) => any): any {\n if (value && typeof value === 'object') {\n // If you wonder why this is all so hard, this is the reason. We cannot lose the methods of our Array objects\n if (Array.isArray(value)) {\n return value.map(x => this.safeObjectTransform(x, mapper));\n }\n return mapper(value);\n }\n return value;\n }\n\n /**\n * Given a (AST) tree, return a copy of that tree where it and it's\n * descendents all have a {@link SourceLocationNodeAutoGenerate} localization.\n */\n public forcedAutoGenTree<T extends object>(obj: T): T {\n const copy = { ...obj };\n for (const [ key, value ] of Object.entries(copy)) {\n (<Record<string, object>> copy)[key] = this.safeObjectTransform(value, obj => this.forcedAutoGenTree(obj));\n }\n if (this.isLocalized(copy)) {\n copy.loc = this.gen();\n }\n return copy;\n }\n\n /**\n * In case the provided Node is not yet materialized, force it to be autoGenerated.\n */\n public forceMaterialized<T extends Node>(arg: T): T {\n if (this.isSourceLocationNoMaterialize(arg.loc)) {\n return this.forcedAutoGenTree(arg);\n }\n return { ...arg };\n }\n\n /**\n * Check whether an object is in fact a {@link SourceLocation}.\n * @param loc\n */\n public isSourceLocation(loc: object): loc is SourceLocation {\n return 'sourceLocationType' in loc;\n }\n\n /**\n * Create a {@link SourceLocation} that indicates what range of characters this node represents in the source string.\n */\n public sourceLocationSource(start: number, end: number): SourceLocationSource {\n return {\n sourceLocationType: 'source',\n start,\n end,\n };\n }\n\n /**\n * Create a {@link SourceLocation} that indicates a given range of the current range should be replaced by\n * a new source.\n */\n public sourceLocationInlinedSource(\n newSource: string,\n subLoc: SourceLocation,\n start: number,\n end: number,\n startOnNew = 0,\n endOnNew: number = newSource.length,\n ): SourceLocation {\n if (!this.tracksSourceLocation) {\n return this.gen();\n }\n if (this.isSourceLocationSource(subLoc)) {\n startOnNew = subLoc.start;\n endOnNew = subLoc.end;\n }\n return {\n sourceLocationType: 'inlinedSource',\n newSource,\n start,\n end,\n loc: subLoc,\n startOnNew,\n endOnNew,\n }satisfies SourceLocationInlinedSource;\n };\n\n /**\n * Guard to check if an object is a {@link SourceLocation} of type {@link SourceLocationInlinedSource}.\n */\n public isSourceLocationInlinedSource(loc: object): loc is SourceLocationInlinedSource {\n return this.isSourceLocation(loc) && loc.sourceLocationType === 'inlinedSource';\n }\n\n /**\n * Create a {@link SourceLocation} indicating the node should be autoGenerated by a generator.\n */\n public gen(): SourceLocationNodeAutoGenerate {\n return { sourceLocationType: 'autoGenerate' };\n }\n\n /**\n * Guard to check if an object is a {@link SourceLocation} of type {@link SourceLocationSource}.\n */\n public isSourceLocationSource(loc: object): loc is SourceLocationSource {\n return this.isSourceLocation(loc) && loc.sourceLocationType === 'source';\n }\n\n /**\n * Create a {@link SourceLocation} that indicates this node,\n * representing a range of characters in the original string, should be replaced by some string during generation.\n */\n public sourceLocationStringReplace(newSource: string, start: number, end: number): SourceLocation {\n if (!this.tracksSourceLocation) {\n return this.gen();\n }\n return { sourceLocationType: 'stringReplace', newSource, start, end } satisfies SourceLocationStringReplace;\n }\n\n /**\n * Guard to check if an object is a {@link SourceLocation} of type {@link SourceLocationStringReplace}.\n * @param loc\n */\n public isSourceLocationStringReplace(loc: object): loc is SourceLocationStringReplace {\n return this.isSourceLocation(loc) && loc.sourceLocationType === 'stringReplace';\n }\n\n /**\n * Given a sourceLocation, generate a new {@link SourceLocation}\n * that indicates the range of the given location should now be autoGenerated\n */\n public sourceLocationNodeReplaceUnsafe(loc: SourceLocation): SourceLocationNodeReplace {\n if (this.isSourceLocationSource(loc)) {\n return this.sourceLocationNodeReplace(loc);\n }\n if (this.isSourceLocationInlinedSource(loc)) {\n return this.sourceLocationNodeReplaceUnsafe(loc.loc);\n }\n throw new Error(`Cannot convert SourceLocation of type ${loc.sourceLocationType} to SourceLocationNodeReplace`);\n }\n\n public sourceLocationNodeReplace(location: SourceLocationSource): SourceLocationNodeReplace;\n public sourceLocationNodeReplace(start: number, end: number): SourceLocationNodeReplace;\n public sourceLocationNodeReplace(startOrLoc: number | SourceLocationSource, end?: number): SourceLocationNodeReplace {\n let starting;\n let ending;\n if (typeof startOrLoc === 'number') {\n starting = startOrLoc;\n ending = end!;\n } else {\n starting = startOrLoc.start;\n ending = startOrLoc.end;\n }\n return {\n sourceLocationType: 'nodeReplace',\n start: starting,\n end: ending,\n };\n }\n\n /**\n * Guard to check if an object is a {@link SourceLocation} of type {@link SourceLocationNodeReplace}.\n */\n public isSourceLocationNodeReplace(loc: object): loc is SourceLocationNodeReplace {\n return this.isSourceLocation(loc) && loc.sourceLocationType === 'nodeReplace';\n }\n\n /**\n * Guard to check if an object is a {@link SourceLocation} of type {@link SourceLocationNodeAutoGenerate}.\n */\n public isSourceLocationNodeAutoGenerate(loc: object): loc is SourceLocationNodeAutoGenerate {\n return this.isSourceLocation(loc) && loc.sourceLocationType === 'autoGenerate';\n }\n\n /**\n * Check whether the provided {@link SourceLocation} expects the generator to autoGenerate.\n */\n public isPrintingLoc(loc: SourceLocation): boolean {\n return this.isSourceLocationNodeReplace(loc) ||\n this.isSourceLocationNodeAutoGenerate(loc) ||\n (this.isSourceLocationInlinedSource(loc) && this.isPrintingLoc(loc.loc));\n }\n\n /**\n * A simple filter that will only execute the provided callback when the provided {@link SourceLocation}\n * expects the generator steps to autoGenerate.\n */\n public printFilter(node: Localized, callback: () => void): void {\n if (this.isPrintingLoc(node.loc)) {\n callback();\n }\n }\n\n /**\n * Guard to check if an object is a {@link SourceLocation} of type {@link SourceLocationNoMaterialize}.\n */\n public isSourceLocationNoMaterialize(loc: object): loc is SourceLocationNoMaterialize {\n return this.isSourceLocation(loc) && loc.sourceLocationType === 'noMaterialize';\n }\n\n /**\n * Guard to check if an object is the specified Type: {@link Typed}.\n */\n public isOfType<Type extends string>(obj: object, type: Type): obj is Typed<Type> {\n const casted: { type?: any } = obj;\n return casted.type === type;\n }\n\n /**\n * Guard to check if an object is the specified Type: {@link SubTyped}.\n */\n public isOfSubType<Type extends string, SubType extends string>(obj: object, type: Type, subType: SubType):\n obj is SubTyped<Type, SubType> {\n const temp: { type?: unknown; subType?: unknown } = obj;\n return temp.type === type && temp.subType === subType;\n }\n}\n", "// needs a separate module as this is required inside chevrotain productive code\n// and also in the entry point for webpack(api.ts).\n// A separate file avoids cyclic dependencies and webpack errors.\nexport const VERSION = \"11.2.0\";\n", "/** Detect free variable `global` from Node.js. */\nvar freeGlobal = typeof global == 'object' && global && global.Object === Object && global;\n\nexport default freeGlobal;\n", "import freeGlobal from './_freeGlobal.js';\n\n/** Detect free variable `self`. */\nvar freeSelf = typeof self == 'object' && self && self.Object === Object && self;\n\n/** Used as a reference to the global object. */\nvar root = freeGlobal || freeSelf || Function('return this')();\n\nexport default root;\n", "import root from './_root.js';\n\n/** Built-in value references. */\nvar Symbol = root.Symbol;\n\nexport default Symbol;\n", "import Symbol from './_Symbol.js';\n\n/** Used for built-in method references. */\nvar objectProto = Object.prototype;\n\n/** Used to check objects for own properties. */\nvar hasOwnProperty = objectProto.hasOwnProperty;\n\n/**\n * Used to resolve the\n * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring)\n * of values.\n */\nvar nativeObjectToString = objectProto.toString;\n\n/** Built-in value references. */\nvar symToStringTag = Symbol ? Symbol.toStringTag : undefined;\n\n/**\n * A specialized version of `baseGetTag` which ignores `Symbol.toStringTag` values.\n *\n * @private\n * @param {*} value The value to query.\n * @returns {string} Returns the raw `toStringTag`.\n */\nfunction getRawTag(value) {\n var isOwn = hasOwnProperty.call(value, symToStringTag),\n tag = value[symToStringTag];\n\n try {\n value[symToStringTag] = undefined;\n var unmasked = true;\n } catch (e) {}\n\n var result = nativeObjectToString.call(value);\n if (unmasked) {\n if (isOwn) {\n value[symToStringTag] = tag;\n } else {\n delete value[symToStringTag];\n }\n }\n return result;\n}\n\nexport default getRawTag;\n", "/** Used for built-in method references. */\nvar objectProto = Object.prototype;\n\n/**\n * Used to resolve the\n * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring)\n * of values.\n */\nvar nativeObjectToString = objectProto.toString;\n\n/**\n * Converts `value` to a string using `Object.prototype.toString`.\n *\n * @private\n * @param {*} value The value to convert.\n * @returns {string} Returns the converted string.\n */\nfunction objectToString(value) {\n return nativeObjectToString.call(value);\n}\n\nexport default objectToString;\n", "import Symbol from './_Symbol.js';\nimport getRawTag from './_getRawTag.js';\nimport objectToString from './_objectToString.js';\n\n/** `Object#toString` result references. */\nvar nullTag = '[object Null]',\n undefinedTag = '[object Undefined]';\n\n/** Built-in value references. */\nvar symToStringTag = Symbol ? Symbol.toStringTag : undefined;\n\n/**\n * The base implementation of `getTag` without fallbacks for buggy environments.\n *\n * @private\n * @param {*} value The value to query.\n * @returns {string} Returns the `toStringTag`.\n */\nfunction baseGetTag(value) {\n if (value == null) {\n return value === undefined ? undefinedTag : nullTag;\n }\n return (symToStringTag && symToStringTag in Object(value))\n ? getRawTag(value)\n : objectToString(value);\n}\n\nexport default baseGetTag;\n", "/**\n * Checks if `value` is object-like. A value is object-like if it's not `null`\n * and has a `typeof` result of \"object\".\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is object-like, else `false`.\n * @example\n *\n * _.isObjectLike({});\n * // => true\n *\n * _.isObjectLike([1, 2, 3]);\n * // => true\n *\n * _.isObjectLike(_.noop);\n * // => false\n *\n * _.isObjectLike(null);\n * // => false\n */\nfunction isObjectLike(value) {\n return value != null && typeof value == 'object';\n}\n\nexport default isObjectLike;\n", "import baseGetTag from './_baseGetTag.js';\nimport isObjectLike from './isObjectLike.js';\n\n/** `Object#toString` result references. */\nvar symbolTag = '[object Symbol]';\n\n/**\n * Checks if `value` is classified as a `Symbol` primitive or object.\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is a symbol, else `false`.\n * @example\n *\n * _.isSymbol(Symbol.iterator);\n * // => true\n *\n * _.isSymbol('abc');\n * // => false\n */\nfunction isSymbol(value) {\n return typeof value == 'symbol' ||\n (isObjectLike(value) && baseGetTag(value) == symbolTag);\n}\n\nexport default isSymbol;\n", "/**\n * A specialized version of `_.map` for arrays without support for iteratee\n * shorthands.\n *\n * @private\n * @param {Array} [array] The array to iterate over.\n * @param {Function} iteratee The function invoked per iteration.\n * @returns {Array} Returns the new mapped array.\n */\nfunction arrayMap(array, iteratee) {\n var index = -1,\n length = array == null ? 0 : array.length,\n result = Array(length);\n\n while (++index < length) {\n result[index] = iteratee(array[index], index, array);\n }\n return result;\n}\n\nexport default arrayMap;\n", "/**\n * Checks if `value` is classified as an `Array` object.\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is an array, else `false`.\n * @example\n *\n * _.isArray([1, 2, 3]);\n * // => true\n *\n * _.isArray(document.body.children);\n * // => false\n *\n * _.isArray('abc');\n * // => false\n *\n * _.isArray(_.noop);\n * // => false\n */\nvar isArray = Array.isArray;\n\nexport default isArray;\n", "import Symbol from './_Symbol.js';\nimport arrayMap from './_arrayMap.js';\nimport isArray from './isArray.js';\nimport isSymbol from './isSymbol.js';\n\n/** Used as references for various `Number` constants. */\nvar INFINITY = 1 / 0;\n\n/** Used to convert symbols to primitives and strings. */\nvar symbolProto = Symbol ? Symbol.prototype : undefined,\n symbolToString = symbolProto ? symbolProto.toString : undefined;\n\n/**\n * The base implementation of `_.toString` which doesn't convert nullish\n * values to empty strings.\n *\n * @private\n * @param {*} value The value to process.\n * @returns {string} Returns the string.\n */\nfunction baseToString(value) {\n // Exit early for strings to avoid a performance hit in some environments.\n if (typeof value == 'string') {\n return value;\n }\n if (isArray(value)) {\n // Recursively convert values (susceptible to call stack limits).\n return arrayMap(value, baseToString) + '';\n }\n if (isSymbol(value)) {\n return symbolToString ? symbolToString.call(value) : '';\n }\n var result = (value + '');\n return (result == '0' && (1 / value) == -INFINITY) ? '-0' : result;\n}\n\nexport default baseToString;\n", "/** Used to match a single whitespace character. */\nvar reWhitespace = /\\s/;\n\n/**\n * Used by `_.trim` and `_.trimEnd` to get the index of the last non-whitespace\n * character of `string`.\n *\n * @private\n * @param {string} string The string to inspect.\n * @returns {number} Returns the index of the last non-whitespace character.\n */\nfunction trimmedEndIndex(string) {\n var index = string.length;\n\n while (index-- && reWhitespace.test(string.charAt(index))) {}\n return index;\n}\n\nexport default trimmedEndIndex;\n", "import trimmedEndIndex from './_trimmedEndIndex.js';\n\n/** Used to match leading whitespace. */\nvar reTrimStart = /^\\s+/;\n\n/**\n * The base implementation of `_.trim`.\n *\n * @private\n * @param {string} string The string to trim.\n * @returns {string} Returns the trimmed string.\n */\nfunction baseTrim(string) {\n return string\n ? string.slice(0, trimmedEndIndex(string) + 1).replace(reTrimStart, '')\n : string;\n}\n\nexport default baseTrim;\n", "/**\n * Checks if `value` is the\n * [language type](http://www.ecma-international.org/ecma-262/7.0/#sec-ecmascript-language-types)\n * of `Object`. (e.g. arrays, functions, objects, regexes, `new Number(0)`, and `new String('')`)\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is an object, else `false`.\n * @example\n *\n * _.isObject({});\n * // => true\n *\n * _.isObject([1, 2, 3]);\n * // => true\n *\n * _.isObject(_.noop);\n * // => true\n *\n * _.isObject(null);\n * // => false\n */\nfunction isObject(value) {\n var type = typeof value;\n return value != null && (type == 'object' || type == 'function');\n}\n\nexport default isObject;\n", "import baseTrim from './_baseTrim.js';\nimport isObject from './isObject.js';\nimport isSymbol from './isSymbol.js';\n\n/** Used as references for various `Number` constants. */\nvar NAN = 0 / 0;\n\n/** Used to detect bad signed hexadecimal string values. */\nvar reIsBadHex = /^[-+]0x[0-9a-f]+$/i;\n\n/** Used to detect binary string values. */\nvar reIsBinary = /^0b[01]+$/i;\n\n/** Used to detect octal string values. */\nvar reIsOctal = /^0o[0-7]+$/i;\n\n/** Built-in method references without a dependency on `root`. */\nvar freeParseInt = parseInt;\n\n/**\n * Converts `value` to a number.\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Lang\n * @param {*} value The value to process.\n * @returns {number} Returns the number.\n * @example\n *\n * _.toNumber(3.2);\n * // => 3.2\n *\n * _.toNumber(Number.MIN_VALUE);\n * // => 5e-324\n *\n * _.toNumber(Infinity);\n * // => Infinity\n *\n * _.toNumber('3.2');\n * // => 3.2\n */\nfunction toNumber(value) {\n if (typeof value == 'number') {\n return value;\n }\n if (isSymbol(value)) {\n return NAN;\n }\n if (isObject(value)) {\n var other = typeof value.valueOf == 'function' ? value.valueOf() : value;\n value = isObject(other) ? (other + '') : other;\n }\n if (typeof value != 'string') {\n return value === 0 ? value : +value;\n }\n value = baseTrim(value);\n var isBinary = reIsBinary.test(value);\n return (isBinary || reIsOctal.test(value))\n ? freeParseInt(value.slice(2), isBinary ? 2 : 8)\n : (reIsBadHex.test(value) ? NAN : +value);\n}\n\nexport default toNumber;\n", "import toNumber from './toNumber.js';\n\n/** Used as references for various `Number` constants. */\nvar INFINITY = 1 / 0,\n MAX_INTEGER = 1.7976931348623157e+308;\n\n/**\n * Converts `value` to a finite number.\n *\n * @static\n * @memberOf _\n * @since 4.12.0\n * @category Lang\n * @param {*} value The value to convert.\n * @returns {number} Returns the converted number.\n * @example\n *\n * _.toFinite(3.2);\n * // => 3.2\n *\n * _.toFinite(Number.MIN_VALUE);\n * // => 5e-324\n *\n * _.toFinite(Infinity);\n * // => 1.7976931348623157e+308\n *\n * _.toFinite('3.2');\n * // => 3.2\n */\nfunction toFinite(value) {\n if (!value) {\n return value === 0 ? value : 0;\n }\n value = toNumber(value);\n if (value === INFINITY || value === -INFINITY) {\n var sign = (value < 0 ? -1 : 1);\n return sign * MAX_INTEGER;\n }\n return value === value ? value : 0;\n}\n\nexport default toFinite;\n", "import toFinite from './toFinite.js';\n\n/**\n * Converts `value` to an integer.\n *\n * **Note:** This method is loosely based on\n * [`ToInteger`](http://www.ecma-international.org/ecma-262/7.0/#sec-tointeger).\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Lang\n * @param {*} value The value to convert.\n * @returns {number} Returns the converted integer.\n * @example\n *\n * _.toInteger(3.2);\n * // => 3\n *\n * _.toInteger(Number.MIN_VALUE);\n * // => 0\n *\n * _.toInteger(Infinity);\n * // => 1.7976931348623157e+308\n *\n * _.toInteger('3.2');\n * // => 3\n */\nfunction toInteger(value) {\n var result = toFinite(value),\n remainder = result % 1;\n\n return result === result ? (remainder ? result - remainder : result) : 0;\n}\n\nexport default toInteger;\n", "/**\n * This method returns the first argument it receives.\n *\n * @static\n * @since 0.1.0\n * @memberOf _\n * @category Util\n * @param {*} value Any value.\n * @returns {*} Returns `value`.\n * @example\n *\n * var object = { 'a': 1 };\n *\n * console.log(_.identity(object) === object);\n * // => true\n */\nfunction identity(value) {\n return value;\n}\n\nexport default identity;\n", "import baseGetTag from './_baseGetTag.js';\nimport isObject from './isObject.js';\n\n/** `Object#toString` result references. */\nvar asyncTag = '[object AsyncFunction]',\n funcTag = '[object Function]',\n genTag = '[object GeneratorFunction]',\n proxyTag = '[object Proxy]';\n\n/**\n * Checks if `value` is classified as a `Function` object.\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is a function, else `false`.\n * @example\n *\n * _.isFunction(_);\n * // => true\n *\n * _.isFunction(/abc/);\n * // => false\n */\nfunction isFunction(value) {\n if (!isObject(value)) {\n return false;\n }\n // The use of `Object#toString` avoids issues with the `typeof` operator\n // in Safari 9 which returns 'object' for typed arrays and other constructors.\n var tag = baseGetTag(value);\n return tag == funcTag || tag == genTag || tag == asyncTag || tag == proxyTag;\n}\n\nexport default isFunction;\n", "import root from './_root.js';\n\n/** Used to detect overreaching core-js shims. */\nvar coreJsData = root['__core-js_shared__'];\n\nexport default coreJsData;\n", "import coreJsData from './_coreJsData.js';\n\n/** Used to detect methods masquerading as native. */\nvar maskSrcKey = (function() {\n var uid = /[^.]+$/.exec(coreJsData && coreJsData.keys && coreJsData.keys.IE_PROTO || '');\n return uid ? ('Symbol(src)_1.' + uid) : '';\n}());\n\n/**\n * Checks if `func` has its source masked.\n *\n * @private\n * @param {Function} func The function to check.\n * @returns {boolean} Returns `true` if `func` is masked, else `false`.\n */\nfunction isMasked(func) {\n return !!maskSrcKey && (maskSrcKey in func);\n}\n\nexport default isMasked;\n", "/** Used for built-in method references. */\nvar funcProto = Function.prototype;\n\n/** Used to resolve the decompiled source of functions. */\nvar funcToString = funcProto.toString;\n\n/**\n * Converts `func` to its source code.\n *\n * @private\n * @param {Function} func The function to convert.\n * @returns {string} Returns the source code.\n */\nfunction toSource(func) {\n if (func != null) {\n try {\n return funcToString.call(func);\n } catch (e) {}\n try {\n return (func + '');\n } catch (e) {}\n }\n return '';\n}\n\nexport default toSource;\n", "import isFunction from './isFunction.js';\nimport isMasked from './_isMasked.js';\nimport isObject from './isObject.js';\nimport toSource from './_toSource.js';\n\n/**\n * Used to match `RegExp`\n * [syntax characters](http://ecma-international.org/ecma-262/7.0/#sec-patterns).\n */\nvar reRegExpChar = /[\\\\^$.*+?()[\\]{}|]/g;\n\n/** Used to detect host constructors (Safari). */\nvar reIsHostCtor = /^\\[object .+?Constructor\\]$/;\n\n/** Used for built-in method references. */\nvar funcProto = Function.prototype,\n objectProto = Object.prototype;\n\n/** Used to resolve the decompiled source of functions. */\nvar funcToString = funcProto.toString;\n\n/** Used to check objects for own properties. */\nvar hasOwnProperty = objectProto.hasOwnProperty;\n\n/** Used to detect if a method is native. */\nvar reIsNative = RegExp('^' +\n funcToString.call(hasOwnProperty).replace(reRegExpChar, '\\\\$&')\n .replace(/hasOwnProperty|(function).*?(?=\\\\\\()| for .+?(?=\\\\\\])/g, '$1.*?') + '$'\n);\n\n/**\n * The base implementation of `_.isNative` without bad shim checks.\n *\n * @private\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is a native function,\n * else `false`.\n */\nfunction baseIsNative(value) {\n if (!isObject(value) || isMasked(value)) {\n return false;\n }\n var pattern = isFunction(value) ? reIsNative : reIsHostCtor;\n return pattern.test(toSource(value));\n}\n\nexport default baseIsNative;\n", "/**\n * Gets the value at `key` of `object`.\n *\n * @private\n * @param {Object} [object] The object to query.\n * @param {string} key The key of the property to get.\n * @returns {*} Returns the property value.\n */\nfunction getValue(object, key) {\n return object == null ? undefined : object[key];\n}\n\nexport default getValue;\n", "import baseIsNative from './_baseIsNative.js';\nimport getValue from './_getValue.js';\n\n/**\n * Gets the native function at `key` of `object`.\n *\n * @private\n * @param {Object} object The object to query.\n * @param {string} key The key of the method to get.\n * @returns {*} Returns the function if it's native, else `undefined`.\n */\nfunction getNative(object, key) {\n var value = getValue(object, key);\n return baseIsNative(value) ? value : undefined;\n}\n\nexport default getNative;\n", "import getNative from './_getNative.js';\nimport root from './_root.js';\n\n/* Built-in method references that are verified to be native. */\nvar WeakMap = getNative(root, 'WeakMap');\n\nexport default WeakMap;\n", "import isObject from './isObject.js';\n\n/** Built-in value references. */\nvar objectCreate = Object.create;\n\n/**\n * The base implementation of `_.create` without support for assigning\n * properties to the created object.\n *\n * @private\n * @param {Object} proto The object to inherit from.\n * @returns {Object} Returns the new object.\n */\nvar baseCreate = (function() {\n function object() {}\n return function(proto) {\n if (!isObject(proto)) {\n return {};\n }\n if (objectCreate) {\n return objectCreate(proto);\n }\n object.prototype = proto;\n var result = new object;\n object.prototype = undefined;\n return result;\n };\n}());\n\nexport default baseCreate;\n", "/**\n * A faster alternative to `Function#apply`, this function invokes `func`\n * with the `this` binding of `thisArg` and the arguments of `args`.\n *\n * @private\n * @param {Function} func The function to invoke.\n * @param {*} thisArg The `this` binding of `func`.\n * @param {Array} args The arguments to invoke `func` with.\n * @returns {*} Returns the result of `func`.\n */\nfunction apply(func, thisArg, args) {\n switch (args.length) {\n case 0: return func.call(thisArg);\n case 1: return func.call(thisArg, args[0]);\n case 2: return func.call(thisArg, args[0], args[1]);\n case 3: return func.call(thisArg, args[0], args[1], args[2]);\n }\n return func.apply(thisArg, args);\n}\n\nexport default apply;\n", "/**\n * This method returns `undefined`.\n *\n * @static\n * @memberOf _\n * @since 2.3.0\n * @category Util\n * @example\n *\n * _.times(2, _.noop);\n * // => [undefined, undefined]\n */\nfunction noop() {\n // No operation performed.\n}\n\nexport default noop;\n", "/**\n * Copies the values of `source` to `array`.\n *\n * @private\n * @param {Array} source The array to copy values from.\n * @param {Array} [array=[]] The array to copy values to.\n * @returns {Array} Returns `array`.\n */\nfunction copyArray(source, array) {\n var index = -1,\n length = source.length;\n\n array || (array = Array(length));\n while (++index < length) {\n array[index] = source[index];\n }\n return array;\n}\n\nexport default copyArray;\n", "/** Used to detect hot functions by number of calls within a span of milliseconds. */\nvar HOT_COUNT = 800,\n HOT_SPAN = 16;\n\n/* Built-in method references for those with the same name as other `lodash` methods. */\nvar nativeNow = Date.now;\n\n/**\n * Creates a function that'll short out and invoke `identity` instead\n * of `func` when it's called `HOT_COUNT` or more times in `HOT_SPAN`\n * milliseconds.\n *\n * @private\n * @param {Function} func The function to restrict.\n * @returns {Function} Returns the new shortable function.\n */\nfunction shortOut(func) {\n var count = 0,\n lastCalled = 0;\n\n return function() {\n var stamp = nativeNow(),\n remaining = HOT_SPAN - (stamp - lastCalled);\n\n lastCalled = stamp;\n if (remaining > 0) {\n if (++count >= HOT_COUNT) {\n return arguments[0];\n }\n } else {\n count = 0;\n }\n return func.apply(undefined, arguments);\n };\n}\n\nexport default shortOut;\n", "/**\n * Creates a function that returns `value`.\n *\n * @static\n * @memberOf _\n * @since 2.4.0\n * @category Util\n * @param {*} value The value to return from the new function.\n * @returns {Function} Returns the new constant function.\n * @example\n *\n * var objects = _.times(2, _.constant({ 'a': 1 }));\n *\n * console.log(objects);\n * // => [{ 'a': 1 }, { 'a': 1 }]\n *\n * console.log(objects[0] === objects[1]);\n * // => true\n */\nfunction constant(value) {\n return function() {\n return value;\n };\n}\n\nexport default constant;\n", "import getNative from './_getNative.js';\n\nvar defineProperty = (function() {\n try {\n var func = getNative(Object, 'defineProperty');\n func({}, '', {});\n return func;\n } catch (e) {}\n}());\n\nexport default defineProperty;\n", "import constant from './constant.js';\nimport defineProperty from './_defineProperty.js';\nimport identity from './identity.js';\n\n/**\n * The base implementation of `setToString` without support for hot loop shorting.\n *\n * @private\n * @param {Function} func The function to modify.\n * @param {Function} string The `toString` result.\n * @returns {Function} Returns `func`.\n */\nvar baseSetToString = !defineProperty ? identity : function(func, string) {\n return defineProperty(func, 'toString', {\n 'configurable': true,\n 'enumerable': false,\n 'value': constant(string),\n 'writable': true\n });\n};\n\nexport default baseSetToString;\n", "import baseSetToString from './_baseSetToString.js';\nimport shortOut from './_shortOut.js';\n\n/**\n * Sets the `toString` method of `func` to return `string`.\n *\n * @private\n * @param {Function} func The function to modify.\n * @param {Function} string The `toString` result.\n * @returns {Function} Returns `func`.\n */\nvar setToString = shortOut(baseSetToString);\n\nexport default setToString;\n", "/**\n * A specialized version of `_.forEach` for arrays without support for\n * iteratee shorthands.\n *\n * @private\n * @param {Array} [array] The array to iterate over.\n * @param {Function} iteratee The function invoked per iteration.\n * @returns {Array} Returns `array`.\n */\nfunction arrayEach(array, iteratee) {\n var index = -1,\n length = array == null ? 0 : array.length;\n\n while (++index < length) {\n if (iteratee(array[index], index, array) === false) {\n break;\n }\n }\n return array;\n}\n\nexport default arrayEach;\n", "/**\n * The base implementation of `_.findIndex` and `_.findLastIndex` without\n * support for iteratee shorthands.\n *\n * @private\n * @param {Array} array The array to inspect.\n * @param {Function} predicate The function invoked per iteration.\n * @param {number} fromIndex The index to search from.\n * @param {boolean} [fromRight] Specify iterating from right to left.\n * @returns {number} Returns the index of the matched value, else `-1`.\n */\nfunction baseFindIndex(array, predicate, fromIndex, fromRight) {\n var length = array.length,\n index = fromIndex + (fromRight ? 1 : -1);\n\n while ((fromRight ? index-- : ++index < length)) {\n if (predicate(array[index], index, array)) {\n return index;\n }\n }\n return -1;\n}\n\nexport default baseFindIndex;\n", "/**\n * The base implementation of `_.isNaN` without support for number objects.\n *\n * @private\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is `NaN`, else `false`.\n */\nfunction baseIsNaN(value) {\n return value !== value;\n}\n\nexport default baseIsNaN;\n", "/**\n * A specialized version of `_.indexOf` which performs strict equality\n * comparisons of values, i.e. `===`.\n *\n * @private\n * @param {Array} array The array to inspect.\n * @param {*} value The value to search for.\n * @param {number} fromIndex The index to search from.\n * @returns {number} Returns the index of the matched value, else `-1`.\n */\nfunction strictIndexOf(array, value, fromIndex) {\n var index = fromIndex - 1,\n length = array.length;\n\n while (++index < length) {\n if (array[index] === value) {\n return index;\n }\n }\n return -1;\n}\n\nexport default strictIndexOf;\n", "import baseFindIndex from './_baseFindIndex.js';\nimport baseIsNaN from './_baseIsNaN.js';\nimport strictIndexOf from './_strictIndexOf.js';\n\n/**\n * The base implementation of `_.indexOf` without `fromIndex` bounds checks.\n *\n * @private\n * @param {Array} array The array to inspect.\n * @param {*} value The value to search for.\n * @param {number} fromIndex The index to search from.\n * @returns {number} Returns the index of the matched value, else `-1`.\n */\nfunction baseIndexOf(array, value, fromIndex) {\n return value === value\n ? strictIndexOf(array, value, fromIndex)\n : baseFindIndex(array, baseIsNaN, fromIndex);\n}\n\nexport default baseIndexOf;\n", "import baseIndexOf from './_baseIndexOf.js';\n\n/**\n * A specialized version of `_.includes` for arrays without support for\n * specifying an index to search from.\n *\n * @private\n * @param {Array} [array] The array to inspect.\n * @param {*} target The value to search for.\n * @returns {boolean} Returns `true` if `target` is found, else `false`.\n */\nfunction arrayIncludes(array, value) {\n var length = array == null ? 0 : array.length;\n return !!length && baseIndexOf(array, value, 0) > -1;\n}\n\nexport default arrayIncludes;\n", "/** Used as references for various `Number` constants. */\nvar MAX_SAFE_INTEGER = 9007199254740991;\n\n/** Used to detect unsigned integer values. */\nvar reIsUint = /^(?:0|[1-9]\\d*)$/;\n\n/**\n * Checks if `value` is a valid array-like index.\n *\n * @private\n * @param {*} value The value to check.\n * @param {number} [length=MAX_SAFE_INTEGER] The upper bounds of a valid index.\n * @returns {boolean} Returns `true` if `value` is a valid index, else `false`.\n */\nfunction isIndex(value, length) {\n var type = typeof value;\n length = length == null ? MAX_SAFE_INTEGER : length;\n\n return !!length &&\n (type == 'number' ||\n (type != 'symbol' && reIsUint.test(value))) &&\n (value > -1 && value % 1 == 0 && value < length);\n}\n\nexport default isIndex;\n", "import defineProperty from './_defineProperty.js';\n\n/**\n * The base implementation of `assignValue` and `assignMergeValue` without\n * value checks.\n *\n * @private\n * @param {Object} object The object to modify.\n * @param {string} key The key of the property to assign.\n * @param {*} value The value to assign.\n */\nfunction baseAssignValue(object, key, value) {\n if (key == '__proto__' && defineProperty) {\n defineProperty(object, key, {\n 'configurable': true,\n 'enumerable': true,\n 'value': value,\n 'writable': true\n });\n } else {\n object[key] = value;\n }\n}\n\nexport default baseAssignValue;\n", "/**\n * Performs a\n * [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero)\n * comparison between two values to determine if they are equivalent.\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Lang\n * @param {*} value The value to compare.\n * @param {*} other The other value to compare.\n * @returns {boolean} Returns `true` if the values are equivalent, else `false`.\n * @example\n *\n * var object = { 'a': 1 };\n * var other = { 'a': 1 };\n *\n * _.eq(object, object);\n * // => true\n *\n * _.eq(object, other);\n * // => false\n *\n * _.eq('a', 'a');\n * // => true\n *\n * _.eq('a', Object('a'));\n * // => false\n *\n * _.eq(NaN, NaN);\n * // => true\n */\nfunction eq(value, other) {\n return value === other || (value !== value && other !== other);\n}\n\nexport default eq;\n", "import baseAssignValue from './_baseAssignValue.js';\nimport eq from './eq.js';\n\n/** Used for built-in method references. */\nvar objectProto = Object.prototype;\n\n/** Used to check objects for own properties. */\nvar hasOwnProperty = objectProto.hasOwnProperty;\n\n/**\n * Assigns `value` to `key` of `object` if the existing value is not equivalent\n * using [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero)\n * for equality comparisons.\n *\n * @private\n * @param {Object} object The object to modify.\n * @param {string} key The key of the property to assign.\n * @param {*} value The value to assign.\n */\nfunction assignValue(object, key, value) {\n var objValue = object[key];\n if (!(hasOwnProperty.call(object, key) && eq(objValue, value)) ||\n (value === undefined && !(key in object))) {\n baseAssignValue(object, key, value);\n }\n}\n\nexport default assignValue;\n", "import assignValue from './_assignValue.js';\nimport baseAssignValue from './_baseAssignValue.js';\n\n/**\n * Copies properties of `source` to `object`.\n *\n * @private\n * @param {Object} source The object to copy properties from.\n * @param {Array} props The property identifiers to copy.\n * @param {Object} [object={}] The object to copy properties to.\n * @param {Function} [customizer] The function to customize copied values.\n * @returns {Object} Returns `object`.\n */\nfunction copyObject(source, props, object, customizer) {\n var isNew = !object;\n object || (object = {});\n\n var index = -1,\n length = props.length;\n\n while (++index < length) {\n var key = props[index];\n\n var newValue = customizer\n ? customizer(object[key], source[key], key, object, source)\n : undefined;\n\n if (newValue === undefined) {\n newValue = source[key];\n }\n if (isNew) {\n baseAssignValue(object, key, newValue);\n } else {\n assignValue(object, key, newValue);\n }\n }\n return object;\n}\n\nexport default copyObject;\n", "import apply from './_apply.js';\n\n/* Built-in method references for those with the same name as other `lodash` methods. */\nvar nativeMax = Math.max;\n\n/**\n * A specialized version of `baseRest` which transforms the rest array.\n *\n * @private\n * @param {Function} func The function to apply a rest parameter to.\n * @param {number} [start=func.length-1] The start position of the rest parameter.\n * @param {Function} transform The rest array transform.\n * @returns {Function} Returns the new function.\n */\nfunction overRest(func, start, transform) {\n start = nativeMax(start === undefined ? (func.length - 1) : start, 0);\n return function() {\n var args = arguments,\n index = -1,\n length = nativeMax(args.length - start, 0),\n array = Array(length);\n\n while (++index < length) {\n array[index] = args[start + index];\n }\n index = -1;\n var otherArgs = Array(start + 1);\n while (++index < start) {\n otherArgs[index] = args[index];\n }\n otherArgs[start] = transform(array);\n return apply(func, this, otherArgs);\n };\n}\n\nexport default overRest;\n", "import identity from './identity.js';\nimport overRest from './_overRest.js';\nimport setToString from './_setToString.js';\n\n/**\n * The base implementation of `_.rest` which doesn't validate or coerce arguments.\n *\n * @private\n * @param {Function} func The function to apply a rest parameter to.\n * @param {number} [start=func.length-1] The start position of the rest parameter.\n * @returns {Function} Returns the new function.\n */\nfunction baseRest(func, start) {\n return setToString(overRest(func, start, identity), func + '');\n}\n\nexport default baseRest;\n", "/** Used as references for various `Number` constants. */\nvar MAX_SAFE_INTEGER = 9007199254740991;\n\n/**\n * Checks if `value` is a valid array-like length.\n *\n * **Note:** This method is loosely based on\n * [`ToLength`](http://ecma-international.org/ecma-262/7.0/#sec-tolength).\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is a valid length, else `false`.\n * @example\n *\n * _.isLength(3);\n * // => true\n *\n * _.isLength(Number.MIN_VALUE);\n * // => false\n *\n * _.isLength(Infinity);\n * // => false\n *\n * _.isLength('3');\n * // => false\n */\nfunction isLength(value) {\n return typeof value == 'number' &&\n value > -1 && value % 1 == 0 && value <= MAX_SAFE_INTEGER;\n}\n\nexport default isLength;\n", "import isFunction from './isFunction.js';\nimport isLength from './isLength.js';\n\n/**\n * Checks if `value` is array-like. A value is considered array-like if it's\n * not a function and has a `value.length` that's an integer greater than or\n * equal to `0` and less than or equal to `Number.MAX_SAFE_INTEGER`.\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is array-like, else `false`.\n * @example\n *\n * _.isArrayLike([1, 2, 3]);\n * // => true\n *\n * _.isArrayLike(document.body.children);\n * // => true\n *\n * _.isArrayLike('abc');\n * // => true\n *\n * _.isArrayLike(_.noop);\n * // => false\n */\nfunction isArrayLike(value) {\n return value != null && isLength(value.length) && !isFunction(value);\n}\n\nexport default isArrayLike;\n", "import eq from './eq.js';\nimport isArrayLike from './isArrayLike.js';\nimport isIndex from './_isIndex.js';\nimport isObject from './isObject.js';\n\n/**\n * Checks if the given arguments are from an iteratee call.\n *\n * @private\n * @param {*} value The potential iteratee value argument.\n * @param {*} index The potential iteratee index or key argument.\n * @param {*} object The potential iteratee object argument.\n * @returns {boolean} Returns `true` if the arguments are from an iteratee call,\n * else `false`.\n */\nfunction isIterateeCall(value, index, object) {\n if (!isObject(object)) {\n return false;\n }\n var type = typeof index;\n if (type == 'number'\n ? (isArrayLike(object) && isIndex(index, object.length))\n : (type == 'string' && index in object)\n ) {\n return eq(object[index], value);\n }\n return false;\n}\n\nexport default isIterateeCall;\n", "import baseRest from './_baseRest.js';\nimport isIterateeCall from './_isIterateeCall.js';\n\n/**\n * Creates a function like `_.assign`.\n *\n * @private\n * @param {Function} assigner The function to assign values.\n * @returns {Function} Returns the new assigner function.\n */\nfunction createAssigner(assigner) {\n return baseRest(function(object, sources) {\n var index = -1,\n length = sources.length,\n customizer = length > 1 ? sources[length - 1] : undefined,\n guard = length > 2 ? sources[2] : undefined;\n\n customizer = (assigner.length > 3 && typeof customizer == 'function')\n ? (length--, customizer)\n : undefined;\n\n if (guard && isIterateeCall(sources[0], sources[1], guard)) {\n customizer = length < 3 ? undefined : customizer;\n length = 1;\n }\n object = Object(object);\n while (++index < length) {\n var source = sources[index];\n if (source) {\n assigner(object, source, index, customizer);\n }\n }\n return object;\n });\n}\n\nexport default createAssigner;\n", "/** Used for built-in method references. */\nvar objectProto = Object.prototype;\n\n/**\n * Checks if `value` is likely a prototype object.\n *\n * @private\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is a prototype, else `false`.\n */\nfunction isPrototype(value) {\n var Ctor = value && value.constructor,\n proto = (typeof Ctor == 'function' && Ctor.prototype) || objectProto;\n\n return value === proto;\n}\n\nexport default isPrototype;\n", "/**\n * The base implementation of `_.times` without support for iteratee shorthands\n * or max array length checks.\n *\n * @private\n * @param {number} n The number of times to invoke `iteratee`.\n * @param {Function} iteratee The function invoked per iteration.\n * @returns {Array} Returns the array of results.\n */\nfunction baseTimes(n, iteratee) {\n var index = -1,\n result = Array(n);\n\n while (++index < n) {\n result[index] = iteratee(index);\n }\n return result;\n}\n\nexport default baseTimes;\n", "import baseGetTag from './_baseGetTag.js';\nimport isObjectLike from './isObjectLike.js';\n\n/** `Object#toString` result references. */\nvar argsTag = '[object Arguments]';\n\n/**\n * The base implementation of `_.isArguments`.\n *\n * @private\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is an `arguments` object,\n */\nfunction baseIsArguments(value) {\n return isObjectLike(value) && baseGetTag(value) == argsTag;\n}\n\nexport default baseIsArguments;\n", "import baseIsArguments from './_baseIsArguments.js';\nimport isObjectLike from './isObjectLike.js';\n\n/** Used for built-in method references. */\nvar objectProto = Object.prototype;\n\n/** Used to check objects for own properties. */\nvar hasOwnProperty = objectProto.hasOwnProperty;\n\n/** Built-in value references. */\nvar propertyIsEnumerable = objectProto.propertyIsEnumerable;\n\n/**\n * Checks if `value` is likely an `arguments` object.\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is an `arguments` object,\n * else `false`.\n * @example\n *\n * _.isArguments(function() { return arguments; }());\n * // => true\n *\n * _.isArguments([1, 2, 3]);\n * // => false\n */\nvar isArguments = baseIsArguments(function() { return arguments; }()) ? baseIsArguments : function(value) {\n return isObjectLike(value) && hasOwnProperty.call(value, 'callee') &&\n !propertyIsEnumerable.call(value, 'callee');\n};\n\nexport default isArguments;\n", "/**\n * This method returns `false`.\n *\n * @static\n * @memberOf _\n * @since 4.13.0\n * @category Util\n * @returns {boolean} Returns `false`.\n * @example\n *\n * _.times(2, _.stubFalse);\n * // => [false, false]\n */\nfunction stubFalse() {\n return false;\n}\n\nexport default stubFalse;\n", "import root from './_root.js';\nimport stubFalse from './stubFalse.js';\n\n/** Detect free variable `exports`. */\nvar freeExports = typeof exports == 'object' && exports && !exports.nodeType && exports;\n\n/** Detect free variable `module`. */\nvar freeModule = freeExports && typeof module == 'object' && module && !module.nodeType && module;\n\n/** Detect the popular CommonJS extension `module.exports`. */\nvar moduleExports = freeModule && freeModule.exports === freeExports;\n\n/** Built-in value references. */\nvar Buffer = moduleExports ? root.Buffer : undefined;\n\n/* Built-in method references for those with the same name as other `lodash` methods. */\nvar nativeIsBuffer = Buffer ? Buffer.isBuffer : undefined;\n\n/**\n * Checks if `value` is a buffer.\n *\n * @static\n * @memberOf _\n * @since 4.3.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is a buffer, else `false`.\n * @example\n *\n * _.isBuffer(new Buffer(2));\n * // => true\n *\n * _.isBuffer(new Uint8Array(2));\n * // => false\n */\nvar isBuffer = nativeIsBuffer || stubFalse;\n\nexport default isBuffer;\n", "import baseGetTag from './_baseGetTag.js';\nimport isLength from './isLength.js';\nimport isObjectLike from './isObjectLike.js';\n\n/** `Object#toString` result references. */\nvar argsTag = '[object Arguments]',\n arrayTag = '[object Array]',\n boolTag = '[object Boolean]',\n dateTag = '[object Date]',\n errorTag = '[object Error]',\n funcTag = '[object Function]',\n mapTag = '[object Map]',\n numberTag = '[object Number]',\n objectTag = '[object Object]',\n regexpTag = '[object RegExp]',\n setTag = '[object Set]',\n stringTag = '[object String]',\n weakMapTag = '[object WeakMap]';\n\nvar arrayBufferTag = '[object ArrayBuffer]',\n dataViewTag = '[object DataView]',\n float32Tag = '[object Float32Array]',\n float64Tag = '[object Float64Array]',\n int8Tag = '[object Int8Array]',\n int16Tag = '[object Int16Array]',\n int32Tag = '[object Int32Array]',\n uint8Tag = '[object Uint8Array]',\n uint8ClampedTag = '[object Uint8ClampedArray]',\n uint16Tag = '[object Uint16Array]',\n uint32Tag = '[object Uint32Array]';\n\n/** Used to identify `toStringTag` values of typed arrays. */\nvar typedArrayTags = {};\ntypedArrayTags[float32Tag] = typedArrayTags[float64Tag] =\ntypedArrayTags[int8Tag] = typedArrayTags[int16Tag] =\ntypedArrayTags[int32Tag] = typedArrayTags[uint8Tag] =\ntypedArrayTags[uint8ClampedTag] = typedArrayTags[uint16Tag] =\ntypedArrayTags[uint32Tag] = true;\ntypedArrayTags[argsTag] = typedArrayTags[arrayTag] =\ntypedArrayTags[arrayBufferTag] = typedArrayTags[boolTag] =\ntypedArrayTags[dataViewTag] = typedArrayTags[dateTag] =\ntypedArrayTags[errorTag] = typedArrayTags[funcTag] =\ntypedArrayTags[mapTag] = typedArrayTags[numberTag] =\ntypedArrayTags[objectTag] = typedArrayTags[regexpTag] =\ntypedArrayTags[setTag] = typedArrayTags[stringTag] =\ntypedArrayTags[weakMapTag] = false;\n\n/**\n * The base implementation of `_.isTypedArray` without Node.js optimizations.\n *\n * @private\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is a typed array, else `false`.\n */\nfunction baseIsTypedArray(value) {\n return isObjectLike(value) &&\n isLength(value.length) && !!typedArrayTags[baseGetTag(value)];\n}\n\nexport default baseIsTypedArray;\n", "/**\n * The base implementation of `_.unary` without support for storing metadata.\n *\n * @private\n * @param {Function} func The function to cap arguments for.\n * @returns {Function} Returns the new capped function.\n */\nfunction baseUnary(func) {\n return function(value) {\n return func(value);\n };\n}\n\nexport default baseUnary;\n", "import freeGlobal from './_freeGlobal.js';\n\n/** Detect free variable `exports`. */\nvar freeExports = typeof exports == 'object' && exports && !exports.nodeType && exports;\n\n/** Detect free variable `module`. */\nvar freeModule = freeExports && typeof module == 'object' && module && !module.nodeType && module;\n\n/** Detect the popular CommonJS extension `module.exports`. */\nvar moduleExports = freeModule && freeModule.exports === freeExports;\n\n/** Detect free variable `process` from Node.js. */\nvar freeProcess = moduleExports && freeGlobal.process;\n\n/** Used to access faster Node.js helpers. */\nvar nodeUtil = (function() {\n try {\n // Use `util.types` for Node.js 10+.\n var types = freeModule && freeModule.require && freeModule.require('util').types;\n\n if (types) {\n return types;\n }\n\n // Legacy `process.binding('util')` for Node.js < 10.\n return freeProcess && freeProcess.binding && freeProcess.binding('util');\n } catch (e) {}\n}());\n\nexport default nodeUtil;\n", "import baseIsTypedArray from './_baseIsTypedArray.js';\nimport baseUnary from './_baseUnary.js';\nimport nodeUtil from './_nodeUtil.js';\n\n/* Node.js helper references. */\nvar nodeIsTypedArray = nodeUtil && nodeUtil.isTypedArray;\n\n/**\n * Checks if `value` is classified as a typed array.\n *\n * @static\n * @memberOf _\n * @since 3.0.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is a typed array, else `false`.\n * @example\n *\n * _.isTypedArray(new Uint8Array);\n * // => true\n *\n * _.isTypedArray([]);\n * // => false\n */\nvar isTypedArray = nodeIsTypedArray ? baseUnary(nodeIsTypedArray) : baseIsTypedArray;\n\nexport default isTypedArray;\n", "import baseTimes from './_baseTimes.js';\nimport isArguments from './isArguments.js';\nimport isArray from './isArray.js';\nimport isBuffer from './isBuffer.js';\nimport isIndex from './_isIndex.js';\nimport isTypedArray from './isTypedArray.js';\n\n/** Used for built-in method references. */\nvar objectProto = Object.prototype;\n\n/** Used to check objects for own properties. */\nvar hasOwnProperty = objectProto.hasOwnProperty;\n\n/**\n * Creates an array of the enumerable property names of the array-like `value`.\n *\n * @private\n * @param {*} value The value to query.\n * @param {boolean} inherited Specify returning inherited property names.\n * @returns {Array} Returns the array of property names.\n */\nfunction arrayLikeKeys(value, inherited) {\n var isArr = isArray(value),\n isArg = !isArr && isArguments(value),\n isBuff = !isArr && !isArg && isBuffer(value),\n isType = !isArr && !isArg && !isBuff && isTypedArray(value),\n skipIndexes = isArr || isArg || isBuff || isType,\n result = skipIndexes ? baseTimes(value.length, String) : [],\n length = result.length;\n\n for (var key in value) {\n if ((inherited || hasOwnProperty.call(value, key)) &&\n !(skipIndexes && (\n // Safari 9 has enumerable `arguments.length` in strict mode.\n key == 'length' ||\n // Node.js 0.10 has enumerable non-index properties on buffers.\n (isBuff && (key == 'offset' || key == 'parent')) ||\n // PhantomJS 2 has enumerable non-index properties on typed arrays.\n (isType && (key == 'buffer' || key == 'byteLength' || key == 'byteOffset')) ||\n // Skip index properties.\n isIndex(key, length)\n ))) {\n result.push(key);\n }\n }\n return result;\n}\n\nexport default arrayLikeKeys;\n", "/**\n * Creates a unary function that invokes `func` with its argument transformed.\n *\n * @private\n * @param {Function} func The function to wrap.\n * @param {Function} transform The argument transform.\n * @returns {Function} Returns the new function.\n */\nfunction overArg(func, transform) {\n return function(arg) {\n return func(transform(arg));\n };\n}\n\nexport default overArg;\n", "import overArg from './_overArg.js';\n\n/* Built-in method references for those with the same name as other `lodash` methods. */\nvar nativeKeys = overArg(Object.keys, Object);\n\nexport default nativeKeys;\n", "import isPrototype from './_isPrototype.js';\nimport nativeKeys from './_nativeKeys.js';\n\n/** Used for built-in method references. */\nvar objectProto = Object.prototype;\n\n/** Used to check objects for own properties. */\nvar hasOwnProperty = objectProto.hasOwnProperty;\n\n/**\n * The base implementation of `_.keys` which doesn't treat sparse arrays as dense.\n *\n * @private\n * @param {Object} object The object to query.\n * @returns {Array} Returns the array of property names.\n */\nfunction baseKeys(object) {\n if (!isPrototype(object)) {\n return nativeKeys(object);\n }\n var result = [];\n for (var key in Object(object)) {\n if (hasOwnProperty.call(object, key) && key != 'constructor') {\n result.push(key);\n }\n }\n return result;\n}\n\nexport default baseKeys;\n", "import arrayLikeKeys from './_arrayLikeKeys.js';\nimport baseKeys from './_baseKeys.js';\nimport isArrayLike from './isArrayLike.js';\n\n/**\n * Creates an array of the own enumerable property names of `object`.\n *\n * **Note:** Non-object values are coerced to objects. See the\n * [ES spec](http://ecma-international.org/ecma-262/7.0/#sec-object.keys)\n * for more details.\n *\n * @static\n * @since 0.1.0\n * @memberOf _\n * @category Object\n * @param {Object} object The object to query.\n * @returns {Array} Returns the array of property names.\n * @example\n *\n * function Foo() {\n * this.a = 1;\n * this.b = 2;\n * }\n *\n * Foo.prototype.c = 3;\n *\n * _.keys(new Foo);\n * // => ['a', 'b'] (iteration order is not guaranteed)\n *\n * _.keys('hi');\n * // => ['0', '1']\n */\nfunction keys(object) {\n return isArrayLike(object) ? arrayLikeKeys(object) : baseKeys(object);\n}\n\nexport default keys;\n", "import assignValue from './_assignValue.js';\nimport copyObject from './_copyObject.js';\nimport createAssigner from './_createAssigner.js';\nimport isArrayLike from './isArrayLike.js';\nimport isPrototype from './_isPrototype.js';\nimport keys from './keys.js';\n\n/** Used for built-in method references. */\nvar objectProto = Object.prototype;\n\n/** Used to check objects for own properties. */\nvar hasOwnProperty = objectProto.hasOwnProperty;\n\n/**\n * Assigns own enumerable string keyed properties of source objects to the\n * destination object. Source objects are applied from left to right.\n * Subsequent sources overwrite property assignments of previous sources.\n *\n * **Note:** This method mutates `object` and is loosely based on\n * [`Object.assign`](https://mdn.io/Object/assign).\n *\n * @static\n * @memberOf _\n * @since 0.10.0\n * @category Object\n * @param {Object} object The destination object.\n * @param {...Object} [sources] The source objects.\n * @returns {Object} Returns `object`.\n * @see _.assignIn\n * @example\n *\n * function Foo() {\n * this.a = 1;\n * }\n *\n * function Bar() {\n * this.c = 3;\n * }\n *\n * Foo.prototype.b = 2;\n * Bar.prototype.d = 4;\n *\n * _.assign({ 'a': 0 }, new Foo, new Bar);\n * // => { 'a': 1, 'c': 3 }\n */\nvar assign = createAssigner(function(object, source) {\n if (isPrototype(source) || isArrayLike(source)) {\n copyObject(source, keys(source), object);\n return;\n }\n for (var key in source) {\n if (hasOwnProperty.call(source, key)) {\n assignValue(object, key, source[key]);\n }\n }\n});\n\nexport default assign;\n", "/**\n * This function is like\n * [`Object.keys`](http://ecma-international.org/ecma-262/7.0/#sec-object.keys)\n * except that it includes inherited enumerable properties.\n *\n * @private\n * @param {Object} object The object to query.\n * @returns {Array} Returns the array of property names.\n */\nfunction nativeKeysIn(object) {\n var result = [];\n if (object != null) {\n for (var key in Object(object)) {\n result.push(key);\n }\n }\n return result;\n}\n\nexport default nativeKeysIn;\n", "import isObject from './isObject.js';\nimport isPrototype from './_isPrototype.js';\nimport nativeKeysIn from './_nativeKeysIn.js';\n\n/** Used for built-in method references. */\nvar objectProto = Object.prototype;\n\n/** Used to check objects for own properties. */\nvar hasOwnProperty = objectProto.hasOwnProperty;\n\n/**\n * The base implementation of `_.keysIn` which doesn't treat sparse arrays as dense.\n *\n * @private\n * @param {Object} object The object to query.\n * @returns {Array} Returns the array of property names.\n */\nfunction baseKeysIn(object) {\n if (!isObject(object)) {\n return nativeKeysIn(object);\n }\n var isProto = isPrototype(object),\n result = [];\n\n for (var key in object) {\n if (!(key == 'constructor' && (isProto || !hasOwnProperty.call(object, key)))) {\n result.push(key);\n }\n }\n return result;\n}\n\nexport default baseKeysIn;\n", "import arrayLikeKeys from './_arrayLikeKeys.js';\nimport baseKeysIn from './_baseKeysIn.js';\nimport isArrayLike from './isArrayLike.js';\n\n/**\n * Creates an array of the own and inherited enumerable property names of `object`.\n *\n * **Note:** Non-object values are coerced to objects.\n *\n * @static\n * @memberOf _\n * @since 3.0.0\n * @category Object\n * @param {Object} object The object to query.\n * @returns {Array} Returns the array of property names.\n * @example\n *\n * function Foo() {\n * this.a = 1;\n * this.b = 2;\n * }\n *\n * Foo.prototype.c = 3;\n *\n * _.keysIn(new Foo);\n * // => ['a', 'b', 'c'] (iteration order is not guaranteed)\n */\nfunction keysIn(object) {\n return isArrayLike(object) ? arrayLikeKeys(object, true) : baseKeysIn(object);\n}\n\nexport default keysIn;\n", "import isArray from './isArray.js';\nimport isSymbol from './isSymbol.js';\n\n/** Used to match property names within property paths. */\nvar reIsDeepProp = /\\.|\\[(?:[^[\\]]*|([\"'])(?:(?!\\1)[^\\\\]|\\\\.)*?\\1)\\]/,\n reIsPlainProp = /^\\w*$/;\n\n/**\n * Checks if `value` is a property name and not a property path.\n *\n * @private\n * @param {*} value The value to check.\n * @param {Object} [object] The object to query keys on.\n * @returns {boolean} Returns `true` if `value` is a property name, else `false`.\n */\nfunction isKey(value, object) {\n if (isArray(value)) {\n return false;\n }\n var type = typeof value;\n if (type == 'number' || type == 'symbol' || type == 'boolean' ||\n value == null || isSymbol(value)) {\n return true;\n }\n return reIsPlainProp.test(value) || !reIsDeepProp.test(value) ||\n (object != null && value in Object(object));\n}\n\nexport default isKey;\n", "import getNative from './_getNative.js';\n\n/* Built-in method references that are verified to be native. */\nvar nativeCreate = getNative(Object, 'create');\n\nexport default nativeCreate;\n", "import nativeCreate from './_nativeCreate.js';\n\n/**\n * Removes all key-value entries from the hash.\n *\n * @private\n * @name clear\n * @memberOf Hash\n */\nfunction hashClear() {\n this.__data__ = nativeCreate ? nativeCreate(null) : {};\n this.size = 0;\n}\n\nexport default hashClear;\n", "/**\n * Removes `key` and its value from the hash.\n *\n * @private\n * @name delete\n * @memberOf Hash\n * @param {Object} hash The hash to modify.\n * @param {string} key The key of the value to remove.\n * @returns {boolean} Returns `true` if the entry was removed, else `false`.\n */\nfunction hashDelete(key) {\n var result = this.has(key) && delete this.__data__[key];\n this.size -= result ? 1 : 0;\n return result;\n}\n\nexport default hashDelete;\n", "import nativeCreate from './_nativeCreate.js';\n\n/** Used to stand-in for `undefined` hash values. */\nvar HASH_UNDEFINED = '__lodash_hash_undefined__';\n\n/** Used for built-in method references. */\nvar objectProto = Object.prototype;\n\n/** Used to check objects for own properties. */\nvar hasOwnProperty = objectProto.hasOwnProperty;\n\n/**\n * Gets the hash value for `key`.\n *\n * @private\n * @name get\n * @memberOf Hash\n * @param {string} key The key of the value to get.\n * @returns {*} Returns the entry value.\n */\nfunction hashGet(key) {\n var data = this.__data__;\n if (nativeCreate) {\n var result = data[key];\n return result === HASH_UNDEFINED ? undefined : result;\n }\n return hasOwnProperty.call(data, key) ? data[key] : undefined;\n}\n\nexport default hashGet;\n", "import nativeCreate from './_nativeCreate.js';\n\n/** Used for built-in method references. */\nvar objectProto = Object.prototype;\n\n/** Used to check objects for own properties. */\nvar hasOwnProperty = objectProto.hasOwnProperty;\n\n/**\n * Checks if a hash value for `key` exists.\n *\n * @private\n * @name has\n * @memberOf Hash\n * @param {string} key The key of the entry to check.\n * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.\n */\nfunction hashHas(key) {\n var data = this.__data__;\n return nativeCreate ? (data[key] !== undefined) : hasOwnProperty.call(data, key);\n}\n\nexport default hashHas;\n", "import nativeCreate from './_nativeCreate.js';\n\n/** Used to stand-in for `undefined` hash values. */\nvar HASH_UNDEFINED = '__lodash_hash_undefined__';\n\n/**\n * Sets the hash `key` to `value`.\n *\n * @private\n * @name set\n * @memberOf Hash\n * @param {string} key The key of the value to set.\n * @param {*} value The value to set.\n * @returns {Object} Returns the hash instance.\n */\nfunction hashSet(key, value) {\n var data = this.__data__;\n this.size += this.has(key) ? 0 : 1;\n data[key] = (nativeCreate && value === undefined) ? HASH_UNDEFINED : value;\n return this;\n}\n\nexport default hashSet;\n", "import hashClear from './_hashClear.js';\nimport hashDelete from './_hashDelete.js';\nimport hashGet from './_hashGet.js';\nimport hashHas from './_hashHas.js';\nimport hashSet from './_hashSet.js';\n\n/**\n * Creates a hash object.\n *\n * @private\n * @constructor\n * @param {Array} [entries] The key-value pairs to cache.\n */\nfunction Hash(entries) {\n var index = -1,\n length = entries == null ? 0 : entries.length;\n\n this.clear();\n while (++index < length) {\n var entry = entries[index];\n this.set(entry[0], entry[1]);\n }\n}\n\n// Add methods to `Hash`.\nHash.prototype.clear = hashClear;\nHash.prototype['delete'] = hashDelete;\nHash.prototype.get = hashGet;\nHash.prototype.has = hashHas;\nHash.prototype.set = hashSet;\n\nexport default Hash;\n", "/**\n * Removes all key-value entries from the list cache.\n *\n * @private\n * @name clear\n * @memberOf ListCache\n */\nfunction listCacheClear() {\n this.__data__ = [];\n this.size = 0;\n}\n\nexport default listCacheClear;\n", "import eq from './eq.js';\n\n/**\n * Gets the index at which the `key` is found in `array` of key-value pairs.\n *\n * @private\n * @param {Array} array The array to inspect.\n * @param {*} key The key to search for.\n * @returns {number} Returns the index of the matched value, else `-1`.\n */\nfunction assocIndexOf(array, key) {\n var length = array.length;\n while (length--) {\n if (eq(array[length][0], key)) {\n return length;\n }\n }\n return -1;\n}\n\nexport default assocIndexOf;\n", "import assocIndexOf from './_assocIndexOf.js';\n\n/** Used for built-in method references. */\nvar arrayProto = Array.prototype;\n\n/** Built-in value references. */\nvar splice = arrayProto.splice;\n\n/**\n * Removes `key` and its value from the list cache.\n *\n * @private\n * @name delete\n * @memberOf ListCache\n * @param {string} key The key of the value to remove.\n * @returns {boolean} Returns `true` if the entry was removed, else `false`.\n */\nfunction listCacheDelete(key) {\n var data = this.__data__,\n index = assocIndexOf(data, key);\n\n if (index < 0) {\n return false;\n }\n var lastIndex = data.length - 1;\n if (index == lastIndex) {\n data.pop();\n } else {\n splice.call(data, index, 1);\n }\n --this.size;\n return true;\n}\n\nexport default listCacheDelete;\n", "import assocIndexOf from './_assocIndexOf.js';\n\n/**\n * Gets the list cache value for `key`.\n *\n * @private\n * @name get\n * @memberOf ListCache\n * @param {string} key The key of the value to get.\n * @returns {*} Returns the entry value.\n */\nfunction listCacheGet(key) {\n var data = this.__data__,\n index = assocIndexOf(data, key);\n\n return index < 0 ? undefined : data[index][1];\n}\n\nexport default listCacheGet;\n", "import assocIndexOf from './_assocIndexOf.js';\n\n/**\n * Checks if a list cache value for `key` exists.\n *\n * @private\n * @name has\n * @memberOf ListCache\n * @param {string} key The key of the entry to check.\n * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.\n */\nfunction listCacheHas(key) {\n return assocIndexOf(this.__data__, key) > -1;\n}\n\nexport default listCacheHas;\n", "import assocIndexOf from './_assocIndexOf.js';\n\n/**\n * Sets the list cache `key` to `value`.\n *\n * @private\n * @name set\n * @memberOf ListCache\n * @param {string} key The key of the value to set.\n * @param {*} value The value to set.\n * @returns {Object} Returns the list cache instance.\n */\nfunction listCacheSet(key, value) {\n var data = this.__data__,\n index = assocIndexOf(data, key);\n\n if (index < 0) {\n ++this.size;\n data.push([key, value]);\n } else {\n data[index][1] = value;\n }\n return this;\n}\n\nexport default listCacheSet;\n", "import listCacheClear from './_listCacheClear.js';\nimport listCacheDelete from './_listCacheDelete.js';\nimport listCacheGet from './_listCacheGet.js';\nimport listCacheHas from './_listCacheHas.js';\nimport listCacheSet from './_listCacheSet.js';\n\n/**\n * Creates an list cache object.\n *\n * @private\n * @constructor\n * @param {Array} [entries] The key-value pairs to cache.\n */\nfunction ListCache(entries) {\n var index = -1,\n length = entries == null ? 0 : entries.length;\n\n this.clear();\n while (++index < length) {\n var entry = entries[index];\n this.set(entry[0], entry[1]);\n }\n}\n\n// Add methods to `ListCache`.\nListCache.prototype.clear = listCacheClear;\nListCache.prototype['delete'] = listCacheDelete;\nListCache.prototype.get = listCacheGet;\nListCache.prototype.has = listCacheHas;\nListCache.prototype.set = listCacheSet;\n\nexport default ListCache;\n", "import getNative from './_getNative.js';\nimport root from './_root.js';\n\n/* Built-in method references that are verified to be native. */\nvar Map = getNative(root, 'Map');\n\nexport default Map;\n", "import Hash from './_Hash.js';\nimport ListCache from './_ListCache.js';\nimport Map from './_Map.js';\n\n/**\n * Removes all key-value entries from the map.\n *\n * @private\n * @name clear\n * @memberOf MapCache\n */\nfunction mapCacheClear() {\n this.size = 0;\n this.__data__ = {\n 'hash': new Hash,\n 'map': new (Map || ListCache),\n 'string': new Hash\n };\n}\n\nexport default mapCacheClear;\n", "/**\n * Checks if `value` is suitable for use as unique object key.\n *\n * @private\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is suitable, else `false`.\n */\nfunction isKeyable(value) {\n var type = typeof value;\n return (type == 'string' || type == 'number' || type == 'symbol' || type == 'boolean')\n ? (value !== '__proto__')\n : (value === null);\n}\n\nexport default isKeyable;\n", "import isKeyable from './_isKeyable.js';\n\n/**\n * Gets the data for `map`.\n *\n * @private\n * @param {Object} map The map to query.\n * @param {string} key The reference key.\n * @returns {*} Returns the map data.\n */\nfunction getMapData(map, key) {\n var data = map.__data__;\n return isKeyable(key)\n ? data[typeof key == 'string' ? 'string' : 'hash']\n : data.map;\n}\n\nexport default getMapData;\n", "import getMapData from './_getMapData.js';\n\n/**\n * Removes `key` and its value from the map.\n *\n * @private\n * @name delete\n * @memberOf MapCache\n * @param {string} key The key of the value to remove.\n * @returns {boolean} Returns `true` if the entry was removed, else `false`.\n */\nfunction mapCacheDelete(key) {\n var result = getMapData(this, key)['delete'](key);\n this.size -= result ? 1 : 0;\n return result;\n}\n\nexport default mapCacheDelete;\n", "import getMapData from './_getMapData.js';\n\n/**\n * Gets the map value for `key`.\n *\n * @private\n * @name get\n * @memberOf MapCache\n * @param {string} key The key of the value to get.\n * @returns {*} Returns the entry value.\n */\nfunction mapCacheGet(key) {\n return getMapData(this, key).get(key);\n}\n\nexport default mapCacheGet;\n", "import getMapData from './_getMapData.js';\n\n/**\n * Checks if a map value for `key` exists.\n *\n * @private\n * @name has\n * @memberOf MapCache\n * @param {string} key The key of the entry to check.\n * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.\n */\nfunction mapCacheHas(key) {\n return getMapData(this, key).has(key);\n}\n\nexport default mapCacheHas;\n", "import getMapData from './_getMapData.js';\n\n/**\n * Sets the map `key` to `value`.\n *\n * @private\n * @name set\n * @memberOf MapCache\n * @param {string} key The key of the value to set.\n * @param {*} value The value to set.\n * @returns {Object} Returns the map cache instance.\n */\nfunction mapCacheSet(key, value) {\n var data = getMapData(this, key),\n size = data.size;\n\n data.set(key, value);\n this.size += data.size == size ? 0 : 1;\n return this;\n}\n\nexport default mapCacheSet;\n", "import mapCacheClear from './_mapCacheClear.js';\nimport mapCacheDelete from './_mapCacheDelete.js';\nimport mapCacheGet from './_mapCacheGet.js';\nimport mapCacheHas from './_mapCacheHas.js';\nimport mapCacheSet from './_mapCacheSet.js';\n\n/**\n * Creates a map cache object to store key-value pairs.\n *\n * @private\n * @constructor\n * @param {Array} [entries] The key-value pairs to cache.\n */\nfunction MapCache(entries) {\n var index = -1,\n length = entries == null ? 0 : entries.length;\n\n this.clear();\n while (++index < length) {\n var entry = entries[index];\n this.set(entry[0], entry[1]);\n }\n}\n\n// Add methods to `MapCache`.\nMapCache.prototype.clear = mapCacheClear;\nMapCache.prototype['delete'] = mapCacheDelete;\nMapCache.prototype.get = mapCacheGet;\nMapCache.prototype.has = mapCacheHas;\nMapCache.prototype.set = mapCacheSet;\n\nexport default MapCache;\n", "import MapCache from './_MapCache.js';\n\n/** Error message constants. */\nvar FUNC_ERROR_TEXT = 'Expected a function';\n\n/**\n * Creates a function that memoizes the result of `func`. If `resolver` is\n * provided, it determines the cache key for storing the result based on the\n * arguments provided to the memoized function. By default, the first argument\n * provided to the memoized function is used as the map cache key. The `func`\n * is invoked with the `this` binding of the memoized function.\n *\n * **Note:** The cache is exposed as the `cache` property on the memoized\n * function. Its creation may be customized by replacing the `_.memoize.Cache`\n * constructor with one whose instances implement the\n * [`Map`](http://ecma-international.org/ecma-262/7.0/#sec-properties-of-the-map-prototype-object)\n * method interface of `clear`, `delete`, `get`, `has`, and `set`.\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @category Function\n * @param {Function} func The function to have its output memoized.\n * @param {Function} [resolver] The function to resolve the cache key.\n * @returns {Function} Returns the new memoized function.\n * @example\n *\n * var object = { 'a': 1, 'b': 2 };\n * var other = { 'c': 3, 'd': 4 };\n *\n * var values = _.memoize(_.values);\n * values(object);\n * // => [1, 2]\n *\n * values(other);\n * // => [3, 4]\n *\n * object.a = 2;\n * values(object);\n * // => [1, 2]\n *\n * // Modify the result cache.\n * values.cache.set(object, ['a', 'b']);\n * values(object);\n * // => ['a', 'b']\n *\n * // Replace `_.memoize.Cache`.\n * _.memoize.Cache = WeakMap;\n */\nfunction memoize(func, resolver) {\n if (typeof func != 'function' || (resolver != null && typeof resolver != 'function')) {\n throw new TypeError(FUNC_ERROR_TEXT);\n }\n var memoized = function() {\n var args = arguments,\n key = resolver ? resolver.apply(this, args) : args[0],\n cache = memoized.cache;\n\n if (cache.has(key)) {\n return cache.get(key);\n }\n var result = func.apply(this, args);\n memoized.cache = cache.set(key, result) || cache;\n return result;\n };\n memoized.cache = new (memoize.Cache || MapCache);\n return memoized;\n}\n\n// Expose `MapCache`.\nmemoize.Cache = MapCache;\n\nexport default memoize;\n", "import memoize from './memoize.js';\n\n/** Used as the maximum memoize cache size. */\nvar MAX_MEMOIZE_SIZE = 500;\n\n/**\n * A specialized version of `_.memoize` which clears the memoized function's\n * cache when it exceeds `MAX_MEMOIZE_SIZE`.\n *\n * @private\n * @param {Function} func The function to have its output memoized.\n * @returns {Function} Returns the new memoized function.\n */\nfunction memoizeCapped(func) {\n var result = memoize(func, function(key) {\n if (cache.size === MAX_MEMOIZE_SIZE) {\n cache.clear();\n }\n return key;\n });\n\n var cache = result.cache;\n return result;\n}\n\nexport default memoizeCapped;\n", "import memoizeCapped from './_memoizeCapped.js';\n\n/** Used to match property names within property paths. */\nvar rePropName = /[^.[\\]]+|\\[(?:(-?\\d+(?:\\.\\d+)?)|([\"'])((?:(?!\\2)[^\\\\]|\\\\.)*?)\\2)\\]|(?=(?:\\.|\\[\\])(?:\\.|\\[\\]|$))/g;\n\n/** Used to match backslashes in property paths. */\nvar reEscapeChar = /\\\\(\\\\)?/g;\n\n/**\n * Converts `string` to a property path array.\n *\n * @private\n * @param {string} string The string to convert.\n * @returns {Array} Returns the property path array.\n */\nvar stringToPath = memoizeCapped(function(string) {\n var result = [];\n if (string.charCodeAt(0) === 46 /* . */) {\n result.push('');\n }\n string.replace(rePropName, function(match, number, quote, subString) {\n result.push(quote ? subString.replace(reEscapeChar, '$1') : (number || match));\n });\n return result;\n});\n\nexport default stringToPath;\n", "import baseToString from './_baseToString.js';\n\n/**\n * Converts `value` to a string. An empty string is returned for `null`\n * and `undefined` values. The sign of `-0` is preserved.\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Lang\n * @param {*} value The value to convert.\n * @returns {string} Returns the converted string.\n * @example\n *\n * _.toString(null);\n * // => ''\n *\n * _.toString(-0);\n * // => '-0'\n *\n * _.toString([1, 2, 3]);\n * // => '1,2,3'\n */\nfunction toString(value) {\n return value == null ? '' : baseToString(value);\n}\n\nexport default toString;\n", "import isArray from './isArray.js';\nimport isKey from './_isKey.js';\nimport stringToPath from './_stringToPath.js';\nimport toString from './toString.js';\n\n/**\n * Casts `value` to a path array if it's not one.\n *\n * @private\n * @param {*} value The value to inspect.\n * @param {Object} [object] The object to query keys on.\n * @returns {Array} Returns the cast property path array.\n */\nfunction castPath(value, object) {\n if (isArray(value)) {\n return value;\n }\n return isKey(value, object) ? [value] : stringToPath(toString(value));\n}\n\nexport default castPath;\n", "import isSymbol from './isSymbol.js';\n\n/** Used as references for various `Number` constants. */\nvar INFINITY = 1 / 0;\n\n/**\n * Converts `value` to a string key if it's not a string or symbol.\n *\n * @private\n * @param {*} value The value to inspect.\n * @returns {string|symbol} Returns the key.\n */\nfunction toKey(value) {\n if (typeof value == 'string' || isSymbol(value)) {\n return value;\n }\n var result = (value + '');\n return (result == '0' && (1 / value) == -INFINITY) ? '-0' : result;\n}\n\nexport default toKey;\n", "import castPath from './_castPath.js';\nimport toKey from './_toKey.js';\n\n/**\n * The base implementation of `_.get` without support for default values.\n *\n * @private\n * @param {Object} object The object to query.\n * @param {Array|string} path The path of the property to get.\n * @returns {*} Returns the resolved value.\n */\nfunction baseGet(object, path) {\n path = castPath(path, object);\n\n var index = 0,\n length = path.length;\n\n while (object != null && index < length) {\n object = object[toKey(path[index++])];\n }\n return (index && index == length) ? object : undefined;\n}\n\nexport default baseGet;\n", "import baseGet from './_baseGet.js';\n\n/**\n * Gets the value at `path` of `object`. If the resolved value is\n * `undefined`, the `defaultValue` is returned in its place.\n *\n * @static\n * @memberOf _\n * @since 3.7.0\n * @category Object\n * @param {Object} object The object to query.\n * @param {Array|string} path The path of the property to get.\n * @param {*} [defaultValue] The value returned for `undefined` resolved values.\n * @returns {*} Returns the resolved value.\n * @example\n *\n * var object = { 'a': [{ 'b': { 'c': 3 } }] };\n *\n * _.get(object, 'a[0].b.c');\n * // => 3\n *\n * _.get(object, ['a', '0', 'b', 'c']);\n * // => 3\n *\n * _.get(object, 'a.b.c', 'default');\n * // => 'default'\n */\nfunction get(object, path, defaultValue) {\n var result = object == null ? undefined : baseGet(object, path);\n return result === undefined ? defaultValue : result;\n}\n\nexport default get;\n", "/**\n * Appends the elements of `values` to `array`.\n *\n * @private\n * @param {Array} array The array to modify.\n * @param {Array} values The values to append.\n * @returns {Array} Returns `array`.\n */\nfunction arrayPush(array, values) {\n var index = -1,\n length = values.length,\n offset = array.length;\n\n while (++index < length) {\n array[offset + index] = values[index];\n }\n return array;\n}\n\nexport default arrayPush;\n", "import Symbol from './_Symbol.js';\nimport isArguments from './isArguments.js';\nimport isArray from './isArray.js';\n\n/** Built-in value references. */\nvar spreadableSymbol = Symbol ? Symbol.isConcatSpreadable : undefined;\n\n/**\n * Checks if `value` is a flattenable `arguments` object or array.\n *\n * @private\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is flattenable, else `false`.\n */\nfunction isFlattenable(value) {\n return isArray(value) || isArguments(value) ||\n !!(spreadableSymbol && value && value[spreadableSymbol]);\n}\n\nexport default isFlattenable;\n", "import arrayPush from './_arrayPush.js';\nimport isFlattenable from './_isFlattenable.js';\n\n/**\n * The base implementation of `_.flatten` with support for restricting flattening.\n *\n * @private\n * @param {Array} array The array to flatten.\n * @param {number} depth The maximum recursion depth.\n * @param {boolean} [predicate=isFlattenable] The function invoked per iteration.\n * @param {boolean} [isStrict] Restrict to values that pass `predicate` checks.\n * @param {Array} [result=[]] The initial result value.\n * @returns {Array} Returns the new flattened array.\n */\nfunction baseFlatten(array, depth, predicate, isStrict, result) {\n var index = -1,\n length = array.length;\n\n predicate || (predicate = isFlattenable);\n result || (result = []);\n\n while (++index < length) {\n var value = array[index];\n if (depth > 0 && predicate(value)) {\n if (depth > 1) {\n // Recursively flatten arrays (susceptible to call stack limits).\n baseFlatten(value, depth - 1, predicate, isStrict, result);\n } else {\n arrayPush(result, value);\n }\n } else if (!isStrict) {\n result[result.length] = value;\n }\n }\n return result;\n}\n\nexport default baseFlatten;\n", "import baseFlatten from './_baseFlatten.js';\n\n/**\n * Flattens `array` a single level deep.\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @category Array\n * @param {Array} array The array to flatten.\n * @returns {Array} Returns the new flattened array.\n * @example\n *\n * _.flatten([1, [2, [3, [4]], 5]]);\n * // => [1, 2, [3, [4]], 5]\n */\nfunction flatten(array) {\n var length = array == null ? 0 : array.length;\n return length ? baseFlatten(array, 1) : [];\n}\n\nexport default flatten;\n", "import overArg from './_overArg.js';\n\n/** Built-in value references. */\nvar getPrototype = overArg(Object.getPrototypeOf, Object);\n\nexport default getPrototype;\n", "/**\n * The base implementation of `_.slice` without an iteratee call guard.\n *\n * @private\n * @param {Array} array The array to slice.\n * @param {number} [start=0] The start position.\n * @param {number} [end=array.length] The end position.\n * @returns {Array} Returns the slice of `array`.\n */\nfunction baseSlice(array, start, end) {\n var index = -1,\n length = array.length;\n\n if (start < 0) {\n start = -start > length ? 0 : (length + start);\n }\n end = end > length ? length : end;\n if (end < 0) {\n end += length;\n }\n length = start > end ? 0 : ((end - start) >>> 0);\n start >>>= 0;\n\n var result = Array(length);\n while (++index < length) {\n result[index] = array[index + start];\n }\n return result;\n}\n\nexport default baseSlice;\n", "import baseSlice from './_baseSlice.js';\n\n/**\n * Casts `array` to a slice if it's needed.\n *\n * @private\n * @param {Array} array The array to inspect.\n * @param {number} start The start position.\n * @param {number} [end=array.length] The end position.\n * @returns {Array} Returns the cast slice.\n */\nfunction castSlice(array, start, end) {\n var length = array.length;\n end = end === undefined ? length : end;\n return (!start && end >= length) ? array : baseSlice(array, start, end);\n}\n\nexport default castSlice;\n", "/** Used to compose unicode character classes. */\nvar rsAstralRange = '\\\\ud800-\\\\udfff',\n rsComboMarksRange = '\\\\u0300-\\\\u036f',\n reComboHalfMarksRange = '\\\\ufe20-\\\\ufe2f',\n rsComboSymbolsRange = '\\\\u20d0-\\\\u20ff',\n rsComboRange = rsComboMarksRange + reComboHalfMarksRange + rsComboSymbolsRange,\n rsVarRange = '\\\\ufe0e\\\\ufe0f';\n\n/** Used to compose unicode capture groups. */\nvar rsZWJ = '\\\\u200d';\n\n/** Used to detect strings with [zero-width joiners or code points from the astral planes](http://eev.ee/blog/2015/09/12/dark-corners-of-unicode/). */\nvar reHasUnicode = RegExp('[' + rsZWJ + rsAstralRange + rsComboRange + rsVarRange + ']');\n\n/**\n * Checks if `string` contains Unicode symbols.\n *\n * @private\n * @param {string} string The string to inspect.\n * @returns {boolean} Returns `true` if a symbol is found, else `false`.\n */\nfunction hasUnicode(string) {\n return reHasUnicode.test(string);\n}\n\nexport default hasUnicode;\n", "/**\n * Converts an ASCII `string` to an array.\n *\n * @private\n * @param {string} string The string to convert.\n * @returns {Array} Returns the converted array.\n */\nfunction asciiToArray(string) {\n return string.split('');\n}\n\nexport default asciiToArray;\n", "/** Used to compose unicode character classes. */\nvar rsAstralRange = '\\\\ud800-\\\\udfff',\n rsComboMarksRange = '\\\\u0300-\\\\u036f',\n reComboHalfMarksRange = '\\\\ufe20-\\\\ufe2f',\n rsComboSymbolsRange = '\\\\u20d0-\\\\u20ff',\n rsComboRange = rsComboMarksRange + reComboHalfMarksRange + rsComboSymbolsRange,\n rsVarRange = '\\\\ufe0e\\\\ufe0f';\n\n/** Used to compose unicode capture groups. */\nvar rsAstral = '[' + rsAstralRange + ']',\n rsCombo = '[' + rsComboRange + ']',\n rsFitz = '\\\\ud83c[\\\\udffb-\\\\udfff]',\n rsModifier = '(?:' + rsCombo + '|' + rsFitz + ')',\n rsNonAstral = '[^' + rsAstralRange + ']',\n rsRegional = '(?:\\\\ud83c[\\\\udde6-\\\\uddff]){2}',\n rsSurrPair = '[\\\\ud800-\\\\udbff][\\\\udc00-\\\\udfff]',\n rsZWJ = '\\\\u200d';\n\n/** Used to compose unicode regexes. */\nvar reOptMod = rsModifier + '?',\n rsOptVar = '[' + rsVarRange + ']?',\n rsOptJoin = '(?:' + rsZWJ + '(?:' + [rsNonAstral, rsRegional, rsSurrPair].join('|') + ')' + rsOptVar + reOptMod + ')*',\n rsSeq = rsOptVar + reOptMod + rsOptJoin,\n rsSymbol = '(?:' + [rsNonAstral + rsCombo + '?', rsCombo, rsRegional, rsSurrPair, rsAstral].join('|') + ')';\n\n/** Used to match [string symbols](https://mathiasbynens.be/notes/javascript-unicode). */\nvar reUnicode = RegExp(rsFitz + '(?=' + rsFitz + ')|' + rsSymbol + rsSeq, 'g');\n\n/**\n * Converts a Unicode `string` to an array.\n *\n * @private\n * @param {string} string The string to convert.\n * @returns {Array} Returns the converted array.\n */\nfunction unicodeToArray(string) {\n return string.match(reUnicode) || [];\n}\n\nexport default unicodeToArray;\n", "import asciiToArray from './_asciiToArray.js';\nimport hasUnicode from './_hasUnicode.js';\nimport unicodeToArray from './_unicodeToArray.js';\n\n/**\n * Converts `string` to an array.\n *\n * @private\n * @param {string} string The string to convert.\n * @returns {Array} Returns the converted array.\n */\nfunction stringToArray(string) {\n return hasUnicode(string)\n ? unicodeToArray(string)\n : asciiToArray(string);\n}\n\nexport default stringToArray;\n", "import castSlice from './_castSlice.js';\nimport hasUnicode from './_hasUnicode.js';\nimport stringToArray from './_stringToArray.js';\nimport toString from './toString.js';\n\n/**\n * Creates a function like `_.lowerFirst`.\n *\n * @private\n * @param {string} methodName The name of the `String` case method to use.\n * @returns {Function} Returns the new case function.\n */\nfunction createCaseFirst(methodName) {\n return function(string) {\n string = toString(string);\n\n var strSymbols = hasUnicode(string)\n ? stringToArray(string)\n : undefined;\n\n var chr = strSymbols\n ? strSymbols[0]\n : string.charAt(0);\n\n var trailing = strSymbols\n ? castSlice(strSymbols, 1).join('')\n : string.slice(1);\n\n return chr[methodName]() + trailing;\n };\n}\n\nexport default createCaseFirst;\n", "import createCaseFirst from './_createCaseFirst.js';\n\n/**\n * Converts the first character of `string` to upper case.\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category String\n * @param {string} [string=''] The string to convert.\n * @returns {string} Returns the converted string.\n * @example\n *\n * _.upperFirst('fred');\n * // => 'Fred'\n *\n * _.upperFirst('FRED');\n * // => 'FRED'\n */\nvar upperFirst = createCaseFirst('toUpperCase');\n\nexport default upperFirst;\n", "/**\n * A specialized version of `_.reduce` for arrays without support for\n * iteratee shorthands.\n *\n * @private\n * @param {Array} [array] The array to iterate over.\n * @param {Function} iteratee The function invoked per iteration.\n * @param {*} [accumulator] The initial value.\n * @param {boolean} [initAccum] Specify using the first element of `array` as\n * the initial value.\n * @returns {*} Returns the accumulated value.\n */\nfunction arrayReduce(array, iteratee, accumulator, initAccum) {\n var index = -1,\n length = array == null ? 0 : array.length;\n\n if (initAccum && length) {\n accumulator = array[++index];\n }\n while (++index < length) {\n accumulator = iteratee(accumulator, array[index], index, array);\n }\n return accumulator;\n}\n\nexport default arrayReduce;\n", "import ListCache from './_ListCache.js';\n\n/**\n * Removes all key-value entries from the stack.\n *\n * @private\n * @name clear\n * @memberOf Stack\n */\nfunction stackClear() {\n this.__data__ = new ListCache;\n this.size = 0;\n}\n\nexport default stackClear;\n", "/**\n * Removes `key` and its value from the stack.\n *\n * @private\n * @name delete\n * @memberOf Stack\n * @param {string} key The key of the value to remove.\n * @returns {boolean} Returns `true` if the entry was removed, else `false`.\n */\nfunction stackDelete(key) {\n var data = this.__data__,\n result = data['delete'](key);\n\n this.size = data.size;\n return result;\n}\n\nexport default stackDelete;\n", "/**\n * Gets the stack value for `key`.\n *\n * @private\n * @name get\n * @memberOf Stack\n * @param {string} key The key of the value to get.\n * @returns {*} Returns the entry value.\n */\nfunction stackGet(key) {\n return this.__data__.get(key);\n}\n\nexport default stackGet;\n", "/**\n * Checks if a stack value for `key` exists.\n *\n * @private\n * @name has\n * @memberOf Stack\n * @param {string} key The key of the entry to check.\n * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.\n */\nfunction stackHas(key) {\n return this.__data__.has(key);\n}\n\nexport default stackHas;\n", "import ListCache from './_ListCache.js';\nimport Map from './_Map.js';\nimport MapCache from './_MapCache.js';\n\n/** Used as the size to enable large array optimizations. */\nvar LARGE_ARRAY_SIZE = 200;\n\n/**\n * Sets the stack `key` to `value`.\n *\n * @private\n * @name set\n * @memberOf Stack\n * @param {string} key The key of the value to set.\n * @param {*} value The value to set.\n * @returns {Object} Returns the stack cache instance.\n */\nfunction stackSet(key, value) {\n var data = this.__data__;\n if (data instanceof ListCache) {\n var pairs = data.__data__;\n if (!Map || (pairs.length < LARGE_ARRAY_SIZE - 1)) {\n pairs.push([key, value]);\n this.size = ++data.size;\n return this;\n }\n data = this.__data__ = new MapCache(pairs);\n }\n data.set(key, value);\n this.size = data.size;\n return this;\n}\n\nexport default stackSet;\n", "import ListCache from './_ListCache.js';\nimport stackClear from './_stackClear.js';\nimport stackDelete from './_stackDelete.js';\nimport stackGet from './_stackGet.js';\nimport stackHas from './_stackHas.js';\nimport stackSet from './_stackSet.js';\n\n/**\n * Creates a stack cache object to store key-value pairs.\n *\n * @private\n * @constructor\n * @param {Array} [entries] The key-value pairs to cache.\n */\nfunction Stack(entries) {\n var data = this.__data__ = new ListCache(entries);\n this.size = data.size;\n}\n\n// Add methods to `Stack`.\nStack.prototype.clear = stackClear;\nStack.prototype['delete'] = stackDelete;\nStack.prototype.get = stackGet;\nStack.prototype.has = stackHas;\nStack.prototype.set = stackSet;\n\nexport default Stack;\n", "import copyObject from './_copyObject.js';\nimport keys from './keys.js';\n\n/**\n * The base implementation of `_.assign` without support for multiple sources\n * or `customizer` functions.\n *\n * @private\n * @param {Object} object The destination object.\n * @param {Object} source The source object.\n * @returns {Object} Returns `object`.\n */\nfunction baseAssign(object, source) {\n return object && copyObject(source, keys(source), object);\n}\n\nexport default baseAssign;\n", "import copyObject from './_copyObject.js';\nimport keysIn from './keysIn.js';\n\n/**\n * The base implementation of `_.assignIn` without support for multiple sources\n * or `customizer` functions.\n *\n * @private\n * @param {Object} object The destination object.\n * @param {Object} source The source object.\n * @returns {Object} Returns `object`.\n */\nfunction baseAssignIn(object, source) {\n return object && copyObject(source, keysIn(source), object);\n}\n\nexport default baseAssignIn;\n", "import root from './_root.js';\n\n/** Detect free variable `exports`. */\nvar freeExports = typeof exports == 'object' && exports && !exports.nodeType && exports;\n\n/** Detect free variable `module`. */\nvar freeModule = freeExports && typeof module == 'object' && module && !module.nodeType && module;\n\n/** Detect the popular CommonJS extension `module.exports`. */\nvar moduleExports = freeModule && freeModule.exports === freeExports;\n\n/** Built-in value references. */\nvar Buffer = moduleExports ? root.Buffer : undefined,\n allocUnsafe = Buffer ? Buffer.allocUnsafe : undefined;\n\n/**\n * Creates a clone of `buffer`.\n *\n * @private\n * @param {Buffer} buffer The buffer to clone.\n * @param {boolean} [isDeep] Specify a deep clone.\n * @returns {Buffer} Returns the cloned buffer.\n */\nfunction cloneBuffer(buffer, isDeep) {\n if (isDeep) {\n return buffer.slice();\n }\n var length = buffer.length,\n result = allocUnsafe ? allocUnsafe(length) : new buffer.constructor(length);\n\n buffer.copy(result);\n return result;\n}\n\nexport default cloneBuffer;\n", "/**\n * A specialized version of `_.filter` for arrays without support for\n * iteratee shorthands.\n *\n * @private\n * @param {Array} [array] The array to iterate over.\n * @param {Function} predicate The function invoked per iteration.\n * @returns {Array} Returns the new filtered array.\n */\nfunction arrayFilter(array, predicate) {\n var index = -1,\n length = array == null ? 0 : array.length,\n resIndex = 0,\n result = [];\n\n while (++index < length) {\n var value = array[index];\n if (predicate(value, index, array)) {\n result[resIndex++] = value;\n }\n }\n return result;\n}\n\nexport default arrayFilter;\n", "/**\n * This method returns a new empty array.\n *\n * @static\n * @memberOf _\n * @since 4.13.0\n * @category Util\n * @returns {Array} Returns the new empty array.\n * @example\n *\n * var arrays = _.times(2, _.stubArray);\n *\n * console.log(arrays);\n * // => [[], []]\n *\n * console.log(arrays[0] === arrays[1]);\n * // => false\n */\nfunction stubArray() {\n return [];\n}\n\nexport default stubArray;\n", "import arrayFilter from './_arrayFilter.js';\nimport stubArray from './stubArray.js';\n\n/** Used for built-in method references. */\nvar objectProto = Object.prototype;\n\n/** Built-in value references. */\nvar propertyIsEnumerable = objectProto.propertyIsEnumerable;\n\n/* Built-in method references for those with the same name as other `lodash` methods. */\nvar nativeGetSymbols = Object.getOwnPropertySymbols;\n\n/**\n * Creates an array of the own enumerable symbols of `object`.\n *\n * @private\n * @param {Object} object The object to query.\n * @returns {Array} Returns the array of symbols.\n */\nvar getSymbols = !nativeGetSymbols ? stubArray : function(object) {\n if (object == null) {\n return [];\n }\n object = Object(object);\n return arrayFilter(nativeGetSymbols(object), function(symbol) {\n return propertyIsEnumerable.call(object, symbol);\n });\n};\n\nexport default getSymbols;\n", "import copyObject from './_copyObject.js';\nimport getSymbols from './_getSymbols.js';\n\n/**\n * Copies own symbols of `source` to `object`.\n *\n * @private\n * @param {Object} source The object to copy symbols from.\n * @param {Object} [object={}] The object to copy symbols to.\n * @returns {Object} Returns `object`.\n */\nfunction copySymbols(source, object) {\n return copyObject(source, getSymbols(source), object);\n}\n\nexport default copySymbols;\n", "import arrayPush from './_arrayPush.js';\nimport getPrototype from './_getPrototype.js';\nimport getSymbols from './_getSymbols.js';\nimport stubArray from './stubArray.js';\n\n/* Built-in method references for those with the same name as other `lodash` methods. */\nvar nativeGetSymbols = Object.getOwnPropertySymbols;\n\n/**\n * Creates an array of the own and inherited enumerable symbols of `object`.\n *\n * @private\n * @param {Object} object The object to query.\n * @returns {Array} Returns the array of symbols.\n */\nvar getSymbolsIn = !nativeGetSymbols ? stubArray : function(object) {\n var result = [];\n while (object) {\n arrayPush(result, getSymbols(object));\n object = getPrototype(object);\n }\n return result;\n};\n\nexport default getSymbolsIn;\n", "import copyObject from './_copyObject.js';\nimport getSymbolsIn from './_getSymbolsIn.js';\n\n/**\n * Copies own and inherited symbols of `source` to `object`.\n *\n * @private\n * @param {Object} source The object to copy symbols from.\n * @param {Object} [object={}] The object to copy symbols to.\n * @returns {Object} Returns `object`.\n */\nfunction copySymbolsIn(source, object) {\n return copyObject(source, getSymbolsIn(source), object);\n}\n\nexport default copySymbolsIn;\n", "import arrayPush from './_arrayPush.js';\nimport isArray from './isArray.js';\n\n/**\n * The base implementation of `getAllKeys` and `getAllKeysIn` which uses\n * `keysFunc` and `symbolsFunc` to get the enumerable property names and\n * symbols of `object`.\n *\n * @private\n * @param {Object} object The object to query.\n * @param {Function} keysFunc The function to get the keys of `object`.\n * @param {Function} symbolsFunc The function to get the symbols of `object`.\n * @returns {Array} Returns the array of property names and symbols.\n */\nfunction baseGetAllKeys(object, keysFunc, symbolsFunc) {\n var result = keysFunc(object);\n return isArray(object) ? result : arrayPush(result, symbolsFunc(object));\n}\n\nexport default baseGetAllKeys;\n", "import baseGetAllKeys from './_baseGetAllKeys.js';\nimport getSymbols from './_getSymbols.js';\nimport keys from './keys.js';\n\n/**\n * Creates an array of own enumerable property names and symbols of `object`.\n *\n * @private\n * @param {Object} object The object to query.\n * @returns {Array} Returns the array of property names and symbols.\n */\nfunction getAllKeys(object) {\n return baseGetAllKeys(object, keys, getSymbols);\n}\n\nexport default getAllKeys;\n", "import baseGetAllKeys from './_baseGetAllKeys.js';\nimport getSymbolsIn from './_getSymbolsIn.js';\nimport keysIn from './keysIn.js';\n\n/**\n * Creates an array of own and inherited enumerable property names and\n * symbols of `object`.\n *\n * @private\n * @param {Object} object The object to query.\n * @returns {Array} Returns the array of property names and symbols.\n */\nfunction getAllKeysIn(object) {\n return baseGetAllKeys(object, keysIn, getSymbolsIn);\n}\n\nexport default getAllKeysIn;\n", "import getNative from './_getNative.js';\nimport root from './_root.js';\n\n/* Built-in method references that are verified to be native. */\nvar DataView = getNative(root, 'DataView');\n\nexport default DataView;\n", "import getNative from './_getNative.js';\nimport root from './_root.js';\n\n/* Built-in method references that are verified to be native. */\nvar Promise = getNative(root, 'Promise');\n\nexport default Promise;\n", "import getNative from './_getNative.js';\nimport root from './_root.js';\n\n/* Built-in method references that are verified to be native. */\nvar Set = getNative(root, 'Set');\n\nexport default Set;\n", "import DataView from './_DataView.js';\nimport Map from './_Map.js';\nimport Promise from './_Promise.js';\nimport Set from './_Set.js';\nimport WeakMap from './_WeakMap.js';\nimport baseGetTag from './_baseGetTag.js';\nimport toSource from './_toSource.js';\n\n/** `Object#toString` result references. */\nvar mapTag = '[object Map]',\n objectTag = '[object Object]',\n promiseTag = '[object Promise]',\n setTag = '[object Set]',\n weakMapTag = '[object WeakMap]';\n\nvar dataViewTag = '[object DataView]';\n\n/** Used to detect maps, sets, and weakmaps. */\nvar dataViewCtorString = toSource(DataView),\n mapCtorString = toSource(Map),\n promiseCtorString = toSource(Promise),\n setCtorString = toSource(Set),\n weakMapCtorString = toSource(WeakMap);\n\n/**\n * Gets the `toStringTag` of `value`.\n *\n * @private\n * @param {*} value The value to query.\n * @returns {string} Returns the `toStringTag`.\n */\nvar getTag = baseGetTag;\n\n// Fallback for data views, maps, sets, and weak maps in IE 11 and promises in Node.js < 6.\nif ((DataView && getTag(new DataView(new ArrayBuffer(1))) != dataViewTag) ||\n (Map && getTag(new Map) != mapTag) ||\n (Promise && getTag(Promise.resolve()) != promiseTag) ||\n (Set && getTag(new Set) != setTag) ||\n (WeakMap && getTag(new WeakMap) != weakMapTag)) {\n getTag = function(value) {\n var result = baseGetTag(value),\n Ctor = result == objectTag ? value.constructor : undefined,\n ctorString = Ctor ? toSource(Ctor) : '';\n\n if (ctorString) {\n switch (ctorString) {\n case dataViewCtorString: return dataViewTag;\n case mapCtorString: return mapTag;\n case promiseCtorString: return promiseTag;\n case setCtorString: return setTag;\n case weakMapCtorString: return weakMapTag;\n }\n }\n return result;\n };\n}\n\nexport default getTag;\n", "/** Used for built-in method references. */\nvar objectProto = Object.prototype;\n\n/** Used to check objects for own properties. */\nvar hasOwnProperty = objectProto.hasOwnProperty;\n\n/**\n * Initializes an array clone.\n *\n * @private\n * @param {Array} array The array to clone.\n * @returns {Array} Returns the initialized clone.\n */\nfunction initCloneArray(array) {\n var length = array.length,\n result = new array.constructor(length);\n\n // Add properties assigned by `RegExp#exec`.\n if (length && typeof array[0] == 'string' && hasOwnProperty.call(array, 'index')) {\n result.index = array.index;\n result.input = array.input;\n }\n return result;\n}\n\nexport default initCloneArray;\n", "import root from './_root.js';\n\n/** Built-in value references. */\nvar Uint8Array = root.Uint8Array;\n\nexport default Uint8Array;\n", "import Uint8Array from './_Uint8Array.js';\n\n/**\n * Creates a clone of `arrayBuffer`.\n *\n * @private\n * @param {ArrayBuffer} arrayBuffer The array buffer to clone.\n * @returns {ArrayBuffer} Returns the cloned array buffer.\n */\nfunction cloneArrayBuffer(arrayBuffer) {\n var result = new arrayBuffer.constructor(arrayBuffer.byteLength);\n new Uint8Array(result).set(new Uint8Array(arrayBuffer));\n return result;\n}\n\nexport default cloneArrayBuffer;\n", "import cloneArrayBuffer from './_cloneArrayBuffer.js';\n\n/**\n * Creates a clone of `dataView`.\n *\n * @private\n * @param {Object} dataView The data view to clone.\n * @param {boolean} [isDeep] Specify a deep clone.\n * @returns {Object} Returns the cloned data view.\n */\nfunction cloneDataView(dataView, isDeep) {\n var buffer = isDeep ? cloneArrayBuffer(dataView.buffer) : dataView.buffer;\n return new dataView.constructor(buffer, dataView.byteOffset, dataView.byteLength);\n}\n\nexport default cloneDataView;\n", "/** Used to match `RegExp` flags from their coerced string values. */\nvar reFlags = /\\w*$/;\n\n/**\n * Creates a clone of `regexp`.\n *\n * @private\n * @param {Object} regexp The regexp to clone.\n * @returns {Object} Returns the cloned regexp.\n */\nfunction cloneRegExp(regexp) {\n var result = new regexp.constructor(regexp.source, reFlags.exec(regexp));\n result.lastIndex = regexp.lastIndex;\n return result;\n}\n\nexport default cloneRegExp;\n", "import Symbol from './_Symbol.js';\n\n/** Used to convert symbols to primitives and strings. */\nvar symbolProto = Symbol ? Symbol.prototype : undefined,\n symbolValueOf = symbolProto ? symbolProto.valueOf : undefined;\n\n/**\n * Creates a clone of the `symbol` object.\n *\n * @private\n * @param {Object} symbol The symbol object to clone.\n * @returns {Object} Returns the cloned symbol object.\n */\nfunction cloneSymbol(symbol) {\n return symbolValueOf ? Object(symbolValueOf.call(symbol)) : {};\n}\n\nexport default cloneSymbol;\n", "import cloneArrayBuffer from './_cloneArrayBuffer.js';\n\n/**\n * Creates a clone of `typedArray`.\n *\n * @private\n * @param {Object} typedArray The typed array to clone.\n * @param {boolean} [isDeep] Specify a deep clone.\n * @returns {Object} Returns the cloned typed array.\n */\nfunction cloneTypedArray(typedArray, isDeep) {\n var buffer = isDeep ? cloneArrayBuffer(typedArray.buffer) : typedArray.buffer;\n return new typedArray.constructor(buffer, typedArray.byteOffset, typedArray.length);\n}\n\nexport default cloneTypedArray;\n", "import cloneArrayBuffer from './_cloneArrayBuffer.js';\nimport cloneDataView from './_cloneDataView.js';\nimport cloneRegExp from './_cloneRegExp.js';\nimport cloneSymbol from './_cloneSymbol.js';\nimport cloneTypedArray from './_cloneTypedArray.js';\n\n/** `Object#toString` result references. */\nvar boolTag = '[object Boolean]',\n dateTag = '[object Date]',\n mapTag = '[object Map]',\n numberTag = '[object Number]',\n regexpTag = '[object RegExp]',\n setTag = '[object Set]',\n stringTag = '[object String]',\n symbolTag = '[object Symbol]';\n\nvar arrayBufferTag = '[object ArrayBuffer]',\n dataViewTag = '[object DataView]',\n float32Tag = '[object Float32Array]',\n float64Tag = '[object Float64Array]',\n int8Tag = '[object Int8Array]',\n int16Tag = '[object Int16Array]',\n int32Tag = '[object Int32Array]',\n uint8Tag = '[object Uint8Array]',\n uint8ClampedTag = '[object Uint8ClampedArray]',\n uint16Tag = '[object Uint16Array]',\n uint32Tag = '[object Uint32Array]';\n\n/**\n * Initializes an object clone based on its `toStringTag`.\n *\n * **Note:** This function only supports cloning values with tags of\n * `Boolean`, `Date`, `Error`, `Map`, `Number`, `RegExp`, `Set`, or `String`.\n *\n * @private\n * @param {Object} object The object to clone.\n * @param {string} tag The `toStringTag` of the object to clone.\n * @param {boolean} [isDeep] Specify a deep clone.\n * @returns {Object} Returns the initialized clone.\n */\nfunction initCloneByTag(object, tag, isDeep) {\n var Ctor = object.constructor;\n switch (tag) {\n case arrayBufferTag:\n return cloneArrayBuffer(object);\n\n case boolTag:\n case dateTag:\n return new Ctor(+object);\n\n case dataViewTag:\n return cloneDataView(object, isDeep);\n\n case float32Tag: case float64Tag:\n case int8Tag: case int16Tag: case int32Tag:\n case uint8Tag: case uint8ClampedTag: case uint16Tag: case uint32Tag:\n return cloneTypedArray(object, isDeep);\n\n case mapTag:\n return new Ctor;\n\n case numberTag:\n case stringTag:\n return new Ctor(object);\n\n case regexpTag:\n return cloneRegExp(object);\n\n case setTag:\n return new Ctor;\n\n case symbolTag:\n return cloneSymbol(object);\n }\n}\n\nexport default initCloneByTag;\n", "import baseCreate from './_baseCreate.js';\nimport getPrototype from './_getPrototype.js';\nimport isPrototype from './_isPrototype.js';\n\n/**\n * Initializes an object clone.\n *\n * @private\n * @param {Object} object The object to clone.\n * @returns {Object} Returns the initialized clone.\n */\nfunction initCloneObject(object) {\n return (typeof object.constructor == 'function' && !isPrototype(object))\n ? baseCreate(getPrototype(object))\n : {};\n}\n\nexport default initCloneObject;\n", "import getTag from './_getTag.js';\nimport isObjectLike from './isObjectLike.js';\n\n/** `Object#toString` result references. */\nvar mapTag = '[object Map]';\n\n/**\n * The base implementation of `_.isMap` without Node.js optimizations.\n *\n * @private\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is a map, else `false`.\n */\nfunction baseIsMap(value) {\n return isObjectLike(value) && getTag(value) == mapTag;\n}\n\nexport default baseIsMap;\n", "import baseIsMap from './_baseIsMap.js';\nimport baseUnary from './_baseUnary.js';\nimport nodeUtil from './_nodeUtil.js';\n\n/* Node.js helper references. */\nvar nodeIsMap = nodeUtil && nodeUtil.isMap;\n\n/**\n * Checks if `value` is classified as a `Map` object.\n *\n * @static\n * @memberOf _\n * @since 4.3.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is a map, else `false`.\n * @example\n *\n * _.isMap(new Map);\n * // => true\n *\n * _.isMap(new WeakMap);\n * // => false\n */\nvar isMap = nodeIsMap ? baseUnary(nodeIsMap) : baseIsMap;\n\nexport default isMap;\n", "import getTag from './_getTag.js';\nimport isObjectLike from './isObjectLike.js';\n\n/** `Object#toString` result references. */\nvar setTag = '[object Set]';\n\n/**\n * The base implementation of `_.isSet` without Node.js optimizations.\n *\n * @private\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is a set, else `false`.\n */\nfunction baseIsSet(value) {\n return isObjectLike(value) && getTag(value) == setTag;\n}\n\nexport default baseIsSet;\n", "import baseIsSet from './_baseIsSet.js';\nimport baseUnary from './_baseUnary.js';\nimport nodeUtil from './_nodeUtil.js';\n\n/* Node.js helper references. */\nvar nodeIsSet = nodeUtil && nodeUtil.isSet;\n\n/**\n * Checks if `value` is classified as a `Set` object.\n *\n * @static\n * @memberOf _\n * @since 4.3.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is a set, else `false`.\n * @example\n *\n * _.isSet(new Set);\n * // => true\n *\n * _.isSet(new WeakSet);\n * // => false\n */\nvar isSet = nodeIsSet ? baseUnary(nodeIsSet) : baseIsSet;\n\nexport default isSet;\n", "import Stack from './_Stack.js';\nimport arrayEach from './_arrayEach.js';\nimport assignValue from './_assignValue.js';\nimport baseAssign from './_baseAssign.js';\nimport baseAssignIn from './_baseAssignIn.js';\nimport cloneBuffer from './_cloneBuffer.js';\nimport copyArray from './_copyArray.js';\nimport copySymbols from './_copySymbols.js';\nimport copySymbolsIn from './_copySymbolsIn.js';\nimport getAllKeys from './_getAllKeys.js';\nimport getAllKeysIn from './_getAllKeysIn.js';\nimport getTag from './_getTag.js';\nimport initCloneArray from './_initCloneArray.js';\nimport initCloneByTag from './_initCloneByTag.js';\nimport initCloneObject from './_initCloneObject.js';\nimport isArray from './isArray.js';\nimport isBuffer from './isBuffer.js';\nimport isMap from './isMap.js';\nimport isObject from './isObject.js';\nimport isSet from './isSet.js';\nimport keys from './keys.js';\nimport keysIn from './keysIn.js';\n\n/** Used to compose bitmasks for cloning. */\nvar CLONE_DEEP_FLAG = 1,\n CLONE_FLAT_FLAG = 2,\n CLONE_SYMBOLS_FLAG = 4;\n\n/** `Object#toString` result references. */\nvar argsTag = '[object Arguments]',\n arrayTag = '[object Array]',\n boolTag = '[object Boolean]',\n dateTag = '[object Date]',\n errorTag = '[object Error]',\n funcTag = '[object Function]',\n genTag = '[object GeneratorFunction]',\n mapTag = '[object Map]',\n numberTag = '[object Number]',\n objectTag = '[object Object]',\n regexpTag = '[object RegExp]',\n setTag = '[object Set]',\n stringTag = '[object String]',\n symbolTag = '[object Symbol]',\n weakMapTag = '[object WeakMap]';\n\nvar arrayBufferTag = '[object ArrayBuffer]',\n dataViewTag = '[object DataView]',\n float32Tag = '[object Float32Array]',\n float64Tag = '[object Float64Array]',\n int8Tag = '[object Int8Array]',\n int16Tag = '[object Int16Array]',\n int32Tag = '[object Int32Array]',\n uint8Tag = '[object Uint8Array]',\n uint8ClampedTag = '[object Uint8ClampedArray]',\n uint16Tag = '[object Uint16Array]',\n uint32Tag = '[object Uint32Array]';\n\n/** Used to identify `toStringTag` values supported by `_.clone`. */\nvar cloneableTags = {};\ncloneableTags[argsTag] = cloneableTags[arrayTag] =\ncloneableTags[arrayBufferTag] = cloneableTags[dataViewTag] =\ncloneableTags[boolTag] = cloneableTags[dateTag] =\ncloneableTags[float32Tag] = cloneableTags[float64Tag] =\ncloneableTags[int8Tag] = cloneableTags[int16Tag] =\ncloneableTags[int32Tag] = cloneableTags[mapTag] =\ncloneableTags[numberTag] = cloneableTags[objectTag] =\ncloneableTags[regexpTag] = cloneableTags[setTag] =\ncloneableTags[stringTag] = cloneableTags[symbolTag] =\ncloneableTags[uint8Tag] = cloneableTags[uint8ClampedTag] =\ncloneableTags[uint16Tag] = cloneableTags[uint32Tag] = true;\ncloneableTags[errorTag] = cloneableTags[funcTag] =\ncloneableTags[weakMapTag] = false;\n\n/**\n * The base implementation of `_.clone` and `_.cloneDeep` which tracks\n * traversed objects.\n *\n * @private\n * @param {*} value The value to clone.\n * @param {boolean} bitmask The bitmask flags.\n * 1 - Deep clone\n * 2 - Flatten inherited properties\n * 4 - Clone symbols\n * @param {Function} [customizer] The function to customize cloning.\n * @param {string} [key] The key of `value`.\n * @param {Object} [object] The parent object of `value`.\n * @param {Object} [stack] Tracks traversed objects and their clone counterparts.\n * @returns {*} Returns the cloned value.\n */\nfunction baseClone(value, bitmask, customizer, key, object, stack) {\n var result,\n isDeep = bitmask & CLONE_DEEP_FLAG,\n isFlat = bitmask & CLONE_FLAT_FLAG,\n isFull = bitmask & CLONE_SYMBOLS_FLAG;\n\n if (customizer) {\n result = object ? customizer(value, key, object, stack) : customizer(value);\n }\n if (result !== undefined) {\n return result;\n }\n if (!isObject(value)) {\n return value;\n }\n var isArr = isArray(value);\n if (isArr) {\n result = initCloneArray(value);\n if (!isDeep) {\n return copyArray(value, result);\n }\n } else {\n var tag = getTag(value),\n isFunc = tag == funcTag || tag == genTag;\n\n if (isBuffer(value)) {\n return cloneBuffer(value, isDeep);\n }\n if (tag == objectTag || tag == argsTag || (isFunc && !object)) {\n result = (isFlat || isFunc) ? {} : initCloneObject(value);\n if (!isDeep) {\n return isFlat\n ? copySymbolsIn(value, baseAssignIn(result, value))\n : copySymbols(value, baseAssign(result, value));\n }\n } else {\n if (!cloneableTags[tag]) {\n return object ? value : {};\n }\n result = initCloneByTag(value, tag, isDeep);\n }\n }\n // Check for circular references and return its corresponding clone.\n stack || (stack = new Stack);\n var stacked = stack.get(value);\n if (stacked) {\n return stacked;\n }\n stack.set(value, result);\n\n if (isSet(value)) {\n value.forEach(function(subValue) {\n result.add(baseClone(subValue, bitmask, customizer, subValue, value, stack));\n });\n } else if (isMap(value)) {\n value.forEach(function(subValue, key) {\n result.set(key, baseClone(subValue, bitmask, customizer, key, value, stack));\n });\n }\n\n var keysFunc = isFull\n ? (isFlat ? getAllKeysIn : getAllKeys)\n : (isFlat ? keysIn : keys);\n\n var props = isArr ? undefined : keysFunc(value);\n arrayEach(props || value, function(subValue, key) {\n if (props) {\n key = subValue;\n subValue = value[key];\n }\n // Recursively populate clone (susceptible to call stack limits).\n assignValue(result, key, baseClone(subValue, bitmask, customizer, key, value, stack));\n });\n return result;\n}\n\nexport default baseClone;\n", "import baseClone from './_baseClone.js';\n\n/** Used to compose bitmasks for cloning. */\nvar CLONE_SYMBOLS_FLAG = 4;\n\n/**\n * Creates a shallow clone of `value`.\n *\n * **Note:** This method is loosely based on the\n * [structured clone algorithm](https://mdn.io/Structured_clone_algorithm)\n * and supports cloning arrays, array buffers, booleans, date objects, maps,\n * numbers, `Object` objects, regexes, sets, strings, symbols, and typed\n * arrays. The own enumerable properties of `arguments` objects are cloned\n * as plain objects. An empty object is returned for uncloneable values such\n * as error objects, functions, DOM nodes, and WeakMaps.\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @category Lang\n * @param {*} value The value to clone.\n * @returns {*} Returns the cloned value.\n * @see _.cloneDeep\n * @example\n *\n * var objects = [{ 'a': 1 }, { 'b': 2 }];\n *\n * var shallow = _.clone(objects);\n * console.log(shallow[0] === objects[0]);\n * // => true\n */\nfunction clone(value) {\n return baseClone(value, CLONE_SYMBOLS_FLAG);\n}\n\nexport default clone;\n", "/**\n * Creates an array with all falsey values removed. The values `false`, `null`,\n * `0`, `-0`, `0n`, `\"\"`, `undefined`, and `NaN` are falsy.\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @category Array\n * @param {Array} array The array to compact.\n * @returns {Array} Returns the new array of filtered values.\n * @example\n *\n * _.compact([0, 1, false, 2, '', 3]);\n * // => [1, 2, 3]\n */\nfunction compact(array) {\n var index = -1,\n length = array == null ? 0 : array.length,\n resIndex = 0,\n result = [];\n\n while (++index < length) {\n var value = array[index];\n if (value) {\n result[resIndex++] = value;\n }\n }\n return result;\n}\n\nexport default compact;\n", "/** Used to stand-in for `undefined` hash values. */\nvar HASH_UNDEFINED = '__lodash_hash_undefined__';\n\n/**\n * Adds `value` to the array cache.\n *\n * @private\n * @name add\n * @memberOf SetCache\n * @alias push\n * @param {*} value The value to cache.\n * @returns {Object} Returns the cache instance.\n */\nfunction setCacheAdd(value) {\n this.__data__.set(value, HASH_UNDEFINED);\n return this;\n}\n\nexport default setCacheAdd;\n", "/**\n * Checks if `value` is in the array cache.\n *\n * @private\n * @name has\n * @memberOf SetCache\n * @param {*} value The value to search for.\n * @returns {boolean} Returns `true` if `value` is found, else `false`.\n */\nfunction setCacheHas(value) {\n return this.__data__.has(value);\n}\n\nexport default setCacheHas;\n", "import MapCache from './_MapCache.js';\nimport setCacheAdd from './_setCacheAdd.js';\nimport setCacheHas from './_setCacheHas.js';\n\n/**\n *\n * Creates an array cache object to store unique values.\n *\n * @private\n * @constructor\n * @param {Array} [values] The values to cache.\n */\nfunction SetCache(values) {\n var index = -1,\n length = values == null ? 0 : values.length;\n\n this.__data__ = new MapCache;\n while (++index < length) {\n this.add(values[index]);\n }\n}\n\n// Add methods to `SetCache`.\nSetCache.prototype.add = SetCache.prototype.push = setCacheAdd;\nSetCache.prototype.has = setCacheHas;\n\nexport default SetCache;\n", "/**\n * A specialized version of `_.some` for arrays without support for iteratee\n * shorthands.\n *\n * @private\n * @param {Array} [array] The array to iterate over.\n * @param {Function} predicate The function invoked per iteration.\n * @returns {boolean} Returns `true` if any element passes the predicate check,\n * else `false`.\n */\nfunction arraySome(array, predicate) {\n var index = -1,\n length = array == null ? 0 : array.length;\n\n while (++index < length) {\n if (predicate(array[index], index, array)) {\n return true;\n }\n }\n return false;\n}\n\nexport default arraySome;\n", "/**\n * Checks if a `cache` value for `key` exists.\n *\n * @private\n * @param {Object} cache The cache to query.\n * @param {string} key The key of the entry to check.\n * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.\n */\nfunction cacheHas(cache, key) {\n return cache.has(key);\n}\n\nexport default cacheHas;\n", "import SetCache from './_SetCache.js';\nimport arraySome from './_arraySome.js';\nimport cacheHas from './_cacheHas.js';\n\n/** Used to compose bitmasks for value comparisons. */\nvar COMPARE_PARTIAL_FLAG = 1,\n COMPARE_UNORDERED_FLAG = 2;\n\n/**\n * A specialized version of `baseIsEqualDeep` for arrays with support for\n * partial deep comparisons.\n *\n * @private\n * @param {Array} array The array to compare.\n * @param {Array} other The other array to compare.\n * @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details.\n * @param {Function} customizer The function to customize comparisons.\n * @param {Function} equalFunc The function to determine equivalents of values.\n * @param {Object} stack Tracks traversed `array` and `other` objects.\n * @returns {boolean} Returns `true` if the arrays are equivalent, else `false`.\n */\nfunction equalArrays(array, other, bitmask, customizer, equalFunc, stack) {\n var isPartial = bitmask & COMPARE_PARTIAL_FLAG,\n arrLength = array.length,\n othLength = other.length;\n\n if (arrLength != othLength && !(isPartial && othLength > arrLength)) {\n return false;\n }\n // Check that cyclic values are equal.\n var arrStacked = stack.get(array);\n var othStacked = stack.get(other);\n if (arrStacked && othStacked) {\n return arrStacked == other && othStacked == array;\n }\n var index = -1,\n result = true,\n seen = (bitmask & COMPARE_UNORDERED_FLAG) ? new SetCache : undefined;\n\n stack.set(array, other);\n stack.set(other, array);\n\n // Ignore non-index properties.\n while (++index < arrLength) {\n var arrValue = array[index],\n othValue = other[index];\n\n if (customizer) {\n var compared = isPartial\n ? customizer(othValue, arrValue, index, other, array, stack)\n : customizer(arrValue, othValue, index, array, other, stack);\n }\n if (compared !== undefined) {\n if (compared) {\n continue;\n }\n result = false;\n break;\n }\n // Recursively compare arrays (susceptible to call stack limits).\n if (seen) {\n if (!arraySome(other, function(othValue, othIndex) {\n if (!cacheHas(seen, othIndex) &&\n (arrValue === othValue || equalFunc(arrValue, othValue, bitmask, customizer, stack))) {\n return seen.push(othIndex);\n }\n })) {\n result = false;\n break;\n }\n } else if (!(\n arrValue === othValue ||\n equalFunc(arrValue, othValue, bitmask, customizer, stack)\n )) {\n result = false;\n break;\n }\n }\n stack['delete'](array);\n stack['delete'](other);\n return result;\n}\n\nexport default equalArrays;\n", "/**\n * Converts `map` to its key-value pairs.\n *\n * @private\n * @param {Object} map The map to convert.\n * @returns {Array} Returns the key-value pairs.\n */\nfunction mapToArray(map) {\n var index = -1,\n result = Array(map.size);\n\n map.forEach(function(value, key) {\n result[++index] = [key, value];\n });\n return result;\n}\n\nexport default mapToArray;\n", "/**\n * Converts `set` to an array of its values.\n *\n * @private\n * @param {Object} set The set to convert.\n * @returns {Array} Returns the values.\n */\nfunction setToArray(set) {\n var index = -1,\n result = Array(set.size);\n\n set.forEach(function(value) {\n result[++index] = value;\n });\n return result;\n}\n\nexport default setToArray;\n", "import Symbol from './_Symbol.js';\nimport Uint8Array from './_Uint8Array.js';\nimport eq from './eq.js';\nimport equalArrays from './_equalArrays.js';\nimport mapToArray from './_mapToArray.js';\nimport setToArray from './_setToArray.js';\n\n/** Used to compose bitmasks for value comparisons. */\nvar COMPARE_PARTIAL_FLAG = 1,\n COMPARE_UNORDERED_FLAG = 2;\n\n/** `Object#toString` result references. */\nvar boolTag = '[object Boolean]',\n dateTag = '[object Date]',\n errorTag = '[object Error]',\n mapTag = '[object Map]',\n numberTag = '[object Number]',\n regexpTag = '[object RegExp]',\n setTag = '[object Set]',\n stringTag = '[object String]',\n symbolTag = '[object Symbol]';\n\nvar arrayBufferTag = '[object ArrayBuffer]',\n dataViewTag = '[object DataView]';\n\n/** Used to convert symbols to primitives and strings. */\nvar symbolProto = Symbol ? Symbol.prototype : undefined,\n symbolValueOf = symbolProto ? symbolProto.valueOf : undefined;\n\n/**\n * A specialized version of `baseIsEqualDeep` for comparing objects of\n * the same `toStringTag`.\n *\n * **Note:** This function only supports comparing values with tags of\n * `Boolean`, `Date`, `Error`, `Number`, `RegExp`, or `String`.\n *\n * @private\n * @param {Object} object The object to compare.\n * @param {Object} other The other object to compare.\n * @param {string} tag The `toStringTag` of the objects to compare.\n * @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details.\n * @param {Function} customizer The function to customize comparisons.\n * @param {Function} equalFunc The function to determine equivalents of values.\n * @param {Object} stack Tracks traversed `object` and `other` objects.\n * @returns {boolean} Returns `true` if the objects are equivalent, else `false`.\n */\nfunction equalByTag(object, other, tag, bitmask, customizer, equalFunc, stack) {\n switch (tag) {\n case dataViewTag:\n if ((object.byteLength != other.byteLength) ||\n (object.byteOffset != other.byteOffset)) {\n return false;\n }\n object = object.buffer;\n other = other.buffer;\n\n case arrayBufferTag:\n if ((object.byteLength != other.byteLength) ||\n !equalFunc(new Uint8Array(object), new Uint8Array(other))) {\n return false;\n }\n return true;\n\n case boolTag:\n case dateTag:\n case numberTag:\n // Coerce booleans to `1` or `0` and dates to milliseconds.\n // Invalid dates are coerced to `NaN`.\n return eq(+object, +other);\n\n case errorTag:\n return object.name == other.name && object.message == other.message;\n\n case regexpTag:\n case stringTag:\n // Coerce regexes to strings and treat strings, primitives and objects,\n // as equal. See http://www.ecma-international.org/ecma-262/7.0/#sec-regexp.prototype.tostring\n // for more details.\n return object == (other + '');\n\n case mapTag:\n var convert = mapToArray;\n\n case setTag:\n var isPartial = bitmask & COMPARE_PARTIAL_FLAG;\n convert || (convert = setToArray);\n\n if (object.size != other.size && !isPartial) {\n return false;\n }\n // Assume cyclic values are equal.\n var stacked = stack.get(object);\n if (stacked) {\n return stacked == other;\n }\n bitmask |= COMPARE_UNORDERED_FLAG;\n\n // Recursively compare objects (susceptible to call stack limits).\n stack.set(object, other);\n var result = equalArrays(convert(object), convert(other), bitmask, customizer, equalFunc, stack);\n stack['delete'](object);\n return result;\n\n case symbolTag:\n if (symbolValueOf) {\n return symbolValueOf.call(object) == symbolValueOf.call(other);\n }\n }\n return false;\n}\n\nexport default equalByTag;\n", "import getAllKeys from './_getAllKeys.js';\n\n/** Used to compose bitmasks for value comparisons. */\nvar COMPARE_PARTIAL_FLAG = 1;\n\n/** Used for built-in method references. */\nvar objectProto = Object.prototype;\n\n/** Used to check objects for own properties. */\nvar hasOwnProperty = objectProto.hasOwnProperty;\n\n/**\n * A specialized version of `baseIsEqualDeep` for objects with support for\n * partial deep comparisons.\n *\n * @private\n * @param {Object} object The object to compare.\n * @param {Object} other The other object to compare.\n * @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details.\n * @param {Function} customizer The function to customize comparisons.\n * @param {Function} equalFunc The function to determine equivalents of values.\n * @param {Object} stack Tracks traversed `object` and `other` objects.\n * @returns {boolean} Returns `true` if the objects are equivalent, else `false`.\n */\nfunction equalObjects(object, other, bitmask, customizer, equalFunc, stack) {\n var isPartial = bitmask & COMPARE_PARTIAL_FLAG,\n objProps = getAllKeys(object),\n objLength = objProps.length,\n othProps = getAllKeys(other),\n othLength = othProps.length;\n\n if (objLength != othLength && !isPartial) {\n return false;\n }\n var index = objLength;\n while (index--) {\n var key = objProps[index];\n if (!(isPartial ? key in other : hasOwnProperty.call(other, key))) {\n return false;\n }\n }\n // Check that cyclic values are equal.\n var objStacked = stack.get(object);\n var othStacked = stack.get(other);\n if (objStacked && othStacked) {\n return objStacked == other && othStacked == object;\n }\n var result = true;\n stack.set(object, other);\n stack.set(other, object);\n\n var skipCtor = isPartial;\n while (++index < objLength) {\n key = objProps[index];\n var objValue = object[key],\n othValue = other[key];\n\n if (customizer) {\n var compared = isPartial\n ? customizer(othValue, objValue, key, other, object, stack)\n : customizer(objValue, othValue, key, object, other, stack);\n }\n // Recursively compare objects (susceptible to call stack limits).\n if (!(compared === undefined\n ? (objValue === othValue || equalFunc(objValue, othValue, bitmask, customizer, stack))\n : compared\n )) {\n result = false;\n break;\n }\n skipCtor || (skipCtor = key == 'constructor');\n }\n if (result && !skipCtor) {\n var objCtor = object.constructor,\n othCtor = other.constructor;\n\n // Non `Object` object instances with different constructors are not equal.\n if (objCtor != othCtor &&\n ('constructor' in object && 'constructor' in other) &&\n !(typeof objCtor == 'function' && objCtor instanceof objCtor &&\n typeof othCtor == 'function' && othCtor instanceof othCtor)) {\n result = false;\n }\n }\n stack['delete'](object);\n stack['delete'](other);\n return result;\n}\n\nexport default equalObjects;\n", "import Stack from './_Stack.js';\nimport equalArrays from './_equalArrays.js';\nimport equalByTag from './_equalByTag.js';\nimport equalObjects from './_equalObjects.js';\nimport getTag from './_getTag.js';\nimport isArray from './isArray.js';\nimport isBuffer from './isBuffer.js';\nimport isTypedArray from './isTypedArray.js';\n\n/** Used to compose bitmasks for value comparisons. */\nvar COMPARE_PARTIAL_FLAG = 1;\n\n/** `Object#toString` result references. */\nvar argsTag = '[object Arguments]',\n arrayTag = '[object Array]',\n objectTag = '[object Object]';\n\n/** Used for built-in method references. */\nvar objectProto = Object.prototype;\n\n/** Used to check objects for own properties. */\nvar hasOwnProperty = objectProto.hasOwnProperty;\n\n/**\n * A specialized version of `baseIsEqual` for arrays and objects which performs\n * deep comparisons and tracks traversed objects enabling objects with circular\n * references to be compared.\n *\n * @private\n * @param {Object} object The object to compare.\n * @param {Object} other The other object to compare.\n * @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details.\n * @param {Function} customizer The function to customize comparisons.\n * @param {Function} equalFunc The function to determine equivalents of values.\n * @param {Object} [stack] Tracks traversed `object` and `other` objects.\n * @returns {boolean} Returns `true` if the objects are equivalent, else `false`.\n */\nfunction baseIsEqualDeep(object, other, bitmask, customizer, equalFunc, stack) {\n var objIsArr = isArray(object),\n othIsArr = isArray(other),\n objTag = objIsArr ? arrayTag : getTag(object),\n othTag = othIsArr ? arrayTag : getTag(other);\n\n objTag = objTag == argsTag ? objectTag : objTag;\n othTag = othTag == argsTag ? objectTag : othTag;\n\n var objIsObj = objTag == objectTag,\n othIsObj = othTag == objectTag,\n isSameTag = objTag == othTag;\n\n if (isSameTag && isBuffer(object)) {\n if (!isBuffer(other)) {\n return false;\n }\n objIsArr = true;\n objIsObj = false;\n }\n if (isSameTag && !objIsObj) {\n stack || (stack = new Stack);\n return (objIsArr || isTypedArray(object))\n ? equalArrays(object, other, bitmask, customizer, equalFunc, stack)\n : equalByTag(object, other, objTag, bitmask, customizer, equalFunc, stack);\n }\n if (!(bitmask & COMPARE_PARTIAL_FLAG)) {\n var objIsWrapped = objIsObj && hasOwnProperty.call(object, '__wrapped__'),\n othIsWrapped = othIsObj && hasOwnProperty.call(other, '__wrapped__');\n\n if (objIsWrapped || othIsWrapped) {\n var objUnwrapped = objIsWrapped ? object.value() : object,\n othUnwrapped = othIsWrapped ? other.value() : other;\n\n stack || (stack = new Stack);\n return equalFunc(objUnwrapped, othUnwrapped, bitmask, customizer, stack);\n }\n }\n if (!isSameTag) {\n return false;\n }\n stack || (stack = new Stack);\n return equalObjects(object, other, bitmask, customizer, equalFunc, stack);\n}\n\nexport default baseIsEqualDeep;\n", "import baseIsEqualDeep from './_baseIsEqualDeep.js';\nimport isObjectLike from './isObjectLike.js';\n\n/**\n * The base implementation of `_.isEqual` which supports partial comparisons\n * and tracks traversed objects.\n *\n * @private\n * @param {*} value The value to compare.\n * @param {*} other The other value to compare.\n * @param {boolean} bitmask The bitmask flags.\n * 1 - Unordered comparison\n * 2 - Partial comparison\n * @param {Function} [customizer] The function to customize comparisons.\n * @param {Object} [stack] Tracks traversed `value` and `other` objects.\n * @returns {boolean} Returns `true` if the values are equivalent, else `false`.\n */\nfunction baseIsEqual(value, other, bitmask, customizer, stack) {\n if (value === other) {\n return true;\n }\n if (value == null || other == null || (!isObjectLike(value) && !isObjectLike(other))) {\n return value !== value && other !== other;\n }\n return baseIsEqualDeep(value, other, bitmask, customizer, baseIsEqual, stack);\n}\n\nexport default baseIsEqual;\n", "import Stack from './_Stack.js';\nimport baseIsEqual from './_baseIsEqual.js';\n\n/** Used to compose bitmasks for value comparisons. */\nvar COMPARE_PARTIAL_FLAG = 1,\n COMPARE_UNORDERED_FLAG = 2;\n\n/**\n * The base implementation of `_.isMatch` without support for iteratee shorthands.\n *\n * @private\n * @param {Object} object The object to inspect.\n * @param {Object} source The object of property values to match.\n * @param {Array} matchData The property names, values, and compare flags to match.\n * @param {Function} [customizer] The function to customize comparisons.\n * @returns {boolean} Returns `true` if `object` is a match, else `false`.\n */\nfunction baseIsMatch(object, source, matchData, customizer) {\n var index = matchData.length,\n length = index,\n noCustomizer = !customizer;\n\n if (object == null) {\n return !length;\n }\n object = Object(object);\n while (index--) {\n var data = matchData[index];\n if ((noCustomizer && data[2])\n ? data[1] !== object[data[0]]\n : !(data[0] in object)\n ) {\n return false;\n }\n }\n while (++index < length) {\n data = matchData[index];\n var key = data[0],\n objValue = object[key],\n srcValue = data[1];\n\n if (noCustomizer && data[2]) {\n if (objValue === undefined && !(key in object)) {\n return false;\n }\n } else {\n var stack = new Stack;\n if (customizer) {\n var result = customizer(objValue, srcValue, key, object, source, stack);\n }\n if (!(result === undefined\n ? baseIsEqual(srcValue, objValue, COMPARE_PARTIAL_FLAG | COMPARE_UNORDERED_FLAG, customizer, stack)\n : result\n )) {\n return false;\n }\n }\n }\n return true;\n}\n\nexport default baseIsMatch;\n", "import isObject from './isObject.js';\n\n/**\n * Checks if `value` is suitable for strict equality comparisons, i.e. `===`.\n *\n * @private\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` if suitable for strict\n * equality comparisons, else `false`.\n */\nfunction isStrictComparable(value) {\n return value === value && !isObject(value);\n}\n\nexport default isStrictComparable;\n", "import isStrictComparable from './_isStrictComparable.js';\nimport keys from './keys.js';\n\n/**\n * Gets the property names, values, and compare flags of `object`.\n *\n * @private\n * @param {Object} object The object to query.\n * @returns {Array} Returns the match data of `object`.\n */\nfunction getMatchData(object) {\n var result = keys(object),\n length = result.length;\n\n while (length--) {\n var key = result[length],\n value = object[key];\n\n result[length] = [key, value, isStrictComparable(value)];\n }\n return result;\n}\n\nexport default getMatchData;\n", "/**\n * A specialized version of `matchesProperty` for source values suitable\n * for strict equality comparisons, i.e. `===`.\n *\n * @private\n * @param {string} key The key of the property to get.\n * @param {*} srcValue The value to match.\n * @returns {Function} Returns the new spec function.\n */\nfunction matchesStrictComparable(key, srcValue) {\n return function(object) {\n if (object == null) {\n return false;\n }\n return object[key] === srcValue &&\n (srcValue !== undefined || (key in Object(object)));\n };\n}\n\nexport default matchesStrictComparable;\n", "import baseIsMatch from './_baseIsMatch.js';\nimport getMatchData from './_getMatchData.js';\nimport matchesStrictComparable from './_matchesStrictComparable.js';\n\n/**\n * The base implementation of `_.matches` which doesn't clone `source`.\n *\n * @private\n * @param {Object} source The object of property values to match.\n * @returns {Function} Returns the new spec function.\n */\nfunction baseMatches(source) {\n var matchData = getMatchData(source);\n if (matchData.length == 1 && matchData[0][2]) {\n return matchesStrictComparable(matchData[0][0], matchData[0][1]);\n }\n return function(object) {\n return object === source || baseIsMatch(object, source, matchData);\n };\n}\n\nexport default baseMatches;\n", "/**\n * The base implementation of `_.hasIn` without support for deep paths.\n *\n * @private\n * @param {Object} [object] The object to query.\n * @param {Array|string} key The key to check.\n * @returns {boolean} Returns `true` if `key` exists, else `false`.\n */\nfunction baseHasIn(object, key) {\n return object != null && key in Object(object);\n}\n\nexport default baseHasIn;\n", "import castPath from './_castPath.js';\nimport isArguments from './isArguments.js';\nimport isArray from './isArray.js';\nimport isIndex from './_isIndex.js';\nimport isLength from './isLength.js';\nimport toKey from './_toKey.js';\n\n/**\n * Checks if `path` exists on `object`.\n *\n * @private\n * @param {Object} object The object to query.\n * @param {Array|string} path The path to check.\n * @param {Function} hasFunc The function to check properties.\n * @returns {boolean} Returns `true` if `path` exists, else `false`.\n */\nfunction hasPath(object, path, hasFunc) {\n path = castPath(path, object);\n\n var index = -1,\n length = path.length,\n result = false;\n\n while (++index < length) {\n var key = toKey(path[index]);\n if (!(result = object != null && hasFunc(object, key))) {\n break;\n }\n object = object[key];\n }\n if (result || ++index != length) {\n return result;\n }\n length = object == null ? 0 : object.length;\n return !!length && isLength(length) && isIndex(key, length) &&\n (isArray(object) || isArguments(object));\n}\n\nexport default hasPath;\n", "import baseHasIn from './_baseHasIn.js';\nimport hasPath from './_hasPath.js';\n\n/**\n * Checks if `path` is a direct or inherited property of `object`.\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Object\n * @param {Object} object The object to query.\n * @param {Array|string} path The path to check.\n * @returns {boolean} Returns `true` if `path` exists, else `false`.\n * @example\n *\n * var object = _.create({ 'a': _.create({ 'b': 2 }) });\n *\n * _.hasIn(object, 'a');\n * // => true\n *\n * _.hasIn(object, 'a.b');\n * // => true\n *\n * _.hasIn(object, ['a', 'b']);\n * // => true\n *\n * _.hasIn(object, 'b');\n * // => false\n */\nfunction hasIn(object, path) {\n return object != null && hasPath(object, path, baseHasIn);\n}\n\nexport default hasIn;\n", "import baseIsEqual from './_baseIsEqual.js';\nimport get from './get.js';\nimport hasIn from './hasIn.js';\nimport isKey from './_isKey.js';\nimport isStrictComparable from './_isStrictComparable.js';\nimport matchesStrictComparable from './_matchesStrictComparable.js';\nimport toKey from './_toKey.js';\n\n/** Used to compose bitmasks for value comparisons. */\nvar COMPARE_PARTIAL_FLAG = 1,\n COMPARE_UNORDERED_FLAG = 2;\n\n/**\n * The base implementation of `_.matchesProperty` which doesn't clone `srcValue`.\n *\n * @private\n * @param {string} path The path of the property to get.\n * @param {*} srcValue The value to match.\n * @returns {Function} Returns the new spec function.\n */\nfunction baseMatchesProperty(path, srcValue) {\n if (isKey(path) && isStrictComparable(srcValue)) {\n return matchesStrictComparable(toKey(path), srcValue);\n }\n return function(object) {\n var objValue = get(object, path);\n return (objValue === undefined && objValue === srcValue)\n ? hasIn(object, path)\n : baseIsEqual(srcValue, objValue, COMPARE_PARTIAL_FLAG | COMPARE_UNORDERED_FLAG);\n };\n}\n\nexport default baseMatchesProperty;\n", "/**\n * The base implementation of `_.property` without support for deep paths.\n *\n * @private\n * @param {string} key The key of the property to get.\n * @returns {Function} Returns the new accessor function.\n */\nfunction baseProperty(key) {\n return function(object) {\n return object == null ? undefined : object[key];\n };\n}\n\nexport default baseProperty;\n", "import baseGet from './_baseGet.js';\n\n/**\n * A specialized version of `baseProperty` which supports deep paths.\n *\n * @private\n * @param {Array|string} path The path of the property to get.\n * @returns {Function} Returns the new accessor function.\n */\nfunction basePropertyDeep(path) {\n return function(object) {\n return baseGet(object, path);\n };\n}\n\nexport default basePropertyDeep;\n", "import baseProperty from './_baseProperty.js';\nimport basePropertyDeep from './_basePropertyDeep.js';\nimport isKey from './_isKey.js';\nimport toKey from './_toKey.js';\n\n/**\n * Creates a function that returns the value at `path` of a given object.\n *\n * @static\n * @memberOf _\n * @since 2.4.0\n * @category Util\n * @param {Array|string} path The path of the property to get.\n * @returns {Function} Returns the new accessor function.\n * @example\n *\n * var objects = [\n * { 'a': { 'b': 2 } },\n * { 'a': { 'b': 1 } }\n * ];\n *\n * _.map(objects, _.property('a.b'));\n * // => [2, 1]\n *\n * _.map(_.sortBy(objects, _.property(['a', 'b'])), 'a.b');\n * // => [1, 2]\n */\nfunction property(path) {\n return isKey(path) ? baseProperty(toKey(path)) : basePropertyDeep(path);\n}\n\nexport default property;\n", "import baseMatches from './_baseMatches.js';\nimport baseMatchesProperty from './_baseMatchesProperty.js';\nimport identity from './identity.js';\nimport isArray from './isArray.js';\nimport property from './property.js';\n\n/**\n * The base implementation of `_.iteratee`.\n *\n * @private\n * @param {*} [value=_.identity] The value to convert to an iteratee.\n * @returns {Function} Returns the iteratee.\n */\nfunction baseIteratee(value) {\n // Don't store the `typeof` result in a variable to avoid a JIT bug in Safari 9.\n // See https://bugs.webkit.org/show_bug.cgi?id=156034 for more details.\n if (typeof value == 'function') {\n return value;\n }\n if (value == null) {\n return identity;\n }\n if (typeof value == 'object') {\n return isArray(value)\n ? baseMatchesProperty(value[0], value[1])\n : baseMatches(value);\n }\n return property(value);\n}\n\nexport default baseIteratee;\n", "/**\n * A specialized version of `baseAggregator` for arrays.\n *\n * @private\n * @param {Array} [array] The array to iterate over.\n * @param {Function} setter The function to set `accumulator` values.\n * @param {Function} iteratee The iteratee to transform keys.\n * @param {Object} accumulator The initial aggregated object.\n * @returns {Function} Returns `accumulator`.\n */\nfunction arrayAggregator(array, setter, iteratee, accumulator) {\n var index = -1,\n length = array == null ? 0 : array.length;\n\n while (++index < length) {\n var value = array[index];\n setter(accumulator, value, iteratee(value), array);\n }\n return accumulator;\n}\n\nexport default arrayAggregator;\n", "/**\n * Creates a base function for methods like `_.forIn` and `_.forOwn`.\n *\n * @private\n * @param {boolean} [fromRight] Specify iterating from right to left.\n * @returns {Function} Returns the new base function.\n */\nfunction createBaseFor(fromRight) {\n return function(object, iteratee, keysFunc) {\n var index = -1,\n iterable = Object(object),\n props = keysFunc(object),\n length = props.length;\n\n while (length--) {\n var key = props[fromRight ? length : ++index];\n if (iteratee(iterable[key], key, iterable) === false) {\n break;\n }\n }\n return object;\n };\n}\n\nexport default createBaseFor;\n", "import createBaseFor from './_createBaseFor.js';\n\n/**\n * The base implementation of `baseForOwn` which iterates over `object`\n * properties returned by `keysFunc` and invokes `iteratee` for each property.\n * Iteratee functions may exit iteration early by explicitly returning `false`.\n *\n * @private\n * @param {Object} object The object to iterate over.\n * @param {Function} iteratee The function invoked per iteration.\n * @param {Function} keysFunc The function to get the keys of `object`.\n * @returns {Object} Returns `object`.\n */\nvar baseFor = createBaseFor();\n\nexport default baseFor;\n", "import baseFor from './_baseFor.js';\nimport keys from './keys.js';\n\n/**\n * The base implementation of `_.forOwn` without support for iteratee shorthands.\n *\n * @private\n * @param {Object} object The object to iterate over.\n * @param {Function} iteratee The function invoked per iteration.\n * @returns {Object} Returns `object`.\n */\nfunction baseForOwn(object, iteratee) {\n return object && baseFor(object, iteratee, keys);\n}\n\nexport default baseForOwn;\n", "import isArrayLike from './isArrayLike.js';\n\n/**\n * Creates a `baseEach` or `baseEachRight` function.\n *\n * @private\n * @param {Function} eachFunc The function to iterate over a collection.\n * @param {boolean} [fromRight] Specify iterating from right to left.\n * @returns {Function} Returns the new base function.\n */\nfunction createBaseEach(eachFunc, fromRight) {\n return function(collection, iteratee) {\n if (collection == null) {\n return collection;\n }\n if (!isArrayLike(collection)) {\n return eachFunc(collection, iteratee);\n }\n var length = collection.length,\n index = fromRight ? length : -1,\n iterable = Object(collection);\n\n while ((fromRight ? index-- : ++index < length)) {\n if (iteratee(iterable[index], index, iterable) === false) {\n break;\n }\n }\n return collection;\n };\n}\n\nexport default createBaseEach;\n", "import baseForOwn from './_baseForOwn.js';\nimport createBaseEach from './_createBaseEach.js';\n\n/**\n * The base implementation of `_.forEach` without support for iteratee shorthands.\n *\n * @private\n * @param {Array|Object} collection The collection to iterate over.\n * @param {Function} iteratee The function invoked per iteration.\n * @returns {Array|Object} Returns `collection`.\n */\nvar baseEach = createBaseEach(baseForOwn);\n\nexport default baseEach;\n", "import baseEach from './_baseEach.js';\n\n/**\n * Aggregates elements of `collection` on `accumulator` with keys transformed\n * by `iteratee` and values set by `setter`.\n *\n * @private\n * @param {Array|Object} collection The collection to iterate over.\n * @param {Function} setter The function to set `accumulator` values.\n * @param {Function} iteratee The iteratee to transform keys.\n * @param {Object} accumulator The initial aggregated object.\n * @returns {Function} Returns `accumulator`.\n */\nfunction baseAggregator(collection, setter, iteratee, accumulator) {\n baseEach(collection, function(value, key, collection) {\n setter(accumulator, value, iteratee(value), collection);\n });\n return accumulator;\n}\n\nexport default baseAggregator;\n", "import arrayAggregator from './_arrayAggregator.js';\nimport baseAggregator from './_baseAggregator.js';\nimport baseIteratee from './_baseIteratee.js';\nimport isArray from './isArray.js';\n\n/**\n * Creates a function like `_.groupBy`.\n *\n * @private\n * @param {Function} setter The function to set accumulator values.\n * @param {Function} [initializer] The accumulator object initializer.\n * @returns {Function} Returns the new aggregator function.\n */\nfunction createAggregator(setter, initializer) {\n return function(collection, iteratee) {\n var func = isArray(collection) ? arrayAggregator : baseAggregator,\n accumulator = initializer ? initializer() : {};\n\n return func(collection, setter, baseIteratee(iteratee, 2), accumulator);\n };\n}\n\nexport default createAggregator;\n", "import baseRest from './_baseRest.js';\nimport eq from './eq.js';\nimport isIterateeCall from './_isIterateeCall.js';\nimport keysIn from './keysIn.js';\n\n/** Used for built-in method references. */\nvar objectProto = Object.prototype;\n\n/** Used to check objects for own properties. */\nvar hasOwnProperty = objectProto.hasOwnProperty;\n\n/**\n * Assigns own and inherited enumerable string keyed properties of source\n * objects to the destination object for all destination properties that\n * resolve to `undefined`. Source objects are applied from left to right.\n * Once a property is set, additional values of the same property are ignored.\n *\n * **Note:** This method mutates `object`.\n *\n * @static\n * @since 0.1.0\n * @memberOf _\n * @category Object\n * @param {Object} object The destination object.\n * @param {...Object} [sources] The source objects.\n * @returns {Object} Returns `object`.\n * @see _.defaultsDeep\n * @example\n *\n * _.defaults({ 'a': 1 }, { 'b': 2 }, { 'a': 3 });\n * // => { 'a': 1, 'b': 2 }\n */\nvar defaults = baseRest(function(object, sources) {\n object = Object(object);\n\n var index = -1;\n var length = sources.length;\n var guard = length > 2 ? sources[2] : undefined;\n\n if (guard && isIterateeCall(sources[0], sources[1], guard)) {\n length = 1;\n }\n\n while (++index < length) {\n var source = sources[index];\n var props = keysIn(source);\n var propsIndex = -1;\n var propsLength = props.length;\n\n while (++propsIndex < propsLength) {\n var key = props[propsIndex];\n var value = object[key];\n\n if (value === undefined ||\n (eq(value, objectProto[key]) && !hasOwnProperty.call(object, key))) {\n object[key] = source[key];\n }\n }\n }\n\n return object;\n});\n\nexport default defaults;\n", "import isArrayLike from './isArrayLike.js';\nimport isObjectLike from './isObjectLike.js';\n\n/**\n * This method is like `_.isArrayLike` except that it also checks if `value`\n * is an object.\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is an array-like object,\n * else `false`.\n * @example\n *\n * _.isArrayLikeObject([1, 2, 3]);\n * // => true\n *\n * _.isArrayLikeObject(document.body.children);\n * // => true\n *\n * _.isArrayLikeObject('abc');\n * // => false\n *\n * _.isArrayLikeObject(_.noop);\n * // => false\n */\nfunction isArrayLikeObject(value) {\n return isObjectLike(value) && isArrayLike(value);\n}\n\nexport default isArrayLikeObject;\n", "/**\n * This function is like `arrayIncludes` except that it accepts a comparator.\n *\n * @private\n * @param {Array} [array] The array to inspect.\n * @param {*} target The value to search for.\n * @param {Function} comparator The comparator invoked per element.\n * @returns {boolean} Returns `true` if `target` is found, else `false`.\n */\nfunction arrayIncludesWith(array, value, comparator) {\n var index = -1,\n length = array == null ? 0 : array.length;\n\n while (++index < length) {\n if (comparator(value, array[index])) {\n return true;\n }\n }\n return false;\n}\n\nexport default arrayIncludesWith;\n", "import SetCache from './_SetCache.js';\nimport arrayIncludes from './_arrayIncludes.js';\nimport arrayIncludesWith from './_arrayIncludesWith.js';\nimport arrayMap from './_arrayMap.js';\nimport baseUnary from './_baseUnary.js';\nimport cacheHas from './_cacheHas.js';\n\n/** Used as the size to enable large array optimizations. */\nvar LARGE_ARRAY_SIZE = 200;\n\n/**\n * The base implementation of methods like `_.difference` without support\n * for excluding multiple arrays or iteratee shorthands.\n *\n * @private\n * @param {Array} array The array to inspect.\n * @param {Array} values The values to exclude.\n * @param {Function} [iteratee] The iteratee invoked per element.\n * @param {Function} [comparator] The comparator invoked per element.\n * @returns {Array} Returns the new array of filtered values.\n */\nfunction baseDifference(array, values, iteratee, comparator) {\n var index = -1,\n includes = arrayIncludes,\n isCommon = true,\n length = array.length,\n result = [],\n valuesLength = values.length;\n\n if (!length) {\n return result;\n }\n if (iteratee) {\n values = arrayMap(values, baseUnary(iteratee));\n }\n if (comparator) {\n includes = arrayIncludesWith;\n isCommon = false;\n }\n else if (values.length >= LARGE_ARRAY_SIZE) {\n includes = cacheHas;\n isCommon = false;\n values = new SetCache(values);\n }\n outer:\n while (++index < length) {\n var value = array[index],\n computed = iteratee == null ? value : iteratee(value);\n\n value = (comparator || value !== 0) ? value : 0;\n if (isCommon && computed === computed) {\n var valuesIndex = valuesLength;\n while (valuesIndex--) {\n if (values[valuesIndex] === computed) {\n continue outer;\n }\n }\n result.push(value);\n }\n else if (!includes(values, computed, comparator)) {\n result.push(value);\n }\n }\n return result;\n}\n\nexport default baseDifference;\n", "import baseDifference from './_baseDifference.js';\nimport baseFlatten from './_baseFlatten.js';\nimport baseRest from './_baseRest.js';\nimport isArrayLikeObject from './isArrayLikeObject.js';\n\n/**\n * Creates an array of `array` values not included in the other given arrays\n * using [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero)\n * for equality comparisons. The order and references of result values are\n * determined by the first array.\n *\n * **Note:** Unlike `_.pullAll`, this method returns a new array.\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @category Array\n * @param {Array} array The array to inspect.\n * @param {...Array} [values] The values to exclude.\n * @returns {Array} Returns the new array of filtered values.\n * @see _.without, _.xor\n * @example\n *\n * _.difference([2, 1], [2, 3]);\n * // => [1]\n */\nvar difference = baseRest(function(array, values) {\n return isArrayLikeObject(array)\n ? baseDifference(array, baseFlatten(values, 1, isArrayLikeObject, true))\n : [];\n});\n\nexport default difference;\n", "/**\n * Gets the last element of `array`.\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @category Array\n * @param {Array} array The array to query.\n * @returns {*} Returns the last element of `array`.\n * @example\n *\n * _.last([1, 2, 3]);\n * // => 3\n */\nfunction last(array) {\n var length = array == null ? 0 : array.length;\n return length ? array[length - 1] : undefined;\n}\n\nexport default last;\n", "import baseSlice from './_baseSlice.js';\nimport toInteger from './toInteger.js';\n\n/**\n * Creates a slice of `array` with `n` elements dropped from the beginning.\n *\n * @static\n * @memberOf _\n * @since 0.5.0\n * @category Array\n * @param {Array} array The array to query.\n * @param {number} [n=1] The number of elements to drop.\n * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`.\n * @returns {Array} Returns the slice of `array`.\n * @example\n *\n * _.drop([1, 2, 3]);\n * // => [2, 3]\n *\n * _.drop([1, 2, 3], 2);\n * // => [3]\n *\n * _.drop([1, 2, 3], 5);\n * // => []\n *\n * _.drop([1, 2, 3], 0);\n * // => [1, 2, 3]\n */\nfunction drop(array, n, guard) {\n var length = array == null ? 0 : array.length;\n if (!length) {\n return [];\n }\n n = (guard || n === undefined) ? 1 : toInteger(n);\n return baseSlice(array, n < 0 ? 0 : n, length);\n}\n\nexport default drop;\n", "import baseSlice from './_baseSlice.js';\nimport toInteger from './toInteger.js';\n\n/**\n * Creates a slice of `array` with `n` elements dropped from the end.\n *\n * @static\n * @memberOf _\n * @since 3.0.0\n * @category Array\n * @param {Array} array The array to query.\n * @param {number} [n=1] The number of elements to drop.\n * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`.\n * @returns {Array} Returns the slice of `array`.\n * @example\n *\n * _.dropRight([1, 2, 3]);\n * // => [1, 2]\n *\n * _.dropRight([1, 2, 3], 2);\n * // => [1]\n *\n * _.dropRight([1, 2, 3], 5);\n * // => []\n *\n * _.dropRight([1, 2, 3], 0);\n * // => [1, 2, 3]\n */\nfunction dropRight(array, n, guard) {\n var length = array == null ? 0 : array.length;\n if (!length) {\n return [];\n }\n n = (guard || n === undefined) ? 1 : toInteger(n);\n n = length - n;\n return baseSlice(array, 0, n < 0 ? 0 : n);\n}\n\nexport default dropRight;\n", "import identity from './identity.js';\n\n/**\n * Casts `value` to `identity` if it's not a function.\n *\n * @private\n * @param {*} value The value to inspect.\n * @returns {Function} Returns cast function.\n */\nfunction castFunction(value) {\n return typeof value == 'function' ? value : identity;\n}\n\nexport default castFunction;\n", "import arrayEach from './_arrayEach.js';\nimport baseEach from './_baseEach.js';\nimport castFunction from './_castFunction.js';\nimport isArray from './isArray.js';\n\n/**\n * Iterates over elements of `collection` and invokes `iteratee` for each element.\n * The iteratee is invoked with three arguments: (value, index|key, collection).\n * Iteratee functions may exit iteration early by explicitly returning `false`.\n *\n * **Note:** As with other \"Collections\" methods, objects with a \"length\"\n * property are iterated like arrays. To avoid this behavior use `_.forIn`\n * or `_.forOwn` for object iteration.\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @alias each\n * @category Collection\n * @param {Array|Object} collection The collection to iterate over.\n * @param {Function} [iteratee=_.identity] The function invoked per iteration.\n * @returns {Array|Object} Returns `collection`.\n * @see _.forEachRight\n * @example\n *\n * _.forEach([1, 2], function(value) {\n * console.log(value);\n * });\n * // => Logs `1` then `2`.\n *\n * _.forEach({ 'a': 1, 'b': 2 }, function(value, key) {\n * console.log(key);\n * });\n * // => Logs 'a' then 'b' (iteration order is not guaranteed).\n */\nfunction forEach(collection, iteratee) {\n var func = isArray(collection) ? arrayEach : baseEach;\n return func(collection, castFunction(iteratee));\n}\n\nexport default forEach;\n", "/**\n * A specialized version of `_.every` for arrays without support for\n * iteratee shorthands.\n *\n * @private\n * @param {Array} [array] The array to iterate over.\n * @param {Function} predicate The function invoked per iteration.\n * @returns {boolean} Returns `true` if all elements pass the predicate check,\n * else `false`.\n */\nfunction arrayEvery(array, predicate) {\n var index = -1,\n length = array == null ? 0 : array.length;\n\n while (++index < length) {\n if (!predicate(array[index], index, array)) {\n return false;\n }\n }\n return true;\n}\n\nexport default arrayEvery;\n", "import baseEach from './_baseEach.js';\n\n/**\n * The base implementation of `_.every` without support for iteratee shorthands.\n *\n * @private\n * @param {Array|Object} collection The collection to iterate over.\n * @param {Function} predicate The function invoked per iteration.\n * @returns {boolean} Returns `true` if all elements pass the predicate check,\n * else `false`\n */\nfunction baseEvery(collection, predicate) {\n var result = true;\n baseEach(collection, function(value, index, collection) {\n result = !!predicate(value, index, collection);\n return result;\n });\n return result;\n}\n\nexport default baseEvery;\n", "import arrayEvery from './_arrayEvery.js';\nimport baseEvery from './_baseEvery.js';\nimport baseIteratee from './_baseIteratee.js';\nimport isArray from './isArray.js';\nimport isIterateeCall from './_isIterateeCall.js';\n\n/**\n * Checks if `predicate` returns truthy for **all** elements of `collection`.\n * Iteration is stopped once `predicate` returns falsey. The predicate is\n * invoked with three arguments: (value, index|key, collection).\n *\n * **Note:** This method returns `true` for\n * [empty collections](https://en.wikipedia.org/wiki/Empty_set) because\n * [everything is true](https://en.wikipedia.org/wiki/Vacuous_truth) of\n * elements of empty collections.\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @category Collection\n * @param {Array|Object} collection The collection to iterate over.\n * @param {Function} [predicate=_.identity] The function invoked per iteration.\n * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`.\n * @returns {boolean} Returns `true` if all elements pass the predicate check,\n * else `false`.\n * @example\n *\n * _.every([true, 1, null, 'yes'], Boolean);\n * // => false\n *\n * var users = [\n * { 'user': 'barney', 'age': 36, 'active': false },\n * { 'user': 'fred', 'age': 40, 'active': false }\n * ];\n *\n * // The `_.matches` iteratee shorthand.\n * _.every(users, { 'user': 'barney', 'active': false });\n * // => false\n *\n * // The `_.matchesProperty` iteratee shorthand.\n * _.every(users, ['active', false]);\n * // => true\n *\n * // The `_.property` iteratee shorthand.\n * _.every(users, 'active');\n * // => false\n */\nfunction every(collection, predicate, guard) {\n var func = isArray(collection) ? arrayEvery : baseEvery;\n if (guard && isIterateeCall(collection, predicate, guard)) {\n predicate = undefined;\n }\n return func(collection, baseIteratee(predicate, 3));\n}\n\nexport default every;\n", "import baseEach from './_baseEach.js';\n\n/**\n * The base implementation of `_.filter` without support for iteratee shorthands.\n *\n * @private\n * @param {Array|Object} collection The collection to iterate over.\n * @param {Function} predicate The function invoked per iteration.\n * @returns {Array} Returns the new filtered array.\n */\nfunction baseFilter(collection, predicate) {\n var result = [];\n baseEach(collection, function(value, index, collection) {\n if (predicate(value, index, collection)) {\n result.push(value);\n }\n });\n return result;\n}\n\nexport default baseFilter;\n", "import arrayFilter from './_arrayFilter.js';\nimport baseFilter from './_baseFilter.js';\nimport baseIteratee from './_baseIteratee.js';\nimport isArray from './isArray.js';\n\n/**\n * Iterates over elements of `collection`, returning an array of all elements\n * `predicate` returns truthy for. The predicate is invoked with three\n * arguments: (value, index|key, collection).\n *\n * **Note:** Unlike `_.remove`, this method returns a new array.\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @category Collection\n * @param {Array|Object} collection The collection to iterate over.\n * @param {Function} [predicate=_.identity] The function invoked per iteration.\n * @returns {Array} Returns the new filtered array.\n * @see _.reject\n * @example\n *\n * var users = [\n * { 'user': 'barney', 'age': 36, 'active': true },\n * { 'user': 'fred', 'age': 40, 'active': false }\n * ];\n *\n * _.filter(users, function(o) { return !o.active; });\n * // => objects for ['fred']\n *\n * // The `_.matches` iteratee shorthand.\n * _.filter(users, { 'age': 36, 'active': true });\n * // => objects for ['barney']\n *\n * // The `_.matchesProperty` iteratee shorthand.\n * _.filter(users, ['active', false]);\n * // => objects for ['fred']\n *\n * // The `_.property` iteratee shorthand.\n * _.filter(users, 'active');\n * // => objects for ['barney']\n *\n * // Combining several predicates using `_.overEvery` or `_.overSome`.\n * _.filter(users, _.overSome([{ 'age': 36 }, ['age', 40]]));\n * // => objects for ['fred', 'barney']\n */\nfunction filter(collection, predicate) {\n var func = isArray(collection) ? arrayFilter : baseFilter;\n return func(collection, baseIteratee(predicate, 3));\n}\n\nexport default filter;\n", "import baseIteratee from './_baseIteratee.js';\nimport isArrayLike from './isArrayLike.js';\nimport keys from './keys.js';\n\n/**\n * Creates a `_.find` or `_.findLast` function.\n *\n * @private\n * @param {Function} findIndexFunc The function to find the collection index.\n * @returns {Function} Returns the new find function.\n */\nfunction createFind(findIndexFunc) {\n return function(collection, predicate, fromIndex) {\n var iterable = Object(collection);\n if (!isArrayLike(collection)) {\n var iteratee = baseIteratee(predicate, 3);\n collection = keys(collection);\n predicate = function(key) { return iteratee(iterable[key], key, iterable); };\n }\n var index = findIndexFunc(collection, predicate, fromIndex);\n return index > -1 ? iterable[iteratee ? collection[index] : index] : undefined;\n };\n}\n\nexport default createFind;\n", "import baseFindIndex from './_baseFindIndex.js';\nimport baseIteratee from './_baseIteratee.js';\nimport toInteger from './toInteger.js';\n\n/* Built-in method references for those with the same name as other `lodash` methods. */\nvar nativeMax = Math.max;\n\n/**\n * This method is like `_.find` except that it returns the index of the first\n * element `predicate` returns truthy for instead of the element itself.\n *\n * @static\n * @memberOf _\n * @since 1.1.0\n * @category Array\n * @param {Array} array The array to inspect.\n * @param {Function} [predicate=_.identity] The function invoked per iteration.\n * @param {number} [fromIndex=0] The index to search from.\n * @returns {number} Returns the index of the found element, else `-1`.\n * @example\n *\n * var users = [\n * { 'user': 'barney', 'active': false },\n * { 'user': 'fred', 'active': false },\n * { 'user': 'pebbles', 'active': true }\n * ];\n *\n * _.findIndex(users, function(o) { return o.user == 'barney'; });\n * // => 0\n *\n * // The `_.matches` iteratee shorthand.\n * _.findIndex(users, { 'user': 'fred', 'active': false });\n * // => 1\n *\n * // The `_.matchesProperty` iteratee shorthand.\n * _.findIndex(users, ['active', false]);\n * // => 0\n *\n * // The `_.property` iteratee shorthand.\n * _.findIndex(users, 'active');\n * // => 2\n */\nfunction findIndex(array, predicate, fromIndex) {\n var length = array == null ? 0 : array.length;\n if (!length) {\n return -1;\n }\n var index = fromIndex == null ? 0 : toInteger(fromIndex);\n if (index < 0) {\n index = nativeMax(length + index, 0);\n }\n return baseFindIndex(array, baseIteratee(predicate, 3), index);\n}\n\nexport default findIndex;\n", "import createFind from './_createFind.js';\nimport findIndex from './findIndex.js';\n\n/**\n * Iterates over elements of `collection`, returning the first element\n * `predicate` returns truthy for. The predicate is invoked with three\n * arguments: (value, index|key, collection).\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @category Collection\n * @param {Array|Object} collection The collection to inspect.\n * @param {Function} [predicate=_.identity] The function invoked per iteration.\n * @param {number} [fromIndex=0] The index to search from.\n * @returns {*} Returns the matched element, else `undefined`.\n * @example\n *\n * var users = [\n * { 'user': 'barney', 'age': 36, 'active': true },\n * { 'user': 'fred', 'age': 40, 'active': false },\n * { 'user': 'pebbles', 'age': 1, 'active': true }\n * ];\n *\n * _.find(users, function(o) { return o.age < 40; });\n * // => object for 'barney'\n *\n * // The `_.matches` iteratee shorthand.\n * _.find(users, { 'age': 1, 'active': true });\n * // => object for 'pebbles'\n *\n * // The `_.matchesProperty` iteratee shorthand.\n * _.find(users, ['active', false]);\n * // => object for 'fred'\n *\n * // The `_.property` iteratee shorthand.\n * _.find(users, 'active');\n * // => object for 'barney'\n */\nvar find = createFind(findIndex);\n\nexport default find;\n", "/**\n * Gets the first element of `array`.\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @alias first\n * @category Array\n * @param {Array} array The array to query.\n * @returns {*} Returns the first element of `array`.\n * @example\n *\n * _.head([1, 2, 3]);\n * // => 1\n *\n * _.head([]);\n * // => undefined\n */\nfunction head(array) {\n return (array && array.length) ? array[0] : undefined;\n}\n\nexport default head;\n", "import baseEach from './_baseEach.js';\nimport isArrayLike from './isArrayLike.js';\n\n/**\n * The base implementation of `_.map` without support for iteratee shorthands.\n *\n * @private\n * @param {Array|Object} collection The collection to iterate over.\n * @param {Function} iteratee The function invoked per iteration.\n * @returns {Array} Returns the new mapped array.\n */\nfunction baseMap(collection, iteratee) {\n var index = -1,\n result = isArrayLike(collection) ? Array(collection.length) : [];\n\n baseEach(collection, function(value, key, collection) {\n result[++index] = iteratee(value, key, collection);\n });\n return result;\n}\n\nexport default baseMap;\n", "import arrayMap from './_arrayMap.js';\nimport baseIteratee from './_baseIteratee.js';\nimport baseMap from './_baseMap.js';\nimport isArray from './isArray.js';\n\n/**\n * Creates an array of values by running each element in `collection` thru\n * `iteratee`. The iteratee is invoked with three arguments:\n * (value, index|key, collection).\n *\n * Many lodash methods are guarded to work as iteratees for methods like\n * `_.every`, `_.filter`, `_.map`, `_.mapValues`, `_.reject`, and `_.some`.\n *\n * The guarded methods are:\n * `ary`, `chunk`, `curry`, `curryRight`, `drop`, `dropRight`, `every`,\n * `fill`, `invert`, `parseInt`, `random`, `range`, `rangeRight`, `repeat`,\n * `sampleSize`, `slice`, `some`, `sortBy`, `split`, `take`, `takeRight`,\n * `template`, `trim`, `trimEnd`, `trimStart`, and `words`\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @category Collection\n * @param {Array|Object} collection The collection to iterate over.\n * @param {Function} [iteratee=_.identity] The function invoked per iteration.\n * @returns {Array} Returns the new mapped array.\n * @example\n *\n * function square(n) {\n * return n * n;\n * }\n *\n * _.map([4, 8], square);\n * // => [16, 64]\n *\n * _.map({ 'a': 4, 'b': 8 }, square);\n * // => [16, 64] (iteration order is not guaranteed)\n *\n * var users = [\n * { 'user': 'barney' },\n * { 'user': 'fred' }\n * ];\n *\n * // The `_.property` iteratee shorthand.\n * _.map(users, 'user');\n * // => ['barney', 'fred']\n */\nfunction map(collection, iteratee) {\n var func = isArray(collection) ? arrayMap : baseMap;\n return func(collection, baseIteratee(iteratee, 3));\n}\n\nexport default map;\n", "import baseFlatten from './_baseFlatten.js';\nimport map from './map.js';\n\n/**\n * Creates a flattened array of values by running each element in `collection`\n * thru `iteratee` and flattening the mapped results. The iteratee is invoked\n * with three arguments: (value, index|key, collection).\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Collection\n * @param {Array|Object} collection The collection to iterate over.\n * @param {Function} [iteratee=_.identity] The function invoked per iteration.\n * @returns {Array} Returns the new flattened array.\n * @example\n *\n * function duplicate(n) {\n * return [n, n];\n * }\n *\n * _.flatMap([1, 2], duplicate);\n * // => [1, 1, 2, 2]\n */\nfunction flatMap(collection, iteratee) {\n return baseFlatten(map(collection, iteratee), 1);\n}\n\nexport default flatMap;\n", "import baseAssignValue from './_baseAssignValue.js';\nimport createAggregator from './_createAggregator.js';\n\n/** Used for built-in method references. */\nvar objectProto = Object.prototype;\n\n/** Used to check objects for own properties. */\nvar hasOwnProperty = objectProto.hasOwnProperty;\n\n/**\n * Creates an object composed of keys generated from the results of running\n * each element of `collection` thru `iteratee`. The order of grouped values\n * is determined by the order they occur in `collection`. The corresponding\n * value of each key is an array of elements responsible for generating the\n * key. The iteratee is invoked with one argument: (value).\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @category Collection\n * @param {Array|Object} collection The collection to iterate over.\n * @param {Function} [iteratee=_.identity] The iteratee to transform keys.\n * @returns {Object} Returns the composed aggregate object.\n * @example\n *\n * _.groupBy([6.1, 4.2, 6.3], Math.floor);\n * // => { '4': [4.2], '6': [6.1, 6.3] }\n *\n * // The `_.property` iteratee shorthand.\n * _.groupBy(['one', 'two', 'three'], 'length');\n * // => { '3': ['one', 'two'], '5': ['three'] }\n */\nvar groupBy = createAggregator(function(result, value, key) {\n if (hasOwnProperty.call(result, key)) {\n result[key].push(value);\n } else {\n baseAssignValue(result, key, [value]);\n }\n});\n\nexport default groupBy;\n", "/** Used for built-in method references. */\nvar objectProto = Object.prototype;\n\n/** Used to check objects for own properties. */\nvar hasOwnProperty = objectProto.hasOwnProperty;\n\n/**\n * The base implementation of `_.has` without support for deep paths.\n *\n * @private\n * @param {Object} [object] The object to query.\n * @param {Array|string} key The key to check.\n * @returns {boolean} Returns `true` if `key` exists, else `false`.\n */\nfunction baseHas(object, key) {\n return object != null && hasOwnProperty.call(object, key);\n}\n\nexport default baseHas;\n", "import baseHas from './_baseHas.js';\nimport hasPath from './_hasPath.js';\n\n/**\n * Checks if `path` is a direct property of `object`.\n *\n * @static\n * @since 0.1.0\n * @memberOf _\n * @category Object\n * @param {Object} object The object to query.\n * @param {Array|string} path The path to check.\n * @returns {boolean} Returns `true` if `path` exists, else `false`.\n * @example\n *\n * var object = { 'a': { 'b': 2 } };\n * var other = _.create({ 'a': _.create({ 'b': 2 }) });\n *\n * _.has(object, 'a');\n * // => true\n *\n * _.has(object, 'a.b');\n * // => true\n *\n * _.has(object, ['a', 'b']);\n * // => true\n *\n * _.has(other, 'a');\n * // => false\n */\nfunction has(object, path) {\n return object != null && hasPath(object, path, baseHas);\n}\n\nexport default has;\n", "import baseGetTag from './_baseGetTag.js';\nimport isArray from './isArray.js';\nimport isObjectLike from './isObjectLike.js';\n\n/** `Object#toString` result references. */\nvar stringTag = '[object String]';\n\n/**\n * Checks if `value` is classified as a `String` primitive or object.\n *\n * @static\n * @since 0.1.0\n * @memberOf _\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is a string, else `false`.\n * @example\n *\n * _.isString('abc');\n * // => true\n *\n * _.isString(1);\n * // => false\n */\nfunction isString(value) {\n return typeof value == 'string' ||\n (!isArray(value) && isObjectLike(value) && baseGetTag(value) == stringTag);\n}\n\nexport default isString;\n", "import arrayMap from './_arrayMap.js';\n\n/**\n * The base implementation of `_.values` and `_.valuesIn` which creates an\n * array of `object` property values corresponding to the property names\n * of `props`.\n *\n * @private\n * @param {Object} object The object to query.\n * @param {Array} props The property names to get values for.\n * @returns {Object} Returns the array of property values.\n */\nfunction baseValues(object, props) {\n return arrayMap(props, function(key) {\n return object[key];\n });\n}\n\nexport default baseValues;\n", "import baseValues from './_baseValues.js';\nimport keys from './keys.js';\n\n/**\n * Creates an array of the own enumerable string keyed property values of `object`.\n *\n * **Note:** Non-object values are coerced to objects.\n *\n * @static\n * @since 0.1.0\n * @memberOf _\n * @category Object\n * @param {Object} object The object to query.\n * @returns {Array} Returns the array of property values.\n * @example\n *\n * function Foo() {\n * this.a = 1;\n * this.b = 2;\n * }\n *\n * Foo.prototype.c = 3;\n *\n * _.values(new Foo);\n * // => [1, 2] (iteration order is not guaranteed)\n *\n * _.values('hi');\n * // => ['h', 'i']\n */\nfunction values(object) {\n return object == null ? [] : baseValues(object, keys(object));\n}\n\nexport default values;\n", "import baseIndexOf from './_baseIndexOf.js';\nimport isArrayLike from './isArrayLike.js';\nimport isString from './isString.js';\nimport toInteger from './toInteger.js';\nimport values from './values.js';\n\n/* Built-in method references for those with the same name as other `lodash` methods. */\nvar nativeMax = Math.max;\n\n/**\n * Checks if `value` is in `collection`. If `collection` is a string, it's\n * checked for a substring of `value`, otherwise\n * [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero)\n * is used for equality comparisons. If `fromIndex` is negative, it's used as\n * the offset from the end of `collection`.\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @category Collection\n * @param {Array|Object|string} collection The collection to inspect.\n * @param {*} value The value to search for.\n * @param {number} [fromIndex=0] The index to search from.\n * @param- {Object} [guard] Enables use as an iteratee for methods like `_.reduce`.\n * @returns {boolean} Returns `true` if `value` is found, else `false`.\n * @example\n *\n * _.includes([1, 2, 3], 1);\n * // => true\n *\n * _.includes([1, 2, 3], 1, 2);\n * // => false\n *\n * _.includes({ 'a': 1, 'b': 2 }, 1);\n * // => true\n *\n * _.includes('abcd', 'bc');\n * // => true\n */\nfunction includes(collection, value, fromIndex, guard) {\n collection = isArrayLike(collection) ? collection : values(collection);\n fromIndex = (fromIndex && !guard) ? toInteger(fromIndex) : 0;\n\n var length = collection.length;\n if (fromIndex < 0) {\n fromIndex = nativeMax(length + fromIndex, 0);\n }\n return isString(collection)\n ? (fromIndex <= length && collection.indexOf(value, fromIndex) > -1)\n : (!!length && baseIndexOf(collection, value, fromIndex) > -1);\n}\n\nexport default includes;\n", "import baseIndexOf from './_baseIndexOf.js';\nimport toInteger from './toInteger.js';\n\n/* Built-in method references for those with the same name as other `lodash` methods. */\nvar nativeMax = Math.max;\n\n/**\n * Gets the index at which the first occurrence of `value` is found in `array`\n * using [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero)\n * for equality comparisons. If `fromIndex` is negative, it's used as the\n * offset from the end of `array`.\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @category Array\n * @param {Array} array The array to inspect.\n * @param {*} value The value to search for.\n * @param {number} [fromIndex=0] The index to search from.\n * @returns {number} Returns the index of the matched value, else `-1`.\n * @example\n *\n * _.indexOf([1, 2, 1, 2], 2);\n * // => 1\n *\n * // Search from the `fromIndex`.\n * _.indexOf([1, 2, 1, 2], 2, 2);\n * // => 3\n */\nfunction indexOf(array, value, fromIndex) {\n var length = array == null ? 0 : array.length;\n if (!length) {\n return -1;\n }\n var index = fromIndex == null ? 0 : toInteger(fromIndex);\n if (index < 0) {\n index = nativeMax(length + index, 0);\n }\n return baseIndexOf(array, value, index);\n}\n\nexport default indexOf;\n", "import baseKeys from './_baseKeys.js';\nimport getTag from './_getTag.js';\nimport isArguments from './isArguments.js';\nimport isArray from './isArray.js';\nimport isArrayLike from './isArrayLike.js';\nimport isBuffer from './isBuffer.js';\nimport isPrototype from './_isPrototype.js';\nimport isTypedArray from './isTypedArray.js';\n\n/** `Object#toString` result references. */\nvar mapTag = '[object Map]',\n setTag = '[object Set]';\n\n/** Used for built-in method references. */\nvar objectProto = Object.prototype;\n\n/** Used to check objects for own properties. */\nvar hasOwnProperty = objectProto.hasOwnProperty;\n\n/**\n * Checks if `value` is an empty object, collection, map, or set.\n *\n * Objects are considered empty if they have no own enumerable string keyed\n * properties.\n *\n * Array-like values such as `arguments` objects, arrays, buffers, strings, or\n * jQuery-like collections are considered empty if they have a `length` of `0`.\n * Similarly, maps and sets are considered empty if they have a `size` of `0`.\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is empty, else `false`.\n * @example\n *\n * _.isEmpty(null);\n * // => true\n *\n * _.isEmpty(true);\n * // => true\n *\n * _.isEmpty(1);\n * // => true\n *\n * _.isEmpty([1, 2, 3]);\n * // => false\n *\n * _.isEmpty({ 'a': 1 });\n * // => false\n */\nfunction isEmpty(value) {\n if (value == null) {\n return true;\n }\n if (isArrayLike(value) &&\n (isArray(value) || typeof value == 'string' || typeof value.splice == 'function' ||\n isBuffer(value) || isTypedArray(value) || isArguments(value))) {\n return !value.length;\n }\n var tag = getTag(value);\n if (tag == mapTag || tag == setTag) {\n return !value.size;\n }\n if (isPrototype(value)) {\n return !baseKeys(value).length;\n }\n for (var key in value) {\n if (hasOwnProperty.call(value, key)) {\n return false;\n }\n }\n return true;\n}\n\nexport default isEmpty;\n", "import baseGetTag from './_baseGetTag.js';\nimport isObjectLike from './isObjectLike.js';\n\n/** `Object#toString` result references. */\nvar regexpTag = '[object RegExp]';\n\n/**\n * The base implementation of `_.isRegExp` without Node.js optimizations.\n *\n * @private\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is a regexp, else `false`.\n */\nfunction baseIsRegExp(value) {\n return isObjectLike(value) && baseGetTag(value) == regexpTag;\n}\n\nexport default baseIsRegExp;\n", "import baseIsRegExp from './_baseIsRegExp.js';\nimport baseUnary from './_baseUnary.js';\nimport nodeUtil from './_nodeUtil.js';\n\n/* Node.js helper references. */\nvar nodeIsRegExp = nodeUtil && nodeUtil.isRegExp;\n\n/**\n * Checks if `value` is classified as a `RegExp` object.\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is a regexp, else `false`.\n * @example\n *\n * _.isRegExp(/abc/);\n * // => true\n *\n * _.isRegExp('/abc/');\n * // => false\n */\nvar isRegExp = nodeIsRegExp ? baseUnary(nodeIsRegExp) : baseIsRegExp;\n\nexport default isRegExp;\n", "/**\n * Checks if `value` is `undefined`.\n *\n * @static\n * @since 0.1.0\n * @memberOf _\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is `undefined`, else `false`.\n * @example\n *\n * _.isUndefined(void 0);\n * // => true\n *\n * _.isUndefined(null);\n * // => false\n */\nfunction isUndefined(value) {\n return value === undefined;\n}\n\nexport default isUndefined;\n", "/** Error message constants. */\nvar FUNC_ERROR_TEXT = 'Expected a function';\n\n/**\n * Creates a function that negates the result of the predicate `func`. The\n * `func` predicate is invoked with the `this` binding and arguments of the\n * created function.\n *\n * @static\n * @memberOf _\n * @since 3.0.0\n * @category Function\n * @param {Function} predicate The predicate to negate.\n * @returns {Function} Returns the new negated function.\n * @example\n *\n * function isEven(n) {\n * return n % 2 == 0;\n * }\n *\n * _.filter([1, 2, 3, 4, 5, 6], _.negate(isEven));\n * // => [1, 3, 5]\n */\nfunction negate(predicate) {\n if (typeof predicate != 'function') {\n throw new TypeError(FUNC_ERROR_TEXT);\n }\n return function() {\n var args = arguments;\n switch (args.length) {\n case 0: return !predicate.call(this);\n case 1: return !predicate.call(this, args[0]);\n case 2: return !predicate.call(this, args[0], args[1]);\n case 3: return !predicate.call(this, args[0], args[1], args[2]);\n }\n return !predicate.apply(this, args);\n };\n}\n\nexport default negate;\n", "import assignValue from './_assignValue.js';\nimport castPath from './_castPath.js';\nimport isIndex from './_isIndex.js';\nimport isObject from './isObject.js';\nimport toKey from './_toKey.js';\n\n/**\n * The base implementation of `_.set`.\n *\n * @private\n * @param {Object} object The object to modify.\n * @param {Array|string} path The path of the property to set.\n * @param {*} value The value to set.\n * @param {Function} [customizer] The function to customize path creation.\n * @returns {Object} Returns `object`.\n */\nfunction baseSet(object, path, value, customizer) {\n if (!isObject(object)) {\n return object;\n }\n path = castPath(path, object);\n\n var index = -1,\n length = path.length,\n lastIndex = length - 1,\n nested = object;\n\n while (nested != null && ++index < length) {\n var key = toKey(path[index]),\n newValue = value;\n\n if (key === '__proto__' || key === 'constructor' || key === 'prototype') {\n return object;\n }\n\n if (index != lastIndex) {\n var objValue = nested[key];\n newValue = customizer ? customizer(objValue, key, nested) : undefined;\n if (newValue === undefined) {\n newValue = isObject(objValue)\n ? objValue\n : (isIndex(path[index + 1]) ? [] : {});\n }\n }\n assignValue(nested, key, newValue);\n nested = nested[key];\n }\n return object;\n}\n\nexport default baseSet;\n", "import baseGet from './_baseGet.js';\nimport baseSet from './_baseSet.js';\nimport castPath from './_castPath.js';\n\n/**\n * The base implementation of `_.pickBy` without support for iteratee shorthands.\n *\n * @private\n * @param {Object} object The source object.\n * @param {string[]} paths The property paths to pick.\n * @param {Function} predicate The function invoked per property.\n * @returns {Object} Returns the new object.\n */\nfunction basePickBy(object, paths, predicate) {\n var index = -1,\n length = paths.length,\n result = {};\n\n while (++index < length) {\n var path = paths[index],\n value = baseGet(object, path);\n\n if (predicate(value, path)) {\n baseSet(result, castPath(path, object), value);\n }\n }\n return result;\n}\n\nexport default basePickBy;\n", "import arrayMap from './_arrayMap.js';\nimport baseIteratee from './_baseIteratee.js';\nimport basePickBy from './_basePickBy.js';\nimport getAllKeysIn from './_getAllKeysIn.js';\n\n/**\n * Creates an object composed of the `object` properties `predicate` returns\n * truthy for. The predicate is invoked with two arguments: (value, key).\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Object\n * @param {Object} object The source object.\n * @param {Function} [predicate=_.identity] The function invoked per property.\n * @returns {Object} Returns the new object.\n * @example\n *\n * var object = { 'a': 1, 'b': '2', 'c': 3 };\n *\n * _.pickBy(object, _.isNumber);\n * // => { 'a': 1, 'c': 3 }\n */\nfunction pickBy(object, predicate) {\n if (object == null) {\n return {};\n }\n var props = arrayMap(getAllKeysIn(object), function(prop) {\n return [prop];\n });\n predicate = baseIteratee(predicate);\n return basePickBy(object, props, function(value, path) {\n return predicate(value, path[0]);\n });\n}\n\nexport default pickBy;\n", "/**\n * The base implementation of `_.reduce` and `_.reduceRight`, without support\n * for iteratee shorthands, which iterates over `collection` using `eachFunc`.\n *\n * @private\n * @param {Array|Object} collection The collection to iterate over.\n * @param {Function} iteratee The function invoked per iteration.\n * @param {*} accumulator The initial value.\n * @param {boolean} initAccum Specify using the first or last element of\n * `collection` as the initial value.\n * @param {Function} eachFunc The function to iterate over `collection`.\n * @returns {*} Returns the accumulated value.\n */\nfunction baseReduce(collection, iteratee, accumulator, initAccum, eachFunc) {\n eachFunc(collection, function(value, index, collection) {\n accumulator = initAccum\n ? (initAccum = false, value)\n : iteratee(accumulator, value, index, collection);\n });\n return accumulator;\n}\n\nexport default baseReduce;\n", "import arrayReduce from './_arrayReduce.js';\nimport baseEach from './_baseEach.js';\nimport baseIteratee from './_baseIteratee.js';\nimport baseReduce from './_baseReduce.js';\nimport isArray from './isArray.js';\n\n/**\n * Reduces `collection` to a value which is the accumulated result of running\n * each element in `collection` thru `iteratee`, where each successive\n * invocation is supplied the return value of the previous. If `accumulator`\n * is not given, the first element of `collection` is used as the initial\n * value. The iteratee is invoked with four arguments:\n * (accumulator, value, index|key, collection).\n *\n * Many lodash methods are guarded to work as iteratees for methods like\n * `_.reduce`, `_.reduceRight`, and `_.transform`.\n *\n * The guarded methods are:\n * `assign`, `defaults`, `defaultsDeep`, `includes`, `merge`, `orderBy`,\n * and `sortBy`\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @category Collection\n * @param {Array|Object} collection The collection to iterate over.\n * @param {Function} [iteratee=_.identity] The function invoked per iteration.\n * @param {*} [accumulator] The initial value.\n * @returns {*} Returns the accumulated value.\n * @see _.reduceRight\n * @example\n *\n * _.reduce([1, 2], function(sum, n) {\n * return sum + n;\n * }, 0);\n * // => 3\n *\n * _.reduce({ 'a': 1, 'b': 2, 'c': 1 }, function(result, value, key) {\n * (result[value] || (result[value] = [])).push(key);\n * return result;\n * }, {});\n * // => { '1': ['a', 'c'], '2': ['b'] } (iteration order is not guaranteed)\n */\nfunction reduce(collection, iteratee, accumulator) {\n var func = isArray(collection) ? arrayReduce : baseReduce,\n initAccum = arguments.length < 3;\n\n return func(collection, baseIteratee(iteratee, 4), accumulator, initAccum, baseEach);\n}\n\nexport default reduce;\n", "import arrayFilter from './_arrayFilter.js';\nimport baseFilter from './_baseFilter.js';\nimport baseIteratee from './_baseIteratee.js';\nimport isArray from './isArray.js';\nimport negate from './negate.js';\n\n/**\n * The opposite of `_.filter`; this method returns the elements of `collection`\n * that `predicate` does **not** return truthy for.\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @category Collection\n * @param {Array|Object} collection The collection to iterate over.\n * @param {Function} [predicate=_.identity] The function invoked per iteration.\n * @returns {Array} Returns the new filtered array.\n * @see _.filter\n * @example\n *\n * var users = [\n * { 'user': 'barney', 'age': 36, 'active': false },\n * { 'user': 'fred', 'age': 40, 'active': true }\n * ];\n *\n * _.reject(users, function(o) { return !o.active; });\n * // => objects for ['fred']\n *\n * // The `_.matches` iteratee shorthand.\n * _.reject(users, { 'age': 40, 'active': true });\n * // => objects for ['barney']\n *\n * // The `_.matchesProperty` iteratee shorthand.\n * _.reject(users, ['active', false]);\n * // => objects for ['fred']\n *\n * // The `_.property` iteratee shorthand.\n * _.reject(users, 'active');\n * // => objects for ['barney']\n */\nfunction reject(collection, predicate) {\n var func = isArray(collection) ? arrayFilter : baseFilter;\n return func(collection, negate(baseIteratee(predicate, 3)));\n}\n\nexport default reject;\n", "import baseEach from './_baseEach.js';\n\n/**\n * The base implementation of `_.some` without support for iteratee shorthands.\n *\n * @private\n * @param {Array|Object} collection The collection to iterate over.\n * @param {Function} predicate The function invoked per iteration.\n * @returns {boolean} Returns `true` if any element passes the predicate check,\n * else `false`.\n */\nfunction baseSome(collection, predicate) {\n var result;\n\n baseEach(collection, function(value, index, collection) {\n result = predicate(value, index, collection);\n return !result;\n });\n return !!result;\n}\n\nexport default baseSome;\n", "import arraySome from './_arraySome.js';\nimport baseIteratee from './_baseIteratee.js';\nimport baseSome from './_baseSome.js';\nimport isArray from './isArray.js';\nimport isIterateeCall from './_isIterateeCall.js';\n\n/**\n * Checks if `predicate` returns truthy for **any** element of `collection`.\n * Iteration is stopped once `predicate` returns truthy. The predicate is\n * invoked with three arguments: (value, index|key, collection).\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @category Collection\n * @param {Array|Object} collection The collection to iterate over.\n * @param {Function} [predicate=_.identity] The function invoked per iteration.\n * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`.\n * @returns {boolean} Returns `true` if any element passes the predicate check,\n * else `false`.\n * @example\n *\n * _.some([null, 0, 'yes', false], Boolean);\n * // => true\n *\n * var users = [\n * { 'user': 'barney', 'active': true },\n * { 'user': 'fred', 'active': false }\n * ];\n *\n * // The `_.matches` iteratee shorthand.\n * _.some(users, { 'user': 'barney', 'active': false });\n * // => false\n *\n * // The `_.matchesProperty` iteratee shorthand.\n * _.some(users, ['active', false]);\n * // => true\n *\n * // The `_.property` iteratee shorthand.\n * _.some(users, 'active');\n * // => true\n */\nfunction some(collection, predicate, guard) {\n var func = isArray(collection) ? arraySome : baseSome;\n if (guard && isIterateeCall(collection, predicate, guard)) {\n predicate = undefined;\n }\n return func(collection, baseIteratee(predicate, 3));\n}\n\nexport default some;\n", "import Set from './_Set.js';\nimport noop from './noop.js';\nimport setToArray from './_setToArray.js';\n\n/** Used as references for various `Number` constants. */\nvar INFINITY = 1 / 0;\n\n/**\n * Creates a set object of `values`.\n *\n * @private\n * @param {Array} values The values to add to the set.\n * @returns {Object} Returns the new set.\n */\nvar createSet = !(Set && (1 / setToArray(new Set([,-0]))[1]) == INFINITY) ? noop : function(values) {\n return new Set(values);\n};\n\nexport default createSet;\n", "import SetCache from './_SetCache.js';\nimport arrayIncludes from './_arrayIncludes.js';\nimport arrayIncludesWith from './_arrayIncludesWith.js';\nimport cacheHas from './_cacheHas.js';\nimport createSet from './_createSet.js';\nimport setToArray from './_setToArray.js';\n\n/** Used as the size to enable large array optimizations. */\nvar LARGE_ARRAY_SIZE = 200;\n\n/**\n * The base implementation of `_.uniqBy` without support for iteratee shorthands.\n *\n * @private\n * @param {Array} array The array to inspect.\n * @param {Function} [iteratee] The iteratee invoked per element.\n * @param {Function} [comparator] The comparator invoked per element.\n * @returns {Array} Returns the new duplicate free array.\n */\nfunction baseUniq(array, iteratee, comparator) {\n var index = -1,\n includes = arrayIncludes,\n length = array.length,\n isCommon = true,\n result = [],\n seen = result;\n\n if (comparator) {\n isCommon = false;\n includes = arrayIncludesWith;\n }\n else if (length >= LARGE_ARRAY_SIZE) {\n var set = iteratee ? null : createSet(array);\n if (set) {\n return setToArray(set);\n }\n isCommon = false;\n includes = cacheHas;\n seen = new SetCache;\n }\n else {\n seen = iteratee ? [] : result;\n }\n outer:\n while (++index < length) {\n var value = array[index],\n computed = iteratee ? iteratee(value) : value;\n\n value = (comparator || value !== 0) ? value : 0;\n if (isCommon && computed === computed) {\n var seenIndex = seen.length;\n while (seenIndex--) {\n if (seen[seenIndex] === computed) {\n continue outer;\n }\n }\n if (iteratee) {\n seen.push(computed);\n }\n result.push(value);\n }\n else if (!includes(seen, computed, comparator)) {\n if (seen !== result) {\n seen.push(computed);\n }\n result.push(value);\n }\n }\n return result;\n}\n\nexport default baseUniq;\n", "import baseUniq from './_baseUniq.js';\n\n/**\n * Creates a duplicate-free version of an array, using\n * [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero)\n * for equality comparisons, in which only the first occurrence of each element\n * is kept. The order of result values is determined by the order they occur\n * in the array.\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @category Array\n * @param {Array} array The array to inspect.\n * @returns {Array} Returns the new duplicate free array.\n * @example\n *\n * _.uniq([2, 1, 2]);\n * // => [2, 1]\n */\nfunction uniq(array) {\n return (array && array.length) ? baseUniq(array) : [];\n}\n\nexport default uniq;\n", "export function PRINT_ERROR(msg: string) {\n /* istanbul ignore else - can't override global.console in node.js */\n if (console && console.error) {\n console.error(`Error: ${msg}`);\n }\n}\n\nexport function PRINT_WARNING(msg: string) {\n /* istanbul ignore else - can't override global.console in node.js*/\n if (console && console.warn) {\n // TODO: modify docs accordingly\n console.warn(`Warning: ${msg}`);\n }\n}\n", "export function timer<T>(func: () => T): { time: number; value: T } {\n const start = new Date().getTime();\n const val = func();\n const end = new Date().getTime();\n const total = end - start;\n return { time: total, value: val };\n}\n", "// based on: https://github.com/petkaantonov/bluebird/blob/b97c0d2d487e8c5076e8bd897e0dcd4622d31846/src/util.js#L201-L216\nexport function toFastProperties(toBecomeFast: any) {\n function FakeConstructor() {}\n\n // If our object is used as a constructor, it would receive\n FakeConstructor.prototype = toBecomeFast;\n const fakeInstance = new (FakeConstructor as any)();\n\n function fakeAccess() {\n return typeof fakeInstance.bar;\n }\n\n // help V8 understand this is a \"real\" prototype by actually using\n // the fake instance.\n fakeAccess();\n fakeAccess();\n\n // Always true condition to suppress the Firefox warning of unreachable\n // code after a return statement.\n if (1) return toBecomeFast;\n\n // Eval prevents optimization of this method (even though this is dead code)\n // - https://esbuild.github.io/content-types/#direct-eval\n /* istanbul ignore next */\n // tslint:disable-next-line\n (0, eval)(toBecomeFast);\n}\n", "import { assign, forEach, isRegExp, isString, map, pickBy } from \"lodash-es\";\nimport type {\n IGASTVisitor,\n IProduction,\n IProductionWithOccurrence,\n ISerializedGast,\n TokenType,\n} from \"@chevrotain/types\";\n\n// TODO: duplicated code to avoid extracting another sub-package -- how to avoid?\nfunction tokenLabel(tokType: TokenType): string {\n if (hasTokenLabel(tokType)) {\n return tokType.LABEL;\n } else {\n return tokType.name;\n }\n}\n\n// TODO: duplicated code to avoid extracting another sub-package -- how to avoid?\nfunction hasTokenLabel(\n obj: TokenType,\n): obj is TokenType & Pick<Required<TokenType>, \"LABEL\"> {\n return isString(obj.LABEL) && obj.LABEL !== \"\";\n}\n\nexport abstract class AbstractProduction<\n T extends IProduction = IProduction,\n> implements IProduction {\n public get definition(): T[] {\n return this._definition;\n }\n public set definition(value: T[]) {\n this._definition = value;\n }\n\n constructor(protected _definition: T[]) {}\n\n accept(visitor: IGASTVisitor): void {\n visitor.visit(this);\n forEach(this.definition, (prod) => {\n prod.accept(visitor);\n });\n }\n}\n\nexport class NonTerminal\n extends AbstractProduction\n implements IProductionWithOccurrence\n{\n public nonTerminalName!: string;\n public label?: string;\n public referencedRule!: Rule;\n public idx: number = 1;\n\n constructor(options: {\n nonTerminalName: string;\n label?: string;\n referencedRule?: Rule;\n idx?: number;\n }) {\n super([]);\n assign(\n this,\n pickBy(options, (v) => v !== undefined),\n );\n }\n\n set definition(definition: IProduction[]) {\n // immutable\n }\n\n get definition(): IProduction[] {\n if (this.referencedRule !== undefined) {\n return this.referencedRule.definition;\n }\n return [];\n }\n\n accept(visitor: IGASTVisitor): void {\n visitor.visit(this);\n // don't visit children of a reference, we will get cyclic infinite loops if we do so\n }\n}\n\nexport class Rule extends AbstractProduction {\n public name!: string;\n public orgText: string = \"\";\n\n constructor(options: {\n name: string;\n definition: IProduction[];\n orgText?: string;\n }) {\n super(options.definition);\n assign(\n this,\n pickBy(options, (v) => v !== undefined),\n );\n }\n}\n\nexport class Alternative extends AbstractProduction {\n public ignoreAmbiguities: boolean = false;\n\n constructor(options: {\n definition: IProduction[];\n ignoreAmbiguities?: boolean;\n }) {\n super(options.definition);\n assign(\n this,\n pickBy(options, (v) => v !== undefined),\n );\n }\n}\n\nexport class Option\n extends AbstractProduction\n implements IProductionWithOccurrence\n{\n public idx: number = 1;\n public maxLookahead?: number;\n\n constructor(options: {\n definition: IProduction[];\n idx?: number;\n maxLookahead?: number;\n }) {\n super(options.definition);\n assign(\n this,\n pickBy(options, (v) => v !== undefined),\n );\n }\n}\n\nexport class RepetitionMandatory\n extends AbstractProduction\n implements IProductionWithOccurrence\n{\n public idx: number = 1;\n public maxLookahead?: number;\n\n constructor(options: {\n definition: IProduction[];\n idx?: number;\n maxLookahead?: number;\n }) {\n super(options.definition);\n assign(\n this,\n pickBy(options, (v) => v !== undefined),\n );\n }\n}\n\nexport class RepetitionMandatoryWithSeparator\n extends AbstractProduction\n implements IProductionWithOccurrence\n{\n public separator!: TokenType;\n public idx: number = 1;\n public maxLookahead?: number;\n\n constructor(options: {\n definition: IProduction[];\n separator: TokenType;\n idx?: number;\n }) {\n super(options.definition);\n assign(\n this,\n pickBy(options, (v) => v !== undefined),\n );\n }\n}\n\nexport class Repetition\n extends AbstractProduction\n implements IProductionWithOccurrence\n{\n public separator!: TokenType;\n public idx: number = 1;\n public maxLookahead?: number;\n\n constructor(options: {\n definition: IProduction[];\n idx?: number;\n maxLookahead?: number;\n }) {\n super(options.definition);\n assign(\n this,\n pickBy(options, (v) => v !== undefined),\n );\n }\n}\n\nexport class RepetitionWithSeparator\n extends AbstractProduction\n implements IProductionWithOccurrence\n{\n public separator!: TokenType;\n public idx: number = 1;\n public maxLookahead?: number;\n\n constructor(options: {\n definition: IProduction[];\n separator: TokenType;\n idx?: number;\n }) {\n super(options.definition);\n assign(\n this,\n pickBy(options, (v) => v !== undefined),\n );\n }\n}\n\nexport class Alternation\n extends AbstractProduction<Alternative>\n implements IProductionWithOccurrence\n{\n public idx: number = 1;\n public ignoreAmbiguities: boolean = false;\n public hasPredicates: boolean = false;\n public maxLookahead?: number;\n\n public get definition(): Alternative[] {\n return this._definition;\n }\n public set definition(value: Alternative[]) {\n this._definition = value;\n }\n\n constructor(options: {\n definition: Alternative[];\n idx?: number;\n ignoreAmbiguities?: boolean;\n hasPredicates?: boolean;\n maxLookahead?: number;\n }) {\n super(options.definition);\n assign(\n this,\n pickBy(options, (v) => v !== undefined),\n );\n }\n}\n\nexport class Terminal implements IProductionWithOccurrence {\n public terminalType!: TokenType;\n public label?: string;\n public idx: number = 1;\n\n constructor(options: {\n terminalType: TokenType;\n label?: string;\n idx?: number;\n }) {\n assign(\n this,\n pickBy(options, (v) => v !== undefined),\n );\n }\n\n accept(visitor: IGASTVisitor): void {\n visitor.visit(this);\n }\n}\n\nexport interface ISerializedBasic extends ISerializedGast {\n type:\n | \"Alternative\"\n | \"Option\"\n | \"RepetitionMandatory\"\n | \"Repetition\"\n | \"Alternation\";\n idx?: number;\n}\n\nexport interface ISerializedGastRule extends ISerializedGast {\n type: \"Rule\";\n name: string;\n orgText: string;\n}\n\nexport interface ISerializedNonTerminal extends ISerializedGast {\n type: \"NonTerminal\";\n name: string;\n label?: string;\n idx: number;\n}\n\nexport interface ISerializedTerminal extends ISerializedGast {\n type: \"Terminal\";\n name: string;\n terminalLabel?: string;\n label?: string;\n pattern?: string;\n idx: number;\n}\n\nexport interface ISerializedTerminalWithSeparator extends ISerializedGast {\n type: \"RepetitionMandatoryWithSeparator\" | \"RepetitionWithSeparator\";\n idx: number;\n separator: ISerializedTerminal;\n}\n\nexport type ISerializedGastAny =\n | ISerializedBasic\n | ISerializedGastRule\n | ISerializedNonTerminal\n | ISerializedTerminal\n | ISerializedTerminalWithSeparator;\n\nexport function serializeGrammar(topRules: Rule[]): ISerializedGast[] {\n return map(topRules, serializeProduction);\n}\n\nexport function serializeProduction(node: IProduction): ISerializedGast {\n function convertDefinition(definition: IProduction[]): ISerializedGast[] {\n return map(definition, serializeProduction);\n }\n /* istanbul ignore else */\n if (node instanceof NonTerminal) {\n const serializedNonTerminal: ISerializedNonTerminal = {\n type: \"NonTerminal\",\n name: node.nonTerminalName,\n idx: node.idx,\n };\n\n if (isString(node.label)) {\n serializedNonTerminal.label = node.label;\n }\n\n return serializedNonTerminal;\n } else if (node instanceof Alternative) {\n return <ISerializedBasic>{\n type: \"Alternative\",\n definition: convertDefinition(node.definition),\n };\n } else if (node instanceof Option) {\n return <ISerializedBasic>{\n type: \"Option\",\n idx: node.idx,\n definition: convertDefinition(node.definition),\n };\n } else if (node instanceof RepetitionMandatory) {\n return <ISerializedBasic>{\n type: \"RepetitionMandatory\",\n idx: node.idx,\n definition: convertDefinition(node.definition),\n };\n } else if (node instanceof RepetitionMandatoryWithSeparator) {\n return <ISerializedTerminalWithSeparator>{\n type: \"RepetitionMandatoryWithSeparator\",\n idx: node.idx,\n separator: <ISerializedTerminal>(\n serializeProduction(new Terminal({ terminalType: node.separator }))\n ),\n definition: convertDefinition(node.definition),\n };\n } else if (node instanceof RepetitionWithSeparator) {\n return <ISerializedTerminalWithSeparator>{\n type: \"RepetitionWithSeparator\",\n idx: node.idx,\n separator: <ISerializedTerminal>(\n serializeProduction(new Terminal({ terminalType: node.separator }))\n ),\n definition: convertDefinition(node.definition),\n };\n } else if (node instanceof Repetition) {\n return <ISerializedBasic>{\n type: \"Repetition\",\n idx: node.idx,\n definition: convertDefinition(node.definition),\n };\n } else if (node instanceof Alternation) {\n return <ISerializedBasic>{\n type: \"Alternation\",\n idx: node.idx,\n definition: convertDefinition(node.definition),\n };\n } else if (node instanceof Terminal) {\n const serializedTerminal = <ISerializedTerminal>{\n type: \"Terminal\",\n name: node.terminalType.name,\n label: tokenLabel(node.terminalType),\n idx: node.idx,\n };\n\n if (isString(node.label)) {\n serializedTerminal.terminalLabel = node.label;\n }\n\n const pattern = node.terminalType.PATTERN;\n if (node.terminalType.PATTERN) {\n serializedTerminal.pattern = isRegExp(pattern)\n ? (<any>pattern).source\n : pattern;\n }\n\n return serializedTerminal;\n } else if (node instanceof Rule) {\n return <ISerializedGastRule>{\n type: \"Rule\",\n name: node.name,\n orgText: node.orgText,\n definition: convertDefinition(node.definition),\n };\n /* c8 ignore next 3 */\n } else {\n throw Error(\"non exhaustive match\");\n }\n}\n", "import {\n Alternation,\n Alternative,\n NonTerminal,\n Option,\n Repetition,\n RepetitionMandatory,\n RepetitionMandatoryWithSeparator,\n RepetitionWithSeparator,\n Rule,\n Terminal,\n} from \"./model.js\";\nimport type { IProduction } from \"@chevrotain/types\";\n\nexport abstract class GAstVisitor {\n public visit(node: IProduction): any {\n const nodeAny: any = node;\n switch (nodeAny.constructor) {\n case NonTerminal:\n return this.visitNonTerminal(nodeAny);\n case Alternative:\n return this.visitAlternative(nodeAny);\n case Option:\n return this.visitOption(nodeAny);\n case RepetitionMandatory:\n return this.visitRepetitionMandatory(nodeAny);\n case RepetitionMandatoryWithSeparator:\n return this.visitRepetitionMandatoryWithSeparator(nodeAny);\n case RepetitionWithSeparator:\n return this.visitRepetitionWithSeparator(nodeAny);\n case Repetition:\n return this.visitRepetition(nodeAny);\n case Alternation:\n return this.visitAlternation(nodeAny);\n case Terminal:\n return this.visitTerminal(nodeAny);\n case Rule:\n return this.visitRule(nodeAny);\n /* c8 ignore next 2 */\n default:\n throw Error(\"non exhaustive match\");\n }\n }\n\n /* c8 ignore next */\n public visitNonTerminal(node: NonTerminal): any {}\n\n /* c8 ignore next */\n public visitAlternative(node: Alternative): any {}\n\n /* c8 ignore next */\n public visitOption(node: Option): any {}\n\n /* c8 ignore next */\n public visitRepetition(node: Repetition): any {}\n\n /* c8 ignore next */\n public visitRepetitionMandatory(node: RepetitionMandatory): any {}\n\n /* c8 ignore next 3 */\n public visitRepetitionMandatoryWithSeparator(\n node: RepetitionMandatoryWithSeparator,\n ): any {}\n\n /* c8 ignore next */\n public visitRepetitionWithSeparator(node: RepetitionWithSeparator): any {}\n\n /* c8 ignore next */\n public visitAlternation(node: Alternation): any {}\n\n /* c8 ignore next */\n public visitTerminal(node: Terminal): any {}\n\n /* c8 ignore next */\n public visitRule(node: Rule): any {}\n}\n", "import { every, includes, some } from \"lodash-es\";\nimport {\n AbstractProduction,\n Alternation,\n Alternative,\n NonTerminal,\n Option,\n Repetition,\n RepetitionMandatory,\n RepetitionMandatoryWithSeparator,\n RepetitionWithSeparator,\n Rule,\n Terminal,\n} from \"./model.js\";\nimport type { IProduction, IProductionWithOccurrence } from \"@chevrotain/types\";\n\nexport function isSequenceProd(\n prod: IProduction,\n): prod is { definition: IProduction[] } & IProduction {\n return (\n prod instanceof Alternative ||\n prod instanceof Option ||\n prod instanceof Repetition ||\n prod instanceof RepetitionMandatory ||\n prod instanceof RepetitionMandatoryWithSeparator ||\n prod instanceof RepetitionWithSeparator ||\n prod instanceof Terminal ||\n prod instanceof Rule\n );\n}\n\nexport function isOptionalProd(\n prod: IProduction,\n alreadyVisited: NonTerminal[] = [],\n): boolean {\n const isDirectlyOptional =\n prod instanceof Option ||\n prod instanceof Repetition ||\n prod instanceof RepetitionWithSeparator;\n if (isDirectlyOptional) {\n return true;\n }\n\n // note that this can cause infinite loop if one optional empty TOP production has a cyclic dependency with another\n // empty optional top rule\n // may be indirectly optional ((A?B?C?) | (D?E?F?))\n if (prod instanceof Alternation) {\n // for OR its enough for just one of the alternatives to be optional\n return some((<Alternation>prod).definition, (subProd: IProduction) => {\n return isOptionalProd(subProd, alreadyVisited);\n });\n } else if (prod instanceof NonTerminal && includes(alreadyVisited, prod)) {\n // avoiding stack overflow due to infinite recursion\n return false;\n } else if (prod instanceof AbstractProduction) {\n if (prod instanceof NonTerminal) {\n alreadyVisited.push(prod);\n }\n return every(\n (<AbstractProduction>prod).definition,\n (subProd: IProduction) => {\n return isOptionalProd(subProd, alreadyVisited);\n },\n );\n } else {\n return false;\n }\n}\n\nexport function isBranchingProd(\n prod: IProduction,\n): prod is { definition: IProduction[] } & IProduction {\n return prod instanceof Alternation;\n}\n\nexport function getProductionDslName(prod: IProductionWithOccurrence): string {\n /* istanbul ignore else */\n if (prod instanceof NonTerminal) {\n return \"SUBRULE\";\n } else if (prod instanceof Option) {\n return \"OPTION\";\n } else if (prod instanceof Alternation) {\n return \"OR\";\n } else if (prod instanceof RepetitionMandatory) {\n return \"AT_LEAST_ONE\";\n } else if (prod instanceof RepetitionMandatoryWithSeparator) {\n return \"AT_LEAST_ONE_SEP\";\n } else if (prod instanceof RepetitionWithSeparator) {\n return \"MANY_SEP\";\n } else if (prod instanceof Repetition) {\n return \"MANY\";\n } else if (prod instanceof Terminal) {\n return \"CONSUME\";\n /* c8 ignore next 3 */\n } else {\n throw Error(\"non exhaustive match\");\n }\n}\n", "import { drop, forEach } from \"lodash-es\";\nimport {\n Alternation,\n Alternative,\n NonTerminal,\n Option,\n Repetition,\n RepetitionMandatory,\n RepetitionMandatoryWithSeparator,\n RepetitionWithSeparator,\n Terminal,\n} from \"@chevrotain/gast\";\nimport { IProduction } from \"@chevrotain/types\";\n\n/**\n * A Grammar Walker that computes the \"remaining\" grammar \"after\" a productions in the grammar.\n */\nexport abstract class RestWalker {\n walk(prod: { definition: IProduction[] }, prevRest: any[] = []): void {\n forEach(prod.definition, (subProd: IProduction, index) => {\n const currRest = drop(prod.definition, index + 1);\n /* istanbul ignore else */\n if (subProd instanceof NonTerminal) {\n this.walkProdRef(subProd, currRest, prevRest);\n } else if (subProd instanceof Terminal) {\n this.walkTerminal(subProd, currRest, prevRest);\n } else if (subProd instanceof Alternative) {\n this.walkFlat(subProd, currRest, prevRest);\n } else if (subProd instanceof Option) {\n this.walkOption(subProd, currRest, prevRest);\n } else if (subProd instanceof RepetitionMandatory) {\n this.walkAtLeastOne(subProd, currRest, prevRest);\n } else if (subProd instanceof RepetitionMandatoryWithSeparator) {\n this.walkAtLeastOneSep(subProd, currRest, prevRest);\n } else if (subProd instanceof RepetitionWithSeparator) {\n this.walkManySep(subProd, currRest, prevRest);\n } else if (subProd instanceof Repetition) {\n this.walkMany(subProd, currRest, prevRest);\n } else if (subProd instanceof Alternation) {\n this.walkOr(subProd, currRest, prevRest);\n } else {\n throw Error(\"non exhaustive match\");\n }\n });\n }\n\n walkTerminal(\n terminal: Terminal,\n currRest: IProduction[],\n prevRest: IProduction[],\n ): void {}\n\n walkProdRef(\n refProd: NonTerminal,\n currRest: IProduction[],\n prevRest: IProduction[],\n ): void {}\n\n walkFlat(\n flatProd: Alternative,\n currRest: IProduction[],\n prevRest: IProduction[],\n ): void {\n // ABCDEF => after the D the rest is EF\n const fullOrRest = currRest.concat(prevRest);\n this.walk(flatProd, <any>fullOrRest);\n }\n\n walkOption(\n optionProd: Option,\n currRest: IProduction[],\n prevRest: IProduction[],\n ): void {\n // ABC(DE)?F => after the (DE)? the rest is F\n const fullOrRest = currRest.concat(prevRest);\n this.walk(optionProd, <any>fullOrRest);\n }\n\n walkAtLeastOne(\n atLeastOneProd: RepetitionMandatory,\n currRest: IProduction[],\n prevRest: IProduction[],\n ): void {\n // ABC(DE)+F => after the (DE)+ the rest is (DE)?F\n const fullAtLeastOneRest: IProduction[] = [\n new Option({ definition: atLeastOneProd.definition }),\n ].concat(<any>currRest, <any>prevRest);\n this.walk(atLeastOneProd, fullAtLeastOneRest);\n }\n\n walkAtLeastOneSep(\n atLeastOneSepProd: RepetitionMandatoryWithSeparator,\n currRest: IProduction[],\n prevRest: IProduction[],\n ): void {\n // ABC DE(,DE)* F => after the (,DE)+ the rest is (,DE)?F\n const fullAtLeastOneSepRest = restForRepetitionWithSeparator(\n atLeastOneSepProd,\n currRest,\n prevRest,\n );\n this.walk(atLeastOneSepProd, fullAtLeastOneSepRest);\n }\n\n walkMany(\n manyProd: Repetition,\n currRest: IProduction[],\n prevRest: IProduction[],\n ): void {\n // ABC(DE)*F => after the (DE)* the rest is (DE)?F\n const fullManyRest: IProduction[] = [\n new Option({ definition: manyProd.definition }),\n ].concat(<any>currRest, <any>prevRest);\n this.walk(manyProd, fullManyRest);\n }\n\n walkManySep(\n manySepProd: RepetitionWithSeparator,\n currRest: IProduction[],\n prevRest: IProduction[],\n ): void {\n // ABC (DE(,DE)*)? F => after the (,DE)* the rest is (,DE)?F\n const fullManySepRest = restForRepetitionWithSeparator(\n manySepProd,\n currRest,\n prevRest,\n );\n this.walk(manySepProd, fullManySepRest);\n }\n\n walkOr(\n orProd: Alternation,\n currRest: IProduction[],\n prevRest: IProduction[],\n ): void {\n // ABC(D|E|F)G => when finding the (D|E|F) the rest is G\n const fullOrRest = currRest.concat(prevRest);\n // walk all different alternatives\n forEach(orProd.definition, (alt) => {\n // wrapping each alternative in a single definition wrapper\n // to avoid errors in computing the rest of that alternative in the invocation to computeInProdFollows\n // (otherwise for OR([alt1,alt2]) alt2 will be considered in 'rest' of alt1\n const prodWrapper = new Alternative({ definition: [alt] });\n this.walk(prodWrapper, <any>fullOrRest);\n });\n }\n}\n\nfunction restForRepetitionWithSeparator(\n repSepProd: RepetitionWithSeparator,\n currRest: IProduction[],\n prevRest: IProduction[],\n) {\n const repSepRest = [\n new Option({\n definition: [\n new Terminal({ terminalType: repSepProd.separator }) as IProduction,\n ].concat(repSepProd.definition),\n }) as IProduction,\n ];\n const fullRepSepRest: IProduction[] = repSepRest.concat(currRest, prevRest);\n return fullRepSepRest;\n}\n", "import { flatten, map, uniq } from \"lodash-es\";\nimport {\n isBranchingProd,\n isOptionalProd,\n isSequenceProd,\n NonTerminal,\n Terminal,\n} from \"@chevrotain/gast\";\nimport { IProduction, TokenType } from \"@chevrotain/types\";\n\nexport function first(prod: IProduction): TokenType[] {\n /* istanbul ignore else */\n if (prod instanceof NonTerminal) {\n // this could in theory cause infinite loops if\n // (1) prod A refs prod B.\n // (2) prod B refs prod A\n // (3) AB can match the empty set\n // in other words a cycle where everything is optional so the first will keep\n // looking ahead for the next optional part and will never exit\n // currently there is no safeguard for this unique edge case because\n // (1) not sure a grammar in which this can happen is useful for anything (productive)\n return first((<NonTerminal>prod).referencedRule);\n } else if (prod instanceof Terminal) {\n return firstForTerminal(<Terminal>prod);\n } else if (isSequenceProd(prod)) {\n return firstForSequence(prod);\n } else if (isBranchingProd(prod)) {\n return firstForBranching(prod);\n } else {\n throw Error(\"non exhaustive match\");\n }\n}\n\nexport function firstForSequence(prod: {\n definition: IProduction[];\n}): TokenType[] {\n let firstSet: TokenType[] = [];\n const seq = prod.definition;\n let nextSubProdIdx = 0;\n let hasInnerProdsRemaining = seq.length > nextSubProdIdx;\n let currSubProd;\n // so we enter the loop at least once (if the definition is not empty\n let isLastInnerProdOptional = true;\n // scan a sequence until it's end or until we have found a NONE optional production in it\n while (hasInnerProdsRemaining && isLastInnerProdOptional) {\n currSubProd = seq[nextSubProdIdx];\n isLastInnerProdOptional = isOptionalProd(currSubProd);\n firstSet = firstSet.concat(first(currSubProd));\n nextSubProdIdx = nextSubProdIdx + 1;\n hasInnerProdsRemaining = seq.length > nextSubProdIdx;\n }\n\n return uniq(firstSet);\n}\n\nexport function firstForBranching(prod: {\n definition: IProduction[];\n}): TokenType[] {\n const allAlternativesFirsts: TokenType[][] = map(\n prod.definition,\n (innerProd) => {\n return first(innerProd);\n },\n );\n return uniq(flatten<TokenType>(allAlternativesFirsts));\n}\n\nexport function firstForTerminal(terminal: Terminal): TokenType[] {\n return [terminal.terminalType];\n}\n", "// TODO: can this be removed? where is it used?\nexport const IN = \"_~IN~_\";\n", "import { RestWalker } from \"./rest.js\";\nimport { first } from \"./first.js\";\nimport { assign, forEach } from \"lodash-es\";\nimport { IN } from \"../constants.js\";\nimport { Alternative, NonTerminal, Rule, Terminal } from \"@chevrotain/gast\";\nimport { IProduction, TokenType } from \"@chevrotain/types\";\n\n// This ResyncFollowsWalker computes all of the follows required for RESYNC\n// (skipping reference production).\nexport class ResyncFollowsWalker extends RestWalker {\n public follows: Record<string, TokenType[]> = {};\n\n constructor(private topProd: Rule) {\n super();\n }\n\n startWalking(): Record<string, TokenType[]> {\n this.walk(this.topProd);\n return this.follows;\n }\n\n walkTerminal(\n terminal: Terminal,\n currRest: IProduction[],\n prevRest: IProduction[],\n ): void {\n // do nothing! just like in the public sector after 13:00\n }\n\n walkProdRef(\n refProd: NonTerminal,\n currRest: IProduction[],\n prevRest: IProduction[],\n ): void {\n const followName =\n buildBetweenProdsFollowPrefix(refProd.referencedRule, refProd.idx) +\n this.topProd.name;\n const fullRest: IProduction[] = currRest.concat(prevRest);\n const restProd = new Alternative({ definition: fullRest });\n const t_in_topProd_follows = first(restProd);\n this.follows[followName] = t_in_topProd_follows;\n }\n}\n\nexport function computeAllProdsFollows(\n topProductions: Rule[],\n): Record<string, TokenType[]> {\n const reSyncFollows = {};\n\n forEach(topProductions, (topProd) => {\n const currRefsFollow = new ResyncFollowsWalker(topProd).startWalking();\n assign(reSyncFollows, currRefsFollow);\n });\n return reSyncFollows;\n}\n\nexport function buildBetweenProdsFollowPrefix(\n inner: Rule,\n occurenceInParent: number,\n): string {\n return inner.name + occurenceInParent + IN;\n}\n\nexport function buildInProdFollowPrefix(terminal: Terminal): string {\n const terminalName = terminal.terminalType.name;\n return terminalName + terminal.idx + IN;\n}\n", "import type { Character, IRegExpAST, RegExpFlags } from \"../types\";\n\nexport function cc(char: string): number {\n return char.charCodeAt(0);\n}\n\nexport function insertToSet<T>(item: T | T[], set: T[]) {\n if (Array.isArray(item)) {\n item.forEach(function (subItem) {\n set.push(subItem);\n });\n } else {\n set.push(item);\n }\n}\n\nexport function addFlag(\n flagObj: RegExpFlags,\n flagKey: keyof Omit<RegExpFlags, keyof IRegExpAST>,\n) {\n if (flagObj[flagKey] === true) {\n throw \"duplicate flag \" + flagKey;\n }\n\n const x: boolean = flagObj[flagKey];\n flagObj[flagKey] = true;\n}\n\nexport function ASSERT_EXISTS<T = Object>(obj: any): obj is T {\n // istanbul ignore next\n if (obj === undefined) {\n throw Error(\"Internal Error - Should never get here!\");\n }\n return true;\n}\n\n// istanbul ignore next\nexport function ASSERT_NEVER_REACH_HERE(): any {\n throw Error(\"Internal Error - Should never get here!\");\n}\n\nexport function isCharacter(obj: { type: string }): obj is Character {\n return obj[\"type\"] === \"Character\";\n}\n", "import { cc } from \"./utils.js\";\n\nexport const digitsCharCodes: number[] = [];\nfor (let i = cc(\"0\"); i <= cc(\"9\"); i++) {\n digitsCharCodes.push(i);\n}\n\nexport const wordCharCodes: number[] = [cc(\"_\")].concat(digitsCharCodes);\nfor (let i = cc(\"a\"); i <= cc(\"z\"); i++) {\n wordCharCodes.push(i);\n}\n\nfor (let i = cc(\"A\"); i <= cc(\"Z\"); i++) {\n wordCharCodes.push(i);\n}\n\n// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp#character-classes\nexport const whitespaceCodes: number[] = [\n cc(\" \"),\n cc(\"\\f\"),\n cc(\"\\n\"),\n cc(\"\\r\"),\n cc(\"\\t\"),\n cc(\"\\v\"),\n cc(\"\\t\"),\n cc(\"\\u00a0\"),\n cc(\"\\u1680\"),\n cc(\"\\u2000\"),\n cc(\"\\u2001\"),\n cc(\"\\u2002\"),\n cc(\"\\u2003\"),\n cc(\"\\u2004\"),\n cc(\"\\u2005\"),\n cc(\"\\u2006\"),\n cc(\"\\u2007\"),\n cc(\"\\u2008\"),\n cc(\"\\u2009\"),\n cc(\"\\u200a\"),\n cc(\"\\u2028\"),\n cc(\"\\u2029\"),\n cc(\"\\u202f\"),\n cc(\"\\u205f\"),\n cc(\"\\u3000\"),\n cc(\"\\ufeff\"),\n];\n", "import type {\n Alternative,\n Assertion,\n Atom,\n Character,\n Disjunction,\n Group,\n GroupBackReference,\n Location,\n Quantifier,\n Range,\n RegExpFlags,\n RegExpPattern,\n Set,\n Term,\n} from \"../types\";\nimport {\n addFlag,\n ASSERT_EXISTS,\n ASSERT_NEVER_REACH_HERE,\n cc,\n insertToSet,\n isCharacter,\n} from \"./utils.js\";\nimport {\n digitsCharCodes,\n whitespaceCodes,\n wordCharCodes,\n} from \"./character-classes.js\";\n\n// consts and utilities\nconst hexDigitPattern = /[0-9a-fA-F]/;\nconst decimalPattern = /[0-9]/;\nconst decimalPatternNoZero = /[1-9]/;\n\n// https://hackernoon.com/the-madness-of-parsing-real-world-javascript-regexps-d9ee336df983\n// https://www.ecma-international.org/ecma-262/8.0/index.html#prod-Pattern\nexport class RegExpParser {\n protected idx: number = 0;\n protected input: string = \"\";\n protected groupIdx: number = 0;\n\n protected saveState() {\n return {\n idx: this.idx,\n input: this.input,\n groupIdx: this.groupIdx,\n };\n }\n\n protected restoreState(newState: {\n idx: number;\n input: string;\n groupIdx: number;\n }) {\n this.idx = newState.idx;\n this.input = newState.input;\n this.groupIdx = newState.groupIdx;\n }\n\n public pattern(input: string): RegExpPattern {\n // parser state\n this.idx = 0;\n this.input = input;\n this.groupIdx = 0;\n\n this.consumeChar(\"/\");\n const value = this.disjunction();\n this.consumeChar(\"/\");\n\n const flags: RegExpFlags = {\n type: \"Flags\",\n loc: { begin: this.idx, end: input.length },\n global: false,\n ignoreCase: false,\n multiLine: false,\n unicode: false,\n sticky: false,\n };\n\n while (this.isRegExpFlag()) {\n switch (this.popChar()) {\n case \"g\":\n addFlag(flags, \"global\");\n break;\n case \"i\":\n addFlag(flags, \"ignoreCase\");\n break;\n case \"m\":\n addFlag(flags, \"multiLine\");\n break;\n case \"u\":\n addFlag(flags, \"unicode\");\n break;\n case \"y\":\n addFlag(flags, \"sticky\");\n break;\n }\n }\n\n if (this.idx !== this.input.length) {\n throw Error(\"Redundant input: \" + this.input.substring(this.idx));\n }\n return {\n type: \"Pattern\",\n flags: flags,\n value: value,\n loc: this.loc(0),\n };\n }\n\n protected disjunction(): Disjunction {\n const alts = [];\n const begin = this.idx;\n\n alts.push(this.alternative());\n\n while (this.peekChar() === \"|\") {\n this.consumeChar(\"|\");\n alts.push(this.alternative());\n }\n\n return { type: \"Disjunction\", value: alts, loc: this.loc(begin) };\n }\n\n protected alternative(): Alternative {\n const terms = [];\n const begin = this.idx;\n\n while (this.isTerm()) {\n terms.push(this.term());\n }\n\n return { type: \"Alternative\", value: terms, loc: this.loc(begin) };\n }\n\n protected term(): Term {\n if (this.isAssertion()) {\n return this.assertion();\n } else {\n return this.atom();\n }\n }\n\n protected assertion(): Assertion {\n const begin = this.idx;\n switch (this.popChar()) {\n case \"^\":\n return {\n type: \"StartAnchor\",\n loc: this.loc(begin),\n };\n case \"$\":\n return { type: \"EndAnchor\", loc: this.loc(begin) };\n // '\\b' or '\\B'\n case \"\\\\\":\n switch (this.popChar()) {\n case \"b\":\n return {\n type: \"WordBoundary\",\n loc: this.loc(begin),\n };\n case \"B\":\n return {\n type: \"NonWordBoundary\",\n loc: this.loc(begin),\n };\n }\n /* c8 ignore next */\n throw Error(\"Invalid Assertion Escape\");\n // '(?=' or '(?!'\n case \"(\":\n this.consumeChar(\"?\");\n\n let type:\n | \"Lookahead\"\n | \"NegativeLookahead\"\n | \"Lookbehind\"\n | \"NegativeLookbehind\"\n | undefined;\n switch (this.popChar()) {\n case \"=\":\n type = \"Lookahead\";\n break;\n case \"!\":\n type = \"NegativeLookahead\";\n break;\n case \"<\": {\n switch (this.popChar()) {\n case \"=\":\n type = \"Lookbehind\";\n break;\n case \"!\":\n type = \"NegativeLookbehind\";\n }\n break;\n }\n }\n ASSERT_EXISTS(type);\n\n const disjunction = this.disjunction();\n\n this.consumeChar(\")\");\n\n return {\n type: type!,\n value: disjunction,\n loc: this.loc(begin),\n };\n }\n // istanbul ignore next\n return ASSERT_NEVER_REACH_HERE();\n }\n\n protected quantifier(\n isBacktracking: boolean = false,\n ): Quantifier | undefined {\n let range: Partial<Quantifier> | undefined = undefined;\n const begin = this.idx;\n switch (this.popChar()) {\n case \"*\":\n range = {\n atLeast: 0,\n atMost: Infinity,\n };\n break;\n case \"+\":\n range = {\n atLeast: 1,\n atMost: Infinity,\n };\n break;\n case \"?\":\n range = {\n atLeast: 0,\n atMost: 1,\n };\n break;\n case \"{\":\n const atLeast = this.integerIncludingZero();\n switch (this.popChar()) {\n case \"}\":\n range = {\n atLeast: atLeast,\n atMost: atLeast,\n };\n break;\n case \",\":\n let atMost;\n if (this.isDigit()) {\n atMost = this.integerIncludingZero();\n range = {\n atLeast: atLeast,\n atMost: atMost,\n };\n } else {\n range = {\n atLeast: atLeast,\n atMost: Infinity,\n };\n }\n this.consumeChar(\"}\");\n break;\n }\n // throwing exceptions from \"ASSERT_EXISTS\" during backtracking\n // causes severe performance degradations\n if (isBacktracking === true && range === undefined) {\n return undefined;\n }\n ASSERT_EXISTS(range);\n break;\n }\n\n // throwing exceptions from \"ASSERT_EXISTS\" during backtracking\n // causes severe performance degradations\n if (isBacktracking === true && range === undefined) {\n return undefined;\n }\n\n // istanbul ignore else\n if (ASSERT_EXISTS(range)) {\n if (this.peekChar(0) === \"?\") {\n this.consumeChar(\"?\");\n range.greedy = false;\n } else {\n range.greedy = true;\n }\n\n range.type = \"Quantifier\";\n range.loc = this.loc(begin);\n return range as Quantifier;\n }\n }\n\n protected atom(): Atom {\n let atom: Omit<Atom, \"loc\" | \"type\"> | undefined;\n const begin = this.idx;\n switch (this.peekChar()) {\n case \".\":\n atom = this.dotAll();\n break;\n case \"\\\\\":\n atom = this.atomEscape();\n break;\n case \"[\":\n atom = this.characterClass();\n break;\n case \"(\":\n atom = this.group();\n break;\n }\n\n if (atom === undefined && this.isPatternCharacter()) {\n atom = this.patternCharacter();\n }\n\n // istanbul ignore else\n if (ASSERT_EXISTS<Atom>(atom)) {\n atom.loc = this.loc(begin);\n\n if (this.isQuantifier()) {\n atom.quantifier = this.quantifier();\n }\n\n return atom;\n }\n\n // istanbul ignore next\n return ASSERT_NEVER_REACH_HERE();\n }\n\n protected dotAll(): Omit<Set, \"loc\"> {\n this.consumeChar(\".\");\n return {\n type: \"Set\",\n complement: true,\n value: [cc(\"\\n\"), cc(\"\\r\"), cc(\"\\u2028\"), cc(\"\\u2029\")],\n };\n }\n\n protected atomEscape(): Omit<GroupBackReference | Set | Character, \"loc\"> {\n this.consumeChar(\"\\\\\");\n\n switch (this.peekChar()) {\n case \"1\":\n case \"2\":\n case \"3\":\n case \"4\":\n case \"5\":\n case \"6\":\n case \"7\":\n case \"8\":\n case \"9\":\n return this.decimalEscapeAtom();\n case \"d\":\n case \"D\":\n case \"s\":\n case \"S\":\n case \"w\":\n case \"W\":\n return this.characterClassEscape();\n case \"f\":\n case \"n\":\n case \"r\":\n case \"t\":\n case \"v\":\n return this.controlEscapeAtom();\n case \"c\":\n return this.controlLetterEscapeAtom();\n case \"0\":\n return this.nulCharacterAtom();\n case \"x\":\n return this.hexEscapeSequenceAtom();\n case \"u\":\n return this.regExpUnicodeEscapeSequenceAtom();\n default:\n return this.identityEscapeAtom();\n }\n }\n\n protected decimalEscapeAtom(): Omit<GroupBackReference, \"loc\"> {\n const value = this.positiveInteger();\n\n return { type: \"GroupBackReference\", value: value };\n }\n\n protected characterClassEscape(): Omit<Set, \"loc\"> {\n let set: (number | Range)[] | undefined;\n let complement = false;\n switch (this.popChar()) {\n case \"d\":\n set = digitsCharCodes;\n break;\n case \"D\":\n set = digitsCharCodes;\n complement = true;\n break;\n case \"s\":\n set = whitespaceCodes;\n break;\n case \"S\":\n set = whitespaceCodes;\n complement = true;\n break;\n case \"w\":\n set = wordCharCodes;\n break;\n case \"W\":\n set = wordCharCodes;\n complement = true;\n break;\n }\n\n // istanbul ignore else\n if (ASSERT_EXISTS(set)) {\n return { type: \"Set\", value: set, complement: complement };\n }\n // istanbul ignore next\n return ASSERT_NEVER_REACH_HERE();\n }\n\n protected controlEscapeAtom(): Omit<Character, \"loc\"> {\n let escapeCode;\n switch (this.popChar()) {\n case \"f\":\n escapeCode = cc(\"\\f\");\n break;\n case \"n\":\n escapeCode = cc(\"\\n\");\n break;\n case \"r\":\n escapeCode = cc(\"\\r\");\n break;\n case \"t\":\n escapeCode = cc(\"\\t\");\n break;\n case \"v\":\n escapeCode = cc(\"\\v\");\n break;\n }\n\n // istanbul ignore else\n if (ASSERT_EXISTS(escapeCode)) {\n return { type: \"Character\", value: escapeCode };\n }\n // istanbul ignore next\n return ASSERT_NEVER_REACH_HERE();\n }\n\n protected controlLetterEscapeAtom(): Omit<Character, \"loc\"> {\n this.consumeChar(\"c\");\n const letter = this.popChar();\n if (/[a-zA-Z]/.test(letter) === false) {\n throw Error(\"Invalid \");\n }\n\n const letterCode = letter.toUpperCase().charCodeAt(0) - 64;\n return { type: \"Character\", value: letterCode };\n }\n\n protected nulCharacterAtom(): Omit<Character, \"loc\"> {\n // TODO implement '[lookahead \u2209 DecimalDigit]'\n // TODO: for the deprecated octal escape sequence\n this.consumeChar(\"0\");\n return { type: \"Character\", value: cc(\"\\0\") };\n }\n\n protected hexEscapeSequenceAtom(): Omit<Character, \"loc\"> {\n this.consumeChar(\"x\");\n return this.parseHexDigits(2);\n }\n\n protected regExpUnicodeEscapeSequenceAtom(): Omit<Character, \"loc\"> {\n this.consumeChar(\"u\");\n return this.parseHexDigits(4);\n }\n\n protected identityEscapeAtom(): Omit<Character, \"loc\"> {\n // TODO: implement \"SourceCharacter but not UnicodeIDContinue\"\n // // http://unicode.org/reports/tr31/#Specific_Character_Adjustments\n const escapedChar = this.popChar();\n return { type: \"Character\", value: cc(escapedChar) };\n }\n\n protected classPatternCharacterAtom(): Omit<Character, \"loc\"> {\n switch (this.peekChar()) {\n // istanbul ignore next\n case \"\\n\":\n // istanbul ignore next\n case \"\\r\":\n // istanbul ignore next\n case \"\\u2028\":\n // istanbul ignore next\n case \"\\u2029\":\n // istanbul ignore next\n case \"\\\\\":\n // istanbul ignore next\n case \"]\":\n throw Error(\"TBD\");\n default:\n const nextChar = this.popChar();\n return { type: \"Character\", value: cc(nextChar) };\n }\n }\n\n protected characterClass(): Omit<Set, \"loc\"> {\n const set: (number | Range)[] = [];\n let complement = false;\n this.consumeChar(\"[\");\n if (this.peekChar(0) === \"^\") {\n this.consumeChar(\"^\");\n complement = true;\n }\n\n while (this.isClassAtom()) {\n const from = this.classAtom();\n const isFromSingleChar = from.type === \"Character\";\n if (isCharacter(from) && this.isRangeDash()) {\n this.consumeChar(\"-\");\n const to = this.classAtom();\n const isToSingleChar = to.type === \"Character\";\n\n // a range can only be used when both sides are single characters\n if (isCharacter(to)) {\n if (to.value < from.value) {\n throw Error(\"Range out of order in character class\");\n }\n set.push({ from: from.value, to: to.value });\n } else {\n // literal dash\n insertToSet(from.value, set);\n set.push(cc(\"-\"));\n insertToSet(to.value, set);\n }\n } else {\n insertToSet(from.value, set);\n }\n }\n\n this.consumeChar(\"]\");\n\n return { type: \"Set\", complement: complement, value: set };\n }\n\n protected classAtom(): Omit<Character | Set, \"loc\"> {\n switch (this.peekChar()) {\n // istanbul ignore next\n case \"]\":\n // istanbul ignore next\n case \"\\n\":\n // istanbul ignore next\n case \"\\r\":\n // istanbul ignore next\n case \"\\u2028\":\n // istanbul ignore next\n case \"\\u2029\":\n throw Error(\"TBD\");\n case \"\\\\\":\n return this.classEscape();\n default:\n return this.classPatternCharacterAtom();\n }\n }\n\n protected classEscape(): Omit<Character | Set, \"loc\"> {\n this.consumeChar(\"\\\\\");\n switch (this.peekChar()) {\n // Matches a backspace.\n // (Not to be confused with \\b word boundary outside characterClass)\n case \"b\":\n this.consumeChar(\"b\");\n return { type: \"Character\", value: cc(\"\\u0008\") };\n case \"d\":\n case \"D\":\n case \"s\":\n case \"S\":\n case \"w\":\n case \"W\":\n return this.characterClassEscape();\n case \"f\":\n case \"n\":\n case \"r\":\n case \"t\":\n case \"v\":\n return this.controlEscapeAtom();\n case \"c\":\n return this.controlLetterEscapeAtom();\n case \"0\":\n return this.nulCharacterAtom();\n case \"x\":\n return this.hexEscapeSequenceAtom();\n case \"u\":\n return this.regExpUnicodeEscapeSequenceAtom();\n default:\n return this.identityEscapeAtom();\n }\n }\n\n protected group(): Omit<Group, \"loc\"> {\n let capturing = true;\n this.consumeChar(\"(\");\n switch (this.peekChar(0)) {\n case \"?\":\n this.consumeChar(\"?\");\n this.consumeChar(\":\");\n capturing = false;\n break;\n default:\n this.groupIdx++;\n break;\n }\n const value = this.disjunction();\n this.consumeChar(\")\");\n\n const groupAst: Omit<Group, \"loc\"> = {\n type: \"Group\",\n capturing: capturing,\n value: value,\n };\n\n if (capturing) {\n groupAst[\"idx\"] = this.groupIdx;\n }\n\n return groupAst;\n }\n\n protected positiveInteger(): number {\n let number = this.popChar();\n\n // istanbul ignore next - can't ever get here due to previous lookahead checks\n // still implementing this error checking in case this ever changes.\n if (decimalPatternNoZero.test(number) === false) {\n throw Error(\"Expecting a positive integer\");\n }\n\n while (decimalPattern.test(this.peekChar(0))) {\n number += this.popChar();\n }\n\n return parseInt(number, 10);\n }\n\n protected integerIncludingZero(): number {\n let number = this.popChar();\n if (decimalPattern.test(number) === false) {\n throw Error(\"Expecting an integer\");\n }\n\n while (decimalPattern.test(this.peekChar(0))) {\n number += this.popChar();\n }\n\n return parseInt(number, 10);\n }\n\n protected patternCharacter(): Omit<Character, \"loc\"> {\n const nextChar = this.popChar();\n switch (nextChar) {\n // istanbul ignore next\n case \"\\n\":\n // istanbul ignore next\n case \"\\r\":\n // istanbul ignore next\n case \"\\u2028\":\n // istanbul ignore next\n case \"\\u2029\":\n // istanbul ignore next\n case \"^\":\n // istanbul ignore next\n case \"$\":\n // istanbul ignore next\n case \"\\\\\":\n // istanbul ignore next\n case \".\":\n // istanbul ignore next\n case \"*\":\n // istanbul ignore next\n case \"+\":\n // istanbul ignore next\n case \"?\":\n // istanbul ignore next\n case \"(\":\n // istanbul ignore next\n case \")\":\n // istanbul ignore next\n case \"[\":\n // istanbul ignore next\n case \"|\":\n // istanbul ignore next\n throw Error(\"TBD\");\n default:\n return { type: \"Character\", value: cc(nextChar) };\n }\n }\n protected isRegExpFlag(): boolean {\n switch (this.peekChar(0)) {\n case \"g\":\n case \"i\":\n case \"m\":\n case \"u\":\n case \"y\":\n return true;\n default:\n return false;\n }\n }\n\n protected isRangeDash(): boolean {\n return this.peekChar() === \"-\" && this.isClassAtom(1);\n }\n\n protected isDigit(): boolean {\n return decimalPattern.test(this.peekChar(0));\n }\n\n protected isClassAtom(howMuch = 0): boolean {\n switch (this.peekChar(howMuch)) {\n case \"]\":\n case \"\\n\":\n case \"\\r\":\n case \"\\u2028\":\n case \"\\u2029\":\n return false;\n default:\n return true;\n }\n }\n\n protected isTerm() {\n return this.isAtom() || this.isAssertion();\n }\n\n protected isAtom(): boolean {\n if (this.isPatternCharacter()) {\n return true;\n }\n\n switch (this.peekChar(0)) {\n case \".\":\n case \"\\\\\": // atomEscape\n case \"[\": // characterClass\n // TODO: isAtom must be called before isAssertion - disambiguate\n case \"(\": // group\n return true;\n default:\n return false;\n }\n }\n\n protected isAssertion(): boolean {\n switch (this.peekChar(0)) {\n case \"^\":\n case \"$\":\n return true;\n // '\\b' or '\\B'\n case \"\\\\\":\n switch (this.peekChar(1)) {\n case \"b\":\n case \"B\":\n return true;\n default:\n return false;\n }\n // '(?=' or '(?!' or `(?<=` or `(?<!`\n case \"(\":\n return (\n this.peekChar(1) === \"?\" &&\n (this.peekChar(2) === \"=\" ||\n this.peekChar(2) === \"!\" ||\n (this.peekChar(2) === \"<\" &&\n (this.peekChar(3) === \"=\" || this.peekChar(3) === \"!\")))\n );\n default:\n return false;\n }\n }\n\n protected isQuantifier(): boolean {\n const prevState = this.saveState();\n try {\n return this.quantifier(true) !== undefined;\n } catch (e) {\n return false;\n } finally {\n this.restoreState(prevState);\n }\n }\n\n protected isPatternCharacter(): boolean {\n switch (this.peekChar()) {\n case \"^\":\n case \"$\":\n case \"\\\\\":\n case \".\":\n case \"*\":\n case \"+\":\n case \"?\":\n case \"(\":\n case \")\":\n case \"[\":\n case \"|\":\n case \"/\":\n case \"\\n\":\n case \"\\r\":\n case \"\\u2028\":\n case \"\\u2029\":\n return false;\n default:\n return true;\n }\n }\n\n protected parseHexDigits(howMany: number): Omit<Character, \"loc\"> {\n let hexString = \"\";\n for (let i = 0; i < howMany; i++) {\n const hexChar = this.popChar();\n if (hexDigitPattern.test(hexChar) === false) {\n throw Error(\"Expecting a HexDecimal digits\");\n }\n hexString += hexChar;\n }\n const charCode = parseInt(hexString, 16);\n return { type: \"Character\", value: charCode };\n }\n\n protected peekChar(howMuch = 0): string {\n return this.input[this.idx + howMuch];\n }\n\n protected popChar(): string {\n const nextChar = this.peekChar(0);\n this.consumeChar(undefined);\n return nextChar;\n }\n\n protected consumeChar(char: string | undefined): void {\n if (char !== undefined && this.input[this.idx] !== char) {\n throw Error(\n \"Expected: '\" +\n char +\n \"' but found: '\" +\n this.input[this.idx] +\n \"' at offset: \" +\n this.idx,\n );\n }\n\n if (this.idx >= this.input.length) {\n throw Error(\"Unexpected end of input\");\n }\n this.idx++;\n }\n\n protected loc(begin: number): Location {\n return { begin: begin, end: this.idx };\n }\n}\n", "import type {\n Alternative,\n Assertion,\n Character,\n Disjunction,\n Group,\n GroupBackReference,\n IRegExpAST,\n Quantifier,\n RegExpAstPart,\n RegExpFlags,\n RegExpPattern,\n Set,\n} from \"../types\";\n\nexport class BaseRegExpVisitor {\n public visitChildren(node: IRegExpAST) {\n for (const key in node) {\n const child = (node as any)[key];\n /* istanbul ignore else */\n if (node.hasOwnProperty(key)) {\n if (child.type !== undefined) {\n this.visit(child);\n } else if (Array.isArray(child)) {\n child.forEach((subChild) => {\n this.visit(subChild);\n }, this);\n }\n }\n }\n }\n\n public visit(node: RegExpAstPart): void {\n switch (node.type) {\n case \"Pattern\":\n this.visitPattern(node);\n break;\n case \"Flags\":\n this.visitFlags(node);\n break;\n case \"Disjunction\":\n this.visitDisjunction(node);\n break;\n case \"Alternative\":\n this.visitAlternative(node);\n break;\n case \"StartAnchor\":\n this.visitStartAnchor(node);\n break;\n case \"EndAnchor\":\n this.visitEndAnchor(node);\n break;\n case \"WordBoundary\":\n this.visitWordBoundary(node);\n break;\n case \"NonWordBoundary\":\n this.visitNonWordBoundary(node);\n break;\n case \"Lookahead\":\n this.visitLookahead(node);\n break;\n case \"NegativeLookahead\":\n this.visitNegativeLookahead(node);\n break;\n case \"Lookbehind\":\n this.visitLookbehind(node);\n break;\n case \"NegativeLookbehind\":\n this.visitNegativeLookbehind(node);\n break;\n case \"Character\":\n this.visitCharacter(node);\n break;\n case \"Set\":\n this.visitSet(node);\n break;\n case \"Group\":\n this.visitGroup(node);\n break;\n case \"GroupBackReference\":\n this.visitGroupBackReference(node);\n break;\n case \"Quantifier\":\n this.visitQuantifier(node);\n break;\n }\n\n this.visitChildren(node);\n }\n\n public visitPattern(node: RegExpPattern): void {}\n\n public visitFlags(node: RegExpFlags): void {}\n\n public visitDisjunction(node: Disjunction): void {}\n\n public visitAlternative(node: Alternative): void {}\n\n // Assertion\n public visitStartAnchor(node: Assertion): void {}\n\n public visitEndAnchor(node: Assertion): void {}\n\n public visitWordBoundary(node: Assertion): void {}\n\n public visitNonWordBoundary(node: Assertion): void {}\n\n public visitLookahead(node: Assertion): void {}\n\n public visitNegativeLookahead(node: Assertion): void {}\n\n public visitLookbehind(node: Assertion): void {}\n\n public visitNegativeLookbehind(node: Assertion): void {}\n\n // atoms\n public visitCharacter(node: Character): void {}\n\n public visitSet(node: Set): void {}\n\n public visitGroup(node: Group): void {}\n\n public visitGroupBackReference(node: GroupBackReference): void {}\n\n public visitQuantifier(node: Quantifier): void {}\n}\n", "import {\n Alternative,\n Assertion,\n Atom,\n Disjunction,\n RegExpParser,\n RegExpPattern,\n} from \"@chevrotain/regexp-to-ast\";\n\nlet regExpAstCache: { [regex: string]: RegExpPattern } = {};\nconst regExpParser = new RegExpParser();\n\n// this should be moved to regexp-to-ast\nexport type ASTNode =\n | RegExpPattern\n | Disjunction\n | Alternative\n | Assertion\n | Atom;\n\nexport function getRegExpAst(regExp: RegExp): RegExpPattern {\n const regExpStr = regExp.toString();\n if (regExpAstCache.hasOwnProperty(regExpStr)) {\n return regExpAstCache[regExpStr];\n } else {\n const regExpAst = regExpParser.pattern(regExpStr);\n regExpAstCache[regExpStr] = regExpAst;\n return regExpAst;\n }\n}\n\nexport function clearRegExpParserCache() {\n regExpAstCache = {};\n}\n", "import {\n Alternative,\n Atom,\n BaseRegExpVisitor,\n Character,\n Disjunction,\n Group,\n Set,\n} from \"@chevrotain/regexp-to-ast\";\nimport { every, find, forEach, includes, isArray, values } from \"lodash-es\";\nimport { PRINT_ERROR, PRINT_WARNING } from \"@chevrotain/utils\";\nimport { ASTNode, getRegExpAst } from \"./reg_exp_parser.js\";\nimport { charCodeToOptimizedIndex, minOptimizationVal } from \"./lexer.js\";\n\nconst complementErrorMessage =\n \"Complement Sets are not supported for first char optimization\";\nexport const failedOptimizationPrefixMsg =\n 'Unable to use \"first char\" lexer optimizations:\\n';\n\nexport function getOptimizedStartCodesIndices(\n regExp: RegExp,\n ensureOptimizations = false,\n): number[] {\n try {\n const ast = getRegExpAst(regExp);\n const firstChars = firstCharOptimizedIndices(\n ast.value,\n {},\n ast.flags.ignoreCase,\n );\n return firstChars;\n } catch (e) {\n /* istanbul ignore next */\n // Testing this relies on the regexp-to-ast library having a bug... */\n // TODO: only the else branch needs to be ignored, try to fix with newer prettier / tsc\n if (e.message === complementErrorMessage) {\n if (ensureOptimizations) {\n PRINT_WARNING(\n `${failedOptimizationPrefixMsg}` +\n `\\tUnable to optimize: < ${regExp.toString()} >\\n` +\n \"\\tComplement Sets cannot be automatically optimized.\\n\" +\n \"\\tThis will disable the lexer's first char optimizations.\\n\" +\n \"\\tSee: https://chevrotain.io/docs/guide/resolving_lexer_errors.html#COMPLEMENT for details.\",\n );\n }\n } else {\n let msgSuffix = \"\";\n if (ensureOptimizations) {\n msgSuffix =\n \"\\n\\tThis will disable the lexer's first char optimizations.\\n\" +\n \"\\tSee: https://chevrotain.io/docs/guide/resolving_lexer_errors.html#REGEXP_PARSING for details.\";\n }\n PRINT_ERROR(\n `${failedOptimizationPrefixMsg}\\n` +\n `\\tFailed parsing: < ${regExp.toString()} >\\n` +\n `\\tUsing the @chevrotain/regexp-to-ast library\\n` +\n \"\\tPlease open an issue at: https://github.com/chevrotain/chevrotain/issues\" +\n msgSuffix,\n );\n }\n }\n\n return [];\n}\n\nexport function firstCharOptimizedIndices(\n ast: ASTNode,\n result: { [charCode: number]: number },\n ignoreCase: boolean,\n): number[] {\n switch (ast.type) {\n case \"Disjunction\":\n for (let i = 0; i < ast.value.length; i++) {\n firstCharOptimizedIndices(ast.value[i], result, ignoreCase);\n }\n break;\n case \"Alternative\":\n const terms = ast.value;\n for (let i = 0; i < terms.length; i++) {\n const term = terms[i];\n\n // skip terms that cannot effect the first char results\n switch (term.type) {\n case \"EndAnchor\":\n // A group back reference cannot affect potential starting char.\n // because if a back reference is the first production than automatically\n // the group being referenced has had to come BEFORE so its codes have already been added\n case \"GroupBackReference\":\n // assertions do not affect potential starting codes\n case \"Lookahead\":\n case \"NegativeLookahead\":\n case \"Lookbehind\":\n case \"NegativeLookbehind\":\n case \"StartAnchor\":\n case \"WordBoundary\":\n case \"NonWordBoundary\":\n continue;\n }\n\n const atom = term;\n switch (atom.type) {\n case \"Character\":\n addOptimizedIdxToResult(atom.value, result, ignoreCase);\n break;\n case \"Set\":\n if (atom.complement === true) {\n throw Error(complementErrorMessage);\n }\n forEach(atom.value, (code) => {\n if (typeof code === \"number\") {\n addOptimizedIdxToResult(code, result, ignoreCase);\n } else {\n // range\n const range = code as any;\n // cannot optimize when ignoreCase is\n if (ignoreCase === true) {\n for (\n let rangeCode = range.from;\n rangeCode <= range.to;\n rangeCode++\n ) {\n addOptimizedIdxToResult(rangeCode, result, ignoreCase);\n }\n }\n // Optimization (2 orders of magnitude less work for very large ranges)\n else {\n // handle unoptimized values\n for (\n let rangeCode = range.from;\n rangeCode <= range.to && rangeCode < minOptimizationVal;\n rangeCode++\n ) {\n addOptimizedIdxToResult(rangeCode, result, ignoreCase);\n }\n\n // Less common charCode where we optimize for faster init time, by using larger \"buckets\"\n if (range.to >= minOptimizationVal) {\n const minUnOptVal =\n range.from >= minOptimizationVal\n ? range.from\n : minOptimizationVal;\n const maxUnOptVal = range.to;\n const minOptIdx = charCodeToOptimizedIndex(minUnOptVal);\n const maxOptIdx = charCodeToOptimizedIndex(maxUnOptVal);\n\n for (\n let currOptIdx = minOptIdx;\n currOptIdx <= maxOptIdx;\n currOptIdx++\n ) {\n result[currOptIdx] = currOptIdx;\n }\n }\n }\n }\n });\n break;\n case \"Group\":\n firstCharOptimizedIndices(atom.value, result, ignoreCase);\n break;\n /* istanbul ignore next */\n default:\n throw Error(\"Non Exhaustive Match\");\n }\n\n // reached a mandatory production, no more **start** codes can be found on this alternative\n const isOptionalQuantifier =\n atom.quantifier !== undefined && atom.quantifier.atLeast === 0;\n if (\n // A group may be optional due to empty contents /(?:)/\n // or if everything inside it is optional /((a)?)/\n (atom.type === \"Group\" && isWholeOptional(atom) === false) ||\n // If this term is not a group it may only be optional if it has an optional quantifier\n (atom.type !== \"Group\" && isOptionalQuantifier === false)\n ) {\n break;\n }\n }\n break;\n /* istanbul ignore next */\n default:\n throw Error(\"non exhaustive match!\");\n }\n\n // console.log(Object.keys(result).length)\n return values(result);\n}\n\nfunction addOptimizedIdxToResult(\n code: number,\n result: { [charCode: number]: number },\n ignoreCase: boolean,\n) {\n const optimizedCharIdx = charCodeToOptimizedIndex(code);\n result[optimizedCharIdx] = optimizedCharIdx;\n\n if (ignoreCase === true) {\n handleIgnoreCase(code, result);\n }\n}\n\nfunction handleIgnoreCase(\n code: number,\n result: { [charCode: number]: number },\n) {\n const char = String.fromCharCode(code);\n const upperChar = char.toUpperCase();\n /* istanbul ignore else */\n if (upperChar !== char) {\n const optimizedCharIdx = charCodeToOptimizedIndex(upperChar.charCodeAt(0));\n result[optimizedCharIdx] = optimizedCharIdx;\n } else {\n const lowerChar = char.toLowerCase();\n if (lowerChar !== char) {\n const optimizedCharIdx = charCodeToOptimizedIndex(\n lowerChar.charCodeAt(0),\n );\n result[optimizedCharIdx] = optimizedCharIdx;\n }\n }\n}\n\nfunction findCode(setNode: Set, targetCharCodes: number[]) {\n return find(setNode.value, (codeOrRange) => {\n if (typeof codeOrRange === \"number\") {\n return includes(targetCharCodes, codeOrRange);\n } else {\n // range\n const range = <any>codeOrRange;\n return (\n find(\n targetCharCodes,\n (targetCode) => range.from <= targetCode && targetCode <= range.to,\n ) !== undefined\n );\n }\n });\n}\n\nfunction isWholeOptional(ast: any): boolean {\n const quantifier = (ast as Atom).quantifier;\n if (quantifier && quantifier.atLeast === 0) {\n return true;\n }\n\n if (!ast.value) {\n return false;\n }\n\n return isArray(ast.value)\n ? every(ast.value, isWholeOptional)\n : isWholeOptional(ast.value);\n}\n\nclass CharCodeFinder extends BaseRegExpVisitor {\n found: boolean = false;\n\n constructor(private targetCharCodes: number[]) {\n super();\n }\n\n visitChildren(node: ASTNode) {\n // No need to keep looking...\n if (this.found === true) {\n return;\n }\n\n // switch lookaheads / lookbehinds as they do not actually consume any characters thus\n // finding a charCode at lookahead context does not mean that regexp can actually contain it in a match.\n switch (node.type) {\n case \"Lookahead\":\n this.visitLookahead(node);\n return;\n case \"NegativeLookahead\":\n this.visitNegativeLookahead(node);\n return;\n case \"Lookbehind\":\n this.visitLookbehind(node);\n return;\n case \"NegativeLookbehind\":\n this.visitNegativeLookbehind(node);\n return;\n }\n\n super.visitChildren(node);\n }\n\n visitCharacter(node: Character) {\n if (includes(this.targetCharCodes, node.value)) {\n this.found = true;\n }\n }\n\n visitSet(node: Set) {\n if (node.complement) {\n if (findCode(node, this.targetCharCodes) === undefined) {\n this.found = true;\n }\n } else {\n if (findCode(node, this.targetCharCodes) !== undefined) {\n this.found = true;\n }\n }\n }\n}\n\nexport function canMatchCharCode(\n charCodes: number[],\n pattern: RegExp | string,\n) {\n if (pattern instanceof RegExp) {\n const ast = getRegExpAst(pattern);\n const charCodeFinder = new CharCodeFinder(charCodes);\n charCodeFinder.visit(ast);\n return charCodeFinder.found;\n } else {\n return (\n find(<any>pattern, (char) => {\n return includes(charCodes, (<string>char).charCodeAt(0));\n }) !== undefined\n );\n }\n}\n", "import { BaseRegExpVisitor } from \"@chevrotain/regexp-to-ast\";\nimport {\n IRegExpExec,\n Lexer,\n LexerDefinitionErrorType,\n} from \"./lexer_public.js\";\nimport {\n compact,\n defaults,\n difference,\n filter,\n find,\n first,\n flatten,\n forEach,\n has,\n includes,\n indexOf,\n isArray,\n isEmpty,\n isFunction,\n isRegExp,\n isString,\n isUndefined,\n keys,\n map,\n reduce,\n reject,\n values,\n} from \"lodash-es\";\nimport { PRINT_ERROR } from \"@chevrotain/utils\";\nimport {\n canMatchCharCode,\n failedOptimizationPrefixMsg,\n getOptimizedStartCodesIndices,\n} from \"./reg_exp.js\";\nimport {\n ILexerDefinitionError,\n ILineTerminatorsTester,\n IMultiModeLexerDefinition,\n IToken,\n TokenType,\n} from \"@chevrotain/types\";\nimport { getRegExpAst } from \"./reg_exp_parser.js\";\n\nconst PATTERN = \"PATTERN\";\nexport const DEFAULT_MODE = \"defaultMode\";\nexport const MODES = \"modes\";\n\nexport interface IPatternConfig {\n pattern: IRegExpExec | string;\n longerAlt: number[] | undefined;\n canLineTerminator: boolean;\n isCustom: boolean;\n short: number | false;\n group: string | undefined | false;\n push: string | undefined;\n pop: boolean;\n tokenType: TokenType;\n tokenTypeIdx: number;\n}\n\nexport interface IAnalyzeResult {\n patternIdxToConfig: IPatternConfig[];\n charCodeToPatternIdxToConfig: { [charCode: number]: IPatternConfig[] };\n emptyGroups: { [groupName: string]: IToken[] };\n hasCustom: boolean;\n canBeOptimized: boolean;\n}\n\nexport function analyzeTokenTypes(\n tokenTypes: TokenType[],\n options: {\n positionTracking?: \"full\" | \"onlyStart\" | \"onlyOffset\";\n ensureOptimizations?: boolean;\n lineTerminatorCharacters?: (number | string)[];\n safeMode?: boolean;\n tracer?: (msg: string, action: () => void) => void;\n },\n): IAnalyzeResult {\n options = defaults(options, {\n debug: false as boolean,\n safeMode: false as boolean,\n positionTracking: \"full\",\n lineTerminatorCharacters: [\"\\r\", \"\\n\"],\n tracer: (msg: string, action: Function) => action(),\n });\n\n const tracer = options.tracer!;\n\n tracer(\"initCharCodeToOptimizedIndexMap\", () => {\n initCharCodeToOptimizedIndexMap();\n });\n\n let onlyRelevantTypes: TokenType[];\n tracer(\"Reject Lexer.NA\", () => {\n onlyRelevantTypes = reject(tokenTypes, (currType) => {\n return currType[PATTERN] === Lexer.NA;\n });\n });\n\n let hasCustom = false;\n let allTransformedPatterns: (IRegExpExec | string)[];\n tracer(\"Transform Patterns\", () => {\n hasCustom = false;\n allTransformedPatterns = map(\n onlyRelevantTypes,\n (currType): IRegExpExec | string => {\n const currPattern = currType[PATTERN];\n\n /* istanbul ignore else */\n if (isRegExp(currPattern)) {\n const regExpSource = currPattern.source;\n if (\n regExpSource.length === 1 &&\n // only these regExp meta characters which can appear in a length one regExp\n regExpSource !== \"^\" &&\n regExpSource !== \"$\" &&\n regExpSource !== \".\" &&\n !currPattern.ignoreCase\n ) {\n return regExpSource;\n } else if (\n regExpSource.length === 2 &&\n regExpSource[0] === \"\\\\\" &&\n // not a meta character\n !includes(\n [\n \"d\",\n \"D\",\n \"s\",\n \"S\",\n \"t\",\n \"r\",\n \"n\",\n \"t\",\n \"0\",\n \"c\",\n \"b\",\n \"B\",\n \"f\",\n \"v\",\n \"w\",\n \"W\",\n ],\n regExpSource[1],\n )\n ) {\n // escaped meta Characters: /\\+/ /\\[/\n // or redundant escaping: /\\a/\n // without the escaping \"\\\"\n return regExpSource[1];\n } else {\n return addStickyFlag(currPattern);\n }\n } else if (isFunction(currPattern)) {\n hasCustom = true;\n // CustomPatternMatcherFunc - custom patterns do not require any transformations, only wrapping in a RegExp Like object\n return { exec: currPattern };\n } else if (typeof currPattern === \"object\") {\n hasCustom = true;\n // ICustomPattern\n return currPattern;\n } else if (typeof currPattern === \"string\") {\n if (currPattern.length === 1) {\n return currPattern;\n } else {\n const escapedRegExpString = currPattern.replace(\n /[\\\\^$.*+?()[\\]{}|]/g,\n \"\\\\$&\",\n );\n const wrappedRegExp = new RegExp(escapedRegExpString);\n return addStickyFlag(wrappedRegExp);\n }\n } else {\n throw Error(\"non exhaustive match\");\n }\n },\n );\n });\n\n let patternIdxToType: number[];\n let patternIdxToGroup: (string | undefined | false)[];\n let patternIdxToLongerAltIdxArr: (number[] | undefined)[];\n let patternIdxToPushMode: (string | undefined)[];\n let patternIdxToPopMode: boolean[];\n tracer(\"misc mapping\", () => {\n patternIdxToType = map(\n onlyRelevantTypes,\n (currType) => currType.tokenTypeIdx!,\n );\n\n patternIdxToGroup = map(onlyRelevantTypes, (clazz: any) => {\n const groupName = clazz.GROUP;\n /* istanbul ignore next */\n if (groupName === Lexer.SKIPPED) {\n return undefined;\n } else if (isString(groupName)) {\n return groupName;\n } else if (isUndefined(groupName)) {\n return false;\n } else {\n throw Error(\"non exhaustive match\");\n }\n });\n\n patternIdxToLongerAltIdxArr = map(onlyRelevantTypes, (clazz: any) => {\n const longerAltType = clazz.LONGER_ALT;\n\n if (longerAltType) {\n const longerAltIdxArr = isArray(longerAltType)\n ? map(longerAltType, (type: any) => indexOf(onlyRelevantTypes, type))\n : [indexOf(onlyRelevantTypes, longerAltType)];\n return longerAltIdxArr;\n }\n });\n\n patternIdxToPushMode = map(\n onlyRelevantTypes,\n (clazz: any) => clazz.PUSH_MODE,\n );\n\n patternIdxToPopMode = map(onlyRelevantTypes, (clazz: any) =>\n has(clazz, \"POP_MODE\"),\n );\n });\n\n let patternIdxToCanLineTerminator: boolean[];\n tracer(\"Line Terminator Handling\", () => {\n const lineTerminatorCharCodes = getCharCodes(\n options.lineTerminatorCharacters!,\n );\n patternIdxToCanLineTerminator = map(onlyRelevantTypes, (tokType) => false);\n if (options.positionTracking !== \"onlyOffset\") {\n patternIdxToCanLineTerminator = map(onlyRelevantTypes, (tokType) => {\n if (has(tokType, \"LINE_BREAKS\")) {\n return !!tokType.LINE_BREAKS;\n } else {\n return (\n checkLineBreaksIssues(tokType, lineTerminatorCharCodes) === false &&\n canMatchCharCode(\n lineTerminatorCharCodes,\n tokType.PATTERN as RegExp | string,\n )\n );\n }\n });\n }\n });\n\n let patternIdxToIsCustom: boolean[];\n let patternIdxToShort: (number | false)[];\n let emptyGroups!: { [groupName: string]: IToken[] };\n let patternIdxToConfig!: IPatternConfig[];\n tracer(\"Misc Mapping #2\", () => {\n patternIdxToIsCustom = map(onlyRelevantTypes, isCustomPattern);\n patternIdxToShort = map(allTransformedPatterns, isShortPattern);\n\n emptyGroups = reduce(\n onlyRelevantTypes,\n (acc, clazz: any) => {\n const groupName = clazz.GROUP;\n if (isString(groupName) && !(groupName === Lexer.SKIPPED)) {\n acc[groupName] = [];\n }\n return acc;\n },\n {} as { [groupName: string]: IToken[] },\n );\n\n patternIdxToConfig = map(\n allTransformedPatterns,\n (x, idx): IPatternConfig => {\n return {\n pattern: allTransformedPatterns[idx],\n longerAlt: patternIdxToLongerAltIdxArr[idx],\n canLineTerminator: patternIdxToCanLineTerminator[idx],\n isCustom: patternIdxToIsCustom[idx],\n short: patternIdxToShort[idx],\n group: patternIdxToGroup[idx],\n push: patternIdxToPushMode[idx],\n pop: patternIdxToPopMode[idx],\n tokenTypeIdx: patternIdxToType[idx],\n tokenType: onlyRelevantTypes[idx],\n };\n },\n );\n });\n\n let canBeOptimized = true;\n let charCodeToPatternIdxToConfig: { [charCode: number]: IPatternConfig[] } =\n [];\n\n if (!options.safeMode) {\n tracer(\"First Char Optimization\", () => {\n charCodeToPatternIdxToConfig = reduce(\n onlyRelevantTypes,\n (result, currTokType, idx) => {\n if (typeof currTokType.PATTERN === \"string\") {\n const charCode = currTokType.PATTERN.charCodeAt(0);\n const optimizedIdx = charCodeToOptimizedIndex(charCode);\n addToMapOfArrays(result, optimizedIdx, patternIdxToConfig[idx]);\n } else if (isArray(currTokType.START_CHARS_HINT)) {\n let lastOptimizedIdx: number;\n forEach(currTokType.START_CHARS_HINT, (charOrInt) => {\n const charCode =\n typeof charOrInt === \"string\"\n ? charOrInt.charCodeAt(0)\n : charOrInt;\n const currOptimizedIdx = charCodeToOptimizedIndex(charCode);\n // Avoid adding the config multiple times\n /* istanbul ignore else */\n // - Difficult to check this scenario effects as it is only a performance\n // optimization that does not change correctness\n if (lastOptimizedIdx !== currOptimizedIdx) {\n lastOptimizedIdx = currOptimizedIdx;\n addToMapOfArrays(\n result,\n currOptimizedIdx,\n patternIdxToConfig[idx],\n );\n }\n });\n } else if (isRegExp(currTokType.PATTERN)) {\n if (currTokType.PATTERN.unicode) {\n canBeOptimized = false;\n if (options.ensureOptimizations) {\n PRINT_ERROR(\n `${failedOptimizationPrefixMsg}` +\n `\\tUnable to analyze < ${currTokType.PATTERN.toString()} > pattern.\\n` +\n \"\\tThe regexp unicode flag is not currently supported by the regexp-to-ast library.\\n\" +\n \"\\tThis will disable the lexer's first char optimizations.\\n\" +\n \"\\tFor details See: https://chevrotain.io/docs/guide/resolving_lexer_errors.html#UNICODE_OPTIMIZE\",\n );\n }\n } else {\n const optimizedCodes = getOptimizedStartCodesIndices(\n currTokType.PATTERN,\n options.ensureOptimizations,\n );\n /* istanbul ignore if */\n // start code will only be empty given an empty regExp or failure of regexp-to-ast library\n // the first should be a different validation and the second cannot be tested.\n if (isEmpty(optimizedCodes)) {\n // we cannot understand what codes may start possible matches\n // The optimization correctness requires knowing start codes for ALL patterns.\n // Not actually sure this is an error, no debug message\n canBeOptimized = false;\n }\n forEach(optimizedCodes, (code) => {\n addToMapOfArrays(result, code, patternIdxToConfig[idx]);\n });\n }\n } else {\n if (options.ensureOptimizations) {\n PRINT_ERROR(\n `${failedOptimizationPrefixMsg}` +\n `\\tTokenType: <${currTokType.name}> is using a custom token pattern without providing <start_chars_hint> parameter.\\n` +\n \"\\tThis will disable the lexer's first char optimizations.\\n\" +\n \"\\tFor details See: https://chevrotain.io/docs/guide/resolving_lexer_errors.html#CUSTOM_OPTIMIZE\",\n );\n }\n canBeOptimized = false;\n }\n\n return result;\n },\n [] as { [charCode: number]: IPatternConfig[] },\n );\n });\n }\n\n return {\n emptyGroups: emptyGroups,\n patternIdxToConfig: patternIdxToConfig,\n charCodeToPatternIdxToConfig: charCodeToPatternIdxToConfig,\n hasCustom: hasCustom,\n canBeOptimized: canBeOptimized,\n };\n}\n\nexport function validatePatterns(\n tokenTypes: TokenType[],\n validModesNames: string[],\n): ILexerDefinitionError[] {\n let errors: ILexerDefinitionError[] = [];\n\n const missingResult = findMissingPatterns(tokenTypes);\n errors = errors.concat(missingResult.errors);\n\n const invalidResult = findInvalidPatterns(missingResult.valid);\n const validTokenTypes = invalidResult.valid;\n errors = errors.concat(invalidResult.errors);\n\n errors = errors.concat(validateRegExpPattern(validTokenTypes));\n\n errors = errors.concat(findInvalidGroupType(validTokenTypes));\n\n errors = errors.concat(\n findModesThatDoNotExist(validTokenTypes, validModesNames),\n );\n\n errors = errors.concat(findUnreachablePatterns(validTokenTypes));\n\n return errors;\n}\n\nfunction validateRegExpPattern(\n tokenTypes: TokenType[],\n): ILexerDefinitionError[] {\n let errors: ILexerDefinitionError[] = [];\n const withRegExpPatterns = filter(tokenTypes, (currTokType) =>\n isRegExp(currTokType[PATTERN]),\n );\n\n errors = errors.concat(findEndOfInputAnchor(withRegExpPatterns));\n\n errors = errors.concat(findStartOfInputAnchor(withRegExpPatterns));\n\n errors = errors.concat(findUnsupportedFlags(withRegExpPatterns));\n\n errors = errors.concat(findDuplicatePatterns(withRegExpPatterns));\n\n errors = errors.concat(findEmptyMatchRegExps(withRegExpPatterns));\n\n return errors;\n}\n\nexport interface ILexerFilterResult {\n errors: ILexerDefinitionError[];\n valid: TokenType[];\n}\n\nexport function findMissingPatterns(\n tokenTypes: TokenType[],\n): ILexerFilterResult {\n const tokenTypesWithMissingPattern = filter(tokenTypes, (currType) => {\n return !has(currType, PATTERN);\n });\n\n const errors = map(tokenTypesWithMissingPattern, (currType) => {\n return {\n message:\n \"Token Type: ->\" +\n currType.name +\n \"<- missing static 'PATTERN' property\",\n type: LexerDefinitionErrorType.MISSING_PATTERN,\n tokenTypes: [currType],\n };\n });\n\n const valid = difference(tokenTypes, tokenTypesWithMissingPattern);\n return { errors, valid };\n}\n\nexport function findInvalidPatterns(\n tokenTypes: TokenType[],\n): ILexerFilterResult {\n const tokenTypesWithInvalidPattern = filter(tokenTypes, (currType) => {\n const pattern = currType[PATTERN];\n return (\n !isRegExp(pattern) &&\n !isFunction(pattern) &&\n !has(pattern, \"exec\") &&\n !isString(pattern)\n );\n });\n\n const errors = map(tokenTypesWithInvalidPattern, (currType) => {\n return {\n message:\n \"Token Type: ->\" +\n currType.name +\n \"<- static 'PATTERN' can only be a RegExp, a\" +\n \" Function matching the {CustomPatternMatcherFunc} type or an Object matching the {ICustomPattern} interface.\",\n type: LexerDefinitionErrorType.INVALID_PATTERN,\n tokenTypes: [currType],\n };\n });\n\n const valid = difference(tokenTypes, tokenTypesWithInvalidPattern);\n return { errors, valid };\n}\n\nconst end_of_input = /[^\\\\][$]/;\n\nexport function findEndOfInputAnchor(\n tokenTypes: TokenType[],\n): ILexerDefinitionError[] {\n class EndAnchorFinder extends BaseRegExpVisitor {\n found = false;\n\n visitEndAnchor(node: unknown) {\n this.found = true;\n }\n }\n\n const invalidRegex = filter(tokenTypes, (currType) => {\n const pattern = currType.PATTERN;\n\n try {\n const regexpAst = getRegExpAst(pattern as RegExp);\n const endAnchorVisitor = new EndAnchorFinder();\n endAnchorVisitor.visit(regexpAst);\n\n return endAnchorVisitor.found;\n } catch (e) {\n // old behavior in case of runtime exceptions with regexp-to-ast.\n /* istanbul ignore next - cannot ensure an error in regexp-to-ast*/\n return end_of_input.test((pattern as RegExp).source);\n }\n });\n\n const errors = map(invalidRegex, (currType) => {\n return {\n message:\n \"Unexpected RegExp Anchor Error:\\n\" +\n \"\\tToken Type: ->\" +\n currType.name +\n \"<- static 'PATTERN' cannot contain end of input anchor '$'\\n\" +\n \"\\tSee chevrotain.io/docs/guide/resolving_lexer_errors.html#ANCHORS\" +\n \"\\tfor details.\",\n type: LexerDefinitionErrorType.EOI_ANCHOR_FOUND,\n tokenTypes: [currType],\n };\n });\n\n return errors;\n}\n\nexport function findEmptyMatchRegExps(\n tokenTypes: TokenType[],\n): ILexerDefinitionError[] {\n const matchesEmptyString = filter(tokenTypes, (currType) => {\n const pattern = currType.PATTERN as RegExp;\n return pattern.test(\"\");\n });\n\n const errors = map(matchesEmptyString, (currType) => {\n return {\n message:\n \"Token Type: ->\" +\n currType.name +\n \"<- static 'PATTERN' must not match an empty string\",\n type: LexerDefinitionErrorType.EMPTY_MATCH_PATTERN,\n tokenTypes: [currType],\n };\n });\n\n return errors;\n}\n\nconst start_of_input = /[^\\\\[][\\^]|^\\^/;\n\nexport function findStartOfInputAnchor(\n tokenTypes: TokenType[],\n): ILexerDefinitionError[] {\n class StartAnchorFinder extends BaseRegExpVisitor {\n found = false;\n\n visitStartAnchor(node: unknown) {\n this.found = true;\n }\n }\n\n const invalidRegex = filter(tokenTypes, (currType) => {\n const pattern = currType.PATTERN as RegExp;\n try {\n const regexpAst = getRegExpAst(pattern);\n const startAnchorVisitor = new StartAnchorFinder();\n startAnchorVisitor.visit(regexpAst);\n\n return startAnchorVisitor.found;\n } catch (e) {\n // old behavior in case of runtime exceptions with regexp-to-ast.\n /* istanbul ignore next - cannot ensure an error in regexp-to-ast*/\n return start_of_input.test(pattern.source);\n }\n });\n\n const errors = map(invalidRegex, (currType) => {\n return {\n message:\n \"Unexpected RegExp Anchor Error:\\n\" +\n \"\\tToken Type: ->\" +\n currType.name +\n \"<- static 'PATTERN' cannot contain start of input anchor '^'\\n\" +\n \"\\tSee https://chevrotain.io/docs/guide/resolving_lexer_errors.html#ANCHORS\" +\n \"\\tfor details.\",\n type: LexerDefinitionErrorType.SOI_ANCHOR_FOUND,\n tokenTypes: [currType],\n };\n });\n\n return errors;\n}\n\nexport function findUnsupportedFlags(\n tokenTypes: TokenType[],\n): ILexerDefinitionError[] {\n const invalidFlags = filter(tokenTypes, (currType) => {\n const pattern = currType[PATTERN];\n return pattern instanceof RegExp && (pattern.multiline || pattern.global);\n });\n\n const errors = map(invalidFlags, (currType) => {\n return {\n message:\n \"Token Type: ->\" +\n currType.name +\n \"<- static 'PATTERN' may NOT contain global('g') or multiline('m')\",\n type: LexerDefinitionErrorType.UNSUPPORTED_FLAGS_FOUND,\n tokenTypes: [currType],\n };\n });\n\n return errors;\n}\n\n// This can only test for identical duplicate RegExps, not semantically equivalent ones.\nexport function findDuplicatePatterns(\n tokenTypes: TokenType[],\n): ILexerDefinitionError[] {\n const found: TokenType[] = [];\n let identicalPatterns = map(tokenTypes, (outerType: any) => {\n return reduce(\n tokenTypes,\n (result, innerType) => {\n if (\n outerType.PATTERN.source === (innerType.PATTERN as RegExp).source &&\n !includes(found, innerType) &&\n innerType.PATTERN !== Lexer.NA\n ) {\n // this avoids duplicates in the result, each Token Type may only appear in one \"set\"\n // in essence we are creating Equivalence classes on equality relation.\n found.push(innerType);\n result.push(innerType);\n return result;\n }\n return result;\n },\n [] as TokenType[],\n );\n });\n\n identicalPatterns = compact(identicalPatterns);\n\n const duplicatePatterns = filter(identicalPatterns, (currIdenticalSet) => {\n return currIdenticalSet.length > 1;\n });\n\n const errors = map(duplicatePatterns, (setOfIdentical: any) => {\n const tokenTypeNames = map(setOfIdentical, (currType: any) => {\n return currType.name;\n });\n\n const dupPatternSrc = (<any>first(setOfIdentical)).PATTERN;\n return {\n message:\n `The same RegExp pattern ->${dupPatternSrc}<-` +\n `has been used in all of the following Token Types: ${tokenTypeNames.join(\n \", \",\n )} <-`,\n type: LexerDefinitionErrorType.DUPLICATE_PATTERNS_FOUND,\n tokenTypes: setOfIdentical,\n };\n });\n\n return errors;\n}\n\nexport function findInvalidGroupType(\n tokenTypes: TokenType[],\n): ILexerDefinitionError[] {\n const invalidTypes = filter(tokenTypes, (clazz: any) => {\n if (!has(clazz, \"GROUP\")) {\n return false;\n }\n const group = clazz.GROUP;\n\n return group !== Lexer.SKIPPED && group !== Lexer.NA && !isString(group);\n });\n\n const errors = map(invalidTypes, (currType) => {\n return {\n message:\n \"Token Type: ->\" +\n currType.name +\n \"<- static 'GROUP' can only be Lexer.SKIPPED/Lexer.NA/A String\",\n type: LexerDefinitionErrorType.INVALID_GROUP_TYPE_FOUND,\n tokenTypes: [currType],\n };\n });\n\n return errors;\n}\n\nexport function findModesThatDoNotExist(\n tokenTypes: TokenType[],\n validModes: string[],\n): ILexerDefinitionError[] {\n const invalidModes = filter(tokenTypes, (clazz: any) => {\n return (\n clazz.PUSH_MODE !== undefined && !includes(validModes, clazz.PUSH_MODE)\n );\n });\n\n const errors = map(invalidModes, (tokType) => {\n const msg =\n `Token Type: ->${tokType.name}<- static 'PUSH_MODE' value cannot refer to a Lexer Mode ->${tokType.PUSH_MODE}<-` +\n `which does not exist`;\n return {\n message: msg,\n type: LexerDefinitionErrorType.PUSH_MODE_DOES_NOT_EXIST,\n tokenTypes: [tokType],\n };\n });\n\n return errors;\n}\n\nexport function findUnreachablePatterns(\n tokenTypes: TokenType[],\n): ILexerDefinitionError[] {\n const errors: ILexerDefinitionError[] = [];\n\n const canBeTested = reduce(\n tokenTypes,\n (result, tokType, idx) => {\n const pattern = tokType.PATTERN;\n\n if (pattern === Lexer.NA) {\n return result;\n }\n\n // a more comprehensive validation for all forms of regExps would require\n // deeper regExp analysis capabilities\n if (isString(pattern)) {\n result.push({ str: pattern, idx, tokenType: tokType });\n } else if (isRegExp(pattern) && noMetaChar(pattern)) {\n result.push({ str: pattern.source, idx, tokenType: tokType });\n }\n return result;\n },\n [] as { str: string; idx: number; tokenType: TokenType }[],\n );\n\n forEach(tokenTypes, (aTokType, aIdx) => {\n forEach(canBeTested, ({ str: bStr, idx: bIdx, tokenType: bTokType }) => {\n if (aIdx < bIdx && tryToMatchStrToPattern(bStr, aTokType.PATTERN)) {\n const msg =\n `Token: ->${bTokType.name}<- can never be matched.\\n` +\n `Because it appears AFTER the Token Type ->${aTokType.name}<-` +\n `in the lexer's definition.\\n` +\n `See https://chevrotain.io/docs/guide/resolving_lexer_errors.html#UNREACHABLE`;\n errors.push({\n message: msg,\n type: LexerDefinitionErrorType.UNREACHABLE_PATTERN,\n tokenTypes: [aTokType, bTokType],\n });\n }\n });\n });\n\n return errors;\n}\n\nfunction tryToMatchStrToPattern(str: string, pattern: any): boolean {\n if (isRegExp(pattern)) {\n if (usesLookAheadOrBehind(pattern)) {\n // if lookahead or lookbehind assertions are used\n // we assume they would be responsible for disambiguating the match\n // The alternative is to risk false positive unreachable pattern errors.\n // e.g.: /(?<!a)b/ and /b/ tokens would cause such false positives.\n return false;\n }\n const regExpArray = pattern.exec(str);\n return regExpArray !== null && regExpArray.index === 0;\n } else if (isFunction(pattern)) {\n // maintain the API of custom patterns\n return pattern(str, 0, [], {});\n } else if (has(pattern, \"exec\")) {\n // maintain the API of custom patterns\n return pattern.exec(str, 0, [], {});\n } else if (typeof pattern === \"string\") {\n return pattern === str;\n } else {\n throw Error(\"non exhaustive match\");\n }\n}\n\nfunction noMetaChar(regExp: RegExp): boolean {\n //https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp\n const metaChars = [\n \".\",\n \"\\\\\",\n \"[\",\n \"]\",\n \"|\",\n \"^\",\n \"$\",\n \"(\",\n \")\",\n \"?\",\n \"*\",\n \"+\",\n \"{\",\n ];\n return (\n find(metaChars, (char) => regExp.source.indexOf(char) !== -1) === undefined\n );\n}\n\nfunction usesLookAheadOrBehind(regExp: RegExp): boolean {\n return /(\\(\\?=)|(\\(\\?!)|(\\(\\?<=)|(\\(\\?<!)/.test(regExp.source);\n}\n\nexport function addStartOfInput(pattern: RegExp): RegExp {\n const flags = pattern.ignoreCase ? \"i\" : \"\";\n // always wrapping in a none capturing group preceded by '^' to make sure matching can only work on start of input.\n // duplicate/redundant start of input markers have no meaning (/^^^^A/ === /^A/)\n return new RegExp(`^(?:${pattern.source})`, flags);\n}\n\nexport function addStickyFlag(pattern: RegExp): RegExp {\n const flags = pattern.ignoreCase ? \"iy\" : \"y\";\n return new RegExp(`${pattern.source}`, flags);\n}\n\nexport function performRuntimeChecks(\n lexerDefinition: IMultiModeLexerDefinition,\n trackLines: boolean,\n lineTerminatorCharacters: (number | string)[],\n): ILexerDefinitionError[] {\n const errors: ILexerDefinitionError[] = [];\n\n // some run time checks to help the end users.\n if (!has(lexerDefinition, DEFAULT_MODE)) {\n errors.push({\n message:\n \"A MultiMode Lexer cannot be initialized without a <\" +\n DEFAULT_MODE +\n \"> property in its definition\\n\",\n type: LexerDefinitionErrorType.MULTI_MODE_LEXER_WITHOUT_DEFAULT_MODE,\n });\n }\n if (!has(lexerDefinition, MODES)) {\n errors.push({\n message:\n \"A MultiMode Lexer cannot be initialized without a <\" +\n MODES +\n \"> property in its definition\\n\",\n type: LexerDefinitionErrorType.MULTI_MODE_LEXER_WITHOUT_MODES_PROPERTY,\n });\n }\n\n if (\n has(lexerDefinition, MODES) &&\n has(lexerDefinition, DEFAULT_MODE) &&\n !has(lexerDefinition.modes, lexerDefinition.defaultMode)\n ) {\n errors.push({\n message:\n `A MultiMode Lexer cannot be initialized with a ${DEFAULT_MODE}: <${lexerDefinition.defaultMode}>` +\n `which does not exist\\n`,\n type: LexerDefinitionErrorType.MULTI_MODE_LEXER_DEFAULT_MODE_VALUE_DOES_NOT_EXIST,\n });\n }\n\n if (has(lexerDefinition, MODES)) {\n forEach(lexerDefinition.modes, (currModeValue, currModeName) => {\n forEach(currModeValue, (currTokType, currIdx) => {\n if (isUndefined(currTokType)) {\n errors.push({\n message:\n `A Lexer cannot be initialized using an undefined Token Type. Mode:` +\n `<${currModeName}> at index: <${currIdx}>\\n`,\n type: LexerDefinitionErrorType.LEXER_DEFINITION_CANNOT_CONTAIN_UNDEFINED,\n });\n } else if (has(currTokType, \"LONGER_ALT\")) {\n const longerAlt = isArray(currTokType.LONGER_ALT)\n ? currTokType.LONGER_ALT\n : [currTokType.LONGER_ALT];\n forEach(longerAlt, (currLongerAlt) => {\n if (\n !isUndefined(currLongerAlt) &&\n !includes(currModeValue, currLongerAlt)\n ) {\n errors.push({\n message: `A MultiMode Lexer cannot be initialized with a longer_alt <${currLongerAlt.name}> on token <${currTokType.name}> outside of mode <${currModeName}>\\n`,\n type: LexerDefinitionErrorType.MULTI_MODE_LEXER_LONGER_ALT_NOT_IN_CURRENT_MODE,\n });\n }\n });\n }\n });\n });\n }\n\n return errors;\n}\n\nexport function performWarningRuntimeChecks(\n lexerDefinition: IMultiModeLexerDefinition,\n trackLines: boolean,\n lineTerminatorCharacters: (number | string)[],\n): ILexerDefinitionError[] {\n const warnings = [];\n let hasAnyLineBreak = false;\n const allTokenTypes = compact(flatten(values(lexerDefinition.modes)));\n\n const concreteTokenTypes = reject(\n allTokenTypes,\n (currType) => currType[PATTERN] === Lexer.NA,\n );\n const terminatorCharCodes = getCharCodes(lineTerminatorCharacters);\n if (trackLines) {\n forEach(concreteTokenTypes, (tokType) => {\n const currIssue = checkLineBreaksIssues(tokType, terminatorCharCodes);\n if (currIssue !== false) {\n const message = buildLineBreakIssueMessage(tokType, currIssue);\n const warningDescriptor = {\n message,\n type: currIssue.issue,\n tokenType: tokType,\n };\n warnings.push(warningDescriptor);\n } else {\n // we don't want to attempt to scan if the user explicitly specified the line_breaks option.\n if (has(tokType, \"LINE_BREAKS\")) {\n if (tokType.LINE_BREAKS === true) {\n hasAnyLineBreak = true;\n }\n } else {\n if (\n canMatchCharCode(terminatorCharCodes, tokType.PATTERN as RegExp)\n ) {\n hasAnyLineBreak = true;\n }\n }\n }\n });\n }\n\n if (trackLines && !hasAnyLineBreak) {\n warnings.push({\n message:\n \"Warning: No LINE_BREAKS Found.\\n\" +\n \"\\tThis Lexer has been defined to track line and column information,\\n\" +\n \"\\tBut none of the Token Types can be identified as matching a line terminator.\\n\" +\n \"\\tSee https://chevrotain.io/docs/guide/resolving_lexer_errors.html#LINE_BREAKS \\n\" +\n \"\\tfor details.\",\n type: LexerDefinitionErrorType.NO_LINE_BREAKS_FLAGS,\n });\n }\n return warnings;\n}\n\nexport function cloneEmptyGroups(emptyGroups: {\n [groupName: string]: IToken;\n}): { [groupName: string]: IToken } {\n const clonedResult: any = {};\n const groupKeys = keys(emptyGroups);\n\n forEach(groupKeys, (currKey) => {\n const currGroupValue = emptyGroups[currKey];\n\n /* istanbul ignore else */\n if (isArray(currGroupValue)) {\n clonedResult[currKey] = [];\n } else {\n throw Error(\"non exhaustive match\");\n }\n });\n\n return clonedResult;\n}\n\n// TODO: refactor to avoid duplication\nexport function isCustomPattern(tokenType: TokenType): boolean {\n const pattern = tokenType.PATTERN;\n /* istanbul ignore else */\n if (isRegExp(pattern)) {\n return false;\n } else if (isFunction(pattern)) {\n // CustomPatternMatcherFunc - custom patterns do not require any transformations, only wrapping in a RegExp Like object\n return true;\n } else if (has(pattern, \"exec\")) {\n // ICustomPattern\n return true;\n } else if (isString(pattern)) {\n return false;\n } else {\n throw Error(\"non exhaustive match\");\n }\n}\n\nexport function isShortPattern(pattern: any): number | false {\n if (isString(pattern) && pattern.length === 1) {\n return pattern.charCodeAt(0);\n } else {\n return false;\n }\n}\n\n/**\n * Faster than using a RegExp for default newline detection during lexing.\n */\nexport const LineTerminatorOptimizedTester: ILineTerminatorsTester = {\n // implements /\\n|\\r\\n?/g.test\n test: function (text) {\n const len = text.length;\n for (let i = this.lastIndex; i < len; i++) {\n const c = text.charCodeAt(i);\n if (c === 10) {\n this.lastIndex = i + 1;\n return true;\n } else if (c === 13) {\n if (text.charCodeAt(i + 1) === 10) {\n this.lastIndex = i + 2;\n } else {\n this.lastIndex = i + 1;\n }\n return true;\n }\n }\n return false;\n },\n\n lastIndex: 0,\n};\n\nfunction checkLineBreaksIssues(\n tokType: TokenType,\n lineTerminatorCharCodes: number[],\n):\n | {\n issue:\n | LexerDefinitionErrorType.IDENTIFY_TERMINATOR\n | LexerDefinitionErrorType.CUSTOM_LINE_BREAK;\n errMsg?: string;\n }\n | false {\n if (has(tokType, \"LINE_BREAKS\")) {\n // if the user explicitly declared the line_breaks option we will respect their choice\n // and assume it is correct.\n return false;\n } else {\n /* istanbul ignore else */\n if (isRegExp(tokType.PATTERN)) {\n try {\n // TODO: why is the casting suddenly needed?\n canMatchCharCode(lineTerminatorCharCodes, tokType.PATTERN as RegExp);\n } catch (e) {\n /* istanbul ignore next - to test this we would have to mock <canMatchCharCode> to throw an error */\n return {\n issue: LexerDefinitionErrorType.IDENTIFY_TERMINATOR,\n errMsg: (e as Error).message,\n };\n }\n return false;\n } else if (isString(tokType.PATTERN)) {\n // string literal patterns can always be analyzed to detect line terminator usage\n return false;\n } else if (isCustomPattern(tokType)) {\n // custom token types\n return { issue: LexerDefinitionErrorType.CUSTOM_LINE_BREAK };\n } else {\n throw Error(\"non exhaustive match\");\n }\n }\n}\n\nexport function buildLineBreakIssueMessage(\n tokType: TokenType,\n details: {\n issue:\n | LexerDefinitionErrorType.IDENTIFY_TERMINATOR\n | LexerDefinitionErrorType.CUSTOM_LINE_BREAK;\n errMsg?: string;\n },\n): string {\n /* istanbul ignore else */\n if (details.issue === LexerDefinitionErrorType.IDENTIFY_TERMINATOR) {\n return (\n \"Warning: unable to identify line terminator usage in pattern.\\n\" +\n `\\tThe problem is in the <${tokType.name}> Token Type\\n` +\n `\\t Root cause: ${details.errMsg}.\\n` +\n \"\\tFor details See: https://chevrotain.io/docs/guide/resolving_lexer_errors.html#IDENTIFY_TERMINATOR\"\n );\n } else if (details.issue === LexerDefinitionErrorType.CUSTOM_LINE_BREAK) {\n return (\n \"Warning: A Custom Token Pattern should specify the <line_breaks> option.\\n\" +\n `\\tThe problem is in the <${tokType.name}> Token Type\\n` +\n \"\\tFor details See: https://chevrotain.io/docs/guide/resolving_lexer_errors.html#CUSTOM_LINE_BREAK\"\n );\n } else {\n throw Error(\"non exhaustive match\");\n }\n}\n\nfunction getCharCodes(charsOrCodes: (number | string)[]): number[] {\n const charCodes = map(charsOrCodes, (numOrString) => {\n if (isString(numOrString)) {\n return numOrString.charCodeAt(0);\n } else {\n return numOrString;\n }\n });\n\n return charCodes;\n}\n\nfunction addToMapOfArrays<T>(\n map: Record<number, T[]>,\n key: number,\n value: T,\n): void {\n if (map[key] === undefined) {\n map[key] = [value];\n } else {\n map[key].push(value);\n }\n}\n\nexport const minOptimizationVal = 256;\n\n/**\n * We are mapping charCode above ASCI (256) into buckets each in the size of 256.\n * This is because ASCI are the most common start chars so each one of those will get its own\n * possible token configs vector.\n *\n * Tokens starting with charCodes \"above\" ASCI are uncommon, so we can \"afford\"\n * to place these into buckets of possible token configs, What we gain from\n * this is avoiding the case of creating an optimization 'charCodeToPatternIdxToConfig'\n * which would contain 10,000+ arrays of small size (e.g unicode Identifiers scenario).\n * Our 'charCodeToPatternIdxToConfig' max size will now be:\n * 256 + (2^16 / 2^8) - 1 === 511\n *\n * note the hack for fast division integer part extraction\n * See: https://stackoverflow.com/a/4228528\n */\nlet charCodeToOptimizedIdxMap: number[] = [];\nexport function charCodeToOptimizedIndex(charCode: number): number {\n return charCode < minOptimizationVal\n ? charCode\n : charCodeToOptimizedIdxMap[charCode];\n}\n\n/**\n * This is a compromise between cold start / hot running performance\n * Creating this array takes ~3ms on a modern machine,\n * But if we perform the computation at runtime as needed the CSS Lexer benchmark\n * performance degrades by ~10%\n *\n * TODO: Perhaps it should be lazy initialized only if a charCode > 255 is used.\n */\nfunction initCharCodeToOptimizedIndexMap() {\n if (isEmpty(charCodeToOptimizedIdxMap)) {\n charCodeToOptimizedIdxMap = new Array(65536);\n for (let i = 0; i < 65536; i++) {\n charCodeToOptimizedIdxMap[i] = i > 255 ? 255 + ~~(i / 255) : i;\n }\n }\n}\n", "import {\n clone,\n compact,\n difference,\n flatten,\n forEach,\n has,\n includes,\n isArray,\n isEmpty,\n map,\n} from \"lodash-es\";\nimport { IToken, TokenType } from \"@chevrotain/types\";\n\nexport function tokenStructuredMatcher(\n tokInstance: IToken,\n tokConstructor: TokenType,\n) {\n const instanceType = tokInstance.tokenTypeIdx;\n if (instanceType === tokConstructor.tokenTypeIdx) {\n return true;\n } else {\n return (\n tokConstructor.isParent === true &&\n tokConstructor.categoryMatchesMap![instanceType] === true\n );\n }\n}\n\n// Optimized tokenMatcher in case our grammar does not use token categories\n// Being so tiny it is much more likely to be in-lined and this avoid the function call overhead\nexport function tokenStructuredMatcherNoCategories(\n token: IToken,\n tokType: TokenType,\n) {\n return token.tokenTypeIdx === tokType.tokenTypeIdx;\n}\n\nexport let tokenShortNameIdx = 1;\nexport const tokenIdxToClass: { [tokenIdx: number]: TokenType } = {};\n\nexport function augmentTokenTypes(tokenTypes: TokenType[]): void {\n // collect the parent Token Types as well.\n const tokenTypesAndParents = expandCategories(tokenTypes);\n\n // add required tokenType and categoryMatches properties\n assignTokenDefaultProps(tokenTypesAndParents);\n\n // fill up the categoryMatches\n assignCategoriesMapProp(tokenTypesAndParents);\n assignCategoriesTokensProp(tokenTypesAndParents);\n\n forEach(tokenTypesAndParents, (tokType) => {\n tokType.isParent = tokType.categoryMatches!.length > 0;\n });\n}\n\nexport function expandCategories(tokenTypes: TokenType[]): TokenType[] {\n let result = clone(tokenTypes);\n\n let categories = tokenTypes;\n let searching = true;\n while (searching) {\n categories = compact(\n flatten(map(categories, (currTokType) => currTokType.CATEGORIES)),\n );\n\n const newCategories = difference(categories, result);\n\n result = result.concat(newCategories);\n\n if (isEmpty(newCategories)) {\n searching = false;\n } else {\n categories = newCategories;\n }\n }\n return result;\n}\n\nexport function assignTokenDefaultProps(tokenTypes: TokenType[]): void {\n forEach(tokenTypes, (currTokType) => {\n if (!hasShortKeyProperty(currTokType)) {\n tokenIdxToClass[tokenShortNameIdx] = currTokType;\n (<any>currTokType).tokenTypeIdx = tokenShortNameIdx++;\n }\n\n // CATEGORIES? : TokenType | TokenType[]\n if (\n hasCategoriesProperty(currTokType) &&\n !isArray(currTokType.CATEGORIES)\n // &&\n // !isUndefined(currTokType.CATEGORIES.PATTERN)\n ) {\n currTokType.CATEGORIES = [currTokType.CATEGORIES as unknown as TokenType];\n }\n\n if (!hasCategoriesProperty(currTokType)) {\n currTokType.CATEGORIES = [];\n }\n\n if (!hasExtendingTokensTypesProperty(currTokType)) {\n currTokType.categoryMatches = [];\n }\n\n if (!hasExtendingTokensTypesMapProperty(currTokType)) {\n currTokType.categoryMatchesMap = {};\n }\n });\n}\n\nexport function assignCategoriesTokensProp(tokenTypes: TokenType[]): void {\n forEach(tokenTypes, (currTokType) => {\n // avoid duplications\n currTokType.categoryMatches = [];\n forEach(currTokType.categoryMatchesMap!, (val, key) => {\n currTokType.categoryMatches!.push(\n tokenIdxToClass[key as unknown as number].tokenTypeIdx!,\n );\n });\n });\n}\n\nexport function assignCategoriesMapProp(tokenTypes: TokenType[]): void {\n forEach(tokenTypes, (currTokType) => {\n singleAssignCategoriesToksMap([], currTokType);\n });\n}\n\nexport function singleAssignCategoriesToksMap(\n path: TokenType[],\n nextNode: TokenType,\n): void {\n forEach(path, (pathNode) => {\n nextNode.categoryMatchesMap![pathNode.tokenTypeIdx!] = true;\n });\n\n forEach(nextNode.CATEGORIES, (nextCategory) => {\n const newPath = path.concat(nextNode);\n // avoids infinite loops due to cyclic categories.\n if (!includes(newPath, nextCategory)) {\n singleAssignCategoriesToksMap(newPath, nextCategory);\n }\n });\n}\n\nexport function hasShortKeyProperty(tokType: TokenType): boolean {\n return has(tokType, \"tokenTypeIdx\");\n}\n\nexport function hasCategoriesProperty(tokType: TokenType): boolean {\n return has(tokType, \"CATEGORIES\");\n}\n\nexport function hasExtendingTokensTypesProperty(tokType: TokenType): boolean {\n return has(tokType, \"categoryMatches\");\n}\n\nexport function hasExtendingTokensTypesMapProperty(\n tokType: TokenType,\n): boolean {\n return has(tokType, \"categoryMatchesMap\");\n}\n\nexport function isTokenType(tokType: TokenType): boolean {\n return has(tokType, \"tokenTypeIdx\");\n}\n", "import { ILexerErrorMessageProvider, IToken } from \"@chevrotain/types\";\n\nexport const defaultLexerErrorProvider: ILexerErrorMessageProvider = {\n buildUnableToPopLexerModeMessage(token: IToken): string {\n return `Unable to pop Lexer Mode after encountering Token ->${token.image}<- The Mode Stack is empty`;\n },\n\n buildUnexpectedCharactersMessage(\n fullText: string,\n startOffset: number,\n length: number,\n line?: number,\n column?: number,\n mode?: string,\n ): string {\n return (\n `unexpected character: ->${fullText.charAt(\n startOffset,\n )}<- at offset: ${startOffset},` + ` skipped ${length} characters.`\n );\n },\n};\n", "import {\n analyzeTokenTypes,\n charCodeToOptimizedIndex,\n cloneEmptyGroups,\n DEFAULT_MODE,\n IAnalyzeResult,\n IPatternConfig,\n LineTerminatorOptimizedTester,\n performRuntimeChecks,\n performWarningRuntimeChecks,\n validatePatterns,\n} from \"./lexer.js\";\nimport {\n assign,\n clone,\n forEach,\n identity,\n isArray,\n isEmpty,\n isUndefined,\n keys,\n last,\n map,\n noop,\n reduce,\n reject,\n} from \"lodash-es\";\nimport { PRINT_WARNING, timer, toFastProperties } from \"@chevrotain/utils\";\nimport { augmentTokenTypes } from \"./tokens.js\";\nimport {\n CustomPatternMatcherFunc,\n CustomPatternMatcherReturn,\n ILexerConfig,\n ILexerDefinitionError,\n ILexingError,\n IMultiModeLexerDefinition,\n IToken,\n TokenType,\n} from \"@chevrotain/types\";\nimport { defaultLexerErrorProvider } from \"./lexer_errors_public.js\";\nimport { clearRegExpParserCache } from \"./reg_exp_parser.js\";\n\nexport interface ILexingResult {\n tokens: IToken[];\n groups: { [groupName: string]: IToken[] };\n errors: ILexingError[];\n}\n\nexport enum LexerDefinitionErrorType {\n MISSING_PATTERN,\n INVALID_PATTERN,\n EOI_ANCHOR_FOUND,\n UNSUPPORTED_FLAGS_FOUND,\n DUPLICATE_PATTERNS_FOUND,\n INVALID_GROUP_TYPE_FOUND,\n PUSH_MODE_DOES_NOT_EXIST,\n MULTI_MODE_LEXER_WITHOUT_DEFAULT_MODE,\n MULTI_MODE_LEXER_WITHOUT_MODES_PROPERTY,\n MULTI_MODE_LEXER_DEFAULT_MODE_VALUE_DOES_NOT_EXIST,\n LEXER_DEFINITION_CANNOT_CONTAIN_UNDEFINED,\n SOI_ANCHOR_FOUND,\n EMPTY_MATCH_PATTERN,\n NO_LINE_BREAKS_FLAGS,\n UNREACHABLE_PATTERN,\n IDENTIFY_TERMINATOR,\n CUSTOM_LINE_BREAK,\n MULTI_MODE_LEXER_LONGER_ALT_NOT_IN_CURRENT_MODE,\n}\n\nexport interface IRegExpExec {\n exec: CustomPatternMatcherFunc;\n}\n\nconst DEFAULT_LEXER_CONFIG: Required<ILexerConfig> = {\n deferDefinitionErrorsHandling: false,\n positionTracking: \"full\",\n lineTerminatorsPattern: /\\n|\\r\\n?/g,\n lineTerminatorCharacters: [\"\\n\", \"\\r\"],\n ensureOptimizations: false,\n safeMode: false,\n errorMessageProvider: defaultLexerErrorProvider,\n traceInitPerf: false,\n skipValidations: false,\n recoveryEnabled: true,\n};\n\nObject.freeze(DEFAULT_LEXER_CONFIG);\n\nexport class Lexer {\n public static SKIPPED =\n \"This marks a skipped Token pattern, this means each token identified by it will \" +\n \"be consumed and then thrown into oblivion, this can be used to for example to completely ignore whitespace.\";\n\n public static NA = /NOT_APPLICABLE/;\n public lexerDefinitionErrors: ILexerDefinitionError[] = [];\n public lexerDefinitionWarning: ILexerDefinitionError[] = [];\n\n protected patternIdxToConfig: Record<string, IPatternConfig[]> = {};\n protected charCodeToPatternIdxToConfig: {\n [modeName: string]: { [charCode: number]: IPatternConfig[] };\n } = {};\n\n protected modes: string[] = [];\n protected defaultMode!: string;\n protected emptyGroups: { [groupName: string]: IToken } = {};\n\n private config: Required<ILexerConfig>;\n private trackStartLines: boolean = true;\n private trackEndLines: boolean = true;\n private hasCustom: boolean = false;\n private canModeBeOptimized: Record<string, boolean> = {};\n\n private traceInitPerf!: boolean | number;\n private traceInitMaxIdent!: number;\n private traceInitIndent: number;\n\n constructor(\n protected lexerDefinition: TokenType[] | IMultiModeLexerDefinition,\n config: ILexerConfig = DEFAULT_LEXER_CONFIG,\n ) {\n if (typeof config === \"boolean\") {\n throw Error(\n \"The second argument to the Lexer constructor is now an ILexerConfig Object.\\n\" +\n \"a boolean 2nd argument is no longer supported\",\n );\n }\n\n this.config = assign({}, DEFAULT_LEXER_CONFIG, config) as any;\n\n const traceInitVal = this.config.traceInitPerf;\n if (traceInitVal === true) {\n this.traceInitMaxIdent = Infinity;\n this.traceInitPerf = true;\n } else if (typeof traceInitVal === \"number\") {\n this.traceInitMaxIdent = traceInitVal;\n this.traceInitPerf = true;\n }\n this.traceInitIndent = -1;\n\n this.TRACE_INIT(\"Lexer Constructor\", () => {\n let actualDefinition!: IMultiModeLexerDefinition;\n let hasOnlySingleMode = true;\n this.TRACE_INIT(\"Lexer Config handling\", () => {\n if (\n this.config.lineTerminatorsPattern ===\n DEFAULT_LEXER_CONFIG.lineTerminatorsPattern\n ) {\n // optimized built-in implementation for the defaults definition of lineTerminators\n this.config.lineTerminatorsPattern = LineTerminatorOptimizedTester;\n } else {\n if (\n this.config.lineTerminatorCharacters ===\n DEFAULT_LEXER_CONFIG.lineTerminatorCharacters\n ) {\n throw Error(\n \"Error: Missing <lineTerminatorCharacters> property on the Lexer config.\\n\" +\n \"\\tFor details See: https://chevrotain.io/docs/guide/resolving_lexer_errors.html#MISSING_LINE_TERM_CHARS\",\n );\n }\n }\n\n if (config.safeMode && config.ensureOptimizations) {\n throw Error(\n '\"safeMode\" and \"ensureOptimizations\" flags are mutually exclusive.',\n );\n }\n\n this.trackStartLines = /full|onlyStart/i.test(\n this.config.positionTracking,\n );\n this.trackEndLines = /full/i.test(this.config.positionTracking);\n\n // Convert SingleModeLexerDefinition into a IMultiModeLexerDefinition.\n if (isArray(lexerDefinition)) {\n actualDefinition = {\n modes: { defaultMode: clone(lexerDefinition) },\n defaultMode: DEFAULT_MODE,\n };\n } else {\n // no conversion needed, input should already be a IMultiModeLexerDefinition\n hasOnlySingleMode = false;\n actualDefinition = clone(<IMultiModeLexerDefinition>lexerDefinition);\n }\n });\n\n if (this.config.skipValidations === false) {\n this.TRACE_INIT(\"performRuntimeChecks\", () => {\n this.lexerDefinitionErrors = this.lexerDefinitionErrors.concat(\n performRuntimeChecks(\n actualDefinition,\n this.trackStartLines,\n this.config.lineTerminatorCharacters,\n ),\n );\n });\n\n this.TRACE_INIT(\"performWarningRuntimeChecks\", () => {\n this.lexerDefinitionWarning = this.lexerDefinitionWarning.concat(\n performWarningRuntimeChecks(\n actualDefinition,\n this.trackStartLines,\n this.config.lineTerminatorCharacters,\n ),\n );\n });\n }\n\n // for extra robustness to avoid throwing a none informative error message\n actualDefinition.modes = actualDefinition.modes\n ? actualDefinition.modes\n : {};\n\n // an error of undefined TokenTypes will be detected in \"performRuntimeChecks\" above.\n // this transformation is to increase robustness in the case of partially invalid lexer definition.\n forEach(actualDefinition.modes, (currModeValue, currModeName) => {\n actualDefinition.modes[currModeName] = reject<TokenType>(\n currModeValue,\n (currTokType) => isUndefined(currTokType),\n );\n });\n\n const allModeNames = keys(actualDefinition.modes);\n\n forEach(\n actualDefinition.modes,\n (currModDef: TokenType[], currModName) => {\n this.TRACE_INIT(`Mode: <${currModName}> processing`, () => {\n this.modes.push(currModName);\n\n if (this.config.skipValidations === false) {\n this.TRACE_INIT(`validatePatterns`, () => {\n this.lexerDefinitionErrors = this.lexerDefinitionErrors.concat(\n validatePatterns(currModDef, allModeNames),\n );\n });\n }\n\n // If definition errors were encountered, the analysis phase may fail unexpectedly/\n // Considering a lexer with definition errors may never be used, there is no point\n // to performing the analysis anyhow...\n if (isEmpty(this.lexerDefinitionErrors)) {\n augmentTokenTypes(currModDef);\n\n let currAnalyzeResult!: IAnalyzeResult;\n this.TRACE_INIT(`analyzeTokenTypes`, () => {\n currAnalyzeResult = analyzeTokenTypes(currModDef, {\n lineTerminatorCharacters:\n this.config.lineTerminatorCharacters,\n positionTracking: config.positionTracking,\n ensureOptimizations: config.ensureOptimizations,\n safeMode: config.safeMode,\n tracer: this.TRACE_INIT,\n });\n });\n\n this.patternIdxToConfig[currModName] =\n currAnalyzeResult.patternIdxToConfig;\n\n this.charCodeToPatternIdxToConfig[currModName] =\n currAnalyzeResult.charCodeToPatternIdxToConfig;\n\n this.emptyGroups = assign(\n {},\n this.emptyGroups,\n currAnalyzeResult.emptyGroups,\n ) as any;\n\n this.hasCustom = currAnalyzeResult.hasCustom || this.hasCustom;\n\n this.canModeBeOptimized[currModName] =\n currAnalyzeResult.canBeOptimized;\n }\n });\n },\n );\n\n this.defaultMode = actualDefinition.defaultMode;\n\n if (\n !isEmpty(this.lexerDefinitionErrors) &&\n !this.config.deferDefinitionErrorsHandling\n ) {\n const allErrMessages = map(this.lexerDefinitionErrors, (error) => {\n return error.message;\n });\n const allErrMessagesString = allErrMessages.join(\n \"-----------------------\\n\",\n );\n throw new Error(\n \"Errors detected in definition of Lexer:\\n\" + allErrMessagesString,\n );\n }\n\n // Only print warning if there are no errors, This will avoid pl\n forEach(this.lexerDefinitionWarning, (warningDescriptor) => {\n PRINT_WARNING(warningDescriptor.message);\n });\n\n this.TRACE_INIT(\"Choosing sub-methods implementations\", () => {\n // Choose the relevant internal implementations for this specific parser.\n // These implementations should be in-lined by the JavaScript engine\n // to provide optimal performance in each scenario.\n\n if (hasOnlySingleMode) {\n this.handleModes = noop;\n }\n\n if (this.trackStartLines === false) {\n this.computeNewColumn = identity;\n }\n\n if (this.trackEndLines === false) {\n this.updateTokenEndLineColumnLocation = noop;\n }\n\n if (/full/i.test(this.config.positionTracking)) {\n this.createTokenInstance = this.createFullToken;\n } else if (/onlyStart/i.test(this.config.positionTracking)) {\n this.createTokenInstance = this.createStartOnlyToken;\n } else if (/onlyOffset/i.test(this.config.positionTracking)) {\n this.createTokenInstance = this.createOffsetOnlyToken;\n } else {\n throw Error(\n `Invalid <positionTracking> config option: \"${this.config.positionTracking}\"`,\n );\n }\n\n if (this.hasCustom) {\n this.addToken = this.addTokenUsingPush;\n this.handlePayload = this.handlePayloadWithCustom;\n } else {\n this.addToken = this.addTokenUsingMemberAccess;\n this.handlePayload = this.handlePayloadNoCustom;\n }\n });\n\n this.TRACE_INIT(\"Failed Optimization Warnings\", () => {\n const unOptimizedModes = reduce(\n this.canModeBeOptimized,\n (cannotBeOptimized, canBeOptimized, modeName) => {\n if (canBeOptimized === false) {\n cannotBeOptimized.push(modeName);\n }\n return cannotBeOptimized;\n },\n [] as string[],\n );\n\n if (config.ensureOptimizations && !isEmpty(unOptimizedModes)) {\n throw Error(\n `Lexer Modes: < ${unOptimizedModes.join(\n \", \",\n )} > cannot be optimized.\\n` +\n '\\t Disable the \"ensureOptimizations\" lexer config flag to silently ignore this and run the lexer in an un-optimized mode.\\n' +\n \"\\t Or inspect the console log for details on how to resolve these issues.\",\n );\n }\n });\n\n this.TRACE_INIT(\"clearRegExpParserCache\", () => {\n clearRegExpParserCache();\n });\n\n this.TRACE_INIT(\"toFastProperties\", () => {\n toFastProperties(this);\n });\n });\n }\n\n public tokenize(\n text: string,\n initialMode: string = this.defaultMode,\n ): ILexingResult {\n if (!isEmpty(this.lexerDefinitionErrors)) {\n const allErrMessages = map(this.lexerDefinitionErrors, (error) => {\n return error.message;\n });\n const allErrMessagesString = allErrMessages.join(\n \"-----------------------\\n\",\n );\n throw new Error(\n \"Unable to Tokenize because Errors detected in definition of Lexer:\\n\" +\n allErrMessagesString,\n );\n }\n\n return this.tokenizeInternal(text, initialMode);\n }\n\n // There is quite a bit of duplication between this and \"tokenizeInternalLazy\"\n // This is intentional due to performance considerations.\n // this method also used quite a bit of `!` none null assertions because it is too optimized\n // for `tsc` to always understand it is \"safe\"\n private tokenizeInternal(text: string, initialMode: string): ILexingResult {\n let i,\n j,\n k,\n matchAltImage,\n longerAlt,\n matchedImage: string | null,\n payload,\n altPayload,\n imageLength,\n group,\n tokType,\n newToken: IToken,\n errLength,\n msg,\n match;\n const orgText = text;\n const orgLength = orgText.length;\n let offset = 0;\n let matchedTokensIndex = 0;\n // initializing the tokensArray to the \"guessed\" size.\n // guessing too little will still reduce the number of array re-sizes on pushes.\n // guessing too large (Tested by guessing x4 too large) may cost a bit more of memory\n // but would still have a faster runtime by avoiding (All but one) array resizing.\n const guessedNumberOfTokens = this.hasCustom\n ? 0 // will break custom token pattern APIs the matchedTokens array will contain undefined elements.\n : Math.floor(text.length / 10);\n const matchedTokens = new Array(guessedNumberOfTokens);\n const errors: ILexingError[] = [];\n let line = this.trackStartLines ? 1 : undefined;\n let column = this.trackStartLines ? 1 : undefined;\n const groups: any = cloneEmptyGroups(this.emptyGroups);\n const trackLines = this.trackStartLines;\n const lineTerminatorPattern = this.config.lineTerminatorsPattern;\n\n let currModePatternsLength = 0;\n let patternIdxToConfig: IPatternConfig[] = [];\n let currCharCodeToPatternIdxToConfig: {\n [charCode: number]: IPatternConfig[];\n } = [];\n\n const modeStack: string[] = [];\n\n const emptyArray: IPatternConfig[] = [];\n Object.freeze(emptyArray);\n let isOptimizedMode = false;\n\n const pop_mode = (popToken: IToken) => {\n // TODO: perhaps avoid this error in the edge case there is no more input?\n if (\n modeStack.length === 1 &&\n // if we have both a POP_MODE and a PUSH_MODE this is in-fact a \"transition\"\n // So no error should occur.\n popToken.tokenType.PUSH_MODE === undefined\n ) {\n // if we try to pop the last mode there lexer will no longer have ANY mode.\n // thus the pop is ignored, an error will be created and the lexer will continue parsing in the previous mode.\n const msg =\n this.config.errorMessageProvider.buildUnableToPopLexerModeMessage(\n popToken,\n );\n\n errors.push({\n offset: popToken.startOffset,\n line: popToken.startLine,\n column: popToken.startColumn,\n length: popToken.image.length,\n message: msg,\n });\n } else {\n modeStack.pop();\n const newMode = last(modeStack)!;\n patternIdxToConfig = this.patternIdxToConfig[newMode];\n currCharCodeToPatternIdxToConfig =\n this.charCodeToPatternIdxToConfig[newMode];\n currModePatternsLength = patternIdxToConfig.length;\n const modeCanBeOptimized =\n this.canModeBeOptimized[newMode] && this.config.safeMode === false;\n\n if (currCharCodeToPatternIdxToConfig && modeCanBeOptimized) {\n isOptimizedMode = true;\n } else {\n isOptimizedMode = false;\n }\n }\n };\n\n function push_mode(this: Lexer, newMode: string) {\n modeStack.push(newMode);\n currCharCodeToPatternIdxToConfig =\n this.charCodeToPatternIdxToConfig[newMode];\n\n patternIdxToConfig = this.patternIdxToConfig[newMode];\n currModePatternsLength = patternIdxToConfig.length;\n\n currModePatternsLength = patternIdxToConfig.length;\n const modeCanBeOptimized =\n this.canModeBeOptimized[newMode] && this.config.safeMode === false;\n\n if (currCharCodeToPatternIdxToConfig && modeCanBeOptimized) {\n isOptimizedMode = true;\n } else {\n isOptimizedMode = false;\n }\n }\n\n // this pattern seems to avoid a V8 de-optimization, although that de-optimization does not\n // seem to matter performance wise.\n push_mode.call(this, initialMode);\n\n let currConfig!: IPatternConfig;\n\n const recoveryEnabled = this.config.recoveryEnabled;\n\n while (offset < orgLength) {\n matchedImage = null;\n imageLength = -1;\n\n const nextCharCode = orgText.charCodeAt(offset);\n let chosenPatternIdxToConfig: IPatternConfig[];\n if (isOptimizedMode) {\n const optimizedCharIdx = charCodeToOptimizedIndex(nextCharCode);\n const possiblePatterns =\n currCharCodeToPatternIdxToConfig[optimizedCharIdx];\n chosenPatternIdxToConfig =\n possiblePatterns !== undefined ? possiblePatterns : emptyArray;\n } else {\n chosenPatternIdxToConfig = patternIdxToConfig;\n }\n const chosenPatternsLength = chosenPatternIdxToConfig.length;\n\n for (i = 0; i < chosenPatternsLength; i++) {\n currConfig = chosenPatternIdxToConfig[i];\n const currPattern = currConfig.pattern;\n payload = null;\n\n // manually in-lined because > 600 chars won't be in-lined in V8\n const singleCharCode = currConfig.short;\n if (singleCharCode !== false) {\n if (nextCharCode === singleCharCode) {\n // single character string\n imageLength = 1;\n matchedImage = currPattern as string;\n }\n } else if (currConfig.isCustom === true) {\n match = (currPattern as IRegExpExec).exec(\n orgText,\n offset,\n matchedTokens,\n groups,\n );\n if (match !== null) {\n matchedImage = match[0];\n imageLength = matchedImage.length;\n if ((match as CustomPatternMatcherReturn).payload !== undefined) {\n payload = (match as CustomPatternMatcherReturn).payload;\n }\n } else {\n matchedImage = null;\n }\n } else {\n (currPattern as RegExp).lastIndex = offset;\n imageLength = this.matchLength(currPattern as RegExp, text, offset);\n }\n\n // longer alts handling\n if (imageLength !== -1) {\n // even though this pattern matched we must try a another longer alternative.\n // this can be used to prioritize keywords over identifiers\n longerAlt = currConfig.longerAlt;\n if (longerAlt !== undefined) {\n matchedImage = text.substring(offset, offset + imageLength);\n const longerAltLength = longerAlt.length;\n for (k = 0; k < longerAltLength; k++) {\n const longerAltConfig = patternIdxToConfig[longerAlt[k]];\n const longerAltPattern = longerAltConfig.pattern;\n altPayload = null;\n\n // single Char can never be a longer alt so no need to test it.\n // manually in-lined because > 600 chars won't be in-lined in V8\n if (longerAltConfig.isCustom === true) {\n match = (longerAltPattern as IRegExpExec).exec(\n orgText,\n offset,\n matchedTokens,\n groups,\n );\n if (match !== null) {\n matchAltImage = match[0];\n if (\n (match as CustomPatternMatcherReturn).payload !== undefined\n ) {\n altPayload = (match as CustomPatternMatcherReturn).payload;\n }\n } else {\n matchAltImage = null;\n }\n } else {\n (longerAltPattern as RegExp).lastIndex = offset;\n matchAltImage = this.match(\n longerAltPattern as RegExp,\n text,\n offset,\n );\n }\n\n if (matchAltImage && matchAltImage.length > matchedImage.length) {\n matchedImage = matchAltImage;\n imageLength = matchAltImage.length;\n payload = altPayload;\n currConfig = longerAltConfig;\n // Exit the loop early after matching one of the longer alternatives\n // The first matched alternative takes precedence\n break;\n }\n }\n }\n break;\n }\n }\n\n // successful match\n if (imageLength !== -1) {\n group = currConfig.group;\n if (group !== undefined) {\n matchedImage =\n matchedImage !== null\n ? matchedImage // for custom Tokens we will already have the `matchedImage`\n : text.substring(offset, offset + imageLength);\n tokType = currConfig.tokenTypeIdx;\n newToken = this.createTokenInstance(\n matchedImage,\n offset,\n tokType,\n currConfig.tokenType,\n line,\n column,\n imageLength,\n );\n\n this.handlePayload(newToken, payload);\n\n if (group === false) {\n matchedTokensIndex = this.addToken(\n matchedTokens,\n matchedTokensIndex,\n newToken,\n );\n } else {\n groups[group].push(newToken);\n }\n }\n\n // line terminator handling\n if (trackLines === true && currConfig.canLineTerminator === true) {\n let numOfLTsInMatch = 0;\n let foundTerminator;\n let lastLTEndOffset: number;\n lineTerminatorPattern.lastIndex = 0;\n do {\n // only for skipped tokens the matchedImage may be null at this point\n matchedImage =\n matchedImage !== null\n ? matchedImage\n : text.substring(offset, offset + imageLength);\n foundTerminator = lineTerminatorPattern.test(matchedImage);\n if (foundTerminator === true) {\n lastLTEndOffset = lineTerminatorPattern.lastIndex - 1;\n numOfLTsInMatch++;\n }\n } while (foundTerminator === true);\n\n if (numOfLTsInMatch !== 0) {\n line = line! + numOfLTsInMatch;\n column = imageLength - lastLTEndOffset!;\n this.updateTokenEndLineColumnLocation(\n newToken!,\n group!,\n lastLTEndOffset!,\n numOfLTsInMatch,\n line,\n column,\n imageLength,\n );\n } else {\n column = this.computeNewColumn(column!, imageLength);\n }\n } else {\n column = this.computeNewColumn(column!, imageLength);\n }\n\n offset = offset + imageLength;\n\n // will be NOOP if no modes present\n this.handleModes(currConfig, pop_mode, push_mode, newToken!);\n } else {\n // error recovery, drop characters until we identify a valid token's start point\n const errorStartOffset = offset;\n const errorLine = line;\n const errorColumn = column;\n let foundResyncPoint = recoveryEnabled === false;\n\n while (foundResyncPoint === false && offset < orgLength) {\n offset++;\n for (j = 0; j < currModePatternsLength; j++) {\n const currConfig = patternIdxToConfig[j];\n const currPattern = currConfig.pattern;\n\n // manually in-lined because > 600 chars won't be in-lined in V8\n const singleCharCode = currConfig.short;\n if (singleCharCode !== false) {\n if (orgText.charCodeAt(offset) === singleCharCode) {\n // single character string\n foundResyncPoint = true;\n }\n } else if (currConfig.isCustom === true) {\n foundResyncPoint =\n (currPattern as IRegExpExec).exec(\n orgText,\n offset,\n matchedTokens,\n groups,\n ) !== null;\n } else {\n (currPattern as RegExp).lastIndex = offset;\n foundResyncPoint = (currPattern as RegExp).exec(text) !== null;\n }\n\n if (foundResyncPoint === true) {\n break;\n }\n }\n }\n\n errLength = offset - errorStartOffset;\n column = this.computeNewColumn(column!, errLength);\n // at this point we either re-synced or reached the end of the input text\n msg = this.config.errorMessageProvider.buildUnexpectedCharactersMessage(\n orgText,\n errorStartOffset,\n errLength,\n errorLine,\n errorColumn,\n last(modeStack),\n );\n errors.push({\n offset: errorStartOffset,\n line: errorLine,\n column: errorColumn,\n length: errLength,\n message: msg,\n });\n\n if (recoveryEnabled === false) {\n break;\n }\n }\n }\n\n // if we do have custom patterns which push directly into the\n // TODO: custom tokens should not push directly??\n if (!this.hasCustom) {\n // if we guessed a too large size for the tokens array this will shrink it to the right size.\n matchedTokens.length = matchedTokensIndex;\n }\n\n return {\n tokens: matchedTokens,\n groups: groups,\n errors: errors,\n };\n }\n\n private handleModes(\n config: IPatternConfig,\n pop_mode: (tok: IToken) => void,\n push_mode: (this: Lexer, pushMode: string) => void,\n newToken: IToken,\n ) {\n if (config.pop === true) {\n // need to save the PUSH_MODE property as if the mode is popped\n // patternIdxToPopMode is updated to reflect the new mode after popping the stack\n const pushMode = config.push;\n pop_mode(newToken);\n if (pushMode !== undefined) {\n push_mode.call(this, pushMode);\n }\n } else if (config.push !== undefined) {\n push_mode.call(this, config.push);\n }\n }\n\n // TODO: decrease this under 600 characters? inspect stripping comments option in TSC compiler\n private updateTokenEndLineColumnLocation(\n newToken: IToken,\n group: string | false,\n lastLTIdx: number,\n numOfLTsInMatch: number,\n line: number,\n column: number,\n imageLength: number,\n ): void {\n let lastCharIsLT, fixForEndingInLT;\n if (group !== undefined) {\n // a none skipped multi line Token, need to update endLine/endColumn\n lastCharIsLT = lastLTIdx === imageLength - 1;\n fixForEndingInLT = lastCharIsLT ? -1 : 0;\n if (!(numOfLTsInMatch === 1 && lastCharIsLT === true)) {\n // if a token ends in a LT that last LT only affects the line numbering of following Tokens\n newToken.endLine = line + fixForEndingInLT;\n // the last LT in a token does not affect the endColumn either as the [columnStart ... columnEnd)\n // inclusive to exclusive range.\n newToken.endColumn = column - 1 + -fixForEndingInLT;\n }\n // else single LT in the last character of a token, no need to modify the endLine/EndColumn\n }\n }\n\n private computeNewColumn(oldColumn: number, imageLength: number) {\n return oldColumn + imageLength;\n }\n\n // Place holder, will be replaced by the correct variant according to the locationTracking option at runtime.\n /* istanbul ignore next - place holder */\n private createTokenInstance!: (...args: any[]) => IToken;\n\n private createOffsetOnlyToken(\n image: string,\n startOffset: number,\n tokenTypeIdx: number,\n tokenType: TokenType,\n ) {\n return {\n image,\n startOffset,\n tokenTypeIdx,\n tokenType,\n };\n }\n\n private createStartOnlyToken(\n image: string,\n startOffset: number,\n tokenTypeIdx: number,\n tokenType: TokenType,\n startLine: number,\n startColumn: number,\n ) {\n return {\n image,\n startOffset,\n startLine,\n startColumn,\n tokenTypeIdx,\n tokenType,\n };\n }\n\n private createFullToken(\n image: string,\n startOffset: number,\n tokenTypeIdx: number,\n tokenType: TokenType,\n startLine: number,\n startColumn: number,\n imageLength: number,\n ): IToken {\n return {\n image,\n startOffset,\n endOffset: startOffset + imageLength - 1,\n startLine,\n endLine: startLine,\n startColumn,\n endColumn: startColumn + imageLength - 1,\n tokenTypeIdx,\n tokenType,\n };\n }\n\n // Place holder, will be replaced by the correct variant according to the locationTracking option at runtime.\n /* istanbul ignore next - place holder */\n private addToken!: (\n tokenVector: IToken[],\n index: number,\n tokenToAdd: IToken,\n ) => number;\n\n private addTokenUsingPush(\n tokenVector: IToken[],\n index: number,\n tokenToAdd: IToken,\n ): number {\n tokenVector.push(tokenToAdd);\n return index;\n }\n\n private addTokenUsingMemberAccess(\n tokenVector: IToken[],\n index: number,\n tokenToAdd: IToken,\n ): number {\n tokenVector[index] = tokenToAdd;\n index++;\n return index;\n }\n\n // Place holder, will be replaced by the correct variant according to the hasCustom flag option at runtime.\n private handlePayload: (token: IToken, payload: any) => void;\n\n private handlePayloadNoCustom(token: IToken, payload: any): void {}\n\n private handlePayloadWithCustom(token: IToken, payload: any): void {\n if (payload !== null) {\n token.payload = payload;\n }\n }\n\n private match(pattern: RegExp, text: string, offset: number): string | null {\n const found = pattern.test(text);\n if (found === true) {\n return text.substring(offset, pattern.lastIndex);\n }\n return null;\n }\n\n private matchLength(\n pattern: RegExp,\n text: string,\n offset: number,\n ): number | -1 {\n const found = pattern.test(text);\n if (found === true) {\n return pattern.lastIndex - offset;\n }\n return -1;\n }\n\n // Duplicated from the parser's perf trace trait to allow future extraction\n // of the lexer to a separate package.\n TRACE_INIT = <T>(phaseDesc: string, phaseImpl: () => T): T => {\n // No need to optimize this using NOOP pattern because\n // It is not called in a hot spot...\n if (this.traceInitPerf === true) {\n this.traceInitIndent++;\n const indent = new Array(this.traceInitIndent + 1).join(\"\\t\");\n if (this.traceInitIndent < this.traceInitMaxIdent) {\n console.log(`${indent}--> <${phaseDesc}>`);\n }\n const { time, value } = timer(phaseImpl);\n /* istanbul ignore next - Difficult to reproduce specific performance behavior (>10ms) in tests */\n const traceMethod = time > 10 ? console.warn : console.log;\n if (this.traceInitIndent < this.traceInitMaxIdent) {\n traceMethod(`${indent}<-- <${phaseDesc}> time: ${time}ms`);\n }\n this.traceInitIndent--;\n return value;\n } else {\n return phaseImpl();\n }\n };\n}\n", "import { has, isString, isUndefined } from \"lodash-es\";\nimport { Lexer } from \"./lexer_public.js\";\nimport { augmentTokenTypes, tokenStructuredMatcher } from \"./tokens.js\";\nimport { IToken, ITokenConfig, TokenType } from \"@chevrotain/types\";\n\nexport function tokenLabel(tokType: TokenType): string {\n if (hasTokenLabel(tokType)) {\n return tokType.LABEL;\n } else {\n return tokType.name;\n }\n}\n\nexport function tokenName(tokType: TokenType): string {\n return tokType.name;\n}\n\nexport function hasTokenLabel(\n obj: TokenType,\n): obj is TokenType & Pick<Required<TokenType>, \"LABEL\"> {\n return isString(obj.LABEL) && obj.LABEL !== \"\";\n}\n\nconst PARENT = \"parent\";\nconst CATEGORIES = \"categories\";\nconst LABEL = \"label\";\nconst GROUP = \"group\";\nconst PUSH_MODE = \"push_mode\";\nconst POP_MODE = \"pop_mode\";\nconst LONGER_ALT = \"longer_alt\";\nconst LINE_BREAKS = \"line_breaks\";\nconst START_CHARS_HINT = \"start_chars_hint\";\n\nexport function createToken(config: ITokenConfig): TokenType {\n return createTokenInternal(config);\n}\n\nfunction createTokenInternal(config: ITokenConfig): TokenType {\n const pattern = config.pattern;\n\n const tokenType: TokenType = <any>{};\n tokenType.name = config.name;\n\n if (!isUndefined(pattern)) {\n tokenType.PATTERN = pattern;\n }\n\n if (has(config, PARENT)) {\n throw (\n \"The parent property is no longer supported.\\n\" +\n \"See: https://github.com/chevrotain/chevrotain/issues/564#issuecomment-349062346 for details.\"\n );\n }\n\n if (has(config, CATEGORIES)) {\n // casting to ANY as this will be fixed inside `augmentTokenTypes``\n tokenType.CATEGORIES = <any>config[CATEGORIES];\n }\n\n augmentTokenTypes([tokenType]);\n\n if (has(config, LABEL)) {\n tokenType.LABEL = config[LABEL];\n }\n\n if (has(config, GROUP)) {\n tokenType.GROUP = config[GROUP];\n }\n\n if (has(config, POP_MODE)) {\n tokenType.POP_MODE = config[POP_MODE];\n }\n\n if (has(config, PUSH_MODE)) {\n tokenType.PUSH_MODE = config[PUSH_MODE];\n }\n\n if (has(config, LONGER_ALT)) {\n tokenType.LONGER_ALT = config[LONGER_ALT];\n }\n\n if (has(config, LINE_BREAKS)) {\n tokenType.LINE_BREAKS = config[LINE_BREAKS];\n }\n\n if (has(config, START_CHARS_HINT)) {\n tokenType.START_CHARS_HINT = config[START_CHARS_HINT];\n }\n\n return tokenType;\n}\n\nexport const EOF = createToken({ name: \"EOF\", pattern: Lexer.NA });\naugmentTokenTypes([EOF]);\n\nexport function createTokenInstance(\n tokType: TokenType,\n image: string,\n startOffset: number,\n endOffset: number,\n startLine: number,\n endLine: number,\n startColumn: number,\n endColumn: number,\n): IToken {\n return {\n image,\n startOffset,\n endOffset,\n startLine,\n endLine,\n startColumn,\n endColumn,\n tokenTypeIdx: (<any>tokType).tokenTypeIdx,\n tokenType: tokType,\n };\n}\n\nexport function tokenMatcher(token: IToken, tokType: TokenType): boolean {\n return tokenStructuredMatcher(token, tokType);\n}\n", "import { hasTokenLabel, tokenLabel } from \"../scan/tokens_public.js\";\nimport { first, map, reduce } from \"lodash-es\";\nimport {\n Alternation,\n getProductionDslName,\n NonTerminal,\n Rule,\n Terminal,\n} from \"@chevrotain/gast\";\nimport {\n IParserErrorMessageProvider,\n IProductionWithOccurrence,\n TokenType,\n} from \"@chevrotain/types\";\nimport {\n IGrammarResolverErrorMessageProvider,\n IGrammarValidatorErrorMessageProvider,\n} from \"./grammar/types.js\";\n\nexport const defaultParserErrorProvider: IParserErrorMessageProvider = {\n buildMismatchTokenMessage({ expected, actual, previous, ruleName }): string {\n const hasLabel = hasTokenLabel(expected);\n const expectedMsg = hasLabel\n ? `--> ${tokenLabel(expected)} <--`\n : `token of type --> ${expected.name} <--`;\n\n const msg = `Expecting ${expectedMsg} but found --> '${actual.image}' <--`;\n\n return msg;\n },\n\n buildNotAllInputParsedMessage({ firstRedundant, ruleName }): string {\n return \"Redundant input, expecting EOF but found: \" + firstRedundant.image;\n },\n\n buildNoViableAltMessage({\n expectedPathsPerAlt,\n actual,\n previous,\n customUserDescription,\n ruleName,\n }): string {\n const errPrefix = \"Expecting: \";\n // TODO: issue: No Viable Alternative Error may have incomplete details. #502\n const actualText = first(actual)!.image;\n const errSuffix = \"\\nbut found: '\" + actualText + \"'\";\n\n if (customUserDescription) {\n return errPrefix + customUserDescription + errSuffix;\n } else {\n const allLookAheadPaths = reduce(\n expectedPathsPerAlt,\n (result, currAltPaths) => result.concat(currAltPaths),\n [] as TokenType[][],\n );\n const nextValidTokenSequences = map(\n allLookAheadPaths,\n (currPath) =>\n `[${map(currPath, (currTokenType) => tokenLabel(currTokenType)).join(\n \", \",\n )}]`,\n );\n const nextValidSequenceItems = map(\n nextValidTokenSequences,\n (itemMsg, idx) => ` ${idx + 1}. ${itemMsg}`,\n );\n const calculatedDescription = `one of these possible Token sequences:\\n${nextValidSequenceItems.join(\n \"\\n\",\n )}`;\n\n return errPrefix + calculatedDescription + errSuffix;\n }\n },\n\n buildEarlyExitMessage({\n expectedIterationPaths,\n actual,\n customUserDescription,\n ruleName,\n }): string {\n const errPrefix = \"Expecting: \";\n // TODO: issue: No Viable Alternative Error may have incomplete details. #502\n const actualText = first(actual)!.image;\n const errSuffix = \"\\nbut found: '\" + actualText + \"'\";\n\n if (customUserDescription) {\n return errPrefix + customUserDescription + errSuffix;\n } else {\n const nextValidTokenSequences = map(\n expectedIterationPaths,\n (currPath) =>\n `[${map(currPath, (currTokenType) => tokenLabel(currTokenType)).join(\n \",\",\n )}]`,\n );\n const calculatedDescription =\n `expecting at least one iteration which starts with one of these possible Token sequences::\\n ` +\n `<${nextValidTokenSequences.join(\" ,\")}>`;\n\n return errPrefix + calculatedDescription + errSuffix;\n }\n },\n};\n\nObject.freeze(defaultParserErrorProvider);\n\nexport const defaultGrammarResolverErrorProvider: IGrammarResolverErrorMessageProvider =\n {\n buildRuleNotFoundError(\n topLevelRule: Rule,\n undefinedRule: NonTerminal,\n ): string {\n const msg =\n \"Invalid grammar, reference to a rule which is not defined: ->\" +\n undefinedRule.nonTerminalName +\n \"<-\\n\" +\n \"inside top level rule: ->\" +\n topLevelRule.name +\n \"<-\";\n return msg;\n },\n };\n\nexport const defaultGrammarValidatorErrorProvider: IGrammarValidatorErrorMessageProvider =\n {\n buildDuplicateFoundError(\n topLevelRule: Rule,\n duplicateProds: IProductionWithOccurrence[],\n ): string {\n function getExtraProductionArgument(\n prod: IProductionWithOccurrence,\n ): string {\n if (prod instanceof Terminal) {\n return prod.terminalType.name;\n } else if (prod instanceof NonTerminal) {\n return prod.nonTerminalName;\n } else {\n return \"\";\n }\n }\n\n const topLevelName = topLevelRule.name;\n const duplicateProd = first(duplicateProds)!;\n const index = duplicateProd.idx;\n const dslName = getProductionDslName(duplicateProd);\n const extraArgument = getExtraProductionArgument(duplicateProd);\n\n const hasExplicitIndex = index > 0;\n let msg = `->${dslName}${hasExplicitIndex ? index : \"\"}<- ${\n extraArgument ? `with argument: ->${extraArgument}<-` : \"\"\n }\n appears more than once (${\n duplicateProds.length\n } times) in the top level rule: ->${topLevelName}<-. \n For further details see: https://chevrotain.io/docs/FAQ.html#NUMERICAL_SUFFIXES \n `;\n\n // white space trimming time! better to trim afterwards as it allows to use WELL formatted multi line template strings...\n msg = msg.replace(/[ \\t]+/g, \" \");\n msg = msg.replace(/\\s\\s+/g, \"\\n\");\n\n return msg;\n },\n\n buildNamespaceConflictError(rule: Rule): string {\n const errMsg =\n `Namespace conflict found in grammar.\\n` +\n `The grammar has both a Terminal(Token) and a Non-Terminal(Rule) named: <${rule.name}>.\\n` +\n `To resolve this make sure each Terminal and Non-Terminal names are unique\\n` +\n `This is easy to accomplish by using the convention that Terminal names start with an uppercase letter\\n` +\n `and Non-Terminal names start with a lower case letter.`;\n\n return errMsg;\n },\n\n buildAlternationPrefixAmbiguityError(options: {\n topLevelRule: Rule;\n prefixPath: TokenType[];\n ambiguityIndices: number[];\n alternation: Alternation;\n }): string {\n const pathMsg = map(options.prefixPath, (currTok) =>\n tokenLabel(currTok),\n ).join(\", \");\n const occurrence =\n options.alternation.idx === 0 ? \"\" : options.alternation.idx;\n const errMsg =\n `Ambiguous alternatives: <${options.ambiguityIndices.join(\n \" ,\",\n )}> due to common lookahead prefix\\n` +\n `in <OR${occurrence}> inside <${options.topLevelRule.name}> Rule,\\n` +\n `<${pathMsg}> may appears as a prefix path in all these alternatives.\\n` +\n `See: https://chevrotain.io/docs/guide/resolving_grammar_errors.html#COMMON_PREFIX\\n` +\n `For Further details.`;\n\n return errMsg;\n },\n\n buildAlternationAmbiguityError(options: {\n topLevelRule: Rule;\n prefixPath: TokenType[];\n ambiguityIndices: number[];\n alternation: Alternation;\n }): string {\n const occurrence =\n options.alternation.idx === 0 ? \"\" : options.alternation.idx;\n\n const isEmptyPath = options.prefixPath.length === 0;\n\n let currMessage =\n `Ambiguous Alternatives Detected: <${options.ambiguityIndices.join(\n \" ,\",\n )}> in <OR${occurrence}>` +\n ` inside <${options.topLevelRule.name}> Rule,\\n`;\n\n if (isEmptyPath) {\n currMessage +=\n `These alternatives are all empty (match no tokens), making them indistinguishable.\\n` +\n `Only the last alternative may be empty.\\n`;\n } else {\n const pathMsg = map(options.prefixPath, (currtok) =>\n tokenLabel(currtok),\n ).join(\", \");\n currMessage += `<${pathMsg}> may appears as a prefix path in all these alternatives.\\n`;\n }\n\n currMessage +=\n `See: https://chevrotain.io/docs/guide/resolving_grammar_errors.html#AMBIGUOUS_ALTERNATIVES\\n` +\n `For Further details.`;\n return currMessage;\n },\n\n buildEmptyRepetitionError(options: {\n topLevelRule: Rule;\n repetition: IProductionWithOccurrence;\n }): string {\n let dslName = getProductionDslName(options.repetition);\n if (options.repetition.idx !== 0) {\n dslName += options.repetition.idx;\n }\n\n const errMsg =\n `The repetition <${dslName}> within Rule <${options.topLevelRule.name}> can never consume any tokens.\\n` +\n `This could lead to an infinite loop.`;\n\n return errMsg;\n },\n\n // TODO: remove - `errors_public` from nyc.config.js exclude\n // once this method is fully removed from this file\n buildTokenNameError(options: {\n tokenType: TokenType;\n expectedPattern: RegExp;\n }): string {\n /* istanbul ignore next */\n return \"deprecated\";\n },\n\n buildEmptyAlternationError(options: {\n topLevelRule: Rule;\n alternation: Alternation;\n emptyChoiceIdx: number;\n }): string {\n const errMsg =\n `Ambiguous empty alternative: <${options.emptyChoiceIdx + 1}>` +\n ` in <OR${options.alternation.idx}> inside <${options.topLevelRule.name}> Rule.\\n` +\n `Only the last alternative may be an empty alternative.`;\n\n return errMsg;\n },\n\n buildTooManyAlternativesError(options: {\n topLevelRule: Rule;\n alternation: Alternation;\n }): string {\n const errMsg =\n `An Alternation cannot have more than 256 alternatives:\\n` +\n `<OR${options.alternation.idx}> inside <${\n options.topLevelRule.name\n }> Rule.\\n has ${\n options.alternation.definition.length + 1\n } alternatives.`;\n\n return errMsg;\n },\n\n buildLeftRecursionError(options: {\n topLevelRule: Rule;\n leftRecursionPath: Rule[];\n }): string {\n const ruleName = options.topLevelRule.name;\n const pathNames = map(\n options.leftRecursionPath,\n (currRule) => currRule.name,\n );\n const leftRecursivePath = `${ruleName} --> ${pathNames\n .concat([ruleName])\n .join(\" --> \")}`;\n const errMsg =\n `Left Recursion found in grammar.\\n` +\n `rule: <${ruleName}> can be invoked from itself (directly or indirectly)\\n` +\n `without consuming any Tokens. The grammar path that causes this is: \\n ${leftRecursivePath}\\n` +\n ` To fix this refactor your grammar to remove the left recursion.\\n` +\n `see: https://en.wikipedia.org/wiki/LL_parser#Left_factoring.`;\n\n return errMsg;\n },\n\n // TODO: remove - `errors_public` from nyc.config.js exclude\n // once this method is fully removed from this file\n buildInvalidRuleNameError(options: {\n topLevelRule: Rule;\n expectedPattern: RegExp;\n }): string {\n /* istanbul ignore next */\n return \"deprecated\";\n },\n\n buildDuplicateRuleNameError(options: {\n topLevelRule: Rule | string;\n grammarName: string;\n }): string {\n let ruleName;\n if (options.topLevelRule instanceof Rule) {\n ruleName = options.topLevelRule.name;\n } else {\n ruleName = options.topLevelRule;\n }\n\n const errMsg = `Duplicate definition, rule: ->${ruleName}<- is already defined in the grammar: ->${options.grammarName}<-`;\n\n return errMsg;\n },\n };\n", "import {\n IParserUnresolvedRefDefinitionError,\n ParserDefinitionErrorType,\n} from \"../parser/parser.js\";\nimport { forEach, values } from \"lodash-es\";\nimport { GAstVisitor, NonTerminal, Rule } from \"@chevrotain/gast\";\nimport {\n IGrammarResolverErrorMessageProvider,\n IParserDefinitionError,\n} from \"./types.js\";\n\nexport function resolveGrammar(\n topLevels: Record<string, Rule>,\n errMsgProvider: IGrammarResolverErrorMessageProvider,\n): IParserDefinitionError[] {\n const refResolver = new GastRefResolverVisitor(topLevels, errMsgProvider);\n refResolver.resolveRefs();\n return refResolver.errors;\n}\n\nexport class GastRefResolverVisitor extends GAstVisitor {\n public errors: IParserUnresolvedRefDefinitionError[] = [];\n private currTopLevel: Rule;\n\n constructor(\n private nameToTopRule: Record<string, Rule>,\n private errMsgProvider: IGrammarResolverErrorMessageProvider,\n ) {\n super();\n }\n\n public resolveRefs(): void {\n forEach(values(this.nameToTopRule), (prod) => {\n this.currTopLevel = prod;\n prod.accept(this);\n });\n }\n\n public visitNonTerminal(node: NonTerminal): void {\n const ref = this.nameToTopRule[node.nonTerminalName];\n\n if (!ref) {\n const msg = this.errMsgProvider.buildRuleNotFoundError(\n this.currTopLevel,\n node,\n );\n this.errors.push({\n message: msg,\n type: ParserDefinitionErrorType.UNRESOLVED_SUBRULE_REF,\n ruleName: this.currTopLevel.name,\n unresolvedRefName: node.nonTerminalName,\n });\n } else {\n node.referencedRule = ref;\n }\n }\n}\n", "import {\n clone,\n drop,\n dropRight,\n first as _first,\n forEach,\n isEmpty,\n last,\n} from \"lodash-es\";\nimport { first } from \"./first.js\";\nimport { RestWalker } from \"./rest.js\";\nimport { TokenMatcher } from \"../parser/parser.js\";\nimport {\n Alternation,\n Alternative,\n NonTerminal,\n Option,\n Repetition,\n RepetitionMandatory,\n RepetitionMandatoryWithSeparator,\n RepetitionWithSeparator,\n Rule,\n Terminal,\n} from \"@chevrotain/gast\";\nimport {\n IGrammarPath,\n IProduction,\n ISyntacticContentAssistPath,\n IToken,\n ITokenGrammarPath,\n TokenType,\n} from \"@chevrotain/types\";\n\nexport abstract class AbstractNextPossibleTokensWalker extends RestWalker {\n protected possibleTokTypes: TokenType[] = [];\n protected ruleStack: string[];\n protected occurrenceStack: number[];\n\n protected nextProductionName = \"\";\n protected nextProductionOccurrence = 0;\n protected found = false;\n protected isAtEndOfPath = false;\n\n constructor(\n protected topProd: Rule,\n protected path: IGrammarPath,\n ) {\n super();\n }\n\n startWalking(): TokenType[] {\n this.found = false;\n\n if (this.path.ruleStack[0] !== this.topProd.name) {\n throw Error(\"The path does not start with the walker's top Rule!\");\n }\n\n // immutable for the win\n this.ruleStack = clone(this.path.ruleStack).reverse(); // intelij bug requires assertion\n this.occurrenceStack = clone(this.path.occurrenceStack).reverse(); // intelij bug requires assertion\n\n // already verified that the first production is valid, we now seek the 2nd production\n this.ruleStack.pop();\n this.occurrenceStack.pop();\n\n this.updateExpectedNext();\n this.walk(this.topProd);\n\n return this.possibleTokTypes;\n }\n\n walk(\n prod: { definition: IProduction[] },\n prevRest: IProduction[] = [],\n ): void {\n // stop scanning once we found the path\n if (!this.found) {\n super.walk(prod, prevRest);\n }\n }\n\n walkProdRef(\n refProd: NonTerminal,\n currRest: IProduction[],\n prevRest: IProduction[],\n ): void {\n // found the next production, need to keep walking in it\n if (\n refProd.referencedRule.name === this.nextProductionName &&\n refProd.idx === this.nextProductionOccurrence\n ) {\n const fullRest = currRest.concat(prevRest);\n this.updateExpectedNext();\n this.walk(refProd.referencedRule, <any>fullRest);\n }\n }\n\n updateExpectedNext(): void {\n // need to consume the Terminal\n if (isEmpty(this.ruleStack)) {\n // must reset nextProductionXXX to avoid walking down another Top Level production while what we are\n // really seeking is the last Terminal...\n this.nextProductionName = \"\";\n this.nextProductionOccurrence = 0;\n this.isAtEndOfPath = true;\n } else {\n this.nextProductionName = this.ruleStack.pop()!;\n this.nextProductionOccurrence = this.occurrenceStack.pop()!;\n }\n }\n}\n\nexport class NextAfterTokenWalker extends AbstractNextPossibleTokensWalker {\n private nextTerminalName = \"\";\n private nextTerminalOccurrence = 0;\n\n constructor(\n topProd: Rule,\n protected path: ITokenGrammarPath,\n ) {\n super(topProd, path);\n this.nextTerminalName = this.path.lastTok.name;\n this.nextTerminalOccurrence = this.path.lastTokOccurrence;\n }\n\n walkTerminal(\n terminal: Terminal,\n currRest: IProduction[],\n prevRest: IProduction[],\n ): void {\n if (\n this.isAtEndOfPath &&\n terminal.terminalType.name === this.nextTerminalName &&\n terminal.idx === this.nextTerminalOccurrence &&\n !this.found\n ) {\n const fullRest = currRest.concat(prevRest);\n const restProd = new Alternative({ definition: fullRest });\n this.possibleTokTypes = first(restProd);\n this.found = true;\n }\n }\n}\n\nexport type AlternativesFirstTokens = TokenType[][];\n\nexport interface IFirstAfterRepetition {\n token: TokenType | undefined;\n occurrence: number | undefined;\n isEndOfRule: boolean | undefined;\n}\n\n/**\n * This walker only \"walks\" a single \"TOP\" level in the Grammar Ast, this means\n * it never \"follows\" production refs\n */\nexport class AbstractNextTerminalAfterProductionWalker extends RestWalker {\n protected result: IFirstAfterRepetition = {\n token: undefined,\n occurrence: undefined,\n isEndOfRule: undefined,\n };\n\n constructor(\n protected topRule: Rule,\n protected occurrence: number,\n ) {\n super();\n }\n\n startWalking(): IFirstAfterRepetition {\n this.walk(this.topRule);\n return this.result;\n }\n}\n\nexport class NextTerminalAfterManyWalker extends AbstractNextTerminalAfterProductionWalker {\n walkMany(\n manyProd: Repetition,\n currRest: IProduction[],\n prevRest: IProduction[],\n ): void {\n if (manyProd.idx === this.occurrence) {\n const firstAfterMany = _first(currRest.concat(prevRest));\n this.result.isEndOfRule = firstAfterMany === undefined;\n if (firstAfterMany instanceof Terminal) {\n this.result.token = firstAfterMany.terminalType;\n this.result.occurrence = firstAfterMany.idx;\n }\n } else {\n super.walkMany(manyProd, currRest, prevRest);\n }\n }\n}\n\nexport class NextTerminalAfterManySepWalker extends AbstractNextTerminalAfterProductionWalker {\n walkManySep(\n manySepProd: RepetitionWithSeparator,\n currRest: IProduction[],\n prevRest: IProduction[],\n ): void {\n if (manySepProd.idx === this.occurrence) {\n const firstAfterManySep = _first(currRest.concat(prevRest));\n this.result.isEndOfRule = firstAfterManySep === undefined;\n if (firstAfterManySep instanceof Terminal) {\n this.result.token = firstAfterManySep.terminalType;\n this.result.occurrence = firstAfterManySep.idx;\n }\n } else {\n super.walkManySep(manySepProd, currRest, prevRest);\n }\n }\n}\n\nexport class NextTerminalAfterAtLeastOneWalker extends AbstractNextTerminalAfterProductionWalker {\n walkAtLeastOne(\n atLeastOneProd: RepetitionMandatory,\n currRest: IProduction[],\n prevRest: IProduction[],\n ): void {\n if (atLeastOneProd.idx === this.occurrence) {\n const firstAfterAtLeastOne = _first(currRest.concat(prevRest));\n this.result.isEndOfRule = firstAfterAtLeastOne === undefined;\n if (firstAfterAtLeastOne instanceof Terminal) {\n this.result.token = firstAfterAtLeastOne.terminalType;\n this.result.occurrence = firstAfterAtLeastOne.idx;\n }\n } else {\n super.walkAtLeastOne(atLeastOneProd, currRest, prevRest);\n }\n }\n}\n\n// TODO: reduce code duplication in the AfterWalkers\nexport class NextTerminalAfterAtLeastOneSepWalker extends AbstractNextTerminalAfterProductionWalker {\n walkAtLeastOneSep(\n atleastOneSepProd: RepetitionMandatoryWithSeparator,\n currRest: IProduction[],\n prevRest: IProduction[],\n ): void {\n if (atleastOneSepProd.idx === this.occurrence) {\n const firstAfterfirstAfterAtLeastOneSep = _first(\n currRest.concat(prevRest),\n );\n this.result.isEndOfRule = firstAfterfirstAfterAtLeastOneSep === undefined;\n if (firstAfterfirstAfterAtLeastOneSep instanceof Terminal) {\n this.result.token = firstAfterfirstAfterAtLeastOneSep.terminalType;\n this.result.occurrence = firstAfterfirstAfterAtLeastOneSep.idx;\n }\n } else {\n super.walkAtLeastOneSep(atleastOneSepProd, currRest, prevRest);\n }\n }\n}\n\nexport interface PartialPathAndSuffixes {\n partialPath: TokenType[];\n suffixDef: IProduction[];\n}\n\nexport function possiblePathsFrom(\n targetDef: IProduction[],\n maxLength: number,\n currPath: TokenType[] = [],\n): PartialPathAndSuffixes[] {\n // avoid side effects\n currPath = clone(currPath);\n let result: PartialPathAndSuffixes[] = [];\n let i = 0;\n\n // TODO: avoid inner funcs\n function remainingPathWith(nextDef: IProduction[]) {\n return nextDef.concat(drop(targetDef, i + 1));\n }\n\n // TODO: avoid inner funcs\n function getAlternativesForProd(definition: IProduction[]) {\n const alternatives = possiblePathsFrom(\n remainingPathWith(definition),\n maxLength,\n currPath,\n );\n return result.concat(alternatives);\n }\n\n /**\n * Mandatory productions will halt the loop as the paths computed from their recursive calls will already contain the\n * following (rest) of the targetDef.\n *\n * For optional productions (Option/Repetition/...) the loop will continue to represent the paths that do not include the\n * the optional production.\n */\n while (currPath.length < maxLength && i < targetDef.length) {\n const prod = targetDef[i];\n\n /* istanbul ignore else */\n if (prod instanceof Alternative) {\n return getAlternativesForProd(prod.definition);\n } else if (prod instanceof NonTerminal) {\n return getAlternativesForProd(prod.definition);\n } else if (prod instanceof Option) {\n result = getAlternativesForProd(prod.definition);\n } else if (prod instanceof RepetitionMandatory) {\n const newDef = prod.definition.concat([\n new Repetition({\n definition: prod.definition,\n }),\n ]);\n return getAlternativesForProd(newDef);\n } else if (prod instanceof RepetitionMandatoryWithSeparator) {\n const newDef = [\n new Alternative({ definition: prod.definition }),\n new Repetition({\n definition: [new Terminal({ terminalType: prod.separator })].concat(\n <any>prod.definition,\n ),\n }),\n ];\n return getAlternativesForProd(newDef);\n } else if (prod instanceof RepetitionWithSeparator) {\n const newDef = prod.definition.concat([\n new Repetition({\n definition: [new Terminal({ terminalType: prod.separator })].concat(\n <any>prod.definition,\n ),\n }),\n ]);\n result = getAlternativesForProd(newDef);\n } else if (prod instanceof Repetition) {\n const newDef = prod.definition.concat([\n new Repetition({\n definition: prod.definition,\n }),\n ]);\n result = getAlternativesForProd(newDef);\n } else if (prod instanceof Alternation) {\n forEach(prod.definition, (currAlt) => {\n // TODO: this is a limited check for empty alternatives\n // It would prevent a common case of infinite loops during parser initialization.\n // However **in-directly** empty alternatives may still cause issues.\n if (isEmpty(currAlt.definition) === false) {\n result = getAlternativesForProd(currAlt.definition);\n }\n });\n return result;\n } else if (prod instanceof Terminal) {\n currPath.push(prod.terminalType);\n } else {\n throw Error(\"non exhaustive match\");\n }\n\n i++;\n }\n result.push({\n partialPath: currPath,\n suffixDef: drop(targetDef, i),\n });\n\n return result;\n}\n\ninterface IPathToExamine {\n idx: number;\n def: IProduction[];\n ruleStack: string[];\n occurrenceStack: number[];\n}\n\nexport function nextPossibleTokensAfter(\n initialDef: IProduction[],\n tokenVector: IToken[],\n tokMatcher: TokenMatcher,\n maxLookAhead: number,\n): ISyntacticContentAssistPath[] {\n const EXIT_NON_TERMINAL: any = \"EXIT_NONE_TERMINAL\";\n // to avoid creating a new Array each time.\n const EXIT_NON_TERMINAL_ARR = [EXIT_NON_TERMINAL];\n const EXIT_ALTERNATIVE: any = \"EXIT_ALTERNATIVE\";\n let foundCompletePath = false;\n\n const tokenVectorLength = tokenVector.length;\n const minimalAlternativesIndex = tokenVectorLength - maxLookAhead - 1;\n\n const result: ISyntacticContentAssistPath[] = [];\n\n const possiblePaths: IPathToExamine[] = [];\n possiblePaths.push({\n idx: -1,\n def: initialDef,\n ruleStack: [],\n occurrenceStack: [],\n });\n\n while (!isEmpty(possiblePaths)) {\n const currPath = possiblePaths.pop()!;\n\n // skip alternatives if no more results can be found (assuming deterministic grammar with fixed lookahead)\n if (currPath === EXIT_ALTERNATIVE) {\n if (\n foundCompletePath &&\n last(possiblePaths)!.idx <= minimalAlternativesIndex\n ) {\n // remove irrelevant alternative\n possiblePaths.pop();\n }\n continue;\n }\n\n const currDef = currPath.def;\n const currIdx = currPath.idx;\n const currRuleStack = currPath.ruleStack;\n const currOccurrenceStack = currPath.occurrenceStack;\n\n // For Example: an empty path could exist in a valid grammar in the case of an EMPTY_ALT\n if (isEmpty(currDef)) {\n continue;\n }\n\n const prod = currDef[0];\n /* istanbul ignore else */\n if (prod === EXIT_NON_TERMINAL) {\n const nextPath = {\n idx: currIdx,\n def: drop(currDef),\n ruleStack: dropRight(currRuleStack),\n occurrenceStack: dropRight(currOccurrenceStack),\n };\n possiblePaths.push(nextPath);\n } else if (prod instanceof Terminal) {\n /* istanbul ignore else */\n if (currIdx < tokenVectorLength - 1) {\n const nextIdx = currIdx + 1;\n const actualToken = tokenVector[nextIdx];\n if (tokMatcher!(actualToken, prod.terminalType)) {\n const nextPath = {\n idx: nextIdx,\n def: drop(currDef),\n ruleStack: currRuleStack,\n occurrenceStack: currOccurrenceStack,\n };\n possiblePaths.push(nextPath);\n }\n // end of the line\n } else if (currIdx === tokenVectorLength - 1) {\n // IGNORE ABOVE ELSE\n result.push({\n nextTokenType: prod.terminalType,\n nextTokenOccurrence: prod.idx,\n ruleStack: currRuleStack,\n occurrenceStack: currOccurrenceStack,\n });\n foundCompletePath = true;\n } else {\n throw Error(\"non exhaustive match\");\n }\n } else if (prod instanceof NonTerminal) {\n const newRuleStack = clone(currRuleStack);\n newRuleStack.push(prod.nonTerminalName);\n\n const newOccurrenceStack = clone(currOccurrenceStack);\n newOccurrenceStack.push(prod.idx);\n\n const nextPath = {\n idx: currIdx,\n def: prod.definition.concat(EXIT_NON_TERMINAL_ARR, drop(currDef)),\n ruleStack: newRuleStack,\n occurrenceStack: newOccurrenceStack,\n };\n possiblePaths.push(nextPath);\n } else if (prod instanceof Option) {\n // the order of alternatives is meaningful, FILO (Last path will be traversed first).\n const nextPathWithout = {\n idx: currIdx,\n def: drop(currDef),\n ruleStack: currRuleStack,\n occurrenceStack: currOccurrenceStack,\n };\n possiblePaths.push(nextPathWithout);\n // required marker to avoid backtracking paths whose higher priority alternatives already matched\n possiblePaths.push(EXIT_ALTERNATIVE);\n\n const nextPathWith = {\n idx: currIdx,\n def: prod.definition.concat(drop(currDef)),\n ruleStack: currRuleStack,\n occurrenceStack: currOccurrenceStack,\n };\n possiblePaths.push(nextPathWith);\n } else if (prod instanceof RepetitionMandatory) {\n // TODO:(THE NEW operators here take a while...) (convert once?)\n const secondIteration = new Repetition({\n definition: prod.definition,\n idx: prod.idx,\n });\n const nextDef = prod.definition.concat([secondIteration], drop(currDef));\n const nextPath = {\n idx: currIdx,\n def: nextDef,\n ruleStack: currRuleStack,\n occurrenceStack: currOccurrenceStack,\n };\n possiblePaths.push(nextPath);\n } else if (prod instanceof RepetitionMandatoryWithSeparator) {\n // TODO:(THE NEW operators here take a while...) (convert once?)\n const separatorGast = new Terminal({\n terminalType: prod.separator,\n });\n const secondIteration = new Repetition({\n definition: [<any>separatorGast].concat(prod.definition),\n idx: prod.idx,\n });\n const nextDef = prod.definition.concat([secondIteration], drop(currDef));\n const nextPath = {\n idx: currIdx,\n def: nextDef,\n ruleStack: currRuleStack,\n occurrenceStack: currOccurrenceStack,\n };\n possiblePaths.push(nextPath);\n } else if (prod instanceof RepetitionWithSeparator) {\n // the order of alternatives is meaningful, FILO (Last path will be traversed first).\n const nextPathWithout = {\n idx: currIdx,\n def: drop(currDef),\n ruleStack: currRuleStack,\n occurrenceStack: currOccurrenceStack,\n };\n possiblePaths.push(nextPathWithout);\n // required marker to avoid backtracking paths whose higher priority alternatives already matched\n possiblePaths.push(EXIT_ALTERNATIVE);\n\n const separatorGast = new Terminal({\n terminalType: prod.separator,\n });\n const nthRepetition = new Repetition({\n definition: [<any>separatorGast].concat(prod.definition),\n idx: prod.idx,\n });\n const nextDef = prod.definition.concat([nthRepetition], drop(currDef));\n const nextPathWith = {\n idx: currIdx,\n def: nextDef,\n ruleStack: currRuleStack,\n occurrenceStack: currOccurrenceStack,\n };\n possiblePaths.push(nextPathWith);\n } else if (prod instanceof Repetition) {\n // the order of alternatives is meaningful, FILO (Last path will be traversed first).\n const nextPathWithout = {\n idx: currIdx,\n def: drop(currDef),\n ruleStack: currRuleStack,\n occurrenceStack: currOccurrenceStack,\n };\n possiblePaths.push(nextPathWithout);\n // required marker to avoid backtracking paths whose higher priority alternatives already matched\n possiblePaths.push(EXIT_ALTERNATIVE);\n\n // TODO: an empty repetition will cause infinite loops here, will the parser detect this in selfAnalysis?\n const nthRepetition = new Repetition({\n definition: prod.definition,\n idx: prod.idx,\n });\n const nextDef = prod.definition.concat([nthRepetition], drop(currDef));\n const nextPathWith = {\n idx: currIdx,\n def: nextDef,\n ruleStack: currRuleStack,\n occurrenceStack: currOccurrenceStack,\n };\n possiblePaths.push(nextPathWith);\n } else if (prod instanceof Alternation) {\n // the order of alternatives is meaningful, FILO (Last path will be traversed first).\n for (let i = prod.definition.length - 1; i >= 0; i--) {\n const currAlt: any = prod.definition[i];\n const currAltPath = {\n idx: currIdx,\n def: currAlt.definition.concat(drop(currDef)),\n ruleStack: currRuleStack,\n occurrenceStack: currOccurrenceStack,\n };\n possiblePaths.push(currAltPath);\n possiblePaths.push(EXIT_ALTERNATIVE);\n }\n } else if (prod instanceof Alternative) {\n possiblePaths.push({\n idx: currIdx,\n def: prod.definition.concat(drop(currDef)),\n ruleStack: currRuleStack,\n occurrenceStack: currOccurrenceStack,\n });\n } else if (prod instanceof Rule) {\n // last because we should only encounter at most a single one of these per invocation.\n possiblePaths.push(\n expandTopLevelRule(prod, currIdx, currRuleStack, currOccurrenceStack),\n );\n } else {\n throw Error(\"non exhaustive match\");\n }\n }\n return result;\n}\n\nfunction expandTopLevelRule(\n topRule: Rule,\n currIdx: number,\n currRuleStack: string[],\n currOccurrenceStack: number[],\n): IPathToExamine {\n const newRuleStack = clone(currRuleStack);\n newRuleStack.push(topRule.name);\n\n const newCurrOccurrenceStack = clone(currOccurrenceStack);\n // top rule is always assumed to have been called with occurrence index 1\n newCurrOccurrenceStack.push(1);\n\n return {\n idx: currIdx,\n def: topRule.definition,\n ruleStack: newRuleStack,\n occurrenceStack: newCurrOccurrenceStack,\n };\n}\n", "import { every, flatten, forEach, has, isEmpty, map, reduce } from \"lodash-es\";\nimport { possiblePathsFrom } from \"./interpreter.js\";\nimport { RestWalker } from \"./rest.js\";\nimport { Predicate, TokenMatcher } from \"../parser/parser.js\";\nimport {\n tokenStructuredMatcher,\n tokenStructuredMatcherNoCategories,\n} from \"../../scan/tokens.js\";\nimport {\n Alternation,\n Alternative as AlternativeGAST,\n GAstVisitor,\n Option,\n Repetition,\n RepetitionMandatory,\n RepetitionMandatoryWithSeparator,\n RepetitionWithSeparator,\n} from \"@chevrotain/gast\";\nimport {\n BaseParser,\n IOrAlt,\n IProduction,\n IProductionWithOccurrence,\n LookaheadProductionType,\n LookaheadSequence,\n Rule,\n TokenType,\n} from \"@chevrotain/types\";\n\nexport enum PROD_TYPE {\n OPTION,\n REPETITION,\n REPETITION_MANDATORY,\n REPETITION_MANDATORY_WITH_SEPARATOR,\n REPETITION_WITH_SEPARATOR,\n ALTERNATION,\n}\n\nexport function getProdType(\n prod: IProduction | LookaheadProductionType,\n): PROD_TYPE {\n /* istanbul ignore else */\n if (prod instanceof Option || prod === \"Option\") {\n return PROD_TYPE.OPTION;\n } else if (prod instanceof Repetition || prod === \"Repetition\") {\n return PROD_TYPE.REPETITION;\n } else if (\n prod instanceof RepetitionMandatory ||\n prod === \"RepetitionMandatory\"\n ) {\n return PROD_TYPE.REPETITION_MANDATORY;\n } else if (\n prod instanceof RepetitionMandatoryWithSeparator ||\n prod === \"RepetitionMandatoryWithSeparator\"\n ) {\n return PROD_TYPE.REPETITION_MANDATORY_WITH_SEPARATOR;\n } else if (\n prod instanceof RepetitionWithSeparator ||\n prod === \"RepetitionWithSeparator\"\n ) {\n return PROD_TYPE.REPETITION_WITH_SEPARATOR;\n } else if (prod instanceof Alternation || prod === \"Alternation\") {\n return PROD_TYPE.ALTERNATION;\n } else {\n throw Error(\"non exhaustive match\");\n }\n}\n\nexport function getLookaheadPaths(options: {\n occurrence: number;\n rule: Rule;\n prodType: LookaheadProductionType;\n maxLookahead: number;\n}): LookaheadSequence[] {\n const { occurrence, rule, prodType, maxLookahead } = options;\n const type = getProdType(prodType);\n if (type === PROD_TYPE.ALTERNATION) {\n return getLookaheadPathsForOr(occurrence, rule, maxLookahead);\n } else {\n return getLookaheadPathsForOptionalProd(\n occurrence,\n rule,\n type,\n maxLookahead,\n );\n }\n}\n\nexport function buildLookaheadFuncForOr(\n occurrence: number,\n ruleGrammar: Rule,\n maxLookahead: number,\n hasPredicates: boolean,\n dynamicTokensEnabled: boolean,\n laFuncBuilder: Function,\n): (orAlts?: IOrAlt<any>[]) => number | undefined {\n const lookAheadPaths = getLookaheadPathsForOr(\n occurrence,\n ruleGrammar,\n maxLookahead,\n );\n\n const tokenMatcher = areTokenCategoriesNotUsed(lookAheadPaths)\n ? tokenStructuredMatcherNoCategories\n : tokenStructuredMatcher;\n\n return laFuncBuilder(\n lookAheadPaths,\n hasPredicates,\n tokenMatcher,\n dynamicTokensEnabled,\n );\n}\n\n/**\n * When dealing with an Optional production (OPTION/MANY/2nd iteration of AT_LEAST_ONE/...) we need to compare\n * the lookahead \"inside\" the production and the lookahead immediately \"after\" it in the same top level rule (context free).\n *\n * Example: given a production:\n * ABC(DE)?DF\n *\n * The optional '(DE)?' should only be entered if we see 'DE'. a single Token 'D' is not sufficient to distinguish between the two\n * alternatives.\n *\n * @returns A Lookahead function which will return true IFF the parser should parse the Optional production.\n */\nexport function buildLookaheadFuncForOptionalProd(\n occurrence: number,\n ruleGrammar: Rule,\n k: number,\n dynamicTokensEnabled: boolean,\n prodType: PROD_TYPE,\n lookaheadBuilder: (\n lookAheadSequence: LookaheadSequence,\n tokenMatcher: TokenMatcher,\n dynamicTokensEnabled: boolean,\n ) => () => boolean,\n): () => boolean {\n const lookAheadPaths = getLookaheadPathsForOptionalProd(\n occurrence,\n ruleGrammar,\n prodType,\n k,\n );\n\n const tokenMatcher = areTokenCategoriesNotUsed(lookAheadPaths)\n ? tokenStructuredMatcherNoCategories\n : tokenStructuredMatcher;\n\n return lookaheadBuilder(\n lookAheadPaths[0],\n tokenMatcher,\n dynamicTokensEnabled,\n );\n}\n\nexport type Alternative = TokenType[][];\n\nexport function buildAlternativesLookAheadFunc(\n alts: LookaheadSequence[],\n hasPredicates: boolean,\n tokenMatcher: TokenMatcher,\n dynamicTokensEnabled: boolean,\n): (orAlts: IOrAlt<any>[]) => number | undefined {\n const numOfAlts = alts.length;\n const areAllOneTokenLookahead = every(alts, (currAlt) => {\n return every(currAlt, (currPath) => {\n return currPath.length === 1;\n });\n });\n\n // This version takes into account the predicates as well.\n if (hasPredicates) {\n /**\n * @returns {number} - The chosen alternative index\n */\n return function (\n this: BaseParser,\n orAlts: IOrAlt<any>[],\n ): number | undefined {\n // unfortunately the predicates must be extracted every single time\n // as they cannot be cached due to references to parameters(vars) which are no longer valid.\n // note that in the common case of no predicates, no cpu time will be wasted on this (see else block)\n const predicates: (Predicate | undefined)[] = map(\n orAlts,\n (currAlt) => currAlt.GATE,\n );\n\n for (let t = 0; t < numOfAlts; t++) {\n const currAlt = alts[t];\n const currNumOfPaths = currAlt.length;\n\n const currPredicate = predicates[t];\n if (currPredicate !== undefined && currPredicate.call(this) === false) {\n // if the predicate does not match there is no point in checking the paths\n continue;\n }\n nextPath: for (let j = 0; j < currNumOfPaths; j++) {\n const currPath = currAlt[j];\n const currPathLength = currPath.length;\n for (let i = 0; i < currPathLength; i++) {\n const nextToken = this.LA_FAST(i + 1);\n if (tokenMatcher(nextToken, currPath[i]) === false) {\n // mismatch in current path\n // try the next pth\n continue nextPath;\n }\n }\n // found a full path that matches.\n // this will also work for an empty ALT as the loop will be skipped\n return t;\n }\n // none of the paths for the current alternative matched\n // try the next alternative\n }\n // none of the alternatives could be matched\n return undefined;\n };\n } else if (areAllOneTokenLookahead && !dynamicTokensEnabled) {\n // optimized (common) case of all the lookaheads paths requiring only\n // a single token lookahead. These Optimizations cannot work if dynamically defined Tokens are used.\n const singleTokenAlts = map(alts, (currAlt) => {\n return flatten(currAlt);\n });\n\n const choiceToAlt = reduce(\n singleTokenAlts,\n (result, currAlt, idx) => {\n forEach(currAlt, (currTokType) => {\n if (!has(result, currTokType.tokenTypeIdx!)) {\n result[currTokType.tokenTypeIdx!] = idx;\n }\n forEach(currTokType.categoryMatches!, (currExtendingType) => {\n if (!has(result, currExtendingType)) {\n result[currExtendingType] = idx;\n }\n });\n });\n return result;\n },\n {} as Record<number, number>,\n );\n\n /**\n * @returns {number} - The chosen alternative index\n */\n return function (this: BaseParser): number {\n const nextToken = this.LA_FAST(1);\n return choiceToAlt[nextToken.tokenTypeIdx];\n };\n } else {\n // optimized lookahead without needing to check the predicates at all.\n // this causes code duplication which is intentional to improve performance.\n /**\n * @returns {number} - The chosen alternative index\n */\n return function (this: BaseParser): number | undefined {\n for (let t = 0; t < numOfAlts; t++) {\n const currAlt = alts[t];\n const currNumOfPaths = currAlt.length;\n nextPath: for (let j = 0; j < currNumOfPaths; j++) {\n const currPath = currAlt[j];\n const currPathLength = currPath.length;\n for (let i = 0; i < currPathLength; i++) {\n const nextToken = this.LA_FAST(i + 1);\n if (tokenMatcher(nextToken, currPath[i]) === false) {\n // mismatch in current path\n // try the next pth\n continue nextPath;\n }\n }\n // found a full path that matches.\n // this will also work for an empty ALT as the loop will be skipped\n return t;\n }\n // none of the paths for the current alternative matched\n // try the next alternative\n }\n // none of the alternatives could be matched\n return undefined;\n };\n }\n}\n\nexport function buildSingleAlternativeLookaheadFunction(\n alt: LookaheadSequence,\n tokenMatcher: TokenMatcher,\n dynamicTokensEnabled: boolean,\n): () => boolean {\n const areAllOneTokenLookahead = every(alt, (currPath) => {\n return currPath.length === 1;\n });\n\n const numOfPaths = alt.length;\n\n // optimized (common) case of all the lookaheads paths requiring only\n // a single token lookahead.\n if (areAllOneTokenLookahead && !dynamicTokensEnabled) {\n const singleTokensTypes = flatten(alt);\n\n if (\n singleTokensTypes.length === 1 &&\n isEmpty((<any>singleTokensTypes[0]).categoryMatches)\n ) {\n const expectedTokenType = singleTokensTypes[0];\n const expectedTokenUniqueKey = (<any>expectedTokenType).tokenTypeIdx;\n\n return function (this: BaseParser): boolean {\n return this.LA_FAST(1).tokenTypeIdx === expectedTokenUniqueKey;\n };\n } else {\n const choiceToAlt = reduce(\n singleTokensTypes,\n (result, currTokType, idx) => {\n result[currTokType.tokenTypeIdx!] = true;\n forEach(currTokType.categoryMatches!, (currExtendingType) => {\n result[currExtendingType] = true;\n });\n return result;\n },\n [] as boolean[],\n );\n\n return function (this: BaseParser): boolean {\n const nextToken = this.LA_FAST(1);\n return choiceToAlt[nextToken.tokenTypeIdx] === true;\n };\n }\n } else {\n return function (this: BaseParser): boolean {\n nextPath: for (let j = 0; j < numOfPaths; j++) {\n const currPath = alt[j];\n const currPathLength = currPath.length;\n for (let i = 0; i < currPathLength; i++) {\n const nextToken = this.LA_FAST(i + 1);\n if (tokenMatcher(nextToken, currPath[i]) === false) {\n // mismatch in current path\n // try the next pth\n continue nextPath;\n }\n }\n // found a full path that matches.\n return true;\n }\n\n // none of the paths matched\n return false;\n };\n }\n}\n\nclass RestDefinitionFinderWalker extends RestWalker {\n private restDef: IProduction[];\n\n constructor(\n private topProd: Rule,\n private targetOccurrence: number,\n private targetProdType: PROD_TYPE,\n ) {\n super();\n }\n\n startWalking(): IProduction[] {\n this.walk(this.topProd);\n return this.restDef;\n }\n\n private checkIsTarget(\n node: IProductionWithOccurrence,\n expectedProdType: PROD_TYPE,\n currRest: IProduction[],\n prevRest: IProduction[],\n ): boolean {\n if (\n node.idx === this.targetOccurrence &&\n this.targetProdType === expectedProdType\n ) {\n this.restDef = currRest.concat(prevRest);\n return true;\n }\n // performance optimization, do not iterate over the entire Grammar ast after we have found the target\n return false;\n }\n\n walkOption(\n optionProd: Option,\n currRest: IProduction[],\n prevRest: IProduction[],\n ): void {\n if (!this.checkIsTarget(optionProd, PROD_TYPE.OPTION, currRest, prevRest)) {\n super.walkOption(optionProd, currRest, prevRest);\n }\n }\n\n walkAtLeastOne(\n atLeastOneProd: RepetitionMandatory,\n currRest: IProduction[],\n prevRest: IProduction[],\n ): void {\n if (\n !this.checkIsTarget(\n atLeastOneProd,\n PROD_TYPE.REPETITION_MANDATORY,\n currRest,\n prevRest,\n )\n ) {\n super.walkOption(atLeastOneProd, currRest, prevRest);\n }\n }\n\n walkAtLeastOneSep(\n atLeastOneSepProd: RepetitionMandatoryWithSeparator,\n currRest: IProduction[],\n prevRest: IProduction[],\n ): void {\n if (\n !this.checkIsTarget(\n atLeastOneSepProd,\n PROD_TYPE.REPETITION_MANDATORY_WITH_SEPARATOR,\n currRest,\n prevRest,\n )\n ) {\n super.walkOption(atLeastOneSepProd, currRest, prevRest);\n }\n }\n\n walkMany(\n manyProd: Repetition,\n currRest: IProduction[],\n prevRest: IProduction[],\n ): void {\n if (\n !this.checkIsTarget(manyProd, PROD_TYPE.REPETITION, currRest, prevRest)\n ) {\n super.walkOption(manyProd, currRest, prevRest);\n }\n }\n\n walkManySep(\n manySepProd: RepetitionWithSeparator,\n currRest: IProduction[],\n prevRest: IProduction[],\n ): void {\n if (\n !this.checkIsTarget(\n manySepProd,\n PROD_TYPE.REPETITION_WITH_SEPARATOR,\n currRest,\n prevRest,\n )\n ) {\n super.walkOption(manySepProd, currRest, prevRest);\n }\n }\n}\n\n/**\n * Returns the definition of a target production in a top level level rule.\n */\nclass InsideDefinitionFinderVisitor extends GAstVisitor {\n public result: IProduction[] = [];\n\n constructor(\n private targetOccurrence: number,\n private targetProdType: PROD_TYPE,\n private targetRef?: any,\n ) {\n super();\n }\n\n private checkIsTarget(\n node: { definition: IProduction[] } & IProductionWithOccurrence,\n expectedProdName: PROD_TYPE,\n ): void {\n if (\n node.idx === this.targetOccurrence &&\n this.targetProdType === expectedProdName &&\n (this.targetRef === undefined || node === this.targetRef)\n ) {\n this.result = node.definition;\n }\n }\n\n public visitOption(node: Option): void {\n this.checkIsTarget(node, PROD_TYPE.OPTION);\n }\n\n public visitRepetition(node: Repetition): void {\n this.checkIsTarget(node, PROD_TYPE.REPETITION);\n }\n\n public visitRepetitionMandatory(node: RepetitionMandatory): void {\n this.checkIsTarget(node, PROD_TYPE.REPETITION_MANDATORY);\n }\n\n public visitRepetitionMandatoryWithSeparator(\n node: RepetitionMandatoryWithSeparator,\n ): void {\n this.checkIsTarget(node, PROD_TYPE.REPETITION_MANDATORY_WITH_SEPARATOR);\n }\n\n public visitRepetitionWithSeparator(node: RepetitionWithSeparator): void {\n this.checkIsTarget(node, PROD_TYPE.REPETITION_WITH_SEPARATOR);\n }\n\n public visitAlternation(node: Alternation): void {\n this.checkIsTarget(node, PROD_TYPE.ALTERNATION);\n }\n}\n\nfunction initializeArrayOfArrays(size: number): any[][] {\n const result = new Array(size);\n for (let i = 0; i < size; i++) {\n result[i] = [];\n }\n return result;\n}\n\n/**\n * A sort of hash function between a Path in the grammar and a string.\n * Note that this returns multiple \"hashes\" to support the scenario of token categories.\n * - A single path with categories may match multiple **actual** paths.\n */\nfunction pathToHashKeys(path: TokenType[]): string[] {\n let keys = [\"\"];\n for (let i = 0; i < path.length; i++) {\n const tokType = path[i];\n const longerKeys = [];\n for (let j = 0; j < keys.length; j++) {\n const currShorterKey = keys[j];\n longerKeys.push(currShorterKey + \"_\" + tokType.tokenTypeIdx);\n for (let t = 0; t < tokType.categoryMatches!.length; t++) {\n const categoriesKeySuffix = \"_\" + tokType.categoryMatches![t];\n longerKeys.push(currShorterKey + categoriesKeySuffix);\n }\n }\n keys = longerKeys;\n }\n return keys;\n}\n\n/**\n * Imperative style due to being called from a hot spot\n */\nfunction isUniquePrefixHash(\n altKnownPathsKeys: Record<string, boolean>[],\n searchPathKeys: string[],\n idx: number,\n): boolean {\n for (\n let currAltIdx = 0;\n currAltIdx < altKnownPathsKeys.length;\n currAltIdx++\n ) {\n // We only want to test vs the other alternatives\n if (currAltIdx === idx) {\n continue;\n }\n const otherAltKnownPathsKeys = altKnownPathsKeys[currAltIdx];\n for (let searchIdx = 0; searchIdx < searchPathKeys.length; searchIdx++) {\n const searchKey = searchPathKeys[searchIdx];\n if (otherAltKnownPathsKeys[searchKey] === true) {\n return false;\n }\n }\n }\n // None of the SearchPathKeys were found in any of the other alternatives\n return true;\n}\n\nexport function lookAheadSequenceFromAlternatives(\n altsDefs: IProduction[],\n k: number,\n): LookaheadSequence[] {\n const partialAlts = map(altsDefs, (currAlt) =>\n possiblePathsFrom([currAlt], 1),\n );\n const finalResult = initializeArrayOfArrays(partialAlts.length);\n const altsHashes = map(partialAlts, (currAltPaths) => {\n const dict: { [key: string]: boolean } = {};\n forEach(currAltPaths, (item) => {\n const keys = pathToHashKeys(item.partialPath);\n forEach(keys, (currKey) => {\n dict[currKey] = true;\n });\n });\n return dict;\n });\n let newData = partialAlts;\n\n // maxLookahead loop\n for (let pathLength = 1; pathLength <= k; pathLength++) {\n const currDataset = newData;\n newData = initializeArrayOfArrays(currDataset.length);\n\n // alternatives loop\n for (let altIdx = 0; altIdx < currDataset.length; altIdx++) {\n const currAltPathsAndSuffixes = currDataset[altIdx];\n // paths in current alternative loop\n for (\n let currPathIdx = 0;\n currPathIdx < currAltPathsAndSuffixes.length;\n currPathIdx++\n ) {\n const currPathPrefix = currAltPathsAndSuffixes[currPathIdx].partialPath;\n const suffixDef = currAltPathsAndSuffixes[currPathIdx].suffixDef;\n const prefixKeys = pathToHashKeys(currPathPrefix);\n const isUnique = isUniquePrefixHash(altsHashes, prefixKeys, altIdx);\n // End of the line for this path.\n if (isUnique || isEmpty(suffixDef) || currPathPrefix.length === k) {\n const currAltResult = finalResult[altIdx];\n // TODO: Can we implement a containsPath using Maps/Dictionaries?\n if (containsPath(currAltResult, currPathPrefix) === false) {\n currAltResult.push(currPathPrefix);\n // Update all new keys for the current path.\n for (let j = 0; j < prefixKeys.length; j++) {\n const currKey = prefixKeys[j];\n altsHashes[altIdx][currKey] = true;\n }\n }\n }\n // Expand longer paths\n else {\n const newPartialPathsAndSuffixes = possiblePathsFrom(\n suffixDef,\n pathLength + 1,\n currPathPrefix,\n );\n newData[altIdx] = newData[altIdx].concat(newPartialPathsAndSuffixes);\n\n // Update keys for new known paths\n forEach(newPartialPathsAndSuffixes, (item) => {\n const prefixKeys = pathToHashKeys(item.partialPath);\n forEach(prefixKeys, (key) => {\n altsHashes[altIdx][key] = true;\n });\n });\n }\n }\n }\n }\n\n return finalResult;\n}\n\nexport function getLookaheadPathsForOr(\n occurrence: number,\n ruleGrammar: Rule,\n k: number,\n orProd?: Alternation,\n): LookaheadSequence[] {\n const visitor = new InsideDefinitionFinderVisitor(\n occurrence,\n PROD_TYPE.ALTERNATION,\n orProd,\n );\n ruleGrammar.accept(visitor);\n return lookAheadSequenceFromAlternatives(visitor.result, k);\n}\n\nexport function getLookaheadPathsForOptionalProd(\n occurrence: number,\n ruleGrammar: Rule,\n prodType: PROD_TYPE,\n k: number,\n): LookaheadSequence[] {\n const insideDefVisitor = new InsideDefinitionFinderVisitor(\n occurrence,\n prodType,\n );\n ruleGrammar.accept(insideDefVisitor);\n const insideDef = insideDefVisitor.result;\n\n const afterDefWalker = new RestDefinitionFinderWalker(\n ruleGrammar,\n occurrence,\n prodType,\n );\n const afterDef = afterDefWalker.startWalking();\n\n const insideFlat = new AlternativeGAST({ definition: insideDef });\n const afterFlat = new AlternativeGAST({ definition: afterDef });\n\n return lookAheadSequenceFromAlternatives([insideFlat, afterFlat], k);\n}\n\nexport function containsPath(\n alternative: Alternative,\n searchPath: TokenType[],\n): boolean {\n compareOtherPath: for (let i = 0; i < alternative.length; i++) {\n const otherPath = alternative[i];\n if (otherPath.length !== searchPath.length) {\n continue;\n }\n for (let j = 0; j < otherPath.length; j++) {\n const searchTok = searchPath[j];\n const otherTok = otherPath[j];\n\n const matchingTokens =\n searchTok === otherTok ||\n otherTok.categoryMatchesMap![searchTok.tokenTypeIdx!] !== undefined;\n if (matchingTokens === false) {\n continue compareOtherPath;\n }\n }\n return true;\n }\n\n return false;\n}\n\nexport function isStrictPrefixOfPath(\n prefix: TokenType[],\n other: TokenType[],\n): boolean {\n return (\n prefix.length < other.length &&\n every(prefix, (tokType, idx) => {\n const otherTokType = other[idx];\n return (\n tokType === otherTokType ||\n otherTokType.categoryMatchesMap![tokType.tokenTypeIdx!]\n );\n })\n );\n}\n\nexport function areTokenCategoriesNotUsed(\n lookAheadPaths: LookaheadSequence[],\n): boolean {\n return every(lookAheadPaths, (singleAltPaths) =>\n every(singleAltPaths, (singlePath) =>\n every(singlePath, (token) => isEmpty(token.categoryMatches!)),\n ),\n );\n}\n", "import {\n clone,\n compact,\n difference,\n drop,\n dropRight,\n filter,\n first,\n flatMap,\n flatten,\n forEach,\n groupBy,\n includes,\n isEmpty,\n map,\n pickBy,\n reduce,\n reject,\n values,\n} from \"lodash-es\";\nimport {\n IParserAmbiguousAlternativesDefinitionError,\n IParserDuplicatesDefinitionError,\n IParserEmptyAlternativeDefinitionError,\n ParserDefinitionErrorType,\n} from \"../parser/parser.js\";\nimport {\n Alternation,\n Alternative as AlternativeGAST,\n GAstVisitor,\n getProductionDslName,\n isOptionalProd,\n NonTerminal,\n Option,\n Repetition,\n RepetitionMandatory,\n RepetitionMandatoryWithSeparator,\n RepetitionWithSeparator,\n Terminal,\n} from \"@chevrotain/gast\";\nimport {\n Alternative,\n containsPath,\n getLookaheadPathsForOptionalProd,\n getLookaheadPathsForOr,\n getProdType,\n isStrictPrefixOfPath,\n} from \"./lookahead.js\";\nimport { nextPossibleTokensAfter } from \"./interpreter.js\";\nimport {\n ILookaheadStrategy,\n IProduction,\n IProductionWithOccurrence,\n Rule,\n TokenType,\n} from \"@chevrotain/types\";\nimport {\n IGrammarValidatorErrorMessageProvider,\n IParserDefinitionError,\n} from \"./types.js\";\nimport { tokenStructuredMatcher } from \"../../scan/tokens.js\";\n\nexport function validateLookahead(options: {\n lookaheadStrategy: ILookaheadStrategy;\n rules: Rule[];\n tokenTypes: TokenType[];\n grammarName: string;\n}): IParserDefinitionError[] {\n const lookaheadValidationErrorMessages = options.lookaheadStrategy.validate({\n rules: options.rules,\n tokenTypes: options.tokenTypes,\n grammarName: options.grammarName,\n });\n return map(lookaheadValidationErrorMessages, (errorMessage) => ({\n type: ParserDefinitionErrorType.CUSTOM_LOOKAHEAD_VALIDATION,\n ...errorMessage,\n }));\n}\n\nexport function validateGrammar(\n topLevels: Rule[],\n tokenTypes: TokenType[],\n errMsgProvider: IGrammarValidatorErrorMessageProvider,\n grammarName: string,\n): IParserDefinitionError[] {\n const duplicateErrors: IParserDefinitionError[] = flatMap(\n topLevels,\n (currTopLevel) =>\n validateDuplicateProductions(currTopLevel, errMsgProvider),\n );\n\n const termsNamespaceConflictErrors = checkTerminalAndNoneTerminalsNameSpace(\n topLevels,\n tokenTypes,\n errMsgProvider,\n );\n\n const tooManyAltsErrors = flatMap(topLevels, (curRule) =>\n validateTooManyAlts(curRule, errMsgProvider),\n );\n\n const duplicateRulesError = flatMap(topLevels, (curRule) =>\n validateRuleDoesNotAlreadyExist(\n curRule,\n topLevels,\n grammarName,\n errMsgProvider,\n ),\n );\n\n return duplicateErrors.concat(\n termsNamespaceConflictErrors,\n tooManyAltsErrors,\n duplicateRulesError,\n );\n}\n\nfunction validateDuplicateProductions(\n topLevelRule: Rule,\n errMsgProvider: IGrammarValidatorErrorMessageProvider,\n): IParserDuplicatesDefinitionError[] {\n const collectorVisitor = new OccurrenceValidationCollector();\n topLevelRule.accept(collectorVisitor);\n const allRuleProductions = collectorVisitor.allProductions;\n\n const productionGroups = groupBy(\n allRuleProductions,\n identifyProductionForDuplicates,\n );\n\n const duplicates: any = pickBy(productionGroups, (currGroup) => {\n return currGroup.length > 1;\n });\n\n const errors = map(values(duplicates), (currDuplicates: any) => {\n const firstProd: any = first(currDuplicates);\n const msg = errMsgProvider.buildDuplicateFoundError(\n topLevelRule,\n currDuplicates,\n );\n const dslName = getProductionDslName(firstProd);\n const defError: IParserDuplicatesDefinitionError = {\n message: msg,\n type: ParserDefinitionErrorType.DUPLICATE_PRODUCTIONS,\n ruleName: topLevelRule.name,\n dslName: dslName,\n occurrence: firstProd.idx,\n };\n\n const param = getExtraProductionArgument(firstProd);\n if (param) {\n defError.parameter = param;\n }\n\n return defError;\n });\n return errors;\n}\n\nexport function identifyProductionForDuplicates(\n prod: IProductionWithOccurrence,\n): string {\n return `${getProductionDslName(prod)}_#_${\n prod.idx\n }_#_${getExtraProductionArgument(prod)}`;\n}\n\nfunction getExtraProductionArgument(prod: IProductionWithOccurrence): string {\n if (prod instanceof Terminal) {\n return prod.terminalType.name;\n } else if (prod instanceof NonTerminal) {\n return prod.nonTerminalName;\n } else {\n return \"\";\n }\n}\n\nexport class OccurrenceValidationCollector extends GAstVisitor {\n public allProductions: IProductionWithOccurrence[] = [];\n\n public visitNonTerminal(subrule: NonTerminal): void {\n this.allProductions.push(subrule);\n }\n\n public visitOption(option: Option): void {\n this.allProductions.push(option);\n }\n\n public visitRepetitionWithSeparator(manySep: RepetitionWithSeparator): void {\n this.allProductions.push(manySep);\n }\n\n public visitRepetitionMandatory(atLeastOne: RepetitionMandatory): void {\n this.allProductions.push(atLeastOne);\n }\n\n public visitRepetitionMandatoryWithSeparator(\n atLeastOneSep: RepetitionMandatoryWithSeparator,\n ): void {\n this.allProductions.push(atLeastOneSep);\n }\n\n public visitRepetition(many: Repetition): void {\n this.allProductions.push(many);\n }\n\n public visitAlternation(or: Alternation): void {\n this.allProductions.push(or);\n }\n\n public visitTerminal(terminal: Terminal): void {\n this.allProductions.push(terminal);\n }\n}\n\nexport function validateRuleDoesNotAlreadyExist(\n rule: Rule,\n allRules: Rule[],\n className: string,\n errMsgProvider: IGrammarValidatorErrorMessageProvider,\n): IParserDefinitionError[] {\n const errors = [];\n const occurrences = reduce(\n allRules,\n (result, curRule) => {\n if (curRule.name === rule.name) {\n return result + 1;\n }\n return result;\n },\n 0,\n );\n if (occurrences > 1) {\n const errMsg = errMsgProvider.buildDuplicateRuleNameError({\n topLevelRule: rule,\n grammarName: className,\n });\n errors.push({\n message: errMsg,\n type: ParserDefinitionErrorType.DUPLICATE_RULE_NAME,\n ruleName: rule.name,\n });\n }\n\n return errors;\n}\n\n// TODO: is there anyway to get only the rule names of rules inherited from the super grammars?\n// This is not part of the IGrammarErrorProvider because the validation cannot be performed on\n// The grammar structure, only at runtime.\nexport function validateRuleIsOverridden(\n ruleName: string,\n definedRulesNames: string[],\n className: string,\n): IParserDefinitionError[] {\n const errors = [];\n let errMsg;\n\n if (!includes(definedRulesNames, ruleName)) {\n errMsg =\n `Invalid rule override, rule: ->${ruleName}<- cannot be overridden in the grammar: ->${className}<-` +\n `as it is not defined in any of the super grammars `;\n errors.push({\n message: errMsg,\n type: ParserDefinitionErrorType.INVALID_RULE_OVERRIDE,\n ruleName: ruleName,\n });\n }\n\n return errors;\n}\n\nexport function validateNoLeftRecursion(\n topRule: Rule,\n currRule: Rule,\n errMsgProvider: IGrammarValidatorErrorMessageProvider,\n path: Rule[] = [],\n): IParserDefinitionError[] {\n const errors: IParserDefinitionError[] = [];\n const nextNonTerminals = getFirstNoneTerminal(currRule.definition);\n if (isEmpty(nextNonTerminals)) {\n return [];\n } else {\n const ruleName = topRule.name;\n const foundLeftRecursion = includes(nextNonTerminals, topRule);\n if (foundLeftRecursion) {\n errors.push({\n message: errMsgProvider.buildLeftRecursionError({\n topLevelRule: topRule,\n leftRecursionPath: path,\n }),\n type: ParserDefinitionErrorType.LEFT_RECURSION,\n ruleName: ruleName,\n });\n }\n\n // we are only looking for cyclic paths leading back to the specific topRule\n // other cyclic paths are ignored, we still need this difference to avoid infinite loops...\n const validNextSteps = difference(nextNonTerminals, path.concat([topRule]));\n const errorsFromNextSteps = flatMap(validNextSteps, (currRefRule) => {\n const newPath = clone(path);\n newPath.push(currRefRule);\n return validateNoLeftRecursion(\n topRule,\n currRefRule,\n errMsgProvider,\n newPath,\n );\n });\n\n return errors.concat(errorsFromNextSteps);\n }\n}\n\nexport function getFirstNoneTerminal(definition: IProduction[]): Rule[] {\n let result: Rule[] = [];\n if (isEmpty(definition)) {\n return result;\n }\n const firstProd = first(definition);\n\n /* istanbul ignore else */\n if (firstProd instanceof NonTerminal) {\n result.push(firstProd.referencedRule);\n } else if (\n firstProd instanceof AlternativeGAST ||\n firstProd instanceof Option ||\n firstProd instanceof RepetitionMandatory ||\n firstProd instanceof RepetitionMandatoryWithSeparator ||\n firstProd instanceof RepetitionWithSeparator ||\n firstProd instanceof Repetition\n ) {\n result = result.concat(\n getFirstNoneTerminal(<IProduction[]>firstProd.definition),\n );\n } else if (firstProd instanceof Alternation) {\n // each sub definition in alternation is a FLAT\n result = flatten(\n map(firstProd.definition, (currSubDef) =>\n getFirstNoneTerminal((<AlternativeGAST>currSubDef).definition),\n ),\n );\n } else if (firstProd instanceof Terminal) {\n // nothing to see, move along\n } else {\n throw Error(\"non exhaustive match\");\n }\n\n const isFirstOptional = isOptionalProd(firstProd);\n const hasMore = definition.length > 1;\n if (isFirstOptional && hasMore) {\n const rest = drop(definition);\n return result.concat(getFirstNoneTerminal(rest));\n } else {\n return result;\n }\n}\n\nclass OrCollector extends GAstVisitor {\n public alternations: Alternation[] = [];\n\n public visitAlternation(node: Alternation): void {\n this.alternations.push(node);\n }\n}\n\nexport function validateEmptyOrAlternative(\n topLevelRule: Rule,\n errMsgProvider: IGrammarValidatorErrorMessageProvider,\n): IParserEmptyAlternativeDefinitionError[] {\n const orCollector = new OrCollector();\n topLevelRule.accept(orCollector);\n const ors = orCollector.alternations;\n\n const errors = flatMap<Alternation, IParserEmptyAlternativeDefinitionError>(\n ors,\n (currOr) => {\n const exceptLast = dropRight(currOr.definition);\n return flatMap(exceptLast, (currAlternative, currAltIdx) => {\n const possibleFirstInAlt = nextPossibleTokensAfter(\n [currAlternative],\n [],\n tokenStructuredMatcher,\n 1,\n );\n if (isEmpty(possibleFirstInAlt)) {\n return [\n {\n message: errMsgProvider.buildEmptyAlternationError({\n topLevelRule: topLevelRule,\n alternation: currOr,\n emptyChoiceIdx: currAltIdx,\n }),\n type: ParserDefinitionErrorType.NONE_LAST_EMPTY_ALT,\n ruleName: topLevelRule.name,\n occurrence: currOr.idx,\n alternative: currAltIdx + 1,\n },\n ];\n } else {\n return [];\n }\n });\n },\n );\n\n return errors;\n}\n\nexport function validateAmbiguousAlternationAlternatives(\n topLevelRule: Rule,\n globalMaxLookahead: number,\n errMsgProvider: IGrammarValidatorErrorMessageProvider,\n): IParserAmbiguousAlternativesDefinitionError[] {\n const orCollector = new OrCollector();\n topLevelRule.accept(orCollector);\n let ors = orCollector.alternations;\n\n // New Handling of ignoring ambiguities\n // - https://github.com/chevrotain/chevrotain/issues/869\n ors = reject(ors, (currOr) => currOr.ignoreAmbiguities === true);\n\n const errors = flatMap(ors, (currOr: Alternation) => {\n const currOccurrence = currOr.idx;\n const actualMaxLookahead = currOr.maxLookahead || globalMaxLookahead;\n const alternatives = getLookaheadPathsForOr(\n currOccurrence,\n topLevelRule,\n actualMaxLookahead,\n currOr,\n );\n const altsAmbiguityErrors = checkAlternativesAmbiguities(\n alternatives,\n currOr,\n topLevelRule,\n errMsgProvider,\n );\n const altsPrefixAmbiguityErrors = checkPrefixAlternativesAmbiguities(\n alternatives,\n currOr,\n topLevelRule,\n errMsgProvider,\n );\n\n return altsAmbiguityErrors.concat(altsPrefixAmbiguityErrors);\n });\n\n return errors;\n}\n\nexport class RepetitionCollector extends GAstVisitor {\n public allProductions: (IProductionWithOccurrence & {\n maxLookahead?: number;\n })[] = [];\n\n public visitRepetitionWithSeparator(manySep: RepetitionWithSeparator): void {\n this.allProductions.push(manySep);\n }\n\n public visitRepetitionMandatory(atLeastOne: RepetitionMandatory): void {\n this.allProductions.push(atLeastOne);\n }\n\n public visitRepetitionMandatoryWithSeparator(\n atLeastOneSep: RepetitionMandatoryWithSeparator,\n ): void {\n this.allProductions.push(atLeastOneSep);\n }\n\n public visitRepetition(many: Repetition): void {\n this.allProductions.push(many);\n }\n}\n\nexport function validateTooManyAlts(\n topLevelRule: Rule,\n errMsgProvider: IGrammarValidatorErrorMessageProvider,\n): IParserDefinitionError[] {\n const orCollector = new OrCollector();\n topLevelRule.accept(orCollector);\n const ors = orCollector.alternations;\n\n const errors = flatMap(ors, (currOr) => {\n if (currOr.definition.length > 255) {\n return [\n {\n message: errMsgProvider.buildTooManyAlternativesError({\n topLevelRule: topLevelRule,\n alternation: currOr,\n }),\n type: ParserDefinitionErrorType.TOO_MANY_ALTS,\n ruleName: topLevelRule.name,\n occurrence: currOr.idx,\n },\n ];\n } else {\n return [];\n }\n });\n\n return errors;\n}\n\nexport function validateSomeNonEmptyLookaheadPath(\n topLevelRules: Rule[],\n maxLookahead: number,\n errMsgProvider: IGrammarValidatorErrorMessageProvider,\n): IParserDefinitionError[] {\n const errors: IParserDefinitionError[] = [];\n forEach(topLevelRules, (currTopRule) => {\n const collectorVisitor = new RepetitionCollector();\n currTopRule.accept(collectorVisitor);\n const allRuleProductions = collectorVisitor.allProductions;\n forEach(allRuleProductions, (currProd) => {\n const prodType = getProdType(currProd);\n const actualMaxLookahead = currProd.maxLookahead || maxLookahead;\n const currOccurrence = currProd.idx;\n const paths = getLookaheadPathsForOptionalProd(\n currOccurrence,\n currTopRule,\n prodType,\n actualMaxLookahead,\n );\n const pathsInsideProduction = paths[0];\n if (isEmpty(flatten(pathsInsideProduction))) {\n const errMsg = errMsgProvider.buildEmptyRepetitionError({\n topLevelRule: currTopRule,\n repetition: currProd,\n });\n errors.push({\n message: errMsg,\n type: ParserDefinitionErrorType.NO_NON_EMPTY_LOOKAHEAD,\n ruleName: currTopRule.name,\n });\n }\n });\n });\n\n return errors;\n}\n\nexport interface IAmbiguityDescriptor {\n alts: number[];\n path: TokenType[];\n}\n\nfunction checkAlternativesAmbiguities(\n alternatives: Alternative[],\n alternation: Alternation,\n rule: Rule,\n errMsgProvider: IGrammarValidatorErrorMessageProvider,\n): IParserAmbiguousAlternativesDefinitionError[] {\n const foundAmbiguousPaths: Alternative = [];\n const identicalAmbiguities = reduce(\n alternatives,\n (result, currAlt, currAltIdx) => {\n // ignore (skip) ambiguities with this alternative\n if (alternation.definition[currAltIdx].ignoreAmbiguities === true) {\n return result;\n }\n\n forEach(currAlt, (currPath) => {\n const altsCurrPathAppearsIn = [currAltIdx];\n forEach(alternatives, (currOtherAlt, currOtherAltIdx) => {\n if (\n currAltIdx !== currOtherAltIdx &&\n containsPath(currOtherAlt, currPath) &&\n // ignore (skip) ambiguities with this \"other\" alternative\n alternation.definition[currOtherAltIdx].ignoreAmbiguities !== true\n ) {\n altsCurrPathAppearsIn.push(currOtherAltIdx);\n }\n });\n\n if (\n altsCurrPathAppearsIn.length > 1 &&\n !containsPath(foundAmbiguousPaths, currPath)\n ) {\n foundAmbiguousPaths.push(currPath);\n result.push({\n alts: altsCurrPathAppearsIn,\n path: currPath,\n });\n }\n });\n return result;\n },\n [] as { alts: number[]; path: TokenType[] }[],\n );\n\n const currErrors = map(identicalAmbiguities, (currAmbDescriptor) => {\n const ambgIndices = map(\n currAmbDescriptor.alts,\n (currAltIdx) => currAltIdx + 1,\n );\n\n const currMessage = errMsgProvider.buildAlternationAmbiguityError({\n topLevelRule: rule,\n alternation: alternation,\n ambiguityIndices: ambgIndices,\n prefixPath: currAmbDescriptor.path,\n });\n\n return {\n message: currMessage,\n type: ParserDefinitionErrorType.AMBIGUOUS_ALTS,\n ruleName: rule.name,\n occurrence: alternation.idx,\n alternatives: currAmbDescriptor.alts,\n };\n });\n\n return currErrors;\n}\n\nexport function checkPrefixAlternativesAmbiguities(\n alternatives: Alternative[],\n alternation: Alternation,\n rule: Rule,\n errMsgProvider: IGrammarValidatorErrorMessageProvider,\n): IParserAmbiguousAlternativesDefinitionError[] {\n // flatten\n const pathsAndIndices = reduce(\n alternatives,\n (result, currAlt, idx) => {\n const currPathsAndIdx = map(currAlt, (currPath) => {\n return { idx: idx, path: currPath };\n });\n return result.concat(currPathsAndIdx);\n },\n [] as { idx: number; path: TokenType[] }[],\n );\n\n const errors = compact(\n flatMap(pathsAndIndices, (currPathAndIdx) => {\n const alternativeGast = alternation.definition[currPathAndIdx.idx];\n // ignore (skip) ambiguities with this alternative\n if (alternativeGast.ignoreAmbiguities === true) {\n return [];\n }\n const targetIdx = currPathAndIdx.idx;\n const targetPath = currPathAndIdx.path;\n\n const prefixAmbiguitiesPathsAndIndices = filter(\n pathsAndIndices,\n (searchPathAndIdx) => {\n // prefix ambiguity can only be created from lower idx (higher priority) path\n return (\n // ignore (skip) ambiguities with this \"other\" alternative\n alternation.definition[searchPathAndIdx.idx].ignoreAmbiguities !==\n true &&\n searchPathAndIdx.idx < targetIdx &&\n // checking for strict prefix because identical lookaheads\n // will be be detected using a different validation.\n isStrictPrefixOfPath(searchPathAndIdx.path, targetPath)\n );\n },\n );\n\n const currPathPrefixErrors = map(\n prefixAmbiguitiesPathsAndIndices,\n (currAmbPathAndIdx): IParserAmbiguousAlternativesDefinitionError => {\n const ambgIndices = [currAmbPathAndIdx.idx + 1, targetIdx + 1];\n const occurrence = alternation.idx === 0 ? \"\" : alternation.idx;\n\n const message = errMsgProvider.buildAlternationPrefixAmbiguityError({\n topLevelRule: rule,\n alternation: alternation,\n ambiguityIndices: ambgIndices,\n prefixPath: currAmbPathAndIdx.path,\n });\n return {\n message: message,\n type: ParserDefinitionErrorType.AMBIGUOUS_PREFIX_ALTS,\n ruleName: rule.name,\n occurrence: occurrence,\n alternatives: ambgIndices,\n };\n },\n );\n\n return currPathPrefixErrors;\n }),\n );\n\n return errors;\n}\n\nfunction checkTerminalAndNoneTerminalsNameSpace(\n topLevels: Rule[],\n tokenTypes: TokenType[],\n errMsgProvider: IGrammarValidatorErrorMessageProvider,\n): IParserDefinitionError[] {\n const errors: IParserDefinitionError[] = [];\n\n const tokenNames = map(tokenTypes, (currToken) => currToken.name);\n\n forEach(topLevels, (currRule) => {\n const currRuleName = currRule.name;\n if (includes(tokenNames, currRuleName)) {\n const errMsg = errMsgProvider.buildNamespaceConflictError(currRule);\n\n errors.push({\n message: errMsg,\n type: ParserDefinitionErrorType.CONFLICT_TOKENS_RULES_NAMESPACE,\n ruleName: currRuleName,\n });\n }\n });\n\n return errors;\n}\n", "import { Rule } from \"@chevrotain/gast\";\nimport { defaults, forEach } from \"lodash-es\";\nimport { resolveGrammar as orgResolveGrammar } from \"../resolver.js\";\nimport { validateGrammar as orgValidateGrammar } from \"../checks.js\";\nimport {\n defaultGrammarResolverErrorProvider,\n defaultGrammarValidatorErrorProvider,\n} from \"../../errors_public.js\";\nimport { TokenType } from \"@chevrotain/types\";\nimport {\n IGrammarResolverErrorMessageProvider,\n IGrammarValidatorErrorMessageProvider,\n IParserDefinitionError,\n} from \"../types.js\";\n\ntype ResolveGrammarOpts = {\n rules: Rule[];\n errMsgProvider?: IGrammarResolverErrorMessageProvider;\n};\nexport function resolveGrammar(\n options: ResolveGrammarOpts,\n): IParserDefinitionError[] {\n const actualOptions: Required<ResolveGrammarOpts> = defaults(options, {\n errMsgProvider: defaultGrammarResolverErrorProvider,\n });\n\n const topRulesTable: { [ruleName: string]: Rule } = {};\n forEach(options.rules, (rule) => {\n topRulesTable[rule.name] = rule;\n });\n return orgResolveGrammar(topRulesTable, actualOptions.errMsgProvider);\n}\n\nexport function validateGrammar(options: {\n rules: Rule[];\n tokenTypes: TokenType[];\n grammarName: string;\n errMsgProvider: IGrammarValidatorErrorMessageProvider;\n}): IParserDefinitionError[] {\n options = defaults(options, {\n errMsgProvider: defaultGrammarValidatorErrorProvider,\n });\n\n return orgValidateGrammar(\n options.rules,\n options.tokenTypes,\n options.errMsgProvider,\n options.grammarName,\n );\n}\n", "import { includes } from \"lodash-es\";\nimport {\n IRecognitionException,\n IRecognizerContext,\n IToken,\n} from \"@chevrotain/types\";\n\nconst MISMATCHED_TOKEN_EXCEPTION = \"MismatchedTokenException\";\nconst NO_VIABLE_ALT_EXCEPTION = \"NoViableAltException\";\nconst EARLY_EXIT_EXCEPTION = \"EarlyExitException\";\nconst NOT_ALL_INPUT_PARSED_EXCEPTION = \"NotAllInputParsedException\";\n\nconst RECOGNITION_EXCEPTION_NAMES = [\n MISMATCHED_TOKEN_EXCEPTION,\n NO_VIABLE_ALT_EXCEPTION,\n EARLY_EXIT_EXCEPTION,\n NOT_ALL_INPUT_PARSED_EXCEPTION,\n];\n\nObject.freeze(RECOGNITION_EXCEPTION_NAMES);\n\n// hacks to bypass no support for custom Errors in javascript/typescript\nexport function isRecognitionException(error: Error) {\n // can't do instanceof on hacked custom js exceptions\n return includes(RECOGNITION_EXCEPTION_NAMES, error.name);\n}\n\nabstract class RecognitionException\n extends Error\n implements IRecognitionException\n{\n context: IRecognizerContext;\n resyncedTokens: IToken[] = [];\n\n protected constructor(\n message: string,\n public token: IToken,\n ) {\n super(message);\n\n // fix prototype chain when typescript target is ES5\n Object.setPrototypeOf(this, new.target.prototype);\n\n /* istanbul ignore next - V8 workaround to remove constructor from stacktrace when typescript target is ES5 */\n if (Error.captureStackTrace) {\n Error.captureStackTrace(this, this.constructor);\n }\n }\n}\n\nexport class MismatchedTokenException extends RecognitionException {\n constructor(\n message: string,\n token: IToken,\n public previousToken: IToken,\n ) {\n super(message, token);\n this.name = MISMATCHED_TOKEN_EXCEPTION;\n }\n}\n\nexport class NoViableAltException extends RecognitionException {\n constructor(\n message: string,\n token: IToken,\n public previousToken: IToken,\n ) {\n super(message, token);\n this.name = NO_VIABLE_ALT_EXCEPTION;\n }\n}\n\nexport class NotAllInputParsedException extends RecognitionException {\n constructor(message: string, token: IToken) {\n super(message, token);\n this.name = NOT_ALL_INPUT_PARSED_EXCEPTION;\n }\n}\n\nexport class EarlyExitException extends RecognitionException {\n constructor(\n message: string,\n token: IToken,\n public previousToken: IToken,\n ) {\n super(message, token);\n this.name = EARLY_EXIT_EXCEPTION;\n }\n}\n", "import {\n createTokenInstance,\n EOF,\n tokenMatcher,\n} from \"../../../scan/tokens_public.js\";\nimport {\n AbstractNextTerminalAfterProductionWalker,\n IFirstAfterRepetition,\n} from \"../../grammar/interpreter.js\";\nimport {\n dropRight,\n find,\n flatten,\n has,\n includes,\n isEmpty,\n map,\n} from \"lodash-es\";\nimport {\n IParserConfig,\n IToken,\n ITokenGrammarPath,\n TokenType,\n} from \"@chevrotain/types\";\nimport { MismatchedTokenException } from \"../../exceptions_public.js\";\nimport { IN } from \"../../constants.js\";\nimport { MixedInParser } from \"./parser_traits.js\";\nimport { DEFAULT_PARSER_CONFIG } from \"../parser.js\";\n\nexport const EOF_FOLLOW_KEY: any = {};\n\nexport interface IFollowKey {\n ruleName: string;\n idxInCallingRule: number;\n inRule: string;\n}\n\nexport const IN_RULE_RECOVERY_EXCEPTION = \"InRuleRecoveryException\";\n\nexport class InRuleRecoveryException extends Error {\n constructor(message: string) {\n super(message);\n this.name = IN_RULE_RECOVERY_EXCEPTION;\n }\n}\n\n/**\n * This trait is responsible for the error recovery and fault tolerant logic\n */\nexport class Recoverable {\n recoveryEnabled: boolean;\n firstAfterRepMap: Record<string, IFirstAfterRepetition>;\n resyncFollows: Record<string, TokenType[]>;\n\n initRecoverable(config: IParserConfig) {\n this.firstAfterRepMap = {};\n this.resyncFollows = {};\n\n this.recoveryEnabled = has(config, \"recoveryEnabled\")\n ? (config.recoveryEnabled as boolean) // assumes end user provides the correct config value/type\n : DEFAULT_PARSER_CONFIG.recoveryEnabled;\n\n // performance optimization, NOOP will be inlined which\n // effectively means that this optional feature does not exist\n // when not used.\n if (this.recoveryEnabled) {\n this.attemptInRepetitionRecovery = attemptInRepetitionRecovery;\n }\n }\n\n public getTokenToInsert(tokType: TokenType): IToken {\n const tokToInsert = createTokenInstance(\n tokType,\n \"\",\n NaN,\n NaN,\n NaN,\n NaN,\n NaN,\n NaN,\n );\n tokToInsert.isInsertedInRecovery = true;\n return tokToInsert;\n }\n\n public canTokenTypeBeInsertedInRecovery(tokType: TokenType): boolean {\n return true;\n }\n\n public canTokenTypeBeDeletedInRecovery(tokType: TokenType): boolean {\n return true;\n }\n\n tryInRepetitionRecovery(\n this: MixedInParser,\n grammarRule: Function,\n grammarRuleArgs: any[],\n lookAheadFunc: () => boolean,\n expectedTokType: TokenType,\n ): void {\n // TODO: can the resyncTokenType be cached?\n const reSyncTokType = this.findReSyncTokenType();\n const savedLexerState = this.exportLexerState();\n const resyncedTokens: IToken[] = [];\n let passedResyncPoint = false;\n\n const nextTokenWithoutResync = this.LA_FAST(1);\n let currToken = this.LA_FAST(1);\n\n const generateErrorMessage = () => {\n const previousToken = this.LA(0);\n // we are preemptively re-syncing before an error has been detected, therefor we must reproduce\n // the error that would have been thrown\n const msg = this.errorMessageProvider.buildMismatchTokenMessage({\n expected: expectedTokType,\n actual: nextTokenWithoutResync,\n previous: previousToken,\n ruleName: this.getCurrRuleFullName(),\n });\n const error = new MismatchedTokenException(\n msg,\n nextTokenWithoutResync,\n this.LA(0),\n );\n // the first token here will be the original cause of the error, this is not part of the resyncedTokens property.\n error.resyncedTokens = dropRight(resyncedTokens);\n this.SAVE_ERROR(error);\n };\n\n while (!passedResyncPoint) {\n // re-synced to a point where we can safely exit the repetition/\n if (this.tokenMatcher(currToken, expectedTokType)) {\n generateErrorMessage();\n return; // must return here to avoid reverting the inputIdx\n } else if (lookAheadFunc.call(this)) {\n // we skipped enough tokens so we can resync right back into another iteration of the repetition grammar rule\n generateErrorMessage();\n // recursive invocation in other to support multiple re-syncs in the same top level repetition grammar rule\n grammarRule.apply(this, grammarRuleArgs);\n return; // must return here to avoid reverting the inputIdx\n } else if (this.tokenMatcher(currToken, reSyncTokType)) {\n passedResyncPoint = true;\n } else {\n currToken = this.SKIP_TOKEN();\n this.addToResyncTokens(currToken, resyncedTokens);\n }\n }\n\n // we were unable to find a CLOSER point to resync inside the Repetition, reset the state.\n // The parsing exception we were trying to prevent will happen in the NEXT parsing step. it may be handled by\n // \"between rules\" resync recovery later in the flow.\n this.importLexerState(savedLexerState);\n }\n\n shouldInRepetitionRecoveryBeTried(\n this: MixedInParser,\n expectTokAfterLastMatch: TokenType,\n nextTokIdx: number,\n notStuck: boolean | undefined,\n ): boolean {\n // Edge case of arriving from a MANY repetition which is stuck\n // Attempting recovery in this case could cause an infinite loop\n if (notStuck === false) {\n return false;\n }\n\n // no need to recover, next token is what we expect...\n if (this.tokenMatcher(this.LA_FAST(1), expectTokAfterLastMatch)) {\n return false;\n }\n\n // error recovery is disabled during backtracking as it can make the parser ignore a valid grammar path\n // and prefer some backtracking path that includes recovered errors.\n if (this.isBackTracking()) {\n return false;\n }\n\n // if we can perform inRule recovery (single token insertion or deletion) we always prefer that recovery algorithm\n // because if it works, it makes the least amount of changes to the input stream (greedy algorithm)\n //noinspection RedundantIfStatementJS\n if (\n this.canPerformInRuleRecovery(\n expectTokAfterLastMatch,\n this.getFollowsForInRuleRecovery(expectTokAfterLastMatch, nextTokIdx),\n )\n ) {\n return false;\n }\n\n return true;\n }\n\n // Error Recovery functionality\n getFollowsForInRuleRecovery(\n this: MixedInParser,\n tokType: TokenType,\n tokIdxInRule: number,\n ): TokenType[] {\n const grammarPath = this.getCurrentGrammarPath(tokType, tokIdxInRule);\n const follows = this.getNextPossibleTokenTypes(grammarPath);\n return follows;\n }\n\n tryInRuleRecovery(\n this: MixedInParser,\n expectedTokType: TokenType,\n follows: TokenType[],\n ): IToken {\n if (this.canRecoverWithSingleTokenInsertion(expectedTokType, follows)) {\n const tokToInsert = this.getTokenToInsert(expectedTokType);\n return tokToInsert;\n }\n\n if (this.canRecoverWithSingleTokenDeletion(expectedTokType)) {\n const nextTok = this.SKIP_TOKEN();\n this.consumeToken();\n return nextTok;\n }\n\n throw new InRuleRecoveryException(\"sad sad panda\");\n }\n\n canPerformInRuleRecovery(\n this: MixedInParser,\n expectedToken: TokenType,\n follows: TokenType[],\n ): boolean {\n return (\n this.canRecoverWithSingleTokenInsertion(expectedToken, follows) ||\n this.canRecoverWithSingleTokenDeletion(expectedToken)\n );\n }\n\n canRecoverWithSingleTokenInsertion(\n this: MixedInParser,\n expectedTokType: TokenType,\n follows: TokenType[],\n ): boolean {\n if (!this.canTokenTypeBeInsertedInRecovery(expectedTokType)) {\n return false;\n }\n\n // must know the possible following tokens to perform single token insertion\n if (isEmpty(follows)) {\n return false;\n }\n\n const mismatchedTok = this.LA_FAST(1);\n const isMisMatchedTokInFollows =\n find(follows, (possibleFollowsTokType: TokenType) => {\n return this.tokenMatcher(mismatchedTok, possibleFollowsTokType);\n }) !== undefined;\n\n return isMisMatchedTokInFollows;\n }\n\n canRecoverWithSingleTokenDeletion(\n this: MixedInParser,\n expectedTokType: TokenType,\n ): boolean {\n if (!this.canTokenTypeBeDeletedInRecovery(expectedTokType)) {\n return false;\n }\n\n const isNextTokenWhatIsExpected = this.tokenMatcher(\n // not using LA_FAST because LA(2) might be un-safe with maxLookahead=1\n // in some edge cases (?)\n this.LA(2),\n expectedTokType,\n );\n return isNextTokenWhatIsExpected;\n }\n\n isInCurrentRuleReSyncSet(\n this: MixedInParser,\n tokenTypeIdx: TokenType,\n ): boolean {\n const followKey = this.getCurrFollowKey();\n const currentRuleReSyncSet = this.getFollowSetFromFollowKey(followKey);\n return includes(currentRuleReSyncSet, tokenTypeIdx);\n }\n\n findReSyncTokenType(this: MixedInParser): TokenType {\n const allPossibleReSyncTokTypes = this.flattenFollowSet();\n // this loop will always terminate as EOF is always in the follow stack and also always (virtually) in the input\n let nextToken = this.LA_FAST(1);\n let k = 2;\n while (true) {\n const foundMatch = find(allPossibleReSyncTokTypes, (resyncTokType) => {\n const canMatch = tokenMatcher(nextToken, resyncTokType);\n return canMatch;\n });\n if (foundMatch !== undefined) {\n return foundMatch;\n }\n nextToken = this.LA(k);\n k++;\n }\n }\n\n getCurrFollowKey(this: MixedInParser): IFollowKey {\n // the length is at least one as we always add the ruleName to the stack before invoking the rule.\n if (this.RULE_STACK_IDX === 0) {\n return EOF_FOLLOW_KEY;\n }\n const currRuleShortName = this.currRuleShortName;\n const currRuleIdx = this.getLastExplicitRuleOccurrenceIndex();\n const prevRuleShortName = this.getPreviousExplicitRuleShortName();\n\n return {\n ruleName: this.shortRuleNameToFullName(currRuleShortName),\n idxInCallingRule: currRuleIdx,\n inRule: this.shortRuleNameToFullName(prevRuleShortName),\n };\n }\n\n buildFullFollowKeyStack(this: MixedInParser): IFollowKey[] {\n const explicitRuleStack = this.RULE_STACK;\n const explicitOccurrenceStack = this.RULE_OCCURRENCE_STACK;\n const len = this.RULE_STACK_IDX + 1;\n\n const result: IFollowKey[] = new Array(len);\n for (let idx = 0; idx < len; idx++) {\n if (idx === 0) {\n result[idx] = EOF_FOLLOW_KEY;\n } else {\n result[idx] = {\n ruleName: this.shortRuleNameToFullName(explicitRuleStack[idx]),\n idxInCallingRule: explicitOccurrenceStack[idx],\n inRule: this.shortRuleNameToFullName(explicitRuleStack[idx - 1]),\n };\n }\n }\n return result;\n }\n\n flattenFollowSet(this: MixedInParser): TokenType[] {\n const followStack = map(this.buildFullFollowKeyStack(), (currKey) => {\n return this.getFollowSetFromFollowKey(currKey);\n });\n return <any>flatten(followStack);\n }\n\n getFollowSetFromFollowKey(\n this: MixedInParser,\n followKey: IFollowKey,\n ): TokenType[] {\n if (followKey === EOF_FOLLOW_KEY) {\n return [EOF];\n }\n\n const followName =\n followKey.ruleName + followKey.idxInCallingRule + IN + followKey.inRule;\n\n return this.resyncFollows[followName];\n }\n\n // It does not make any sense to include a virtual EOF token in the list of resynced tokens\n // as EOF does not really exist and thus does not contain any useful information (line/column numbers)\n addToResyncTokens(\n this: MixedInParser,\n token: IToken,\n resyncTokens: IToken[],\n ): IToken[] {\n if (!this.tokenMatcher(token, EOF)) {\n resyncTokens.push(token);\n }\n return resyncTokens;\n }\n\n reSyncTo(this: MixedInParser, tokType: TokenType): IToken[] {\n const resyncedTokens: IToken[] = [];\n let nextTok = this.LA_FAST(1);\n while (this.tokenMatcher(nextTok, tokType) === false) {\n nextTok = this.SKIP_TOKEN();\n this.addToResyncTokens(nextTok, resyncedTokens);\n }\n // the last token is not part of the error.\n return dropRight(resyncedTokens);\n }\n\n attemptInRepetitionRecovery(\n this: MixedInParser,\n prodFunc: Function,\n args: any[],\n lookaheadFunc: () => boolean,\n dslMethodIdx: number,\n prodOccurrence: number,\n nextToksWalker: typeof AbstractNextTerminalAfterProductionWalker,\n notStuck?: boolean,\n ): void {\n // by default this is a NO-OP\n // The actual implementation is with the function(not method) below\n }\n\n getCurrentGrammarPath(\n this: MixedInParser,\n tokType: TokenType,\n tokIdxInRule: number,\n ): ITokenGrammarPath {\n const pathRuleStack: string[] = this.getHumanReadableRuleStack();\n const pathOccurrenceStack: number[] = this.RULE_OCCURRENCE_STACK.slice(\n 0,\n this.RULE_OCCURRENCE_STACK_IDX + 1,\n );\n const grammarPath: any = {\n ruleStack: pathRuleStack,\n occurrenceStack: pathOccurrenceStack,\n lastTok: tokType,\n lastTokOccurrence: tokIdxInRule,\n };\n\n return grammarPath;\n }\n getHumanReadableRuleStack(this: MixedInParser): string[] {\n const len = this.RULE_STACK_IDX + 1;\n const result: string[] = new Array(len);\n for (let i = 0; i < len; i++) {\n result[i] = this.shortRuleNameToFullName(this.RULE_STACK[i]);\n }\n return result;\n }\n}\n\nexport function attemptInRepetitionRecovery(\n this: MixedInParser,\n prodFunc: Function,\n args: any[],\n lookaheadFunc: () => boolean,\n dslMethodIdx: number,\n prodOccurrence: number,\n nextToksWalker: typeof AbstractNextTerminalAfterProductionWalker,\n notStuck?: boolean,\n): void {\n const key = this.getKeyForAutomaticLookahead(dslMethodIdx, prodOccurrence);\n let firstAfterRepInfo = this.firstAfterRepMap[key];\n if (firstAfterRepInfo === undefined) {\n const currRuleName = this.getCurrRuleFullName();\n const ruleGrammar = this.getGAstProductions()[currRuleName];\n const walker: AbstractNextTerminalAfterProductionWalker =\n new nextToksWalker(ruleGrammar, prodOccurrence);\n firstAfterRepInfo = walker.startWalking();\n this.firstAfterRepMap[key] = firstAfterRepInfo;\n }\n\n let expectTokAfterLastMatch = firstAfterRepInfo.token;\n let nextTokIdx = firstAfterRepInfo.occurrence;\n const isEndOfRule = firstAfterRepInfo.isEndOfRule;\n\n // special edge case of a TOP most repetition after which the input should END.\n // this will force an attempt for inRule recovery in that scenario.\n if (\n this.RULE_STACK_IDX === 0 &&\n isEndOfRule &&\n expectTokAfterLastMatch === undefined\n ) {\n expectTokAfterLastMatch = EOF;\n nextTokIdx = 1;\n }\n\n // We don't have anything to re-sync to...\n // this condition was extracted from `shouldInRepetitionRecoveryBeTried` to act as a type-guard\n if (expectTokAfterLastMatch === undefined || nextTokIdx === undefined) {\n return;\n }\n\n if (\n this.shouldInRepetitionRecoveryBeTried(\n expectTokAfterLastMatch,\n nextTokIdx,\n notStuck,\n )\n ) {\n // TODO: performance optimization: instead of passing the original args here, we modify\n // the args param (or create a new one) and make sure the lookahead func is explicitly provided\n // to avoid searching the cache for it once more.\n this.tryInRepetitionRecovery(\n prodFunc,\n args,\n lookaheadFunc,\n expectTokAfterLastMatch,\n );\n }\n}\n", "// Lookahead keys are 32Bit integers in the form\n// TTTTTTTT-ZZZZZZZZZZZZ-YYYY-XXXXXXXX\n// XXXX -> Occurrence Index bitmap.\n// YYYY -> DSL Method Type bitmap.\n// ZZZZZZZZZZZZZZZ -> Rule short Index bitmap.\n// TTTTTTTTT -> alternation alternative index bitmap\n\nexport const BITS_FOR_METHOD_TYPE = 4;\nexport const BITS_FOR_OCCURRENCE_IDX = 8;\nexport const BITS_FOR_RULE_IDX = 12;\n// TODO: validation, this means that there may at most 2^8 --> 256 alternatives for an alternation.\nexport const BITS_FOR_ALT_IDX = 8;\n\n// short string used as part of mapping keys.\n// being short improves the performance when composing KEYS for maps out of these\n// The 5 - 8 bits (16 possible values, are reserved for the DSL method indices)\nexport const OR_IDX = 1 << BITS_FOR_OCCURRENCE_IDX;\nexport const OPTION_IDX = 2 << BITS_FOR_OCCURRENCE_IDX;\nexport const MANY_IDX = 3 << BITS_FOR_OCCURRENCE_IDX;\nexport const AT_LEAST_ONE_IDX = 4 << BITS_FOR_OCCURRENCE_IDX;\nexport const MANY_SEP_IDX = 5 << BITS_FOR_OCCURRENCE_IDX;\nexport const AT_LEAST_ONE_SEP_IDX = 6 << BITS_FOR_OCCURRENCE_IDX;\n\n// this actually returns a number, but it is always used as a string (object prop key)\nexport function getKeyForAutomaticLookahead(\n ruleIdx: number,\n dslMethodIdx: number,\n occurrence: number,\n): number {\n return occurrence | dslMethodIdx | ruleIdx;\n}\n\nconst BITS_START_FOR_ALT_IDX = 32 - BITS_FOR_ALT_IDX;\n", "import {\n ILookaheadStrategy,\n ILookaheadValidationError,\n IOrAlt,\n OptionalProductionType,\n Rule,\n TokenType,\n} from \"@chevrotain/types\";\nimport { flatMap, isEmpty } from \"lodash-es\";\nimport { defaultGrammarValidatorErrorProvider } from \"../errors_public.js\";\nimport { DEFAULT_PARSER_CONFIG } from \"../parser/parser.js\";\nimport {\n validateAmbiguousAlternationAlternatives,\n validateEmptyOrAlternative,\n validateNoLeftRecursion,\n validateSomeNonEmptyLookaheadPath,\n} from \"./checks.js\";\nimport {\n buildAlternativesLookAheadFunc,\n buildLookaheadFuncForOptionalProd,\n buildLookaheadFuncForOr,\n buildSingleAlternativeLookaheadFunction,\n getProdType,\n} from \"./lookahead.js\";\nimport { IParserDefinitionError } from \"./types.js\";\n\nexport class LLkLookaheadStrategy implements ILookaheadStrategy {\n readonly maxLookahead: number;\n\n constructor(options?: { maxLookahead?: number }) {\n this.maxLookahead =\n options?.maxLookahead ?? DEFAULT_PARSER_CONFIG.maxLookahead;\n }\n\n validate(options: {\n rules: Rule[];\n tokenTypes: TokenType[];\n grammarName: string;\n }): ILookaheadValidationError[] {\n const leftRecursionErrors = this.validateNoLeftRecursion(options.rules);\n\n if (isEmpty(leftRecursionErrors)) {\n const emptyAltErrors = this.validateEmptyOrAlternatives(options.rules);\n const ambiguousAltsErrors = this.validateAmbiguousAlternationAlternatives(\n options.rules,\n this.maxLookahead,\n );\n const emptyRepetitionErrors = this.validateSomeNonEmptyLookaheadPath(\n options.rules,\n this.maxLookahead,\n );\n const allErrors = [\n ...leftRecursionErrors,\n ...emptyAltErrors,\n ...ambiguousAltsErrors,\n ...emptyRepetitionErrors,\n ];\n return allErrors;\n }\n return leftRecursionErrors;\n }\n\n validateNoLeftRecursion(rules: Rule[]): IParserDefinitionError[] {\n return flatMap(rules, (currTopRule) =>\n validateNoLeftRecursion(\n currTopRule,\n currTopRule,\n defaultGrammarValidatorErrorProvider,\n ),\n );\n }\n\n validateEmptyOrAlternatives(rules: Rule[]): IParserDefinitionError[] {\n return flatMap(rules, (currTopRule) =>\n validateEmptyOrAlternative(\n currTopRule,\n defaultGrammarValidatorErrorProvider,\n ),\n );\n }\n\n validateAmbiguousAlternationAlternatives(\n rules: Rule[],\n maxLookahead: number,\n ): IParserDefinitionError[] {\n return flatMap(rules, (currTopRule) =>\n validateAmbiguousAlternationAlternatives(\n currTopRule,\n maxLookahead,\n defaultGrammarValidatorErrorProvider,\n ),\n );\n }\n\n validateSomeNonEmptyLookaheadPath(\n rules: Rule[],\n maxLookahead: number,\n ): IParserDefinitionError[] {\n return validateSomeNonEmptyLookaheadPath(\n rules,\n maxLookahead,\n defaultGrammarValidatorErrorProvider,\n );\n }\n\n buildLookaheadForAlternation(options: {\n prodOccurrence: number;\n rule: Rule;\n maxLookahead: number;\n hasPredicates: boolean;\n dynamicTokensEnabled: boolean;\n }): (orAlts?: IOrAlt<any>[] | undefined) => number | undefined {\n return buildLookaheadFuncForOr(\n options.prodOccurrence,\n options.rule,\n options.maxLookahead,\n options.hasPredicates,\n options.dynamicTokensEnabled,\n buildAlternativesLookAheadFunc,\n );\n }\n\n buildLookaheadForOptional(options: {\n prodOccurrence: number;\n prodType: OptionalProductionType;\n rule: Rule;\n maxLookahead: number;\n dynamicTokensEnabled: boolean;\n }): () => boolean {\n return buildLookaheadFuncForOptionalProd(\n options.prodOccurrence,\n options.rule,\n options.maxLookahead,\n options.dynamicTokensEnabled,\n getProdType(options.prodType),\n buildSingleAlternativeLookaheadFunction,\n );\n }\n}\n", "import { forEach, has } from \"lodash-es\";\nimport { DEFAULT_PARSER_CONFIG } from \"../parser.js\";\nimport {\n ILookaheadStrategy,\n IParserConfig,\n OptionalProductionType,\n} from \"@chevrotain/types\";\nimport {\n AT_LEAST_ONE_IDX,\n AT_LEAST_ONE_SEP_IDX,\n getKeyForAutomaticLookahead,\n MANY_IDX,\n MANY_SEP_IDX,\n OPTION_IDX,\n OR_IDX,\n} from \"../../grammar/keys.js\";\nimport { MixedInParser } from \"./parser_traits.js\";\nimport {\n Alternation,\n GAstVisitor,\n getProductionDslName,\n Option,\n Repetition,\n RepetitionMandatory,\n RepetitionMandatoryWithSeparator,\n RepetitionWithSeparator,\n Rule,\n} from \"@chevrotain/gast\";\nimport { LLkLookaheadStrategy } from \"../../grammar/llk_lookahead.js\";\n\n/**\n * Trait responsible for the lookahead related utilities and optimizations.\n */\nexport class LooksAhead {\n maxLookahead: number;\n lookAheadFuncsCache: any;\n dynamicTokensEnabled: boolean;\n lookaheadStrategy: ILookaheadStrategy;\n\n initLooksAhead(config: IParserConfig) {\n this.dynamicTokensEnabled = has(config, \"dynamicTokensEnabled\")\n ? (config.dynamicTokensEnabled as boolean) // assumes end user provides the correct config value/type\n : DEFAULT_PARSER_CONFIG.dynamicTokensEnabled;\n\n this.maxLookahead = has(config, \"maxLookahead\")\n ? (config.maxLookahead as number) // assumes end user provides the correct config value/type\n : DEFAULT_PARSER_CONFIG.maxLookahead;\n\n this.lookaheadStrategy = has(config, \"lookaheadStrategy\")\n ? (config.lookaheadStrategy as ILookaheadStrategy) // assumes end user provides the correct config value/type\n : new LLkLookaheadStrategy({ maxLookahead: this.maxLookahead });\n\n this.lookAheadFuncsCache = new Map();\n }\n\n preComputeLookaheadFunctions(this: MixedInParser, rules: Rule[]): void {\n forEach(rules, (currRule) => {\n this.TRACE_INIT(`${currRule.name} Rule Lookahead`, () => {\n const {\n alternation,\n repetition,\n option,\n repetitionMandatory,\n repetitionMandatoryWithSeparator,\n repetitionWithSeparator,\n } = collectMethods(currRule);\n\n forEach(alternation, (currProd) => {\n const prodIdx = currProd.idx === 0 ? \"\" : currProd.idx;\n this.TRACE_INIT(`${getProductionDslName(currProd)}${prodIdx}`, () => {\n const laFunc = this.lookaheadStrategy.buildLookaheadForAlternation({\n prodOccurrence: currProd.idx,\n rule: currRule,\n maxLookahead: currProd.maxLookahead || this.maxLookahead,\n hasPredicates: currProd.hasPredicates,\n dynamicTokensEnabled: this.dynamicTokensEnabled,\n });\n\n const key = getKeyForAutomaticLookahead(\n this.fullRuleNameToShort[currRule.name],\n OR_IDX,\n currProd.idx,\n );\n this.setLaFuncCache(key, laFunc);\n });\n });\n\n forEach(repetition, (currProd) => {\n this.computeLookaheadFunc(\n currRule,\n currProd.idx,\n MANY_IDX,\n \"Repetition\",\n currProd.maxLookahead,\n getProductionDslName(currProd),\n );\n });\n\n forEach(option, (currProd) => {\n this.computeLookaheadFunc(\n currRule,\n currProd.idx,\n OPTION_IDX,\n \"Option\",\n currProd.maxLookahead,\n getProductionDslName(currProd),\n );\n });\n\n forEach(repetitionMandatory, (currProd) => {\n this.computeLookaheadFunc(\n currRule,\n currProd.idx,\n AT_LEAST_ONE_IDX,\n \"RepetitionMandatory\",\n currProd.maxLookahead,\n getProductionDslName(currProd),\n );\n });\n\n forEach(repetitionMandatoryWithSeparator, (currProd) => {\n this.computeLookaheadFunc(\n currRule,\n currProd.idx,\n AT_LEAST_ONE_SEP_IDX,\n \"RepetitionMandatoryWithSeparator\",\n currProd.maxLookahead,\n getProductionDslName(currProd),\n );\n });\n\n forEach(repetitionWithSeparator, (currProd) => {\n this.computeLookaheadFunc(\n currRule,\n currProd.idx,\n MANY_SEP_IDX,\n \"RepetitionWithSeparator\",\n currProd.maxLookahead,\n getProductionDslName(currProd),\n );\n });\n });\n });\n }\n\n computeLookaheadFunc(\n this: MixedInParser,\n rule: Rule,\n prodOccurrence: number,\n prodKey: number,\n prodType: OptionalProductionType,\n prodMaxLookahead: number | undefined,\n dslMethodName: string,\n ): void {\n this.TRACE_INIT(\n `${dslMethodName}${prodOccurrence === 0 ? \"\" : prodOccurrence}`,\n () => {\n const laFunc = this.lookaheadStrategy.buildLookaheadForOptional({\n prodOccurrence,\n rule,\n maxLookahead: prodMaxLookahead || this.maxLookahead,\n dynamicTokensEnabled: this.dynamicTokensEnabled,\n prodType,\n });\n const key = getKeyForAutomaticLookahead(\n this.fullRuleNameToShort[rule.name],\n prodKey,\n prodOccurrence,\n );\n this.setLaFuncCache(key, laFunc);\n },\n );\n }\n\n // this actually returns a number, but it is always used as a string (object prop key)\n getKeyForAutomaticLookahead(\n this: MixedInParser,\n dslMethodIdx: number,\n occurrence: number,\n ): number {\n return getKeyForAutomaticLookahead(\n this.currRuleShortName,\n dslMethodIdx,\n occurrence,\n );\n }\n\n getLaFuncFromCache(this: MixedInParser, key: number): Function {\n return this.lookAheadFuncsCache.get(key);\n }\n\n /* istanbul ignore next */\n setLaFuncCache(this: MixedInParser, key: number, value: Function): void {\n this.lookAheadFuncsCache.set(key, value);\n }\n}\n\nclass DslMethodsCollectorVisitor extends GAstVisitor {\n public dslMethods: {\n option: Option[];\n alternation: Alternation[];\n repetition: Repetition[];\n repetitionWithSeparator: RepetitionWithSeparator[];\n repetitionMandatory: RepetitionMandatory[];\n repetitionMandatoryWithSeparator: RepetitionMandatoryWithSeparator[];\n } = {\n option: [],\n alternation: [],\n repetition: [],\n repetitionWithSeparator: [],\n repetitionMandatory: [],\n repetitionMandatoryWithSeparator: [],\n };\n\n reset() {\n this.dslMethods = {\n option: [],\n alternation: [],\n repetition: [],\n repetitionWithSeparator: [],\n repetitionMandatory: [],\n repetitionMandatoryWithSeparator: [],\n };\n }\n\n public visitOption(option: Option): void {\n this.dslMethods.option.push(option);\n }\n\n public visitRepetitionWithSeparator(manySep: RepetitionWithSeparator): void {\n this.dslMethods.repetitionWithSeparator.push(manySep);\n }\n\n public visitRepetitionMandatory(atLeastOne: RepetitionMandatory): void {\n this.dslMethods.repetitionMandatory.push(atLeastOne);\n }\n\n public visitRepetitionMandatoryWithSeparator(\n atLeastOneSep: RepetitionMandatoryWithSeparator,\n ): void {\n this.dslMethods.repetitionMandatoryWithSeparator.push(atLeastOneSep);\n }\n\n public visitRepetition(many: Repetition): void {\n this.dslMethods.repetition.push(many);\n }\n\n public visitAlternation(or: Alternation): void {\n this.dslMethods.alternation.push(or);\n }\n}\n\nconst collectorVisitor = new DslMethodsCollectorVisitor();\nexport function collectMethods(rule: Rule): {\n option: Option[];\n alternation: Alternation[];\n repetition: Repetition[];\n repetitionWithSeparator: RepetitionWithSeparator[];\n repetitionMandatory: RepetitionMandatory[];\n repetitionMandatoryWithSeparator: RepetitionMandatoryWithSeparator[];\n} {\n collectorVisitor.reset();\n rule.accept(collectorVisitor);\n const dslMethods = collectorVisitor.dslMethods;\n // avoid uncleaned references\n collectorVisitor.reset();\n return <any>dslMethods;\n}\n", "import { CstNode, CstNodeLocation, IToken } from \"@chevrotain/types\";\n\n/**\n * This nodeLocation tracking is not efficient and should only be used\n * when error recovery is enabled or the Token Vector contains virtual Tokens\n * (e.g, Python Indent/Outdent)\n * As it executes the calculation for every single terminal/nonTerminal\n * and does not rely on the fact the token vector is **sorted**\n */\nexport function setNodeLocationOnlyOffset(\n currNodeLocation: CstNodeLocation,\n newLocationInfo: Required<Pick<IToken, \"startOffset\" | \"endOffset\">>,\n): void {\n // First (valid) update for this cst node\n if (isNaN(currNodeLocation.startOffset) === true) {\n // assumption1: Token location information is either NaN or a valid number\n // assumption2: Token location information is fully valid if it exist\n // (both start/end offsets exist and are numbers).\n currNodeLocation.startOffset = newLocationInfo.startOffset;\n currNodeLocation.endOffset = newLocationInfo.endOffset;\n }\n // Once the startOffset has been updated with a valid number it should never receive\n // any farther updates as the Token vector is sorted.\n // We still have to check this this condition for every new possible location info\n // because with error recovery enabled we may encounter invalid tokens (NaN location props)\n else if (currNodeLocation.endOffset! < newLocationInfo.endOffset === true) {\n currNodeLocation.endOffset = newLocationInfo.endOffset;\n }\n}\n\n/**\n * This nodeLocation tracking is not efficient and should only be used\n * when error recovery is enabled or the Token Vector contains virtual Tokens\n * (e.g, Python Indent/Outdent)\n * As it executes the calculation for every single terminal/nonTerminal\n * and does not rely on the fact the token vector is **sorted**\n */\nexport function setNodeLocationFull(\n currNodeLocation: CstNodeLocation,\n newLocationInfo: CstNodeLocation,\n): void {\n // First (valid) update for this cst node\n if (isNaN(currNodeLocation.startOffset) === true) {\n // assumption1: Token location information is either NaN or a valid number\n // assumption2: Token location information is fully valid if it exist\n // (all start/end props exist and are numbers).\n currNodeLocation.startOffset = newLocationInfo.startOffset;\n currNodeLocation.startColumn = newLocationInfo.startColumn;\n currNodeLocation.startLine = newLocationInfo.startLine;\n currNodeLocation.endOffset = newLocationInfo.endOffset;\n currNodeLocation.endColumn = newLocationInfo.endColumn;\n currNodeLocation.endLine = newLocationInfo.endLine;\n }\n // Once the start props has been updated with a valid number it should never receive\n // any farther updates as the Token vector is sorted.\n // We still have to check this this condition for every new possible location info\n // because with error recovery enabled we may encounter invalid tokens (NaN location props)\n else if (currNodeLocation.endOffset! < newLocationInfo.endOffset! === true) {\n currNodeLocation.endOffset = newLocationInfo.endOffset;\n currNodeLocation.endColumn = newLocationInfo.endColumn;\n currNodeLocation.endLine = newLocationInfo.endLine;\n }\n}\n\nexport function addTerminalToCst(\n node: CstNode,\n token: IToken,\n tokenTypeName: string,\n): void {\n if (node.children[tokenTypeName] === undefined) {\n node.children[tokenTypeName] = [token];\n } else {\n node.children[tokenTypeName].push(token);\n }\n}\n\nexport function addNoneTerminalToCst(\n node: CstNode,\n ruleName: string,\n ruleResult: any,\n): void {\n if (node.children[ruleName] === undefined) {\n node.children[ruleName] = [ruleResult];\n } else {\n node.children[ruleName].push(ruleResult);\n }\n}\n", "const NAME = \"name\";\n\nexport function defineNameProp(obj: {}, nameValue: string): void {\n Object.defineProperty(obj, NAME, {\n enumerable: false,\n configurable: true,\n writable: false,\n value: nameValue,\n });\n}\n", "import {\n compact,\n filter,\n forEach,\n isArray,\n isEmpty,\n isFunction,\n isUndefined,\n keys,\n map,\n} from \"lodash-es\";\nimport { defineNameProp } from \"../../lang/lang_extensions.js\";\nimport { CstNode, ICstVisitor } from \"@chevrotain/types\";\n\nexport function defaultVisit<IN>(ctx: any, param: IN): void {\n const childrenNames = keys(ctx);\n const childrenNamesLength = childrenNames.length;\n for (let i = 0; i < childrenNamesLength; i++) {\n const currChildName = childrenNames[i];\n const currChildArray = ctx[currChildName];\n const currChildArrayLength = currChildArray.length;\n for (let j = 0; j < currChildArrayLength; j++) {\n const currChild: any = currChildArray[j];\n // distinction between Tokens Children and CstNode children\n if (currChild.tokenTypeIdx === undefined) {\n this[currChild.name](currChild.children, param);\n }\n }\n }\n // defaultVisit does not support generic out param\n}\n\nexport function createBaseSemanticVisitorConstructor(\n grammarName: string,\n ruleNames: string[],\n): {\n new (...args: any[]): ICstVisitor<any, any>;\n} {\n const derivedConstructor: any = function () {};\n\n // can be overwritten according to:\n // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/\n // name?redirectlocale=en-US&redirectslug=JavaScript%2FReference%2FGlobal_Objects%2FFunction%2Fname\n defineNameProp(derivedConstructor, grammarName + \"BaseSemantics\");\n\n const semanticProto = {\n visit: function (cstNode: CstNode | CstNode[], param: any) {\n // enables writing more concise visitor methods when CstNode has only a single child\n if (isArray(cstNode)) {\n // A CST Node's children dictionary can never have empty arrays as values\n // If a key is defined there will be at least one element in the corresponding value array.\n cstNode = cstNode[0];\n }\n\n // enables passing optional CstNodes concisely.\n if (isUndefined(cstNode)) {\n return undefined;\n }\n\n return this[cstNode.name](cstNode.children, param);\n },\n\n validateVisitor: function () {\n const semanticDefinitionErrors = validateVisitor(this, ruleNames);\n if (!isEmpty(semanticDefinitionErrors)) {\n const errorMessages = map(\n semanticDefinitionErrors,\n (currDefError) => currDefError.msg,\n );\n throw Error(\n `Errors Detected in CST Visitor <${this.constructor.name}>:\\n\\t` +\n `${errorMessages.join(\"\\n\\n\").replace(/\\n/g, \"\\n\\t\")}`,\n );\n }\n },\n };\n\n derivedConstructor.prototype = semanticProto;\n derivedConstructor.prototype.constructor = derivedConstructor;\n\n derivedConstructor._RULE_NAMES = ruleNames;\n\n return derivedConstructor;\n}\n\nexport function createBaseVisitorConstructorWithDefaults(\n grammarName: string,\n ruleNames: string[],\n baseConstructor: Function,\n): {\n new (...args: any[]): ICstVisitor<any, any>;\n} {\n const derivedConstructor: any = function () {};\n\n // can be overwritten according to:\n // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/\n // name?redirectlocale=en-US&redirectslug=JavaScript%2FReference%2FGlobal_Objects%2FFunction%2Fname\n defineNameProp(derivedConstructor, grammarName + \"BaseSemanticsWithDefaults\");\n\n const withDefaultsProto = Object.create(baseConstructor.prototype);\n forEach(ruleNames, (ruleName) => {\n withDefaultsProto[ruleName] = defaultVisit;\n });\n\n derivedConstructor.prototype = withDefaultsProto;\n derivedConstructor.prototype.constructor = derivedConstructor;\n\n return derivedConstructor;\n}\n\nexport enum CstVisitorDefinitionError {\n REDUNDANT_METHOD,\n MISSING_METHOD,\n}\n\nexport interface IVisitorDefinitionError {\n msg: string;\n type: CstVisitorDefinitionError;\n methodName: string;\n}\n\nexport function validateVisitor(\n visitorInstance: ICstVisitor<unknown, unknown>,\n ruleNames: string[],\n): IVisitorDefinitionError[] {\n const missingErrors = validateMissingCstMethods(visitorInstance, ruleNames);\n\n return missingErrors;\n}\n\nexport function validateMissingCstMethods(\n visitorInstance: ICstVisitor<unknown, unknown>,\n ruleNames: string[],\n): IVisitorDefinitionError[] {\n const missingRuleNames = filter(ruleNames, (currRuleName) => {\n return isFunction((visitorInstance as any)[currRuleName]) === false;\n });\n\n const errors: IVisitorDefinitionError[] = map(\n missingRuleNames,\n (currRuleName) => {\n return {\n msg: `Missing visitor method: <${currRuleName}> on ${<any>(\n visitorInstance.constructor.name\n )} CST Visitor.`,\n type: CstVisitorDefinitionError.MISSING_METHOD,\n methodName: currRuleName,\n };\n },\n );\n\n return compact<IVisitorDefinitionError>(errors);\n}\n", "import {\n addNoneTerminalToCst,\n addTerminalToCst,\n setNodeLocationFull,\n setNodeLocationOnlyOffset,\n} from \"../../cst/cst.js\";\nimport { has, isUndefined, keys, noop } from \"lodash-es\";\nimport {\n createBaseSemanticVisitorConstructor,\n createBaseVisitorConstructorWithDefaults,\n} from \"../../cst/cst_visitor.js\";\nimport {\n CstNode,\n CstNodeLocation,\n ICstVisitor,\n IParserConfig,\n IToken,\n nodeLocationTrackingOptions,\n} from \"@chevrotain/types\";\nimport { MixedInParser } from \"./parser_traits.js\";\nimport { DEFAULT_PARSER_CONFIG } from \"../parser.js\";\n\n/**\n * This trait is responsible for the CST building logic.\n */\nexport class TreeBuilder {\n outputCst: boolean;\n CST_STACK: CstNode[];\n baseCstVisitorConstructor: Function;\n baseCstVisitorWithDefaultsConstructor: Function;\n\n // dynamically assigned Methods\n setNodeLocationFromNode: (\n nodeLocation: CstNodeLocation,\n locationInformation: CstNodeLocation,\n ) => void;\n setNodeLocationFromToken: (\n nodeLocation: CstNodeLocation,\n locationInformation: CstNodeLocation,\n ) => void;\n cstPostRule: (this: MixedInParser, ruleCstNode: CstNode) => void;\n\n setInitialNodeLocation: (cstNode: CstNode) => void;\n nodeLocationTracking: nodeLocationTrackingOptions;\n\n initTreeBuilder(this: MixedInParser, config: IParserConfig) {\n this.CST_STACK = [];\n\n // outputCst is no longer exposed/defined in the pubic API\n this.outputCst = (config as any).outputCst;\n\n this.nodeLocationTracking = has(config, \"nodeLocationTracking\")\n ? (config.nodeLocationTracking as nodeLocationTrackingOptions) // assumes end user provides the correct config value/type\n : DEFAULT_PARSER_CONFIG.nodeLocationTracking;\n\n if (!this.outputCst) {\n this.cstInvocationStateUpdate = noop;\n this.cstFinallyStateUpdate = noop;\n this.cstPostTerminal = noop;\n this.cstPostNonTerminal = noop;\n this.cstPostRule = noop;\n } else {\n if (/full/i.test(this.nodeLocationTracking)) {\n if (this.recoveryEnabled) {\n this.setNodeLocationFromToken = setNodeLocationFull;\n this.setNodeLocationFromNode = setNodeLocationFull;\n this.cstPostRule = noop;\n this.setInitialNodeLocation = this.setInitialNodeLocationFullRecovery;\n } else {\n this.setNodeLocationFromToken = noop;\n this.setNodeLocationFromNode = noop;\n this.cstPostRule = this.cstPostRuleFull;\n this.setInitialNodeLocation = this.setInitialNodeLocationFullRegular;\n }\n } else if (/onlyOffset/i.test(this.nodeLocationTracking)) {\n if (this.recoveryEnabled) {\n this.setNodeLocationFromToken = <any>setNodeLocationOnlyOffset;\n this.setNodeLocationFromNode = <any>setNodeLocationOnlyOffset;\n this.cstPostRule = noop;\n this.setInitialNodeLocation =\n this.setInitialNodeLocationOnlyOffsetRecovery;\n } else {\n this.setNodeLocationFromToken = noop;\n this.setNodeLocationFromNode = noop;\n this.cstPostRule = this.cstPostRuleOnlyOffset;\n this.setInitialNodeLocation =\n this.setInitialNodeLocationOnlyOffsetRegular;\n }\n } else if (/none/i.test(this.nodeLocationTracking)) {\n this.setNodeLocationFromToken = noop;\n this.setNodeLocationFromNode = noop;\n this.cstPostRule = noop;\n this.setInitialNodeLocation = noop;\n } else {\n throw Error(\n `Invalid <nodeLocationTracking> config option: \"${config.nodeLocationTracking}\"`,\n );\n }\n }\n }\n\n setInitialNodeLocationOnlyOffsetRecovery(\n this: MixedInParser,\n cstNode: any,\n ): void {\n cstNode.location = {\n startOffset: NaN,\n endOffset: NaN,\n };\n }\n\n setInitialNodeLocationOnlyOffsetRegular(\n this: MixedInParser,\n cstNode: any,\n ): void {\n cstNode.location = {\n // without error recovery the starting Location of a new CstNode is guaranteed\n // To be the next Token's startOffset (for valid inputs).\n // For invalid inputs there won't be any CSTOutput so this potential\n // inaccuracy does not matter\n startOffset: this.LA_FAST(1).startOffset,\n endOffset: NaN,\n };\n }\n\n setInitialNodeLocationFullRecovery(this: MixedInParser, cstNode: any): void {\n cstNode.location = {\n startOffset: NaN,\n startLine: NaN,\n startColumn: NaN,\n endOffset: NaN,\n endLine: NaN,\n endColumn: NaN,\n };\n }\n\n /**\n * @see setInitialNodeLocationOnlyOffsetRegular for explanation why this work\n\n * @param cstNode\n */\n setInitialNodeLocationFullRegular(this: MixedInParser, cstNode: any): void {\n const nextToken = this.LA_FAST(1);\n cstNode.location = {\n startOffset: nextToken.startOffset,\n startLine: nextToken.startLine,\n startColumn: nextToken.startColumn,\n endOffset: NaN,\n endLine: NaN,\n endColumn: NaN,\n };\n }\n\n cstInvocationStateUpdate(this: MixedInParser, fullRuleName: string): void {\n const cstNode: CstNode = {\n name: fullRuleName,\n children: Object.create(null),\n };\n\n this.setInitialNodeLocation(cstNode);\n this.CST_STACK.push(cstNode);\n }\n\n cstFinallyStateUpdate(this: MixedInParser): void {\n this.CST_STACK.pop();\n }\n\n cstPostRuleFull(this: MixedInParser, ruleCstNode: CstNode): void {\n // casts to `required<CstNodeLocation>` are safe because `cstPostRuleFull` should only be invoked when full location is enabled\n // TODO(perf): can we replace this with LA_FAST?\n // edge case is the empty CstNode on first rule invocation.\n // perhaps create a test case to verify correctness of LA vs LA_FAST in this scenario?\n const prevToken = this.LA(0) as Required<CstNodeLocation>;\n const loc = ruleCstNode.location as Required<CstNodeLocation>;\n\n // If this condition is true it means we consumed at least one Token\n // In this CstNode.\n if (loc.startOffset <= prevToken.startOffset === true) {\n loc.endOffset = prevToken.endOffset;\n loc.endLine = prevToken.endLine;\n loc.endColumn = prevToken.endColumn;\n }\n // \"empty\" CstNode edge case\n else {\n loc.startOffset = NaN;\n loc.startLine = NaN;\n loc.startColumn = NaN;\n }\n }\n\n cstPostRuleOnlyOffset(this: MixedInParser, ruleCstNode: CstNode): void {\n // TODO: can we replace this with LA_FAST? see comment in `cstPostRuleFull()`\n const prevToken = this.LA(0);\n // `location' is not null because `cstPostRuleOnlyOffset` will only be invoked when location tracking is enabled.\n const loc = ruleCstNode.location!;\n\n // If this condition is true it means we consumed at least one Token\n // In this CstNode.\n if (loc.startOffset <= prevToken.startOffset === true) {\n loc.endOffset = prevToken.endOffset;\n }\n // \"empty\" CstNode edge case\n else {\n loc.startOffset = NaN;\n }\n }\n\n cstPostTerminal(\n this: MixedInParser,\n key: string,\n consumedToken: IToken,\n ): void {\n const rootCst = this.CST_STACK[this.CST_STACK.length - 1];\n addTerminalToCst(rootCst, consumedToken, key);\n // This is only used when **both** error recovery and CST Output are enabled.\n this.setNodeLocationFromToken(rootCst.location!, <any>consumedToken);\n }\n\n cstPostNonTerminal(\n this: MixedInParser,\n ruleCstResult: CstNode,\n ruleName: string,\n ): void {\n const preCstNode = this.CST_STACK[this.CST_STACK.length - 1];\n addNoneTerminalToCst(preCstNode, ruleName, ruleCstResult);\n // This is only used when **both** error recovery and CST Output are enabled.\n this.setNodeLocationFromNode(preCstNode.location!, ruleCstResult.location!);\n }\n\n getBaseCstVisitorConstructor<IN = any, OUT = any>(\n this: MixedInParser,\n ): {\n new (...args: any[]): ICstVisitor<IN, OUT>;\n } {\n if (isUndefined(this.baseCstVisitorConstructor)) {\n const newBaseCstVisitorConstructor = createBaseSemanticVisitorConstructor(\n this.className,\n keys(this.gastProductionsCache),\n );\n this.baseCstVisitorConstructor = newBaseCstVisitorConstructor;\n return newBaseCstVisitorConstructor;\n }\n\n return <any>this.baseCstVisitorConstructor;\n }\n\n getBaseCstVisitorConstructorWithDefaults<IN = any, OUT = any>(\n this: MixedInParser,\n ): {\n new (...args: any[]): ICstVisitor<IN, OUT>;\n } {\n if (isUndefined(this.baseCstVisitorWithDefaultsConstructor)) {\n const newConstructor = createBaseVisitorConstructorWithDefaults(\n this.className,\n keys(this.gastProductionsCache),\n this.getBaseCstVisitorConstructor(),\n );\n this.baseCstVisitorWithDefaultsConstructor = newConstructor;\n return newConstructor;\n }\n\n return <any>this.baseCstVisitorWithDefaultsConstructor;\n }\n\n getPreviousExplicitRuleShortName(this: MixedInParser): number {\n return this.RULE_STACK[this.RULE_STACK_IDX - 1];\n }\n\n getLastExplicitRuleOccurrenceIndex(this: MixedInParser): number {\n return this.RULE_OCCURRENCE_STACK[this.RULE_OCCURRENCE_STACK_IDX];\n }\n}\n", "import { END_OF_FILE } from \"../parser.js\";\nimport { IToken } from \"@chevrotain/types\";\nimport { MixedInParser } from \"./parser_traits.js\";\n\n/**\n * Trait responsible abstracting over the interaction with Lexer output (Token vector).\n *\n * This could be generalized to support other kinds of lexers, e.g.\n * - Just in Time Lexing / Lexer-Less parsing.\n * - Streaming Lexer.\n */\nexport class LexerAdapter {\n tokVector: IToken[];\n tokVectorLength: number;\n currIdx: number;\n\n initLexerAdapter() {\n this.tokVector = [];\n this.tokVectorLength = 0;\n this.currIdx = -1;\n }\n\n set input(newInput: IToken[]) {\n // @ts-ignore - `this parameter` not supported in setters/getters\n // - https://www.typescriptlang.org/docs/handbook/functions.html#this-parameters\n if (this.selfAnalysisDone !== true) {\n throw Error(\n `Missing <performSelfAnalysis> invocation at the end of the Parser's constructor.`,\n );\n }\n // @ts-ignore - `this parameter` not supported in setters/getters\n // - https://www.typescriptlang.org/docs/handbook/functions.html#this-parameters\n this.reset();\n this.tokVector = newInput;\n this.tokVectorLength = newInput.length;\n }\n\n get input(): IToken[] {\n return this.tokVector;\n }\n\n // skips a token and returns the next token\n SKIP_TOKEN(this: MixedInParser): IToken {\n if (this.currIdx <= this.tokVectorLength - 2) {\n this.consumeToken();\n return this.LA_FAST(1);\n } else {\n return END_OF_FILE;\n }\n }\n\n // Lexer (accessing Token vector) related methods which can be overridden to implement lazy lexers\n // or lexers dependent on parser context.\n\n // Performance Optimized version of LA without bound checks\n // note that token beyond the end of the token vector EOF Token will still be returned\n // due to using sentinels at the end of the token vector. (for K=max lookahead)\n LA_FAST(this: MixedInParser, howMuch: number): IToken {\n const soughtIdx = this.currIdx + howMuch;\n return this.tokVector[soughtIdx];\n }\n\n LA(this: MixedInParser, howMuch: number): IToken {\n const soughtIdx = this.currIdx + howMuch;\n if (soughtIdx < 0 || this.tokVectorLength <= soughtIdx) {\n return END_OF_FILE;\n } else {\n return this.tokVector[soughtIdx];\n }\n }\n\n consumeToken(this: MixedInParser) {\n this.currIdx++;\n }\n\n exportLexerState(this: MixedInParser): number {\n return this.currIdx;\n }\n\n importLexerState(this: MixedInParser, newState: number) {\n this.currIdx = newState;\n }\n\n resetLexerState(this: MixedInParser): void {\n this.currIdx = -1;\n }\n\n moveToTerminatedState(this: MixedInParser): void {\n this.currIdx = this.tokVectorLength - 1;\n }\n\n getLexerPosition(this: MixedInParser): number {\n return this.exportLexerState();\n }\n}\n", "import {\n AtLeastOneSepMethodOpts,\n ConsumeMethodOpts,\n DSLMethodOpts,\n DSLMethodOptsWithErr,\n GrammarAction,\n IOrAlt,\n IRuleConfig,\n ISerializedGast,\n IToken,\n ManySepMethodOpts,\n OrMethodOpts,\n SubruleMethodOpts,\n TokenType,\n} from \"@chevrotain/types\";\nimport { includes, values } from \"lodash-es\";\nimport { isRecognitionException } from \"../../exceptions_public.js\";\nimport { DEFAULT_RULE_CONFIG, ParserDefinitionErrorType } from \"../parser.js\";\nimport { defaultGrammarValidatorErrorProvider } from \"../../errors_public.js\";\nimport { validateRuleIsOverridden } from \"../../grammar/checks.js\";\nimport { MixedInParser } from \"./parser_traits.js\";\nimport { Rule, serializeGrammar } from \"@chevrotain/gast\";\nimport { IParserDefinitionError } from \"../../grammar/types.js\";\nimport { ParserMethodInternal } from \"../types.js\";\n\n/**\n * This trait is responsible for implementing the public API\n * for defining Chevrotain parsers, i.e:\n * - CONSUME\n * - RULE\n * - OPTION\n * - ...\n */\nexport class RecognizerApi {\n ACTION<T>(this: MixedInParser, impl: () => T): T {\n return impl.call(this);\n }\n\n consume(\n this: MixedInParser,\n idx: number,\n tokType: TokenType,\n options?: ConsumeMethodOpts,\n ): IToken {\n return this.consumeInternal(tokType, idx, options);\n }\n\n subrule<ARGS extends unknown[], R>(\n this: MixedInParser,\n idx: number,\n ruleToCall: ParserMethodInternal<ARGS, R>,\n options?: SubruleMethodOpts<ARGS>,\n ): R {\n return this.subruleInternal(ruleToCall, idx, options);\n }\n\n option<OUT>(\n this: MixedInParser,\n idx: number,\n actionORMethodDef: GrammarAction<OUT> | DSLMethodOpts<OUT>,\n ): OUT | undefined {\n return this.optionInternal(actionORMethodDef, idx);\n }\n\n or(\n this: MixedInParser,\n idx: number,\n altsOrOpts: IOrAlt<any>[] | OrMethodOpts<any>,\n ): any {\n return this.orInternal(altsOrOpts, idx);\n }\n\n many(\n this: MixedInParser,\n idx: number,\n actionORMethodDef: GrammarAction<any> | DSLMethodOpts<any>,\n ): void {\n return this.manyInternal(idx, actionORMethodDef);\n }\n\n atLeastOne(\n this: MixedInParser,\n idx: number,\n actionORMethodDef: GrammarAction<any> | DSLMethodOptsWithErr<any>,\n ): void {\n return this.atLeastOneInternal(idx, actionORMethodDef);\n }\n\n CONSUME(\n this: MixedInParser,\n tokType: TokenType,\n options?: ConsumeMethodOpts,\n ): IToken {\n return this.consumeInternal(tokType, 0, options);\n }\n\n CONSUME1(\n this: MixedInParser,\n tokType: TokenType,\n options?: ConsumeMethodOpts,\n ): IToken {\n return this.consumeInternal(tokType, 1, options);\n }\n\n CONSUME2(\n this: MixedInParser,\n tokType: TokenType,\n options?: ConsumeMethodOpts,\n ): IToken {\n return this.consumeInternal(tokType, 2, options);\n }\n\n CONSUME3(\n this: MixedInParser,\n tokType: TokenType,\n options?: ConsumeMethodOpts,\n ): IToken {\n return this.consumeInternal(tokType, 3, options);\n }\n\n CONSUME4(\n this: MixedInParser,\n tokType: TokenType,\n options?: ConsumeMethodOpts,\n ): IToken {\n return this.consumeInternal(tokType, 4, options);\n }\n\n CONSUME5(\n this: MixedInParser,\n tokType: TokenType,\n options?: ConsumeMethodOpts,\n ): IToken {\n return this.consumeInternal(tokType, 5, options);\n }\n\n CONSUME6(\n this: MixedInParser,\n tokType: TokenType,\n options?: ConsumeMethodOpts,\n ): IToken {\n return this.consumeInternal(tokType, 6, options);\n }\n\n CONSUME7(\n this: MixedInParser,\n tokType: TokenType,\n options?: ConsumeMethodOpts,\n ): IToken {\n return this.consumeInternal(tokType, 7, options);\n }\n\n CONSUME8(\n this: MixedInParser,\n tokType: TokenType,\n options?: ConsumeMethodOpts,\n ): IToken {\n return this.consumeInternal(tokType, 8, options);\n }\n\n CONSUME9(\n this: MixedInParser,\n tokType: TokenType,\n options?: ConsumeMethodOpts,\n ): IToken {\n return this.consumeInternal(tokType, 9, options);\n }\n\n SUBRULE<ARGS extends unknown[], R>(\n this: MixedInParser,\n ruleToCall: ParserMethodInternal<ARGS, R>,\n options?: SubruleMethodOpts<ARGS>,\n ): R {\n return this.subruleInternal(ruleToCall, 0, options);\n }\n\n SUBRULE1<ARGS extends unknown[], R>(\n this: MixedInParser,\n ruleToCall: ParserMethodInternal<ARGS, R>,\n options?: SubruleMethodOpts<ARGS>,\n ): R {\n return this.subruleInternal(ruleToCall, 1, options);\n }\n\n SUBRULE2<ARGS extends unknown[], R>(\n this: MixedInParser,\n ruleToCall: ParserMethodInternal<ARGS, R>,\n options?: SubruleMethodOpts<ARGS>,\n ): R {\n return this.subruleInternal(ruleToCall, 2, options);\n }\n\n SUBRULE3<ARGS extends unknown[], R>(\n this: MixedInParser,\n ruleToCall: ParserMethodInternal<ARGS, R>,\n options?: SubruleMethodOpts<ARGS>,\n ): R {\n return this.subruleInternal(ruleToCall, 3, options);\n }\n\n SUBRULE4<ARGS extends unknown[], R>(\n this: MixedInParser,\n ruleToCall: ParserMethodInternal<ARGS, R>,\n options?: SubruleMethodOpts<ARGS>,\n ): R {\n return this.subruleInternal(ruleToCall, 4, options);\n }\n\n SUBRULE5<ARGS extends unknown[], R>(\n this: MixedInParser,\n ruleToCall: ParserMethodInternal<ARGS, R>,\n options?: SubruleMethodOpts<ARGS>,\n ): R {\n return this.subruleInternal(ruleToCall, 5, options);\n }\n\n SUBRULE6<ARGS extends unknown[], R>(\n this: MixedInParser,\n ruleToCall: ParserMethodInternal<ARGS, R>,\n options?: SubruleMethodOpts<ARGS>,\n ): R {\n return this.subruleInternal(ruleToCall, 6, options);\n }\n\n SUBRULE7<ARGS extends unknown[], R>(\n this: MixedInParser,\n ruleToCall: ParserMethodInternal<ARGS, R>,\n options?: SubruleMethodOpts<ARGS>,\n ): R {\n return this.subruleInternal(ruleToCall, 7, options);\n }\n\n SUBRULE8<ARGS extends unknown[], R>(\n this: MixedInParser,\n ruleToCall: ParserMethodInternal<ARGS, R>,\n options?: SubruleMethodOpts<ARGS>,\n ): R {\n return this.subruleInternal(ruleToCall, 8, options);\n }\n\n SUBRULE9<ARGS extends unknown[], R>(\n this: MixedInParser,\n ruleToCall: ParserMethodInternal<ARGS, R>,\n options?: SubruleMethodOpts<ARGS>,\n ): R {\n return this.subruleInternal(ruleToCall, 9, options);\n }\n\n OPTION<OUT>(\n this: MixedInParser,\n actionORMethodDef: GrammarAction<OUT> | DSLMethodOpts<OUT>,\n ): OUT | undefined {\n return this.optionInternal(actionORMethodDef, 0);\n }\n\n OPTION1<OUT>(\n this: MixedInParser,\n actionORMethodDef: GrammarAction<OUT> | DSLMethodOpts<OUT>,\n ): OUT | undefined {\n return this.optionInternal(actionORMethodDef, 1);\n }\n\n OPTION2<OUT>(\n this: MixedInParser,\n actionORMethodDef: GrammarAction<OUT> | DSLMethodOpts<OUT>,\n ): OUT | undefined {\n return this.optionInternal(actionORMethodDef, 2);\n }\n\n OPTION3<OUT>(\n this: MixedInParser,\n actionORMethodDef: GrammarAction<OUT> | DSLMethodOpts<OUT>,\n ): OUT | undefined {\n return this.optionInternal(actionORMethodDef, 3);\n }\n\n OPTION4<OUT>(\n this: MixedInParser,\n actionORMethodDef: GrammarAction<OUT> | DSLMethodOpts<OUT>,\n ): OUT | undefined {\n return this.optionInternal(actionORMethodDef, 4);\n }\n\n OPTION5<OUT>(\n this: MixedInParser,\n actionORMethodDef: GrammarAction<OUT> | DSLMethodOpts<OUT>,\n ): OUT | undefined {\n return this.optionInternal(actionORMethodDef, 5);\n }\n\n OPTION6<OUT>(\n this: MixedInParser,\n actionORMethodDef: GrammarAction<OUT> | DSLMethodOpts<OUT>,\n ): OUT | undefined {\n return this.optionInternal(actionORMethodDef, 6);\n }\n\n OPTION7<OUT>(\n this: MixedInParser,\n actionORMethodDef: GrammarAction<OUT> | DSLMethodOpts<OUT>,\n ): OUT | undefined {\n return this.optionInternal(actionORMethodDef, 7);\n }\n\n OPTION8<OUT>(\n this: MixedInParser,\n actionORMethodDef: GrammarAction<OUT> | DSLMethodOpts<OUT>,\n ): OUT | undefined {\n return this.optionInternal(actionORMethodDef, 8);\n }\n\n OPTION9<OUT>(\n this: MixedInParser,\n actionORMethodDef: GrammarAction<OUT> | DSLMethodOpts<OUT>,\n ): OUT | undefined {\n return this.optionInternal(actionORMethodDef, 9);\n }\n\n OR<T>(\n this: MixedInParser,\n altsOrOpts: IOrAlt<any>[] | OrMethodOpts<unknown>,\n ): T {\n return this.orInternal(altsOrOpts, 0);\n }\n\n OR1<T>(\n this: MixedInParser,\n altsOrOpts: IOrAlt<any>[] | OrMethodOpts<unknown>,\n ): T {\n return this.orInternal(altsOrOpts, 1);\n }\n\n OR2<T>(\n this: MixedInParser,\n altsOrOpts: IOrAlt<any>[] | OrMethodOpts<unknown>,\n ): T {\n return this.orInternal(altsOrOpts, 2);\n }\n\n OR3<T>(\n this: MixedInParser,\n altsOrOpts: IOrAlt<any>[] | OrMethodOpts<unknown>,\n ): T {\n return this.orInternal(altsOrOpts, 3);\n }\n\n OR4<T>(\n this: MixedInParser,\n altsOrOpts: IOrAlt<any>[] | OrMethodOpts<unknown>,\n ): T {\n return this.orInternal(altsOrOpts, 4);\n }\n\n OR5<T>(\n this: MixedInParser,\n altsOrOpts: IOrAlt<any>[] | OrMethodOpts<unknown>,\n ): T {\n return this.orInternal(altsOrOpts, 5);\n }\n\n OR6<T>(\n this: MixedInParser,\n altsOrOpts: IOrAlt<any>[] | OrMethodOpts<unknown>,\n ): T {\n return this.orInternal(altsOrOpts, 6);\n }\n\n OR7<T>(\n this: MixedInParser,\n altsOrOpts: IOrAlt<any>[] | OrMethodOpts<unknown>,\n ): T {\n return this.orInternal(altsOrOpts, 7);\n }\n\n OR8<T>(\n this: MixedInParser,\n altsOrOpts: IOrAlt<any>[] | OrMethodOpts<unknown>,\n ): T {\n return this.orInternal(altsOrOpts, 8);\n }\n\n OR9<T>(\n this: MixedInParser,\n altsOrOpts: IOrAlt<any>[] | OrMethodOpts<unknown>,\n ): T {\n return this.orInternal(altsOrOpts, 9);\n }\n\n MANY<OUT>(\n this: MixedInParser,\n actionORMethodDef: GrammarAction<OUT> | DSLMethodOpts<OUT>,\n ): void {\n this.manyInternal(0, actionORMethodDef);\n }\n\n MANY1<OUT>(\n this: MixedInParser,\n actionORMethodDef: GrammarAction<OUT> | DSLMethodOpts<OUT>,\n ): void {\n this.manyInternal(1, actionORMethodDef);\n }\n\n MANY2<OUT>(\n this: MixedInParser,\n actionORMethodDef: GrammarAction<OUT> | DSLMethodOpts<OUT>,\n ): void {\n this.manyInternal(2, actionORMethodDef);\n }\n\n MANY3<OUT>(\n this: MixedInParser,\n actionORMethodDef: GrammarAction<OUT> | DSLMethodOpts<OUT>,\n ): void {\n this.manyInternal(3, actionORMethodDef);\n }\n\n MANY4<OUT>(\n this: MixedInParser,\n actionORMethodDef: GrammarAction<OUT> | DSLMethodOpts<OUT>,\n ): void {\n this.manyInternal(4, actionORMethodDef);\n }\n\n MANY5<OUT>(\n this: MixedInParser,\n actionORMethodDef: GrammarAction<OUT> | DSLMethodOpts<OUT>,\n ): void {\n this.manyInternal(5, actionORMethodDef);\n }\n\n MANY6<OUT>(\n this: MixedInParser,\n actionORMethodDef: GrammarAction<OUT> | DSLMethodOpts<OUT>,\n ): void {\n this.manyInternal(6, actionORMethodDef);\n }\n\n MANY7<OUT>(\n this: MixedInParser,\n actionORMethodDef: GrammarAction<OUT> | DSLMethodOpts<OUT>,\n ): void {\n this.manyInternal(7, actionORMethodDef);\n }\n\n MANY8<OUT>(\n this: MixedInParser,\n actionORMethodDef: GrammarAction<OUT> | DSLMethodOpts<OUT>,\n ): void {\n this.manyInternal(8, actionORMethodDef);\n }\n\n MANY9<OUT>(\n this: MixedInParser,\n actionORMethodDef: GrammarAction<OUT> | DSLMethodOpts<OUT>,\n ): void {\n this.manyInternal(9, actionORMethodDef);\n }\n\n MANY_SEP<OUT>(this: MixedInParser, options: ManySepMethodOpts<OUT>): void {\n this.manySepFirstInternal(0, options);\n }\n\n MANY_SEP1<OUT>(this: MixedInParser, options: ManySepMethodOpts<OUT>): void {\n this.manySepFirstInternal(1, options);\n }\n\n MANY_SEP2<OUT>(this: MixedInParser, options: ManySepMethodOpts<OUT>): void {\n this.manySepFirstInternal(2, options);\n }\n\n MANY_SEP3<OUT>(this: MixedInParser, options: ManySepMethodOpts<OUT>): void {\n this.manySepFirstInternal(3, options);\n }\n\n MANY_SEP4<OUT>(this: MixedInParser, options: ManySepMethodOpts<OUT>): void {\n this.manySepFirstInternal(4, options);\n }\n\n MANY_SEP5<OUT>(this: MixedInParser, options: ManySepMethodOpts<OUT>): void {\n this.manySepFirstInternal(5, options);\n }\n\n MANY_SEP6<OUT>(this: MixedInParser, options: ManySepMethodOpts<OUT>): void {\n this.manySepFirstInternal(6, options);\n }\n\n MANY_SEP7<OUT>(this: MixedInParser, options: ManySepMethodOpts<OUT>): void {\n this.manySepFirstInternal(7, options);\n }\n\n MANY_SEP8<OUT>(this: MixedInParser, options: ManySepMethodOpts<OUT>): void {\n this.manySepFirstInternal(8, options);\n }\n\n MANY_SEP9<OUT>(this: MixedInParser, options: ManySepMethodOpts<OUT>): void {\n this.manySepFirstInternal(9, options);\n }\n\n AT_LEAST_ONE<OUT>(\n this: MixedInParser,\n actionORMethodDef: GrammarAction<OUT> | DSLMethodOptsWithErr<OUT>,\n ): void {\n this.atLeastOneInternal(0, actionORMethodDef);\n }\n\n AT_LEAST_ONE1<OUT>(\n this: MixedInParser,\n actionORMethodDef: GrammarAction<OUT> | DSLMethodOptsWithErr<OUT>,\n ): void {\n return this.atLeastOneInternal(1, actionORMethodDef);\n }\n\n AT_LEAST_ONE2<OUT>(\n this: MixedInParser,\n actionORMethodDef: GrammarAction<OUT> | DSLMethodOptsWithErr<OUT>,\n ): void {\n this.atLeastOneInternal(2, actionORMethodDef);\n }\n\n AT_LEAST_ONE3<OUT>(\n this: MixedInParser,\n actionORMethodDef: GrammarAction<OUT> | DSLMethodOptsWithErr<OUT>,\n ): void {\n this.atLeastOneInternal(3, actionORMethodDef);\n }\n\n AT_LEAST_ONE4<OUT>(\n this: MixedInParser,\n actionORMethodDef: GrammarAction<OUT> | DSLMethodOptsWithErr<OUT>,\n ): void {\n this.atLeastOneInternal(4, actionORMethodDef);\n }\n\n AT_LEAST_ONE5<OUT>(\n this: MixedInParser,\n actionORMethodDef: GrammarAction<OUT> | DSLMethodOptsWithErr<OUT>,\n ): void {\n this.atLeastOneInternal(5, actionORMethodDef);\n }\n\n AT_LEAST_ONE6<OUT>(\n this: MixedInParser,\n actionORMethodDef: GrammarAction<OUT> | DSLMethodOptsWithErr<OUT>,\n ): void {\n this.atLeastOneInternal(6, actionORMethodDef);\n }\n\n AT_LEAST_ONE7<OUT>(\n this: MixedInParser,\n actionORMethodDef: GrammarAction<OUT> | DSLMethodOptsWithErr<OUT>,\n ): void {\n this.atLeastOneInternal(7, actionORMethodDef);\n }\n\n AT_LEAST_ONE8<OUT>(\n this: MixedInParser,\n actionORMethodDef: GrammarAction<OUT> | DSLMethodOptsWithErr<OUT>,\n ): void {\n this.atLeastOneInternal(8, actionORMethodDef);\n }\n\n AT_LEAST_ONE9<OUT>(\n this: MixedInParser,\n actionORMethodDef: GrammarAction<OUT> | DSLMethodOptsWithErr<OUT>,\n ): void {\n this.atLeastOneInternal(9, actionORMethodDef);\n }\n\n AT_LEAST_ONE_SEP<OUT>(\n this: MixedInParser,\n options: AtLeastOneSepMethodOpts<OUT>,\n ): void {\n this.atLeastOneSepFirstInternal(0, options);\n }\n\n AT_LEAST_ONE_SEP1<OUT>(\n this: MixedInParser,\n options: AtLeastOneSepMethodOpts<OUT>,\n ): void {\n this.atLeastOneSepFirstInternal(1, options);\n }\n\n AT_LEAST_ONE_SEP2<OUT>(\n this: MixedInParser,\n options: AtLeastOneSepMethodOpts<OUT>,\n ): void {\n this.atLeastOneSepFirstInternal(2, options);\n }\n\n AT_LEAST_ONE_SEP3<OUT>(\n this: MixedInParser,\n options: AtLeastOneSepMethodOpts<OUT>,\n ): void {\n this.atLeastOneSepFirstInternal(3, options);\n }\n\n AT_LEAST_ONE_SEP4<OUT>(\n this: MixedInParser,\n options: AtLeastOneSepMethodOpts<OUT>,\n ): void {\n this.atLeastOneSepFirstInternal(4, options);\n }\n\n AT_LEAST_ONE_SEP5<OUT>(\n this: MixedInParser,\n options: AtLeastOneSepMethodOpts<OUT>,\n ): void {\n this.atLeastOneSepFirstInternal(5, options);\n }\n\n AT_LEAST_ONE_SEP6<OUT>(\n this: MixedInParser,\n options: AtLeastOneSepMethodOpts<OUT>,\n ): void {\n this.atLeastOneSepFirstInternal(6, options);\n }\n\n AT_LEAST_ONE_SEP7<OUT>(\n this: MixedInParser,\n options: AtLeastOneSepMethodOpts<OUT>,\n ): void {\n this.atLeastOneSepFirstInternal(7, options);\n }\n\n AT_LEAST_ONE_SEP8<OUT>(\n this: MixedInParser,\n options: AtLeastOneSepMethodOpts<OUT>,\n ): void {\n this.atLeastOneSepFirstInternal(8, options);\n }\n\n AT_LEAST_ONE_SEP9<OUT>(\n this: MixedInParser,\n options: AtLeastOneSepMethodOpts<OUT>,\n ): void {\n this.atLeastOneSepFirstInternal(9, options);\n }\n\n RULE<T>(\n this: MixedInParser,\n name: string,\n implementation: (...implArgs: any[]) => T,\n config: IRuleConfig<T> = DEFAULT_RULE_CONFIG,\n ): (idxInCallingRule?: number, ...args: any[]) => T | any {\n if (includes(this.definedRulesNames, name)) {\n const errMsg =\n defaultGrammarValidatorErrorProvider.buildDuplicateRuleNameError({\n topLevelRule: name,\n grammarName: this.className,\n });\n\n const error = {\n message: errMsg,\n type: ParserDefinitionErrorType.DUPLICATE_RULE_NAME,\n ruleName: name,\n };\n this.definitionErrors.push(error);\n }\n\n this.definedRulesNames.push(name);\n\n const ruleImplementation = this.defineRule(name, implementation, config);\n (this as any)[name] = ruleImplementation;\n return ruleImplementation;\n }\n\n OVERRIDE_RULE<T>(\n this: MixedInParser,\n name: string,\n impl: (...implArgs: any[]) => T,\n config: IRuleConfig<T> = DEFAULT_RULE_CONFIG,\n ): (idxInCallingRule?: number, ...args: any[]) => T {\n const ruleErrors: IParserDefinitionError[] = validateRuleIsOverridden(\n name,\n this.definedRulesNames,\n this.className,\n );\n this.definitionErrors = this.definitionErrors.concat(ruleErrors);\n\n const ruleImplementation = this.defineRule(name, impl, config);\n (this as any)[name] = ruleImplementation;\n return ruleImplementation;\n }\n\n BACKTRACK<T>(\n this: MixedInParser,\n grammarRule: (...args: any[]) => T,\n args?: any[],\n ): () => boolean {\n // Use coreRule to bypass root-level hooks (onBeforeParse/onAfterParse).\n // Backtracking is speculative and should not trigger parse lifecycle hooks.\n const ruleToCall = (grammarRule as any).coreRule ?? grammarRule;\n return function () {\n // save org state\n this.isBackTrackingStack.push(1);\n const orgState = this.saveRecogState();\n try {\n ruleToCall.apply(this, args);\n // if no exception was thrown we have succeed parsing the rule.\n return true;\n } catch (e) {\n if (isRecognitionException(e)) {\n return false;\n } else {\n throw e;\n }\n } finally {\n this.reloadRecogState(orgState);\n this.isBackTrackingStack.pop();\n }\n };\n }\n\n // GAST export APIs\n public getGAstProductions(this: MixedInParser): Record<string, Rule> {\n return this.gastProductionsCache;\n }\n\n public getSerializedGastProductions(this: MixedInParser): ISerializedGast[] {\n return serializeGrammar(values(this.gastProductionsCache));\n }\n}\n", "import {\n AtLeastOneSepMethodOpts,\n ConsumeMethodOpts,\n DSLMethodOpts,\n DSLMethodOptsWithErr,\n GrammarAction,\n IOrAlt,\n IParserConfig,\n IRuleConfig,\n IToken,\n ManySepMethodOpts,\n OrMethodOpts,\n ParserMethod,\n SubruleMethodOpts,\n TokenType,\n TokenTypeDictionary,\n TokenVocabulary,\n} from \"@chevrotain/types\";\nimport {\n clone,\n every,\n flatten,\n has,\n isArray,\n isEmpty,\n isObject,\n reduce,\n uniq,\n values,\n} from \"lodash-es\";\nimport {\n AT_LEAST_ONE_IDX,\n AT_LEAST_ONE_SEP_IDX,\n BITS_FOR_METHOD_TYPE,\n BITS_FOR_OCCURRENCE_IDX,\n MANY_IDX,\n MANY_SEP_IDX,\n OPTION_IDX,\n OR_IDX,\n} from \"../../grammar/keys.js\";\nimport {\n isRecognitionException,\n MismatchedTokenException,\n NotAllInputParsedException,\n} from \"../../exceptions_public.js\";\nimport { PROD_TYPE } from \"../../grammar/lookahead.js\";\nimport {\n AbstractNextTerminalAfterProductionWalker,\n NextTerminalAfterAtLeastOneSepWalker,\n NextTerminalAfterAtLeastOneWalker,\n NextTerminalAfterManySepWalker,\n NextTerminalAfterManyWalker,\n} from \"../../grammar/interpreter.js\";\nimport {\n DEFAULT_RULE_CONFIG,\n END_OF_FILE,\n IParserState,\n TokenMatcher,\n} from \"../parser.js\";\nimport { IN_RULE_RECOVERY_EXCEPTION } from \"./recoverable.js\";\nimport { EOF } from \"../../../scan/tokens_public.js\";\nimport { MixedInParser } from \"./parser_traits.js\";\nimport {\n augmentTokenTypes,\n isTokenType,\n tokenStructuredMatcher,\n tokenStructuredMatcherNoCategories,\n} from \"../../../scan/tokens.js\";\nimport { Rule } from \"@chevrotain/gast\";\nimport { ParserMethodInternal } from \"../types.js\";\n\n/**\n * This trait is responsible for the runtime parsing engine\n * Used by the official API (recognizer_api.ts)\n */\nexport class RecognizerEngine {\n isBackTrackingStack: boolean[];\n className: string;\n RULE_STACK: number[];\n RULE_OCCURRENCE_STACK: number[];\n // Depth counters for the pre-allocated state stacks.\n // Using index-based access (arr[++idx] = val / idx--) instead of push/pop\n // avoids method-call overhead on every rule entry/exit.\n RULE_STACK_IDX: number;\n RULE_OCCURRENCE_STACK_IDX: number;\n definedRulesNames: string[];\n tokensMap: { [fqn: string]: TokenType };\n gastProductionsCache: Record<string, Rule>;\n shortRuleNameToFull: Record<string, string>;\n fullRuleNameToShort: Record<string, number>;\n // The shortName Index must be coded \"after\" the first 8bits to enable building unique lookahead keys\n ruleShortNameIdx: number;\n tokenMatcher: TokenMatcher;\n subruleIdx: number;\n // Cached value of the current rule's short name to avoid repeated RULE_STACK[length-1] lookups.\n // Updated on rule entry/exit and state reload.\n currRuleShortName: number;\n\n initRecognizerEngine(\n tokenVocabulary: TokenVocabulary,\n config: IParserConfig,\n ) {\n this.className = this.constructor.name;\n // TODO: would using an ES6 Map or plain object be faster (CST building scenario)\n this.shortRuleNameToFull = {};\n this.fullRuleNameToShort = {};\n this.ruleShortNameIdx = 256;\n this.tokenMatcher = tokenStructuredMatcherNoCategories;\n this.subruleIdx = 0;\n this.currRuleShortName = 0;\n\n this.definedRulesNames = [];\n this.tokensMap = {};\n this.isBackTrackingStack = [];\n this.RULE_STACK = [];\n this.RULE_STACK_IDX = -1;\n this.RULE_OCCURRENCE_STACK = [];\n this.RULE_OCCURRENCE_STACK_IDX = -1;\n this.gastProductionsCache = {};\n\n if (has(config, \"serializedGrammar\")) {\n throw Error(\n \"The Parser's configuration can no longer contain a <serializedGrammar> property.\\n\" +\n \"\\tSee: https://chevrotain.io/docs/changes/BREAKING_CHANGES.html#_6-0-0\\n\" +\n \"\\tFor Further details.\",\n );\n }\n\n if (isArray(tokenVocabulary)) {\n // This only checks for Token vocabularies provided as arrays.\n // That is good enough because the main objective is to detect users of pre-V4.0 APIs\n // rather than all edge cases of empty Token vocabularies.\n if (isEmpty(tokenVocabulary as any[])) {\n throw Error(\n \"A Token Vocabulary cannot be empty.\\n\" +\n \"\\tNote that the first argument for the parser constructor\\n\" +\n \"\\tis no longer a Token vector (since v4.0).\",\n );\n }\n\n if (typeof (tokenVocabulary as any[])[0].startOffset === \"number\") {\n throw Error(\n \"The Parser constructor no longer accepts a token vector as the first argument.\\n\" +\n \"\\tSee: https://chevrotain.io/docs/changes/BREAKING_CHANGES.html#_4-0-0\\n\" +\n \"\\tFor Further details.\",\n );\n }\n }\n\n if (isArray(tokenVocabulary)) {\n this.tokensMap = reduce(\n tokenVocabulary,\n (acc, tokType: TokenType) => {\n acc[tokType.name] = tokType;\n return acc;\n },\n {} as { [tokenName: string]: TokenType },\n );\n } else if (\n has(tokenVocabulary, \"modes\") &&\n every(flatten(values((<any>tokenVocabulary).modes)), isTokenType)\n ) {\n const allTokenTypes = flatten(values((<any>tokenVocabulary).modes));\n const uniqueTokens = uniq(allTokenTypes);\n this.tokensMap = <any>reduce(\n uniqueTokens,\n (acc, tokType: TokenType) => {\n acc[tokType.name] = tokType;\n return acc;\n },\n {} as { [tokenName: string]: TokenType },\n );\n } else if (isObject(tokenVocabulary)) {\n this.tokensMap = clone(tokenVocabulary as TokenTypeDictionary);\n } else {\n throw new Error(\n \"<tokensDictionary> argument must be An Array of Token constructors,\" +\n \" A dictionary of Token constructors or an IMultiModeLexerDefinition\",\n );\n }\n\n // always add EOF to the tokenNames -> constructors map. it is useful to assure all the input has been\n // parsed with a clear error message (\"expecting EOF but found ...\")\n this.tokensMap[\"EOF\"] = EOF;\n\n const allTokenTypes = has(tokenVocabulary, \"modes\")\n ? flatten(values((<any>tokenVocabulary).modes))\n : values(tokenVocabulary);\n const noTokenCategoriesUsed = every(allTokenTypes, (tokenConstructor) =>\n isEmpty(tokenConstructor.categoryMatches),\n );\n\n this.tokenMatcher = noTokenCategoriesUsed\n ? tokenStructuredMatcherNoCategories\n : tokenStructuredMatcher;\n\n // Because ES2015+ syntax should be supported for creating Token classes\n // We cannot assume that the Token classes were created using the \"extendToken\" utilities\n // Therefore we must augment the Token classes both on Lexer initialization and on Parser initialization\n augmentTokenTypes(values(this.tokensMap));\n }\n\n defineRule<ARGS extends unknown[], R>(\n this: MixedInParser,\n ruleName: string,\n impl: (...args: ARGS) => R,\n config: IRuleConfig<R>,\n ): ParserMethodInternal<ARGS, R> {\n if (this.selfAnalysisDone) {\n throw Error(\n `Grammar rule <${ruleName}> may not be defined after the 'performSelfAnalysis' method has been called'\\n` +\n `Make sure that all grammar rule definitions are done before 'performSelfAnalysis' is called.`,\n );\n }\n const resyncEnabled: boolean = has(config, \"resyncEnabled\")\n ? (config.resyncEnabled as boolean) // assumes end user provides the correct config value/type\n : DEFAULT_RULE_CONFIG.resyncEnabled;\n const recoveryValueFunc = has(config, \"recoveryValueFunc\")\n ? (config.recoveryValueFunc as () => R) // assumes end user provides the correct config value/type\n : DEFAULT_RULE_CONFIG.recoveryValueFunc;\n\n // performance optimization: Use small integers as keys for the longer human readable \"full\" rule names.\n // this greatly improves Map access time (as much as 8% for some performance benchmarks).\n const shortName =\n this.ruleShortNameIdx << (BITS_FOR_METHOD_TYPE + BITS_FOR_OCCURRENCE_IDX);\n\n this.ruleShortNameIdx++;\n this.shortRuleNameToFull[shortName] = ruleName;\n this.fullRuleNameToShort[ruleName] = shortName;\n\n let coreRuleFunction: ParserMethod<ARGS, R>;\n\n // Micro optimization, only check the condition **once** on rule definition\n // instead of **every single** rule invocation.\n if (this.outputCst === true) {\n coreRuleFunction = function invokeRuleWithTry(\n this: MixedInParser,\n ...args: ARGS\n ): R {\n try {\n this.ruleInvocationStateUpdate(shortName, ruleName, this.subruleIdx);\n impl.apply(this, args);\n const cst = this.CST_STACK[this.CST_STACK.length - 1];\n this.cstPostRule(cst);\n return cst as unknown as R;\n } catch (e) {\n return this.invokeRuleCatch(e, resyncEnabled, recoveryValueFunc) as R;\n } finally {\n this.ruleFinallyStateUpdate();\n }\n };\n } else {\n coreRuleFunction = function invokeRuleWithTryCst(\n this: MixedInParser,\n ...args: ARGS\n ): R {\n try {\n this.ruleInvocationStateUpdate(shortName, ruleName, this.subruleIdx);\n return impl.apply(this, args);\n } catch (e) {\n return this.invokeRuleCatch(e, resyncEnabled, recoveryValueFunc) as R;\n } finally {\n this.ruleFinallyStateUpdate();\n }\n };\n }\n\n // wrapper to allow before/after parsing hooks\n const rootRuleFunction: ParserMethod<ARGS, R> = function rootRule(\n this: MixedInParser,\n ...args: ARGS\n ): R {\n this.onBeforeParse(ruleName);\n try {\n return coreRuleFunction.apply(this, args);\n } finally {\n this.onAfterParse(ruleName);\n }\n };\n\n const wrappedGrammarRule: ParserMethodInternal<ARGS, R> = Object.assign(\n rootRuleFunction as any,\n { ruleName, originalGrammarAction: impl, coreRule: coreRuleFunction },\n );\n\n return wrappedGrammarRule;\n }\n\n invokeRuleCatch(\n this: MixedInParser,\n e: Error,\n resyncEnabledConfig: boolean,\n recoveryValueFunc: Function,\n ): unknown {\n const isFirstInvokedRule = this.RULE_STACK_IDX === 0;\n // note the reSync is always enabled for the first rule invocation, because we must always be able to\n // reSync with EOF and just output some INVALID ParseTree\n // during backtracking reSync recovery is disabled, otherwise we can't be certain the backtracking\n // path is really the most valid one\n const reSyncEnabled =\n resyncEnabledConfig && !this.isBackTracking() && this.recoveryEnabled;\n\n if (isRecognitionException(e)) {\n const recogError: any = e;\n if (reSyncEnabled) {\n const reSyncTokType = this.findReSyncTokenType();\n if (this.isInCurrentRuleReSyncSet(reSyncTokType)) {\n recogError.resyncedTokens = this.reSyncTo(reSyncTokType);\n if (this.outputCst) {\n const partialCstResult: any =\n this.CST_STACK[this.CST_STACK.length - 1];\n partialCstResult.recoveredNode = true;\n return partialCstResult;\n } else {\n return recoveryValueFunc(e);\n }\n } else {\n if (this.outputCst) {\n const partialCstResult: any =\n this.CST_STACK[this.CST_STACK.length - 1];\n partialCstResult.recoveredNode = true;\n recogError.partialCstResult = partialCstResult;\n }\n // to be handled Further up the call stack\n throw recogError;\n }\n } else if (isFirstInvokedRule) {\n // otherwise a Redundant input error will be created as well and we cannot guarantee that this is indeed the case\n this.moveToTerminatedState();\n // the parser should never throw one of its own errors outside its flow.\n // even if error recovery is disabled\n return recoveryValueFunc(e);\n } else {\n // to be recovered Further up the call stack\n throw recogError;\n }\n } else {\n // some other Error type which we don't know how to handle (for example a built in JavaScript Error)\n throw e;\n }\n }\n\n // Implementation of parsing DSL\n optionInternal<OUT>(\n this: MixedInParser,\n actionORMethodDef: GrammarAction<OUT> | DSLMethodOpts<OUT>,\n occurrence: number,\n ): OUT | undefined {\n const key = this.getKeyForAutomaticLookahead(OPTION_IDX, occurrence);\n return this.optionInternalLogic(actionORMethodDef, occurrence, key);\n }\n\n optionInternalLogic<OUT>(\n this: MixedInParser,\n actionORMethodDef: GrammarAction<OUT> | DSLMethodOpts<OUT>,\n occurrence: number,\n key: number,\n ): OUT | undefined {\n let lookAheadFunc = this.getLaFuncFromCache(key);\n let action: GrammarAction<OUT>;\n if (typeof actionORMethodDef !== \"function\") {\n action = actionORMethodDef.DEF;\n const predicate = actionORMethodDef.GATE;\n // predicate present\n if (predicate !== undefined) {\n const orgLookaheadFunction = lookAheadFunc;\n lookAheadFunc = () => {\n return predicate.call(this) && orgLookaheadFunction.call(this);\n };\n }\n } else {\n action = actionORMethodDef;\n }\n\n if (lookAheadFunc.call(this) === true) {\n return action.call(this);\n }\n return undefined;\n }\n\n atLeastOneInternal<OUT>(\n this: MixedInParser,\n prodOccurrence: number,\n actionORMethodDef: GrammarAction<OUT> | DSLMethodOptsWithErr<OUT>,\n ): void {\n const laKey = this.getKeyForAutomaticLookahead(\n AT_LEAST_ONE_IDX,\n prodOccurrence,\n );\n return this.atLeastOneInternalLogic(\n prodOccurrence,\n actionORMethodDef,\n laKey,\n );\n }\n\n atLeastOneInternalLogic<OUT>(\n this: MixedInParser,\n prodOccurrence: number,\n actionORMethodDef: GrammarAction<OUT> | DSLMethodOptsWithErr<OUT>,\n key: number,\n ): void {\n let lookAheadFunc = this.getLaFuncFromCache(key);\n let action;\n if (typeof actionORMethodDef !== \"function\") {\n action = actionORMethodDef.DEF;\n const predicate = actionORMethodDef.GATE;\n // predicate present\n if (predicate !== undefined) {\n const orgLookaheadFunction = lookAheadFunc;\n lookAheadFunc = () => {\n return predicate.call(this) && orgLookaheadFunction.call(this);\n };\n }\n } else {\n action = actionORMethodDef;\n }\n\n if ((<Function>lookAheadFunc).call(this) === true) {\n let notStuck = this.doSingleRepetition(action);\n while (\n (<Function>lookAheadFunc).call(this) === true &&\n notStuck === true\n ) {\n notStuck = this.doSingleRepetition(action);\n }\n } else {\n throw this.raiseEarlyExitException(\n prodOccurrence,\n PROD_TYPE.REPETITION_MANDATORY,\n (<DSLMethodOptsWithErr<OUT>>actionORMethodDef).ERR_MSG,\n );\n }\n\n // note that while it may seem that this can cause an error because by using a recursive call to\n // AT_LEAST_ONE we change the grammar to AT_LEAST_TWO, AT_LEAST_THREE ... , the possible recursive call\n // from the tryInRepetitionRecovery(...) will only happen IFF there really are TWO/THREE/.... items.\n\n // Performance optimization: \"attemptInRepetitionRecovery\" will be defined as NOOP unless recovery is enabled\n this.attemptInRepetitionRecovery(\n this.atLeastOneInternal,\n [prodOccurrence, actionORMethodDef],\n <any>lookAheadFunc,\n AT_LEAST_ONE_IDX,\n prodOccurrence,\n NextTerminalAfterAtLeastOneWalker,\n );\n }\n\n atLeastOneSepFirstInternal<OUT>(\n this: MixedInParser,\n prodOccurrence: number,\n options: AtLeastOneSepMethodOpts<OUT>,\n ): void {\n const laKey = this.getKeyForAutomaticLookahead(\n AT_LEAST_ONE_SEP_IDX,\n prodOccurrence,\n );\n this.atLeastOneSepFirstInternalLogic(prodOccurrence, options, laKey);\n }\n\n atLeastOneSepFirstInternalLogic<OUT>(\n this: MixedInParser,\n prodOccurrence: number,\n options: AtLeastOneSepMethodOpts<OUT>,\n key: number,\n ): void {\n const action = options.DEF;\n const separator = options.SEP;\n\n const firstIterationLookaheadFunc = this.getLaFuncFromCache(key);\n\n // 1st iteration\n if (firstIterationLookaheadFunc.call(this) === true) {\n (<GrammarAction<OUT>>action).call(this);\n\n // TODO: Optimization can move this function construction into \"attemptInRepetitionRecovery\"\n // because it is only needed in error recovery scenarios.\n const separatorLookAheadFunc = () => {\n return this.tokenMatcher(this.LA_FAST(1), separator);\n };\n\n // 2nd..nth iterations\n while (this.tokenMatcher(this.LA_FAST(1), separator) === true) {\n // note that this CONSUME will never enter recovery because\n // the separatorLookAheadFunc checks that the separator really does exist.\n this.CONSUME(separator);\n // No need for checking infinite loop here due to consuming the separator.\n (<GrammarAction<OUT>>action).call(this);\n }\n\n // Performance optimization: \"attemptInRepetitionRecovery\" will be defined as NOOP unless recovery is enabled\n this.attemptInRepetitionRecovery(\n this.repetitionSepSecondInternal,\n [\n prodOccurrence,\n separator,\n separatorLookAheadFunc,\n action,\n NextTerminalAfterAtLeastOneSepWalker,\n ],\n separatorLookAheadFunc,\n AT_LEAST_ONE_SEP_IDX,\n prodOccurrence,\n NextTerminalAfterAtLeastOneSepWalker,\n );\n } else {\n throw this.raiseEarlyExitException(\n prodOccurrence,\n PROD_TYPE.REPETITION_MANDATORY_WITH_SEPARATOR,\n options.ERR_MSG,\n );\n }\n }\n\n manyInternal<OUT>(\n this: MixedInParser,\n prodOccurrence: number,\n actionORMethodDef: GrammarAction<OUT> | DSLMethodOpts<OUT>,\n ): void {\n const laKey = this.getKeyForAutomaticLookahead(MANY_IDX, prodOccurrence);\n return this.manyInternalLogic(prodOccurrence, actionORMethodDef, laKey);\n }\n\n manyInternalLogic<OUT>(\n this: MixedInParser,\n prodOccurrence: number,\n actionORMethodDef: GrammarAction<OUT> | DSLMethodOpts<OUT>,\n key: number,\n ) {\n let lookaheadFunction = this.getLaFuncFromCache(key);\n let action;\n if (typeof actionORMethodDef !== \"function\") {\n action = actionORMethodDef.DEF;\n const predicate = actionORMethodDef.GATE;\n // predicate present\n if (predicate !== undefined) {\n const orgLookaheadFunction = lookaheadFunction;\n lookaheadFunction = () => {\n return predicate.call(this) && orgLookaheadFunction.call(this);\n };\n }\n } else {\n action = actionORMethodDef;\n }\n\n let notStuck = true;\n while (lookaheadFunction.call(this) === true && notStuck === true) {\n notStuck = this.doSingleRepetition(action);\n }\n\n // Performance optimization: \"attemptInRepetitionRecovery\" will be defined as NOOP unless recovery is enabled\n this.attemptInRepetitionRecovery(\n this.manyInternal,\n [prodOccurrence, actionORMethodDef],\n <any>lookaheadFunction,\n MANY_IDX,\n prodOccurrence,\n NextTerminalAfterManyWalker,\n // The notStuck parameter is only relevant when \"attemptInRepetitionRecovery\"\n // is invoked from manyInternal, in the MANY_SEP case and AT_LEAST_ONE[_SEP]\n // An infinite loop cannot occur as:\n // - Either the lookahead is guaranteed to consume something (Single Token Separator)\n // - AT_LEAST_ONE by definition is guaranteed to consume something (or error out).\n notStuck,\n );\n }\n\n manySepFirstInternal<OUT>(\n this: MixedInParser,\n prodOccurrence: number,\n options: ManySepMethodOpts<OUT>,\n ): void {\n const laKey = this.getKeyForAutomaticLookahead(\n MANY_SEP_IDX,\n prodOccurrence,\n );\n this.manySepFirstInternalLogic(prodOccurrence, options, laKey);\n }\n\n manySepFirstInternalLogic<OUT>(\n this: MixedInParser,\n prodOccurrence: number,\n options: ManySepMethodOpts<OUT>,\n key: number,\n ): void {\n const action = options.DEF;\n const separator = options.SEP;\n const firstIterationLaFunc = this.getLaFuncFromCache(key);\n\n // 1st iteration\n if (firstIterationLaFunc.call(this) === true) {\n action.call(this);\n\n const separatorLookAheadFunc = () => {\n return this.tokenMatcher(this.LA_FAST(1), separator);\n };\n // 2nd..nth iterations\n while (this.tokenMatcher(this.LA_FAST(1), separator) === true) {\n // note that this CONSUME will never enter recovery because\n // the separatorLookAheadFunc checks that the separator really does exist.\n this.CONSUME(separator);\n // No need for checking infinite loop here due to consuming the separator.\n action.call(this);\n }\n\n // Performance optimization: \"attemptInRepetitionRecovery\" will be defined as NOOP unless recovery is enabled\n this.attemptInRepetitionRecovery(\n this.repetitionSepSecondInternal,\n [\n prodOccurrence,\n separator,\n separatorLookAheadFunc,\n action,\n NextTerminalAfterManySepWalker,\n ],\n separatorLookAheadFunc,\n MANY_SEP_IDX,\n prodOccurrence,\n NextTerminalAfterManySepWalker,\n );\n }\n }\n\n repetitionSepSecondInternal<OUT>(\n this: MixedInParser,\n prodOccurrence: number,\n separator: TokenType,\n separatorLookAheadFunc: () => boolean,\n action: GrammarAction<OUT>,\n nextTerminalAfterWalker: typeof AbstractNextTerminalAfterProductionWalker,\n ): void {\n while (separatorLookAheadFunc()) {\n // note that this CONSUME will never enter recovery because\n // the separatorLookAheadFunc checks that the separator really does exist.\n this.CONSUME(separator);\n action.call(this);\n }\n\n // we can only arrive to this function after an error\n // has occurred (hence the name 'second') so the following\n // IF will always be entered, its possible to remove it...\n // however it is kept to avoid confusion and be consistent.\n // Performance optimization: \"attemptInRepetitionRecovery\" will be defined as NOOP unless recovery is enabled\n /* istanbul ignore else */\n this.attemptInRepetitionRecovery(\n this.repetitionSepSecondInternal,\n [\n prodOccurrence,\n separator,\n separatorLookAheadFunc,\n action,\n nextTerminalAfterWalker,\n ],\n separatorLookAheadFunc,\n AT_LEAST_ONE_SEP_IDX,\n prodOccurrence,\n nextTerminalAfterWalker,\n );\n }\n\n doSingleRepetition(this: MixedInParser, action: Function): any {\n const beforeIteration = this.getLexerPosition();\n action.call(this);\n const afterIteration = this.getLexerPosition();\n\n // This boolean will indicate if this repetition progressed\n // or if we are \"stuck\" (potential infinite loop in the repetition).\n return afterIteration > beforeIteration;\n }\n\n orInternal<T>(\n this: MixedInParser,\n altsOrOpts: IOrAlt<any>[] | OrMethodOpts<unknown>,\n occurrence: number,\n ): T {\n const laKey = this.getKeyForAutomaticLookahead(OR_IDX, occurrence);\n const alts = isArray(altsOrOpts) ? altsOrOpts : altsOrOpts.DEF;\n\n const laFunc = this.getLaFuncFromCache(laKey);\n const altIdxToTake = laFunc.call(this, alts);\n if (altIdxToTake !== undefined) {\n const chosenAlternative: any = alts[altIdxToTake];\n return chosenAlternative.ALT.call(this);\n }\n this.raiseNoAltException(\n occurrence,\n (altsOrOpts as OrMethodOpts<unknown>).ERR_MSG,\n );\n }\n\n ruleFinallyStateUpdate(this: MixedInParser): void {\n this.RULE_STACK_IDX--;\n this.RULE_OCCURRENCE_STACK_IDX--;\n\n // Restore the cached short name to the parent rule.\n // When the stack is empty (top-level rule exiting), the stale value\n // is harmless \u2014 no DSL methods will be called before the next ruleInvocationStateUpdate.\n if (this.RULE_STACK_IDX >= 0) {\n this.currRuleShortName = this.RULE_STACK[this.RULE_STACK_IDX];\n }\n\n // NOOP when cst is disabled\n this.cstFinallyStateUpdate();\n }\n\n subruleInternal<ARGS extends unknown[], R>(\n this: MixedInParser,\n ruleToCall: ParserMethodInternal<ARGS, R>,\n idx: number,\n options?: SubruleMethodOpts<ARGS>,\n ): R {\n let ruleResult;\n try {\n const args = options !== undefined ? options.ARGS : undefined;\n this.subruleIdx = idx;\n // Use coreRule to bypass root-level hooks (onBeforeParse/onAfterParse)\n ruleResult = ruleToCall.coreRule.apply(this, args);\n this.cstPostNonTerminal(\n ruleResult,\n options !== undefined && options.LABEL !== undefined\n ? options.LABEL\n : ruleToCall.ruleName,\n );\n return ruleResult;\n } catch (e) {\n throw this.subruleInternalError(e, options, ruleToCall.ruleName);\n }\n }\n\n subruleInternalError(\n this: MixedInParser,\n e: any,\n options: SubruleMethodOpts<unknown[]> | undefined,\n ruleName: string,\n ): void {\n if (isRecognitionException(e) && e.partialCstResult !== undefined) {\n this.cstPostNonTerminal(\n e.partialCstResult,\n options !== undefined && options.LABEL !== undefined\n ? options.LABEL\n : ruleName,\n );\n\n delete e.partialCstResult;\n }\n throw e;\n }\n\n consumeInternal(\n this: MixedInParser,\n tokType: TokenType,\n idx: number,\n options: ConsumeMethodOpts | undefined,\n ): IToken {\n let consumedToken!: IToken;\n try {\n const nextToken = this.LA_FAST(1);\n if (this.tokenMatcher(nextToken, tokType) === true) {\n this.consumeToken();\n consumedToken = nextToken;\n } else {\n this.consumeInternalError(tokType, nextToken, options);\n }\n } catch (eFromConsumption) {\n consumedToken = this.consumeInternalRecovery(\n tokType,\n idx,\n eFromConsumption,\n );\n }\n\n this.cstPostTerminal(\n options !== undefined && options.LABEL !== undefined\n ? options.LABEL\n : tokType.name,\n consumedToken,\n );\n return consumedToken;\n }\n\n consumeInternalError(\n this: MixedInParser,\n tokType: TokenType,\n nextToken: IToken,\n options: ConsumeMethodOpts | undefined,\n ): void {\n let msg;\n const previousToken = this.LA(0);\n if (options !== undefined && options.ERR_MSG) {\n msg = options.ERR_MSG;\n } else {\n msg = this.errorMessageProvider.buildMismatchTokenMessage({\n expected: tokType,\n actual: nextToken,\n previous: previousToken,\n ruleName: this.getCurrRuleFullName(),\n });\n }\n throw this.SAVE_ERROR(\n new MismatchedTokenException(msg, nextToken, previousToken),\n );\n }\n\n consumeInternalRecovery(\n this: MixedInParser,\n tokType: TokenType,\n idx: number,\n eFromConsumption: Error,\n ): IToken {\n // no recovery allowed during backtracking, otherwise backtracking may recover invalid syntax and accept it\n // but the original syntax could have been parsed successfully without any backtracking + recovery\n if (\n this.recoveryEnabled &&\n // TODO: more robust checking of the exception type. Perhaps Typescript extending expressions?\n eFromConsumption.name === \"MismatchedTokenException\" &&\n !this.isBackTracking()\n ) {\n const follows = this.getFollowsForInRuleRecovery(<any>tokType, idx);\n try {\n return this.tryInRuleRecovery(<any>tokType, follows);\n } catch (eFromInRuleRecovery) {\n if (eFromInRuleRecovery.name === IN_RULE_RECOVERY_EXCEPTION) {\n // failed in RuleRecovery.\n // throw the original error in order to trigger reSync error recovery\n throw eFromConsumption;\n } else {\n throw eFromInRuleRecovery;\n }\n }\n } else {\n throw eFromConsumption;\n }\n }\n\n saveRecogState(this: MixedInParser): IParserState {\n // errors is a getter which will clone the errors array\n const savedErrors = this.errors;\n // Slice only the active portion of the pre-allocated stack\n const savedRuleStack = this.RULE_STACK.slice(0, this.RULE_STACK_IDX + 1);\n return {\n errors: savedErrors,\n lexerState: this.exportLexerState(),\n RULE_STACK: savedRuleStack,\n CST_STACK: this.CST_STACK,\n };\n }\n\n reloadRecogState(this: MixedInParser, newState: IParserState) {\n this.errors = newState.errors;\n this.importLexerState(newState.lexerState);\n // Copy saved stack back into the pre-allocated array and restore the index\n const saved = newState.RULE_STACK;\n for (let i = 0; i < saved.length; i++) {\n this.RULE_STACK[i] = saved[i];\n }\n this.RULE_STACK_IDX = saved.length - 1;\n // Restore cached short name from the restored stack\n if (this.RULE_STACK_IDX >= 0) {\n this.currRuleShortName = this.RULE_STACK[this.RULE_STACK_IDX];\n }\n }\n\n ruleInvocationStateUpdate(\n this: MixedInParser,\n shortName: number,\n fullName: string,\n idxInCallingRule: number,\n ): void {\n this.RULE_OCCURRENCE_STACK[++this.RULE_OCCURRENCE_STACK_IDX] =\n idxInCallingRule;\n this.RULE_STACK[++this.RULE_STACK_IDX] = shortName;\n this.currRuleShortName = shortName;\n // NOOP when cst is disabled\n this.cstInvocationStateUpdate(fullName);\n }\n\n isBackTracking(this: MixedInParser): boolean {\n return this.isBackTrackingStack.length !== 0;\n }\n\n getCurrRuleFullName(this: MixedInParser): string {\n const shortName = this.currRuleShortName;\n return this.shortRuleNameToFull[shortName];\n }\n\n shortRuleNameToFullName(this: MixedInParser, shortName: number) {\n return this.shortRuleNameToFull[shortName];\n }\n\n public isAtEndOfInput(this: MixedInParser): boolean {\n return this.tokenMatcher(this.LA(1), EOF);\n }\n\n public reset(this: MixedInParser): void {\n this.resetLexerState();\n this.subruleIdx = 0;\n this.currRuleShortName = 0;\n this.isBackTrackingStack = [];\n this.errors = [];\n // Reset depth counters but keep arrays allocated to avoid re-allocation.\n // Stale number values in unused slots are harmless.\n this.RULE_STACK_IDX = -1;\n this.RULE_OCCURRENCE_STACK_IDX = -1;\n // TODO: extract a specific reset for TreeBuilder trait\n this.CST_STACK = [];\n }\n\n /**\n * Hook called before the root-level parsing rule is invoked.\n * This is only called when a rule is invoked directly by the consumer\n * (e.g., `parser.json()`), not when invoked as a sub-rule via SUBRULE.\n *\n * Override this method to perform actions before parsing begins.\n * The default implementation is a no-op.\n *\n * @param ruleName - The name of the root rule being invoked.\n */\n onBeforeParse(this: MixedInParser, ruleName: string): void {\n // Pad with sentinels for bounds-free forward LA()\n for (let i = 0; i < this.maxLookahead + 1; i++) {\n this.tokVector.push(END_OF_FILE);\n }\n }\n\n /**\n * Hook called after the root-level parsing rule has completed (or thrown).\n * This is only called when a rule is invoked directly by the consumer\n * (e.g., `parser.json()`), not when invoked as a sub-rule via SUBRULE.\n *\n * This hook is called in a `finally` block, so it executes regardless of\n * whether parsing succeeded or threw an error.\n *\n * Override this method to perform actions after parsing completes.\n * The default implementation is a no-op.\n *\n * @param ruleName - The name of the root rule that was invoked.\n */\n onAfterParse(this: MixedInParser, ruleName: string): void {\n if (this.isAtEndOfInput() === false) {\n const firstRedundantTok = this.LA(1);\n const errMsg = this.errorMessageProvider.buildNotAllInputParsedMessage({\n firstRedundant: firstRedundantTok,\n ruleName: this.getCurrRuleFullName(),\n });\n this.SAVE_ERROR(\n new NotAllInputParsedException(errMsg, firstRedundantTok),\n );\n }\n\n // undo the padding of sentinels for bounds-free forward LA() in onBeforeParse\n while (this.tokVector.at(-1) === END_OF_FILE) {\n this.tokVector.pop();\n }\n }\n}\n", "import {\n IParserConfig,\n IParserErrorMessageProvider,\n IRecognitionException,\n} from \"@chevrotain/types\";\nimport {\n EarlyExitException,\n isRecognitionException,\n NoViableAltException,\n} from \"../../exceptions_public.js\";\nimport { clone, has } from \"lodash-es\";\nimport {\n getLookaheadPathsForOptionalProd,\n getLookaheadPathsForOr,\n PROD_TYPE,\n} from \"../../grammar/lookahead.js\";\nimport { MixedInParser } from \"./parser_traits.js\";\nimport { DEFAULT_PARSER_CONFIG } from \"../parser.js\";\n\n/**\n * Trait responsible for runtime parsing errors.\n */\nexport class ErrorHandler {\n _errors: IRecognitionException[];\n errorMessageProvider: IParserErrorMessageProvider;\n\n initErrorHandler(config: IParserConfig) {\n this._errors = [];\n this.errorMessageProvider = has(config, \"errorMessageProvider\")\n ? (config.errorMessageProvider as IParserErrorMessageProvider) // assumes end user provides the correct config value/type\n : DEFAULT_PARSER_CONFIG.errorMessageProvider;\n }\n\n SAVE_ERROR(\n this: MixedInParser,\n error: IRecognitionException,\n ): IRecognitionException {\n if (isRecognitionException(error)) {\n error.context = {\n ruleStack: this.getHumanReadableRuleStack(),\n ruleOccurrenceStack: this.RULE_OCCURRENCE_STACK.slice(\n 0,\n this.RULE_OCCURRENCE_STACK_IDX + 1,\n ),\n };\n this._errors.push(error);\n return error;\n } else {\n throw Error(\n \"Trying to save an Error which is not a RecognitionException\",\n );\n }\n }\n\n get errors(): IRecognitionException[] {\n return clone(this._errors);\n }\n\n set errors(newErrors: IRecognitionException[]) {\n this._errors = newErrors;\n }\n\n // TODO: consider caching the error message computed information\n raiseEarlyExitException(\n this: MixedInParser,\n occurrence: number,\n prodType: PROD_TYPE,\n userDefinedErrMsg: string | undefined,\n ): never {\n const ruleName = this.getCurrRuleFullName();\n const ruleGrammar = this.getGAstProductions()[ruleName];\n const lookAheadPathsPerAlternative = getLookaheadPathsForOptionalProd(\n occurrence,\n ruleGrammar,\n prodType,\n this.maxLookahead,\n );\n const insideProdPaths = lookAheadPathsPerAlternative[0];\n const actualTokens = [];\n for (let i = 1; i <= this.maxLookahead; i++) {\n actualTokens.push(this.LA(i));\n }\n const msg = this.errorMessageProvider.buildEarlyExitMessage({\n expectedIterationPaths: insideProdPaths,\n actual: actualTokens,\n previous: this.LA(0),\n customUserDescription: userDefinedErrMsg,\n ruleName: ruleName,\n });\n\n throw this.SAVE_ERROR(new EarlyExitException(msg, this.LA(1), this.LA(0)));\n }\n\n // TODO: consider caching the error message computed information\n raiseNoAltException(\n this: MixedInParser,\n occurrence: number,\n errMsgTypes: string | undefined,\n ): never {\n const ruleName = this.getCurrRuleFullName();\n const ruleGrammar = this.getGAstProductions()[ruleName];\n // TODO: getLookaheadPathsForOr can be slow for large enough maxLookahead and certain grammars, consider caching ?\n const lookAheadPathsPerAlternative = getLookaheadPathsForOr(\n occurrence,\n ruleGrammar,\n this.maxLookahead,\n );\n\n const actualTokens = [];\n for (let i = 1; i <= this.maxLookahead; i++) {\n actualTokens.push(this.LA(i));\n }\n const previousToken = this.LA(0);\n\n const errMsg = this.errorMessageProvider.buildNoViableAltMessage({\n expectedPathsPerAlt: lookAheadPathsPerAlternative,\n actual: actualTokens,\n previous: previousToken,\n customUserDescription: errMsgTypes,\n ruleName: this.getCurrRuleFullName(),\n });\n\n throw this.SAVE_ERROR(\n new NoViableAltException(errMsg, this.LA(1), previousToken),\n );\n }\n}\n", "import {\n ISyntacticContentAssistPath,\n IToken,\n ITokenGrammarPath,\n TokenType,\n} from \"@chevrotain/types\";\nimport {\n NextAfterTokenWalker,\n nextPossibleTokensAfter,\n} from \"../../grammar/interpreter.js\";\nimport { first, isUndefined } from \"lodash-es\";\nimport { MixedInParser } from \"./parser_traits.js\";\n\nexport class ContentAssist {\n initContentAssist() {}\n\n public computeContentAssist(\n this: MixedInParser,\n startRuleName: string,\n precedingInput: IToken[],\n ): ISyntacticContentAssistPath[] {\n const startRuleGast = this.gastProductionsCache[startRuleName];\n\n if (isUndefined(startRuleGast)) {\n throw Error(`Rule ->${startRuleName}<- does not exist in this grammar.`);\n }\n\n return nextPossibleTokensAfter(\n [startRuleGast],\n precedingInput,\n this.tokenMatcher,\n this.maxLookahead,\n );\n }\n\n // TODO: should this be a member method or a utility? it does not have any state or usage of 'this'...\n // TODO: should this be more explicitly part of the public API?\n public getNextPossibleTokenTypes(\n this: MixedInParser,\n grammarPath: ITokenGrammarPath,\n ): TokenType[] {\n const topRuleName = first(grammarPath.ruleStack)!;\n const gastProductions = this.getGAstProductions();\n const topProduction = gastProductions[topRuleName];\n const nextPossibleTokenTypes = new NextAfterTokenWalker(\n topProduction,\n grammarPath,\n ).startWalking();\n return nextPossibleTokenTypes;\n }\n}\n", "import {\n AtLeastOneSepMethodOpts,\n ConsumeMethodOpts,\n CstNode,\n DSLMethodOpts,\n DSLMethodOptsWithErr,\n GrammarAction,\n IOrAlt,\n IParserConfig,\n IProduction,\n IToken,\n ManySepMethodOpts,\n OrMethodOpts,\n SubruleMethodOpts,\n TokenType,\n} from \"@chevrotain/types\";\nimport {\n forEach,\n has,\n isArray,\n isFunction,\n last as peek,\n some,\n} from \"lodash-es\";\nimport { MixedInParser } from \"./parser_traits.js\";\nimport {\n Alternation,\n Alternative,\n NonTerminal,\n Option,\n Repetition,\n RepetitionMandatory,\n RepetitionMandatoryWithSeparator,\n RepetitionWithSeparator,\n Rule,\n Terminal,\n} from \"@chevrotain/gast\";\nimport { Lexer } from \"../../../scan/lexer_public.js\";\nimport {\n augmentTokenTypes,\n hasShortKeyProperty,\n} from \"../../../scan/tokens.js\";\nimport {\n createToken,\n createTokenInstance,\n} from \"../../../scan/tokens_public.js\";\nimport { END_OF_FILE } from \"../parser.js\";\nimport { BITS_FOR_OCCURRENCE_IDX } from \"../../grammar/keys.js\";\nimport { ParserMethodInternal } from \"../types.js\";\n\ntype ProdWithDef = IProduction & { definition?: IProduction[] };\nconst RECORDING_NULL_OBJECT = {\n description: \"This Object indicates the Parser is during Recording Phase\",\n};\nObject.freeze(RECORDING_NULL_OBJECT);\n\nconst HANDLE_SEPARATOR = true;\nconst MAX_METHOD_IDX = Math.pow(2, BITS_FOR_OCCURRENCE_IDX) - 1;\n\nconst RFT = createToken({ name: \"RECORDING_PHASE_TOKEN\", pattern: Lexer.NA });\naugmentTokenTypes([RFT]);\nconst RECORDING_PHASE_TOKEN = createTokenInstance(\n RFT,\n \"This IToken indicates the Parser is in Recording Phase\\n\\t\" +\n \"\" +\n \"See: https://chevrotain.io/docs/guide/internals.html#grammar-recording for details\",\n // Using \"-1\" instead of NaN (as in EOF) because an actual number is less likely to\n // cause errors if the output of LA or CONSUME would be (incorrectly) used during the recording phase.\n -1,\n -1,\n -1,\n -1,\n -1,\n -1,\n);\nObject.freeze(RECORDING_PHASE_TOKEN);\n\nconst RECORDING_PHASE_CSTNODE: CstNode = {\n name:\n \"This CSTNode indicates the Parser is in Recording Phase\\n\\t\" +\n \"See: https://chevrotain.io/docs/guide/internals.html#grammar-recording for details\",\n children: {},\n};\n\n/**\n * This trait handles the creation of the GAST structure for Chevrotain Grammars\n */\nexport class GastRecorder {\n recordingProdStack: ProdWithDef[];\n RECORDING_PHASE: boolean;\n\n initGastRecorder(this: MixedInParser, config: IParserConfig): void {\n this.recordingProdStack = [];\n this.RECORDING_PHASE = false;\n }\n\n enableRecording(this: MixedInParser): void {\n this.RECORDING_PHASE = true;\n\n this.TRACE_INIT(\"Enable Recording\", () => {\n /**\n * Warning Dark Voodoo Magic upcoming!\n * We are \"replacing\" the public parsing DSL methods API\n * With **new** alternative implementations on the Parser **instance**\n *\n * So far this is the only way I've found to avoid performance regressions during parsing time.\n * - Approx 30% performance regression was measured on Chrome 75 Canary when attempting to replace the \"internal\"\n * implementations directly instead.\n */\n for (let i = 0; i < 10; i++) {\n const idx = i > 0 ? i : \"\";\n this[`CONSUME${idx}` as \"CONSUME\"] = function (arg1, arg2) {\n return this.consumeInternalRecord(arg1, i, arg2);\n };\n this[`SUBRULE${idx}` as \"SUBRULE\"] = function (arg1, arg2) {\n return this.subruleInternalRecord(arg1, i, arg2) as any;\n };\n this[`OPTION${idx}` as \"OPTION\"] = function (arg1) {\n return this.optionInternalRecord(arg1, i);\n };\n this[`OR${idx}` as \"OR\"] = function (arg1) {\n return this.orInternalRecord(arg1, i);\n };\n this[`MANY${idx}` as \"MANY\"] = function (arg1) {\n this.manyInternalRecord(i, arg1);\n };\n this[`MANY_SEP${idx}` as \"MANY_SEP\"] = function (arg1) {\n this.manySepFirstInternalRecord(i, arg1);\n };\n this[`AT_LEAST_ONE${idx}` as \"AT_LEAST_ONE\"] = function (arg1) {\n this.atLeastOneInternalRecord(i, arg1);\n };\n this[`AT_LEAST_ONE_SEP${idx}` as \"AT_LEAST_ONE_SEP\"] = function (arg1) {\n this.atLeastOneSepFirstInternalRecord(i, arg1);\n };\n }\n\n // DSL methods with the idx(suffix) as an argument\n this[`consume`] = function (idx, arg1, arg2) {\n return this.consumeInternalRecord(arg1, idx, arg2);\n };\n this[`subrule`] = function (idx, arg1, arg2) {\n return this.subruleInternalRecord(arg1, idx, arg2) as any;\n };\n this[`option`] = function (idx, arg1) {\n return this.optionInternalRecord(arg1, idx);\n };\n this[`or`] = function (idx, arg1) {\n return this.orInternalRecord(arg1, idx);\n };\n this[`many`] = function (idx, arg1) {\n this.manyInternalRecord(idx, arg1);\n };\n this[`atLeastOne`] = function (idx, arg1) {\n this.atLeastOneInternalRecord(idx, arg1);\n };\n\n this.ACTION = this.ACTION_RECORD;\n this.BACKTRACK = this.BACKTRACK_RECORD;\n this.LA = this.LA_RECORD;\n });\n }\n\n disableRecording(this: MixedInParser) {\n this.RECORDING_PHASE = false;\n // By deleting these **instance** properties, any future invocation\n // will be deferred to the original methods on the **prototype** object\n // This seems to get rid of any incorrect optimizations that V8 may\n // do during the recording phase.\n this.TRACE_INIT(\"Deleting Recording methods\", () => {\n const that: any = this;\n\n for (let i = 0; i < 10; i++) {\n const idx = i > 0 ? i : \"\";\n delete that[`CONSUME${idx}`];\n delete that[`SUBRULE${idx}`];\n delete that[`OPTION${idx}`];\n delete that[`OR${idx}`];\n delete that[`MANY${idx}`];\n delete that[`MANY_SEP${idx}`];\n delete that[`AT_LEAST_ONE${idx}`];\n delete that[`AT_LEAST_ONE_SEP${idx}`];\n }\n\n delete that[`consume`];\n delete that[`subrule`];\n delete that[`option`];\n delete that[`or`];\n delete that[`many`];\n delete that[`atLeastOne`];\n\n delete that.ACTION;\n delete that.BACKTRACK;\n delete that.LA;\n });\n }\n\n // Parser methods are called inside an ACTION?\n // Maybe try/catch/finally on ACTIONS while disabling the recorders state changes?\n // @ts-expect-error -- noop place holder\n ACTION_RECORD<T>(this: MixedInParser, impl: () => T): T {\n // NO-OP during recording\n }\n\n // Executing backtracking logic will break our recording logic assumptions\n BACKTRACK_RECORD<T>(\n grammarRule: (...args: any[]) => T,\n args?: any[],\n ): () => boolean {\n return () => true;\n }\n\n // LA is part of the official API and may be used for custom lookahead logic\n // by end users who may forget to wrap it in ACTION or inside a GATE\n LA_RECORD(howMuch: number): IToken {\n // We cannot use the RECORD_PHASE_TOKEN here because someone may depend\n // On LA return EOF at the end of the input so an infinite loop may occur.\n return END_OF_FILE;\n }\n\n topLevelRuleRecord(name: string, def: Function): Rule {\n try {\n const newTopLevelRule = new Rule({ definition: [], name: name });\n newTopLevelRule.name = name;\n this.recordingProdStack.push(newTopLevelRule);\n def.call(this);\n this.recordingProdStack.pop();\n return newTopLevelRule;\n } catch (originalError) {\n if (originalError.KNOWN_RECORDER_ERROR !== true) {\n try {\n originalError.message =\n originalError.message +\n '\\n\\t This error was thrown during the \"grammar recording phase\" For more info see:\\n\\t' +\n \"https://chevrotain.io/docs/guide/internals.html#grammar-recording\";\n } catch (mutabilityError) {\n // We may not be able to modify the original error object\n throw originalError;\n }\n }\n throw originalError;\n }\n }\n\n // Implementation of parsing DSL\n optionInternalRecord<OUT>(\n this: MixedInParser,\n actionORMethodDef: GrammarAction<OUT> | DSLMethodOpts<OUT>,\n occurrence: number,\n ): OUT {\n return recordProd.call(this, Option, actionORMethodDef, occurrence);\n }\n\n atLeastOneInternalRecord<OUT>(\n this: MixedInParser,\n occurrence: number,\n actionORMethodDef: GrammarAction<OUT> | DSLMethodOptsWithErr<OUT>,\n ): void {\n recordProd.call(this, RepetitionMandatory, actionORMethodDef, occurrence);\n }\n\n atLeastOneSepFirstInternalRecord<OUT>(\n this: MixedInParser,\n occurrence: number,\n options: AtLeastOneSepMethodOpts<OUT>,\n ): void {\n recordProd.call(\n this,\n RepetitionMandatoryWithSeparator,\n options,\n occurrence,\n HANDLE_SEPARATOR,\n );\n }\n\n manyInternalRecord<OUT>(\n this: MixedInParser,\n occurrence: number,\n actionORMethodDef: GrammarAction<OUT> | DSLMethodOpts<OUT>,\n ): void {\n recordProd.call(this, Repetition, actionORMethodDef, occurrence);\n }\n\n manySepFirstInternalRecord<OUT>(\n this: MixedInParser,\n occurrence: number,\n options: ManySepMethodOpts<OUT>,\n ): void {\n recordProd.call(\n this,\n RepetitionWithSeparator,\n options,\n occurrence,\n HANDLE_SEPARATOR,\n );\n }\n\n orInternalRecord<T>(\n this: MixedInParser,\n altsOrOpts: IOrAlt<any>[] | OrMethodOpts<unknown>,\n occurrence: number,\n ): T {\n return recordOrProd.call(this, altsOrOpts, occurrence);\n }\n\n subruleInternalRecord<ARGS extends unknown[], R>(\n this: MixedInParser,\n ruleToCall: ParserMethodInternal<ARGS, R>,\n occurrence: number,\n options?: SubruleMethodOpts<ARGS>,\n ): R | CstNode {\n assertMethodIdxIsValid(occurrence);\n if (!ruleToCall || has(ruleToCall, \"ruleName\") === false) {\n const error: any = new Error(\n `<SUBRULE${getIdxSuffix(occurrence)}> argument is invalid` +\n ` expecting a Parser method reference but got: <${JSON.stringify(\n ruleToCall,\n )}>` +\n `\\n inside top level rule: <${\n (<Rule>this.recordingProdStack[0]).name\n }>`,\n );\n error.KNOWN_RECORDER_ERROR = true;\n throw error;\n }\n\n const prevProd: any = peek(this.recordingProdStack);\n const ruleName = ruleToCall.ruleName;\n const newNoneTerminal = new NonTerminal({\n idx: occurrence,\n nonTerminalName: ruleName,\n label: options?.LABEL,\n // The resolving of the `referencedRule` property will be done once all the Rule's GASTs have been created\n referencedRule: undefined,\n });\n prevProd.definition.push(newNoneTerminal);\n\n return this.outputCst\n ? RECORDING_PHASE_CSTNODE\n : <any>RECORDING_NULL_OBJECT;\n }\n\n consumeInternalRecord(\n this: MixedInParser,\n tokType: TokenType,\n occurrence: number,\n options?: ConsumeMethodOpts,\n ): IToken {\n assertMethodIdxIsValid(occurrence);\n if (!hasShortKeyProperty(tokType)) {\n const error: any = new Error(\n `<CONSUME${getIdxSuffix(occurrence)}> argument is invalid` +\n ` expecting a TokenType reference but got: <${JSON.stringify(\n tokType,\n )}>` +\n `\\n inside top level rule: <${\n (<Rule>this.recordingProdStack[0]).name\n }>`,\n );\n error.KNOWN_RECORDER_ERROR = true;\n throw error;\n }\n const prevProd: any = peek(this.recordingProdStack);\n const newNoneTerminal = new Terminal({\n idx: occurrence,\n terminalType: tokType,\n label: options?.LABEL,\n });\n prevProd.definition.push(newNoneTerminal);\n\n return RECORDING_PHASE_TOKEN;\n }\n}\n\nfunction recordProd(\n prodConstructor: any,\n mainProdArg: any,\n occurrence: number,\n handleSep: boolean = false,\n): any {\n assertMethodIdxIsValid(occurrence);\n const prevProd: any = peek(this.recordingProdStack);\n const grammarAction = isFunction(mainProdArg) ? mainProdArg : mainProdArg.DEF;\n\n const newProd = new prodConstructor({ definition: [], idx: occurrence });\n if (handleSep) {\n newProd.separator = mainProdArg.SEP;\n }\n if (has(mainProdArg, \"MAX_LOOKAHEAD\")) {\n newProd.maxLookahead = mainProdArg.MAX_LOOKAHEAD;\n }\n\n this.recordingProdStack.push(newProd);\n grammarAction.call(this);\n prevProd.definition.push(newProd);\n this.recordingProdStack.pop();\n\n return RECORDING_NULL_OBJECT;\n}\n\nfunction recordOrProd(mainProdArg: any, occurrence: number): any {\n assertMethodIdxIsValid(occurrence);\n const prevProd: any = peek(this.recordingProdStack);\n // Only an array of alternatives\n const hasOptions = isArray(mainProdArg) === false;\n const alts: IOrAlt<unknown>[] =\n hasOptions === false ? mainProdArg : mainProdArg.DEF;\n\n const newOrProd = new Alternation({\n definition: [],\n idx: occurrence,\n ignoreAmbiguities: hasOptions && mainProdArg.IGNORE_AMBIGUITIES === true,\n });\n if (has(mainProdArg, \"MAX_LOOKAHEAD\")) {\n newOrProd.maxLookahead = mainProdArg.MAX_LOOKAHEAD;\n }\n\n const hasPredicates = some(alts, (currAlt: any) => isFunction(currAlt.GATE));\n newOrProd.hasPredicates = hasPredicates;\n\n prevProd.definition.push(newOrProd);\n\n forEach(alts, (currAlt) => {\n const currAltFlat = new Alternative({ definition: [] });\n newOrProd.definition.push(currAltFlat);\n if (has(currAlt, \"IGNORE_AMBIGUITIES\")) {\n currAltFlat.ignoreAmbiguities = currAlt.IGNORE_AMBIGUITIES as boolean; // assumes end user provides the correct config value/type\n }\n // **implicit** ignoreAmbiguities due to usage of gate\n else if (has(currAlt, \"GATE\")) {\n currAltFlat.ignoreAmbiguities = true;\n }\n this.recordingProdStack.push(currAltFlat);\n currAlt.ALT.call(this);\n this.recordingProdStack.pop();\n });\n return RECORDING_NULL_OBJECT;\n}\n\nfunction getIdxSuffix(idx: number): string {\n return idx === 0 ? \"\" : `${idx}`;\n}\n\nfunction assertMethodIdxIsValid(idx: number): void {\n if (idx < 0 || idx > MAX_METHOD_IDX) {\n const error: any = new Error(\n // The stack trace will contain all the needed details\n `Invalid DSL Method idx value: <${idx}>\\n\\t` +\n `Idx value must be a none negative value smaller than ${\n MAX_METHOD_IDX + 1\n }`,\n );\n error.KNOWN_RECORDER_ERROR = true;\n throw error;\n }\n}\n", "import { IParserConfig } from \"@chevrotain/types\";\nimport { has } from \"lodash-es\";\nimport { timer } from \"@chevrotain/utils\";\nimport { MixedInParser } from \"./parser_traits.js\";\nimport { DEFAULT_PARSER_CONFIG } from \"../parser.js\";\n\n/**\n * Trait responsible for runtime parsing errors.\n */\nexport class PerformanceTracer {\n traceInitPerf: boolean | number;\n traceInitMaxIdent: number;\n traceInitIndent: number;\n\n initPerformanceTracer(config: IParserConfig) {\n if (has(config, \"traceInitPerf\")) {\n const userTraceInitPerf = config.traceInitPerf;\n const traceIsNumber = typeof userTraceInitPerf === \"number\";\n this.traceInitMaxIdent = traceIsNumber\n ? <number>userTraceInitPerf\n : Infinity;\n this.traceInitPerf = traceIsNumber\n ? userTraceInitPerf > 0\n : (userTraceInitPerf as boolean); // assumes end user provides the correct config value/type\n } else {\n this.traceInitMaxIdent = 0;\n this.traceInitPerf = DEFAULT_PARSER_CONFIG.traceInitPerf;\n }\n\n this.traceInitIndent = -1;\n }\n\n TRACE_INIT<T>(this: MixedInParser, phaseDesc: string, phaseImpl: () => T): T {\n // No need to optimize this using NOOP pattern because\n // It is not called in a hot spot...\n if (this.traceInitPerf === true) {\n this.traceInitIndent++;\n const indent = new Array(this.traceInitIndent + 1).join(\"\\t\");\n if (this.traceInitIndent < this.traceInitMaxIdent) {\n console.log(`${indent}--> <${phaseDesc}>`);\n }\n const { time, value } = timer(phaseImpl);\n /* istanbul ignore next - Difficult to reproduce specific performance behavior (>10ms) in tests */\n const traceMethod = time > 10 ? console.warn : console.log;\n if (this.traceInitIndent < this.traceInitMaxIdent) {\n traceMethod(`${indent}<-- <${phaseDesc}> time: ${time}ms`);\n }\n this.traceInitIndent--;\n return value;\n } else {\n return phaseImpl();\n }\n }\n}\n", "export function applyMixins(derivedCtor: any, baseCtors: any[]) {\n baseCtors.forEach((baseCtor) => {\n const baseProto = baseCtor.prototype;\n Object.getOwnPropertyNames(baseProto).forEach((propName) => {\n if (propName === \"constructor\") {\n return;\n }\n\n const basePropDescriptor = Object.getOwnPropertyDescriptor(\n baseProto,\n propName,\n );\n // Handle Accessors\n if (\n basePropDescriptor &&\n (basePropDescriptor.get || basePropDescriptor.set)\n ) {\n Object.defineProperty(\n derivedCtor.prototype,\n propName,\n basePropDescriptor,\n );\n } else {\n derivedCtor.prototype[propName] = baseCtor.prototype[propName];\n }\n });\n });\n}\n", "import { clone, forEach, has, isEmpty, map, values } from \"lodash-es\";\nimport { toFastProperties } from \"@chevrotain/utils\";\nimport { computeAllProdsFollows } from \"../grammar/follow.js\";\nimport { createTokenInstance, EOF } from \"../../scan/tokens_public.js\";\nimport {\n defaultGrammarValidatorErrorProvider,\n defaultParserErrorProvider,\n} from \"../errors_public.js\";\nimport {\n resolveGrammar,\n validateGrammar,\n} from \"../grammar/gast/gast_resolver_public.js\";\nimport {\n CstNode,\n IParserConfig,\n IRecognitionException,\n IRuleConfig,\n IToken,\n TokenType,\n TokenVocabulary,\n} from \"@chevrotain/types\";\nimport { Recoverable } from \"./traits/recoverable.js\";\nimport { LooksAhead } from \"./traits/looksahead.js\";\nimport { TreeBuilder } from \"./traits/tree_builder.js\";\nimport { LexerAdapter } from \"./traits/lexer_adapter.js\";\nimport { RecognizerApi } from \"./traits/recognizer_api.js\";\nimport { RecognizerEngine } from \"./traits/recognizer_engine.js\";\n\nimport { ErrorHandler } from \"./traits/error_handler.js\";\nimport { MixedInParser } from \"./traits/parser_traits.js\";\nimport { ContentAssist } from \"./traits/context_assist.js\";\nimport { GastRecorder } from \"./traits/gast_recorder.js\";\nimport { PerformanceTracer } from \"./traits/perf_tracer.js\";\nimport { applyMixins } from \"./utils/apply_mixins.js\";\nimport { IParserDefinitionError } from \"../grammar/types.js\";\nimport { Rule } from \"@chevrotain/gast\";\nimport { IParserConfigInternal, ParserMethodInternal } from \"./types.js\";\nimport { validateLookahead } from \"../grammar/checks.js\";\n\nexport const END_OF_FILE = createTokenInstance(\n EOF,\n \"\",\n NaN,\n NaN,\n NaN,\n NaN,\n NaN,\n NaN,\n);\nObject.freeze(END_OF_FILE);\n\nexport type TokenMatcher = (token: IToken, tokType: TokenType) => boolean;\n\nexport const DEFAULT_PARSER_CONFIG: Required<\n Omit<IParserConfigInternal, \"lookaheadStrategy\">\n> = Object.freeze({\n recoveryEnabled: false,\n maxLookahead: 3,\n dynamicTokensEnabled: false,\n outputCst: true,\n errorMessageProvider: defaultParserErrorProvider,\n nodeLocationTracking: \"none\",\n traceInitPerf: false,\n skipValidations: false,\n});\n\nexport const DEFAULT_RULE_CONFIG: Required<IRuleConfig<any>> = Object.freeze({\n recoveryValueFunc: () => undefined,\n resyncEnabled: true,\n});\n\nexport enum ParserDefinitionErrorType {\n INVALID_RULE_NAME = 0,\n DUPLICATE_RULE_NAME = 1,\n INVALID_RULE_OVERRIDE = 2,\n DUPLICATE_PRODUCTIONS = 3,\n UNRESOLVED_SUBRULE_REF = 4,\n LEFT_RECURSION = 5,\n NONE_LAST_EMPTY_ALT = 6,\n AMBIGUOUS_ALTS = 7,\n CONFLICT_TOKENS_RULES_NAMESPACE = 8,\n INVALID_TOKEN_NAME = 9,\n NO_NON_EMPTY_LOOKAHEAD = 10,\n AMBIGUOUS_PREFIX_ALTS = 11,\n TOO_MANY_ALTS = 12,\n CUSTOM_LOOKAHEAD_VALIDATION = 13,\n}\n\nexport interface IParserDuplicatesDefinitionError extends IParserDefinitionError {\n dslName: string;\n occurrence: number;\n parameter?: string;\n}\n\nexport interface IParserEmptyAlternativeDefinitionError extends IParserDefinitionError {\n occurrence: number;\n alternative: number;\n}\n\nexport interface IParserAmbiguousAlternativesDefinitionError extends IParserDefinitionError {\n occurrence: number | string;\n alternatives: number[];\n}\n\nexport interface IParserUnresolvedRefDefinitionError extends IParserDefinitionError {\n unresolvedRefName: string;\n}\n\nexport interface IParserState {\n errors: IRecognitionException[];\n lexerState: any;\n RULE_STACK: number[];\n CST_STACK: CstNode[];\n}\n\nexport type Predicate = () => boolean;\n\nexport function EMPTY_ALT(): () => undefined;\nexport function EMPTY_ALT<T>(value: T): () => T;\nexport function EMPTY_ALT(value: any = undefined) {\n return function () {\n return value;\n };\n}\n\nexport class Parser {\n // Set this flag to true if you don't want the Parser to throw error when problems in it's definition are detected.\n // (normally during the parser's constructor).\n // This is a design time flag, it will not affect the runtime error handling of the parser, just design time errors,\n // for example: duplicate rule names, referencing an unresolved subrule, etc...\n // This flag should not be enabled during normal usage, it is used in special situations, for example when\n // needing to display the parser definition errors in some GUI(online playground).\n static DEFER_DEFINITION_ERRORS_HANDLING: boolean = false;\n\n /**\n * @deprecated use the **instance** method with the same name instead\n */\n static performSelfAnalysis(parserInstance: Parser): void {\n throw Error(\n \"The **static** `performSelfAnalysis` method has been deprecated.\" +\n \"\\t\\nUse the **instance** method with the same name instead.\",\n );\n }\n\n public performSelfAnalysis(this: MixedInParser): void {\n this.TRACE_INIT(\"performSelfAnalysis\", () => {\n let defErrorsMsgs;\n\n this.selfAnalysisDone = true;\n const className = this.className;\n\n this.TRACE_INIT(\"toFastProps\", () => {\n // Without this voodoo magic the parser would be x3-x4 slower\n // It seems it is better to invoke `toFastProperties` **before**\n // Any manipulations of the `this` object done during the recording phase.\n toFastProperties(this);\n });\n\n this.TRACE_INIT(\"Grammar Recording\", () => {\n try {\n this.enableRecording();\n // Building the GAST\n forEach(this.definedRulesNames, (currRuleName) => {\n const wrappedRule = (this as any)[\n currRuleName\n ] as ParserMethodInternal<unknown[], unknown>;\n const originalGrammarAction = wrappedRule[\"originalGrammarAction\"];\n let recordedRuleGast!: Rule;\n this.TRACE_INIT(`${currRuleName} Rule`, () => {\n recordedRuleGast = this.topLevelRuleRecord(\n currRuleName,\n originalGrammarAction,\n );\n });\n this.gastProductionsCache[currRuleName] = recordedRuleGast;\n });\n } finally {\n this.disableRecording();\n }\n });\n\n let resolverErrors: IParserDefinitionError[] = [];\n this.TRACE_INIT(\"Grammar Resolving\", () => {\n resolverErrors = resolveGrammar({\n rules: values(this.gastProductionsCache),\n });\n this.definitionErrors = this.definitionErrors.concat(resolverErrors);\n });\n\n this.TRACE_INIT(\"Grammar Validations\", () => {\n // only perform additional grammar validations IFF no resolving errors have occurred.\n // as unresolved grammar may lead to unhandled runtime exceptions in the follow up validations.\n if (isEmpty(resolverErrors) && this.skipValidations === false) {\n const validationErrors = validateGrammar({\n rules: values(this.gastProductionsCache),\n tokenTypes: values(this.tokensMap),\n errMsgProvider: defaultGrammarValidatorErrorProvider,\n grammarName: className,\n });\n const lookaheadValidationErrors = validateLookahead({\n lookaheadStrategy: this.lookaheadStrategy,\n rules: values(this.gastProductionsCache),\n tokenTypes: values(this.tokensMap),\n grammarName: className,\n });\n this.definitionErrors = this.definitionErrors.concat(\n validationErrors,\n lookaheadValidationErrors,\n );\n }\n });\n\n // this analysis may fail if the grammar is not perfectly valid\n if (isEmpty(this.definitionErrors)) {\n // The results of these computations are not needed unless error recovery is enabled.\n if (this.recoveryEnabled) {\n this.TRACE_INIT(\"computeAllProdsFollows\", () => {\n const allFollows = computeAllProdsFollows(\n values(this.gastProductionsCache),\n );\n this.resyncFollows = allFollows;\n });\n }\n\n this.TRACE_INIT(\"ComputeLookaheadFunctions\", () => {\n this.lookaheadStrategy.initialize?.({\n rules: values(this.gastProductionsCache),\n });\n this.preComputeLookaheadFunctions(values(this.gastProductionsCache));\n });\n }\n\n if (\n !Parser.DEFER_DEFINITION_ERRORS_HANDLING &&\n !isEmpty(this.definitionErrors)\n ) {\n defErrorsMsgs = map(\n this.definitionErrors,\n (defError) => defError.message,\n );\n throw new Error(\n `Parser Definition Errors detected:\\n ${defErrorsMsgs.join(\n \"\\n-------------------------------\\n\",\n )}`,\n );\n }\n });\n }\n\n definitionErrors: IParserDefinitionError[] = [];\n selfAnalysisDone = false;\n protected skipValidations: boolean;\n\n constructor(tokenVocabulary: TokenVocabulary, config: IParserConfig) {\n const that: MixedInParser = this as any;\n that.initErrorHandler(config);\n that.initLexerAdapter();\n that.initLooksAhead(config);\n that.initRecognizerEngine(tokenVocabulary, config);\n that.initRecoverable(config);\n that.initTreeBuilder(config);\n that.initContentAssist();\n that.initGastRecorder(config);\n that.initPerformanceTracer(config);\n\n if (has(config, \"ignoredIssues\")) {\n throw new Error(\n \"The <ignoredIssues> IParserConfig property has been deprecated.\\n\\t\" +\n \"Please use the <IGNORE_AMBIGUITIES> flag on the relevant DSL method instead.\\n\\t\" +\n \"See: https://chevrotain.io/docs/guide/resolving_grammar_errors.html#IGNORING_AMBIGUITIES\\n\\t\" +\n \"For further details.\",\n );\n }\n\n this.skipValidations = has(config, \"skipValidations\")\n ? (config.skipValidations as boolean) // casting assumes the end user passing the correct type\n : DEFAULT_PARSER_CONFIG.skipValidations;\n }\n}\n\napplyMixins(Parser, [\n Recoverable,\n LooksAhead,\n TreeBuilder,\n LexerAdapter,\n RecognizerEngine,\n RecognizerApi,\n ErrorHandler,\n ContentAssist,\n GastRecorder,\n PerformanceTracer,\n]);\n\nexport class CstParser extends Parser {\n constructor(\n tokenVocabulary: TokenVocabulary,\n config: IParserConfigInternal = DEFAULT_PARSER_CONFIG,\n ) {\n const configClone = clone(config);\n configClone.outputCst = true;\n super(tokenVocabulary, configClone);\n }\n}\n\nexport class EmbeddedActionsParser extends Parser {\n constructor(\n tokenVocabulary: TokenVocabulary,\n config: IParserConfigInternal = DEFAULT_PARSER_CONFIG,\n ) {\n const configClone = clone(config);\n configClone.outputCst = false;\n super(tokenVocabulary, configClone);\n }\n}\n", "import type {\n Alternation,\n Alternative,\n IProduction,\n Option,\n Repetition,\n RepetitionMandatory,\n RepetitionMandatoryWithSeparator,\n RepetitionWithSeparator,\n Rule,\n Terminal,\n TokenType,\n} from \"@chevrotain/types\";\nimport { GAstVisitor, NonTerminal } from \"@chevrotain/gast\";\nimport { assign, flatten, groupBy, map, some, values } from \"lodash-es\";\n\nexport function buildModel(\n productions: Record<string, Rule>,\n): CstNodeTypeDefinition[] {\n const generator = new CstNodeDefinitionGenerator();\n const allRules = values(productions);\n return map(allRules, (rule) => generator.visitRule(rule));\n}\n\nexport type CstNodeTypeDefinition = {\n name: string;\n properties: PropertyTypeDefinition[];\n};\n\nexport type PropertyTypeDefinition = {\n name: string;\n type: PropertyArrayType;\n optional: boolean;\n};\n\nexport type PropertyArrayType =\n | TokenArrayType\n | RuleArrayType\n | (TokenArrayType | RuleArrayType)[];\n\nexport type TokenArrayType = { kind: \"token\" };\nexport type RuleArrayType = {\n kind: \"rule\";\n name: string;\n};\n\nclass CstNodeDefinitionGenerator extends GAstVisitor {\n visitRule(node: Rule): CstNodeTypeDefinition {\n const rawElements = this.visitEach(node.definition);\n\n const grouped = groupBy(rawElements, (el) => el.propertyName);\n const properties = map(grouped, (group, propertyName) => {\n const allNullable = !some(group, (el) => !el.canBeNull);\n\n // In an alternation with a label a property name can have\n // multiple types.\n let propertyType: PropertyArrayType = group[0].type;\n if (group.length > 1) {\n propertyType = map(group, (g) => g.type);\n }\n\n return {\n name: propertyName,\n type: propertyType,\n optional: allNullable,\n } as PropertyTypeDefinition;\n });\n\n return {\n name: node.name,\n properties: properties,\n };\n }\n\n visitAlternative(node: Alternative) {\n return this.visitEachAndOverrideWith(node.definition, { canBeNull: true });\n }\n\n visitOption(node: Option) {\n return this.visitEachAndOverrideWith(node.definition, { canBeNull: true });\n }\n\n visitRepetition(node: Repetition) {\n return this.visitEachAndOverrideWith(node.definition, { canBeNull: true });\n }\n\n visitRepetitionMandatory(node: RepetitionMandatory) {\n return this.visitEach(node.definition);\n }\n\n visitRepetitionMandatoryWithSeparator(\n node: RepetitionMandatoryWithSeparator,\n ) {\n return this.visitEach(node.definition).concat({\n propertyName: node.separator.name,\n canBeNull: true,\n type: getType(node.separator),\n });\n }\n\n visitRepetitionWithSeparator(node: RepetitionWithSeparator) {\n return this.visitEachAndOverrideWith(node.definition, {\n canBeNull: true,\n }).concat({\n propertyName: node.separator.name,\n canBeNull: true,\n type: getType(node.separator),\n });\n }\n\n visitAlternation(node: Alternation) {\n return this.visitEachAndOverrideWith(node.definition, { canBeNull: true });\n }\n\n visitTerminal(node: Terminal): PropertyTupleElement[] {\n return [\n {\n propertyName: node.label || node.terminalType.name,\n canBeNull: false,\n type: getType(node),\n },\n ];\n }\n\n visitNonTerminal(node: NonTerminal): PropertyTupleElement[] {\n return [\n {\n propertyName: node.label || node.nonTerminalName,\n canBeNull: false,\n type: getType(node),\n },\n ];\n }\n\n private visitEachAndOverrideWith(\n definition: IProduction[],\n override: Partial<PropertyTupleElement>,\n ) {\n return map(\n this.visitEach(definition),\n (definition) => assign({}, definition, override) as PropertyTupleElement,\n );\n }\n\n private visitEach(definition: IProduction[]) {\n return flatten<PropertyTupleElement>(\n map(\n definition,\n (definition) => this.visit(definition) as PropertyTupleElement[],\n ),\n );\n }\n}\n\ntype PropertyTupleElement = {\n propertyName: string;\n canBeNull: boolean;\n type: TokenArrayType | RuleArrayType;\n};\n\nfunction getType(\n production: Terminal | NonTerminal | TokenType,\n): TokenArrayType | RuleArrayType {\n if (production instanceof NonTerminal) {\n return {\n kind: \"rule\",\n name: production.referencedRule.name,\n };\n }\n\n return { kind: \"token\" };\n}\n", "import { flatten, isArray, map, reduce, uniq, upperFirst } from \"lodash-es\";\nimport { GenerateDtsOptions } from \"@chevrotain/types\";\nimport {\n CstNodeTypeDefinition,\n PropertyArrayType,\n PropertyTypeDefinition,\n RuleArrayType,\n TokenArrayType,\n} from \"./model.js\";\n\nexport function genDts(\n model: CstNodeTypeDefinition[],\n options: Required<GenerateDtsOptions>,\n): string {\n let contentParts: string[] = [];\n\n contentParts = contentParts.concat(\n `import type { CstNode, ICstVisitor, IToken } from \"chevrotain\";`,\n );\n\n contentParts = contentParts.concat(\n flatten(map(model, (node) => genCstNodeTypes(node))),\n );\n\n if (options.includeVisitorInterface) {\n contentParts = contentParts.concat(\n genVisitor(options.visitorInterfaceName, model),\n );\n }\n\n return contentParts.join(\"\\n\\n\") + \"\\n\";\n}\n\nfunction genCstNodeTypes(node: CstNodeTypeDefinition) {\n const nodeCstInterface = genNodeInterface(node);\n const nodeChildrenInterface = genNodeChildrenType(node);\n\n return [nodeCstInterface, nodeChildrenInterface];\n}\n\nfunction genNodeInterface(node: CstNodeTypeDefinition) {\n const nodeInterfaceName = getNodeInterfaceName(node.name);\n const childrenTypeName = getNodeChildrenTypeName(node.name);\n\n return `export interface ${nodeInterfaceName} extends CstNode {\n name: \"${node.name}\";\n children: ${childrenTypeName};\n}`;\n}\n\nfunction genNodeChildrenType(node: CstNodeTypeDefinition) {\n const typeName = getNodeChildrenTypeName(node.name);\n\n return `export type ${typeName} = {\n ${map(node.properties, (property) => genChildProperty(property)).join(\"\\n \")}\n};`;\n}\n\nfunction genChildProperty(prop: PropertyTypeDefinition) {\n const typeName = buildTypeString(prop.type);\n return `${prop.name}${prop.optional ? \"?\" : \"\"}: ${typeName}[];`;\n}\n\nfunction genVisitor(name: string, nodes: CstNodeTypeDefinition[]) {\n return `export interface ${name}<IN, OUT> extends ICstVisitor<IN, OUT> {\n ${map(nodes, (node) => genVisitorFunction(node)).join(\"\\n \")}\n}`;\n}\n\nfunction genVisitorFunction(node: CstNodeTypeDefinition) {\n const childrenTypeName = getNodeChildrenTypeName(node.name);\n return `${node.name}(children: ${childrenTypeName}, param?: IN): OUT;`;\n}\n\nfunction buildTypeString(type: PropertyArrayType) {\n if (isArray(type)) {\n const typeNames = uniq(map(type, (t) => getTypeString(t)));\n const typeString = reduce(typeNames, (sum, t) => sum + \" | \" + t);\n return \"(\" + typeString + \")\";\n } else {\n return getTypeString(type);\n }\n}\n\nfunction getTypeString(type: TokenArrayType | RuleArrayType) {\n if (type.kind === \"token\") {\n return \"IToken\";\n }\n return getNodeInterfaceName(type.name);\n}\n\nfunction getNodeInterfaceName(ruleName: string) {\n return upperFirst(ruleName) + \"CstNode\";\n}\n\nfunction getNodeChildrenTypeName(ruleName: string) {\n return upperFirst(ruleName) + \"CstChildren\";\n}\n", "import { GenerateDtsOptions, Rule } from \"@chevrotain/types\";\nimport { buildModel } from \"./model.js\";\nimport { genDts } from \"./generate.js\";\n\nconst defaultOptions: Required<GenerateDtsOptions> = {\n includeVisitorInterface: true,\n visitorInterfaceName: \"ICstNodeVisitor\",\n};\n\nexport function generateCstDts(\n productions: Record<string, Rule>,\n options?: GenerateDtsOptions,\n): string {\n const effectiveOptions = {\n ...defaultOptions,\n ...options,\n };\n\n const model = buildModel(productions);\n\n return genDts(model, effectiveOptions);\n}\n", "import { VERSION } from \"../version.js\";\nimport { ISerializedGast } from \"@chevrotain/types\";\n\nexport function createSyntaxDiagramsCode(\n grammar: ISerializedGast[],\n {\n resourceBase = `https://unpkg.com/chevrotain@${VERSION}/diagrams/`,\n css = `https://unpkg.com/chevrotain@${VERSION}/diagrams/diagrams.css`,\n }: {\n resourceBase?: string;\n css?: string;\n } = {},\n) {\n const header = `\n<!-- This is a generated file -->\n<!DOCTYPE html>\n<meta charset=\"utf-8\">\n<style>\n body {\n background-color: hsl(30, 20%, 95%)\n }\n</style>\n\n`;\n const cssHtml = `\n<link rel='stylesheet' href='${css}'>\n`;\n\n const scripts = `\n<script src='${resourceBase}vendor/railroad-diagrams.js'></script>\n<script src='${resourceBase}src/diagrams_builder.js'></script>\n<script src='${resourceBase}src/diagrams_behavior.js'></script>\n<script src='${resourceBase}src/main.js'></script>\n`;\n const diagramsDiv = `\n<div id=\"diagrams\" align=\"center\"></div> \n`;\n const serializedGrammar = `\n<script>\n window.serializedGrammar = ${JSON.stringify(grammar, null, \" \")};\n</script>\n`;\n\n const initLogic = `\n<script>\n var diagramsDiv = document.getElementById(\"diagrams\");\n main.drawDiagramsFromSerializedGrammar(serializedGrammar, diagramsDiv);\n</script>\n`;\n return (\n header + cssHtml + scripts + diagramsDiv + serializedGrammar + initLogic\n );\n}\n", "/* istanbul ignore file - tricky to import some things from this module during testing */\n\n// semantic version\nexport { VERSION } from \"./version.js\";\n\nexport {\n CstParser,\n EmbeddedActionsParser,\n ParserDefinitionErrorType,\n EMPTY_ALT,\n} from \"./parse/parser/parser.js\";\n\nexport { Lexer, LexerDefinitionErrorType } from \"./scan/lexer_public.js\";\n\n// Tokens utilities\nexport {\n createToken,\n createTokenInstance,\n EOF,\n tokenLabel,\n tokenMatcher,\n tokenName,\n} from \"./scan/tokens_public.js\";\n\n// Lookahead\n\nexport { getLookaheadPaths } from \"./parse/grammar/lookahead.js\";\n\nexport { LLkLookaheadStrategy } from \"./parse/grammar/llk_lookahead.js\";\n\n// Other Utilities\n\nexport { defaultParserErrorProvider } from \"./parse/errors_public.js\";\n\nexport {\n EarlyExitException,\n isRecognitionException,\n MismatchedTokenException,\n NotAllInputParsedException,\n NoViableAltException,\n} from \"./parse/exceptions_public.js\";\n\nexport { defaultLexerErrorProvider } from \"./scan/lexer_errors_public.js\";\n\n// grammar reflection API\nexport {\n Alternation,\n Alternative,\n NonTerminal,\n Option,\n Repetition,\n RepetitionMandatory,\n RepetitionMandatoryWithSeparator,\n RepetitionWithSeparator,\n Rule,\n Terminal,\n} from \"@chevrotain/gast\";\n\n// GAST Utilities\n\nexport {\n serializeGrammar,\n serializeProduction,\n GAstVisitor,\n} from \"@chevrotain/gast\";\n\nexport { generateCstDts } from \"@chevrotain/cst-dts-gen\";\n\n/* istanbul ignore next */\nexport function clearCache() {\n console.warn(\n \"The clearCache function was 'soft' removed from the Chevrotain API.\" +\n \"\\n\\t It performs no action other than printing this message.\" +\n \"\\n\\t Please avoid using it as it will be completely removed in the future\",\n );\n}\n\nexport { createSyntaxDiagramsCode } from \"./diagrams/render_public.js\";\n\nexport class Parser {\n constructor() {\n throw new Error(\n \"The Parser class has been deprecated, use CstParser or EmbeddedActionsParser instead.\\t\\n\" +\n \"See: https://chevrotain.io/docs/changes/BREAKING_CHANGES.html#_7-0-0\",\n );\n }\n}\n", "import type { ITokenConfig, TokenType } from '@traqula/chevrotain';\nimport { createToken as chevcT } from '@traqula/chevrotain';\n\n/**\n * Check whether the first two types overlap, if no, return the 3th argument, else the 4th.\n */\nexport type CheckOverlap<T, U, V, W = never> = T & U extends never ? V : W;\n\n/**\n * Lowercase the first letter of a given string.\n * @param str\n */\nexport function unCapitalize<T extends string>(str: T): Uncapitalize<T> {\n return <Uncapitalize<T>> (str.charAt(0).toLowerCase() + str.slice(1));\n}\n\nexport type NamedToken<Name extends string = string> = TokenType & { name: Name };\n\n/**\n * Create a token in a typesafe way necessary by the traqula core builders.\n */\nexport function createToken<Name extends string>(config: ITokenConfig & { name: Name }): NamedToken<Name> {\n return <TokenType & { name: Name }> chevcT(config);\n}\n\n/**\n * Patch a given type by changing the value-type of a specific key in the given object type.\n */\nexport type Patch<T extends object, Patch extends {[Key in keyof T ]?: unknown }> =\n {[Key in keyof T]: Key extends keyof Patch ? Patch[Key] : T[Key] };\n\n/**\n * Key that allows you to set the space based indentation of your query when generating newlines using the NEW_LINE.\n * A value of -1 disables the generation of newlines from the NEW_LINE function\n */\nexport const traqulaIndentation = <const>\n 'When you use this string, you expect traqula to handle indentation after every newline';\n\n/**\n * Key that allows you to configure the string that should be printed in case newline generation is disabled by\n * {@link traqulaIndentation} NEW_LINE is called on the generator.\n */\nexport const traqulaNewlineAlternative = <const>\n `When you use this string, you expect that the core generator of Traqula does prints a given string instead of a ewline when NEW_LINE printing is disabled through traqulaIndentation`;\n", "import type { ParseNamesFromList } from '../parser-builder/builderTypes.js';\n\n/**\n * Definition of an indirection function, analogous to {@link ParserRule} for parsers\n * and {@link GeneratorRule} for generators.\n *\n * An indirection definition has a `name` and a `fun` function.\n * The `fun` function receives helper utilities (currently just `SUBRULE`) and returns\n * the actual implementation function that receives a context and optional parameters.\n *\n * @typeParam Context - Context object available in the function implementation.\n * @typeParam NameType - Name of the function, should be a string literal type (e.g., `'myFunction'`).\n * @typeParam ReturnType - Type returned by the function.\n * @typeParam ParamType - Tuple of additional parameter types beyond the context.\n */\nexport type IndirDef<\n Context = any,\n NameType extends string = string,\n ReturnType = unknown,\n ParamType extends any[] = any[],\n> = {\n name: NameType;\n fun: (def: IndirDefArg) => (c: Context, ...params: ParamType) => ReturnType;\n};\n\n/**\n * Helper utilities provided to {@link IndirDef.fun} implementations.\n * Currently exposes only `SUBRULE` for calling other indirection definitions.\n */\nexport type IndirDefArg = {\n /**\n * Calls another rule using the provided arguments.\n * @param rule\n * @param arg\n * @constructor\n */\n SUBRULE: <T, U extends any[]>(rule: IndirDef<any, any, T, U>, ...arg: U) => T;\n};\n\n/**\n * Record type mapping rule names to their corresponding {@link IndirDef} definitions.\n */\nexport type IndirectionMap<RuleNames extends string> = {[Key in RuleNames]: IndirDef<any, Key> };\n\n/**\n * Converts a list of ruledefs to a record mapping a name to the corresponding ruledef.\n */\nexport function listToIndirectionMap<T extends readonly IndirDef[]>(rules: T): ParseIndirsToObject<T> {\n const newRules: Record<string, IndirDef> = Object.create(null);\n for (const rule of rules) {\n newRules[rule.name] = rule;\n }\n return <ParseIndirsToObject<T>>newRules;\n}\n\n/**\n * Convert a list of IndirDefs to a Record with the name of the IndirDef as the key, matching the IndirectionMap type.\n */\nexport type ParseIndirsToObject<\n T extends readonly IndirDef[],\n Names extends string = ParseNamesFromList<T>,\n Agg extends Record<string, IndirDef> = Record<never, never>,\n> = T extends readonly [infer First, ...infer Rest] ? (\n First extends IndirDef ? (\n Rest extends readonly IndirDef[] ? (\n ParseIndirsToObject<Rest, Names, {[K in keyof Agg | First['name']]: K extends First['name'] ? First : Agg[K] }>\n ) : never\n ) : never\n) : IndirectionMap<Names> & Agg;\n\n/**\n * The callable object type produced by {@link IndirBuilder.build}.\n * Maps each rule name to a function with the appropriate context and parameter types.\n */\nexport type IndirectObjFromIndirDefs<Context, Names extends string, RuleDefs extends IndirectionMap<Names>> = {\n [K in Names]: RuleDefs[K] extends IndirDef<Context, K, infer RET, infer ARGS> ?\n (context: Context, ...args: ARGS) => RET : never\n};\n", "import type { IndirDef, IndirDefArg, IndirectionMap } from './helpers.js';\n\nexport class DynamicIndirect<Context, Names extends string, RuleDefs extends IndirectionMap<Names>> {\n protected __context: Context | undefined = undefined;\n\n public constructor(protected rules: RuleDefs) {\n for (const rule of Object.values(<Record<string, IndirDef<Context>>>rules)) {\n this[<keyof (typeof this)>rule.name] = <any> ((context: Context, ...args: any): any => {\n this.setContext(context);\n return this.subrule(rule, ...args);\n });\n }\n }\n\n public setContext(context: Context): void {\n this.__context = context;\n }\n\n protected getSafeContext(): Context {\n return <Context> this.__context;\n }\n\n protected readonly subrule: IndirDefArg['SUBRULE'] = (cstDef, ...args) => {\n const def = this.rules[<Names> <unknown> cstDef.name];\n if (!def) {\n throw new Error(`Rule ${cstDef.name} not found`);\n }\n\n return <any> def.fun({\n SUBRULE: this.subrule,\n })(this.getSafeContext(), ...args);\n };\n}\n", "import type { ParseNamesFromList } from '../parser-builder/builderTypes.js';\nimport type { CheckOverlap } from '../utils.js';\nimport { DynamicIndirect } from './dynamicIndirected.js';\nimport type { IndirDef, IndirectionMap, IndirectObjFromIndirDefs, ParseIndirsToObject } from './helpers.js';\nimport { listToIndirectionMap } from './helpers.js';\n\n/**\n * Builder for composing modular transformation pipelines using indirection definitions.\n * Functions registered through this builder call each other via SUBRULE, enabling the same\n * modularity and extensibility as the parser and generator builders.\n *\n * Builders mutate internal state and return `this`.\n * Always start by copying an existing builder with `IndirBuilder.create(existingBuilder)`.\n */\nexport class IndirBuilder<Context, Names extends string, RuleDefs extends IndirectionMap<Names>> {\n /**\n * Create an IndirBuilder from initial indirection definitions or an existing builder.\n * If a builder is provided, a new copy will be created.\n */\n public static create<Context, Names extends string, RuleDefs extends IndirectionMap<Names>>(\n args: IndirBuilder<Context, Names, RuleDefs>\n ): IndirBuilder<Context, Names, RuleDefs>;\n public static create<\n Rules extends readonly IndirDef[] = readonly IndirDef[],\n Context = Rules[0] extends IndirDef<infer context> ? context : never,\n Names extends string = ParseNamesFromList<Rules>,\n RuleDefs extends IndirectionMap<Names> = ParseIndirsToObject<Rules>,\n >(rules: Rules): IndirBuilder<Context, Names, RuleDefs>;\n public static create<\n Rules extends readonly IndirDef[] = readonly IndirDef[],\n Context = Rules[0] extends IndirDef<infer context> ? context : never,\n Names extends string = ParseNamesFromList<Rules>,\n RuleDefs extends IndirectionMap<Names> = ParseIndirsToObject<Rules>,\n >(\n start: Rules | IndirBuilder<Context, Names, RuleDefs>,\n ): IndirBuilder<Context, Names, RuleDefs> {\n if (Array.isArray(start)) {\n return <IndirBuilder<Context, Names, RuleDefs>> <unknown> new IndirBuilder(listToIndirectionMap(start));\n }\n return new IndirBuilder({ ...(<IndirBuilder<any, any, any>>start).rules });\n }\n\n private rules: RuleDefs;\n\n private constructor(startRules: RuleDefs) {\n this.rules = startRules;\n }\n\n /**\n * Narrow the builder's context type parameter to a more specific subtype.\n * This is a zero-cost type-level operation — the builder instance is returned as-is\n * but with updated type parameters.\n */\n public widenContext<NewContext extends Context>(): IndirBuilder<\n NewContext,\n Names,\n {[Key in keyof RuleDefs]: Key extends Names ?\n (RuleDefs[Key] extends IndirDef<any, any, infer RT, infer PT> ? IndirDef<NewContext, Key, RT, PT> : never)\n : never }\n > {\n return <any> this;\n }\n\n /**\n * Update the type signatures (return types and/or parameter types) of existing indirections\n * without changing their implementations. Use this when a patched indirection changes the types\n * flowing through downstream indirections that don't need new implementations.\n * This is a zero-cost type-level operation.\n */\n public typePatch<Patch extends {[Key in Names]?: [any] | [any, any[]]}>():\n IndirBuilder<Context, Names, {[Key in Names]: Key extends keyof Patch ? (\n Patch[Key] extends [any, any[]] ? IndirDef<Context, Key, Patch[Key][0], Patch[Key][1]> : (\n // Only one - infer arg yourself\n Patch[Key] extends [ any ] ? (\n RuleDefs[Key] extends IndirDef<any, any, any, infer Par> ? IndirDef<Context, Key, Patch[Key][0], Par> : never\n ) : never\n )\n ) : (RuleDefs[Key] extends IndirDef<Context, Key> ? RuleDefs[Key] : never) }> {\n return <any> this;\n }\n\n /**\n * Change the implementation of an existing indirection.\n */\n public patchRule<U extends Names, RET, ARGS extends any[]>(patch: IndirDef<Context, U, RET, ARGS>):\n IndirBuilder<Context, Names, {[Key in Names]: Key extends U ?\n IndirDef<Context, Key, RET, ARGS> :\n (RuleDefs[Key] extends IndirDef<Context, Key> ? RuleDefs[Key] : never)\n } > {\n const self = <IndirBuilder<Context, Names, {[Key in Names]: Key extends U ?\n IndirDef<Context, Key, RET, ARGS> : (RuleDefs[Key] extends IndirDef<Context, Key> ? RuleDefs[Key] : never) }>>\n <unknown> this;\n self.rules[patch.name] = <any> patch;\n return self;\n }\n\n /**\n * Add an indirection function. If the rule already exists, but the implementation differs, an error will be thrown.\n */\n public addRuleRedundant<U extends string, RET, ARGS extends any[]>(rule: IndirDef<Context, U, RET, ARGS>):\n IndirBuilder<Context, Names | U, {[K in Names | U]: K extends U ?\n IndirDef<Context, K, RET, ARGS> :\n (K extends Names ? (RuleDefs[K] extends IndirDef<Context, K> ? RuleDefs[K] : never) : never)\n }> {\n const self = <IndirBuilder<Context, Names | U, {[K in Names | U]: K extends U ?\n IndirDef<Context, K, RET, ARGS> :\n (K extends Names ? (RuleDefs[K] extends IndirDef<Context, K> ? RuleDefs[K] : never) : never) }>>\n <unknown> this;\n const rules = <Record<string, IndirDef<Context>>> self.rules;\n if (rules[rule.name] !== undefined && rules[rule.name] !== rule) {\n throw new Error(`Function ${rule.name} already exists in the builder`);\n }\n rules[rule.name] = rule;\n return self;\n }\n\n /**\n * Add a rule to the grammar. Will raise a typescript error if the rule already exists in the grammar.\n */\n public addRule<U extends string, RET, ARGS extends any[]>(\n rule: CheckOverlap<U, Names, IndirDef<Context, U, RET, ARGS>>,\n ): IndirBuilder<Context, Names | U, {[K in Names | U]: K extends U ?\n IndirDef<Context, K, RET, ARGS> :\n (K extends Names ? (RuleDefs[K] extends IndirDef<Context, K> ? RuleDefs[K] : never) : never) }> {\n return this.addRuleRedundant(rule);\n }\n\n /**\n * Add multiple indirection definitions at once using rest parameters.\n * Provides better TypeScript type inference than calling {@link addRule} in a loop,\n * but avoid passing too many at once as this can cause TypeScript compilation slowdowns.\n * TypeScript errors if any name conflicts with an existing one.\n */\n public addMany<U extends readonly IndirDef<Context>[]>(\n ...rules: CheckOverlap<ParseNamesFromList<U>, Names, U>\n ): IndirBuilder<\n Context,\n Names | ParseNamesFromList<U>,\n {[K in Names | ParseNamesFromList<U>]:\n K extends keyof ParseIndirsToObject<typeof rules> ? (\n ParseIndirsToObject<typeof rules>[K] extends IndirDef<Context, K> ? ParseIndirsToObject<typeof rules>[K] : never\n ) : (\n K extends Names ? (RuleDefs[K] extends IndirDef<Context, K> ? RuleDefs[K] : never) : never\n )\n }\n > {\n this.rules = { ...this.rules, ...listToIndirectionMap(rules) };\n return <any> <unknown> this;\n }\n\n /**\n * Delete a grammar rule by its name.\n */\n public deleteRule<U extends Names>(ruleName: U):\n IndirBuilder<Context, Exclude<Names, U>, {[K in Exclude<Names, U>]:\n RuleDefs[K] extends IndirDef<Context, K> ? RuleDefs[K] : never }> {\n delete this.rules[ruleName];\n return <IndirBuilder<Context, Exclude<Names, U>, {[K in Exclude<Names, U>]:\n RuleDefs[K] extends IndirDef<Context, K> ? RuleDefs[K] : never }>>\n <unknown> this;\n }\n\n /**\n * Delete multiple indirection definitions by name in a single call.\n * @param ruleNames - Names of the indirections to delete.\n */\n public deleteMany<U extends Names>(...ruleNames: U[]):\n IndirBuilder<Context, Exclude<Names, U>, {[K in Exclude<Names, U>]:\n RuleDefs[K] extends IndirDef<Context, K> ? RuleDefs[K] : never }> {\n for (const name of ruleNames) {\n delete this.rules[name];\n }\n return <IndirBuilder<Context, Exclude<Names, U>, {[K in Exclude<Names, U>]:\n RuleDefs[K] extends IndirDef<Context, K> ? RuleDefs[K] : never }>>\n <unknown> this;\n }\n\n /**\n * Retrieve an indirection definition by its name.\n * Useful for inspecting or wrapping existing definitions when extending a pipeline.\n * @param ruleName - The name of the indirection, type-checked against the builder's known names.\n */\n public getRule<U extends Names>(ruleName: U): RuleDefs[U] extends IndirDef<any, U, infer RT, infer PT> ?\n IndirDef<Context, U, RT, PT> : never {\n return <any> this.rules[ruleName];\n }\n\n /**\n * Merge this indirection builder with another.\n * If the two builders both have a definition with the same name,\n * no error will be thrown in case they map to the same object (by reference).\n * If they map to a different object, an error will be thrown.\n * To fix this problem, the overridingRules array should contain a definition with the same conflicting name,\n * whose implementation will be used.\n */\n public merge<\n OtherNames extends string,\n OtherRules extends IndirectionMap<OtherNames>,\n OW extends readonly IndirDef<Context>[],\n >(\n builder: IndirBuilder<Context, OtherNames, OtherRules>,\n overridingRules: OW,\n ):\n IndirBuilder<\n Context,\n Names | OtherNames | ParseNamesFromList<OW>,\n {[K in Names | OtherNames | ParseNamesFromList<OW>]:\n K extends keyof ParseIndirsToObject<OW> ? (\n ParseIndirsToObject<OW>[K] extends IndirDef<Context, K> ? ParseIndirsToObject<OW>[K] : never\n )\n : (\n K extends Names ? (RuleDefs[K] extends IndirDef<Context, K> ? RuleDefs[K] : never)\n : K extends OtherNames ? (OtherRules[K] extends IndirDef<Context, K> ? OtherRules[K] : never) : never\n ) }\n > {\n // Assume the other set is bigger than yours. So start from that one and add this one\n const otherRules: Record<string, IndirDef<Context>> = Object.assign(Object.create(null), builder.rules);\n const myRules: Record<string, IndirDef<Context>> = this.rules;\n\n for (const rule of Object.values(myRules)) {\n if (otherRules[rule.name] === undefined) {\n otherRules[rule.name] = rule;\n } else {\n const existingRule = otherRules[rule.name];\n // If same rule, no issue, move on. Else\n if (existingRule !== rule) {\n const override = overridingRules.find(x => x.name === rule.name);\n // If override specified, take override, else, inform user that there is a conflict\n if (override) {\n otherRules[rule.name] = override;\n } else {\n throw new Error(`Function with name \"${rule.name}\" already exists in the builder, specify an override to resolve conflict`);\n }\n }\n }\n }\n\n this.rules = <any> <unknown> otherRules;\n return <any> <unknown> this;\n }\n\n /**\n * Construct an indirection object from the registered definitions.\n * @returns An object with a method for each registered indirection name.\n */\n public build(): IndirectObjFromIndirDefs<Context, Names, RuleDefs> {\n return <IndirectObjFromIndirDefs<Context, Names, RuleDefs>> new DynamicIndirect(this.rules);\n }\n}\n", "import type { ILexerConfig, TokenType } from '@traqula/chevrotain';\nimport { Lexer } from '@traqula/chevrotain';\nimport type { CheckOverlap, NamedToken } from '../utils.js';\n\n/**\n * Builder for constructing Chevrotain lexers with type-safe token management.\n * Token ordering matters — the lexer matches the first token that fits, so more specific\n * tokens (e.g., keywords) must be positioned before more general ones (e.g., identifiers).\n *\n * Builders mutate internal state and return `this`.\n * Always start by copying an existing builder with `LexerBuilder.create(existingBuilder)`.\n */\nexport class LexerBuilder<NAMES extends string = string> {\n private readonly tokens: TokenType[];\n\n /**\n * Create a new LexerBuilder, optionally copying from an existing one.\n * @param starter - An existing builder to copy tokens from. If omitted, starts empty.\n */\n public static create<U extends LexerBuilder<T>, T extends string = never>(starter?: U): U {\n return <U> new LexerBuilder(starter);\n }\n\n private constructor(starter?: LexerBuilder<NAMES>) {\n this.tokens = starter?.tokens ? [ ...starter.tokens ] : [];\n }\n\n /**\n * Merge tokens from another LexerBuilder into this one.\n * Duplicate tokens (by reference) are skipped. Different tokens with the same name\n * cause an error unless an override is provided.\n * @param merge - The other builder whose tokens to merge.\n * @param overwrite - Tokens that take precedence when names conflict.\n */\n public merge<OtherNames extends string, OW extends string>(\n merge: LexerBuilder<OtherNames>,\n overwrite: NamedToken<OW>[] = [],\n ):\n LexerBuilder<NAMES | OtherNames> {\n const extraTokens = merge.tokens.filter((token) => {\n const overwriteToken = overwrite.find(t => t.name === token.name);\n if (overwriteToken) {\n return false;\n }\n const match = this.tokens.find(t => t.name === token.name);\n if (match) {\n if (match !== token) {\n throw new Error(`Token with name ${token.name} already exists. Implementation is different and no overwrite was provided.`);\n }\n return false;\n }\n return true;\n });\n this.tokens.push(...extraTokens);\n return this;\n }\n\n /**\n * Append tokens to the end of the builder's token list.\n * TypeScript errors if a token name already exists.\n * @param token - One or more tokens to add.\n */\n public add<Name extends string>(...token: CheckOverlap<Name, NAMES, NamedToken<Name>[]>):\n LexerBuilder<Name | NAMES> {\n this.tokens.push(...token);\n return this;\n }\n\n /**\n * Insert tokens before a specified reference token in the ordering.\n * @param before - The existing token to insert before.\n * @param token - One or more tokens to insert.\n */\n public addBefore<Name extends string>(\n before: NamedToken<NAMES>,\n ...token: CheckOverlap<Name, NAMES, NamedToken<Name>[]>\n ): LexerBuilder<NAMES | Name> {\n const index = this.tokens.indexOf(before);\n if (index === -1) {\n throw new Error('Token not found');\n }\n this.tokens.splice(index, 0, ...token);\n return this;\n }\n\n private moveBeforeOrAfter<Name extends string>(\n beforeOrAfter: 'before' | 'after',\n before: NamedToken<NAMES>,\n ...tokens: CheckOverlap<Name, NAMES, never, NamedToken<Name>[]>\n ): LexerBuilder<NAMES> {\n const beforeIndex = this.tokens.indexOf(before) + (beforeOrAfter === 'before' ? 0 : 1);\n if (beforeIndex === -1) {\n throw new Error('BeforeToken not found');\n }\n for (const token of tokens) {\n const tokenIndex = this.tokens.indexOf(token);\n if (tokenIndex === -1) {\n throw new Error('Token not found');\n }\n this.tokens.splice(tokenIndex, 1);\n this.tokens.splice(beforeIndex, 0, token);\n }\n return this;\n }\n\n /**\n * Move existing tokens so they appear before a specified reference token.\n * The tokens must already exist in the builder.\n * @param before - The reference token to move before.\n * @param tokens - The tokens to reposition.\n */\n public moveBefore<Name extends string>(\n before: NamedToken<NAMES>,\n ...tokens: CheckOverlap<Name, NAMES, never, NamedToken<Name>[]>\n ): LexerBuilder<NAMES> {\n return this.moveBeforeOrAfter('before', before, ...tokens);\n }\n\n /**\n * Move existing tokens so they appear after a specified reference token.\n * The tokens must already exist in the builder.\n * @param after - The reference token to move after.\n * @param tokens - The tokens to reposition.\n */\n public moveAfter<Name extends string>(\n after: NamedToken<NAMES>,\n ...tokens: CheckOverlap<Name, NAMES, never, NamedToken<Name>[]>\n ): LexerBuilder<NAMES> {\n return this.moveBeforeOrAfter('after', after, ...tokens);\n }\n\n /**\n * Insert tokens after a specified reference token in the ordering.\n * @param after - The existing token to insert after.\n * @param token - One or more tokens to insert.\n */\n public addAfter<Name extends string>(\n after: NamedToken<NAMES>,\n ...token: CheckOverlap<Name, NAMES, NamedToken<Name>[]>\n ): LexerBuilder<NAMES | Name> {\n const index = this.tokens.indexOf(after);\n if (index === -1) {\n throw new Error('Token not found');\n }\n this.tokens.splice(index + 1, 0, ...token);\n return this;\n }\n\n /**\n * Remove tokens from the builder by reference.\n * @param token - One or more tokens to remove. Throws if a token is not found.\n * @deprecated use deleteName instead. (This function will be removed in next major)\n * It does not work under replaced tokens.\n */\n public delete<Name extends NAMES>(...token: NamedToken<Name>[]): LexerBuilder<Exclude<NAMES, Name>> {\n // TODO: remove in next major\n for (const t of token) {\n const index = this.tokens.indexOf(t);\n if (index === -1) {\n throw new Error('Token not found');\n }\n this.tokens.splice(index, 1);\n }\n return this;\n }\n\n /**\n * Delete a token based on its name.\n */\n public deleteToken<U extends NAMES>(...names: U[]): LexerBuilder<Exclude<NAMES, U>> {\n for (const name of names) {\n const index = this.tokens.findIndex(x => x.name === name);\n if (index === -1) {\n throw new Error(`Token with name \"${name}\" not found`);\n }\n this.tokens.splice(index, 1);\n }\n return this;\n }\n\n /**\n * Replace token with the same name with a new one.\n * @param token\n */\n public replace<Name extends NAMES>(token: NamedToken<Name>): LexerBuilder<NAMES> {\n const index = this.tokens.findIndex(x => x.name === token.name);\n if (index === -1) {\n throw new Error(`Token with name \"${token.name}\" not found`);\n }\n this.tokens[index] = token;\n return this;\n }\n\n /**\n * Construct a Chevrotain {@link Lexer} from the current token ordering.\n * @param lexerConfig - Optional Chevrotain lexer configuration overrides.\n */\n public build(lexerConfig?: ILexerConfig): Lexer {\n return new Lexer(this.tokens, {\n positionTracking: 'onlyStart',\n recoveryEnabled: false,\n ensureOptimizations: true,\n // SafeMode: true,\n // SkipValidations: true,\n ...lexerConfig,\n });\n }\n\n /**\n * Get the current token list (readonly).\n * Useful for passing to {@link ParserBuilder.build} as the `tokenVocabulary` argument.\n */\n public get tokenVocabulary(): readonly TokenType[] {\n return this.tokens;\n }\n}\n", "import { EmbeddedActionsParser } from '@traqula/chevrotain';\nimport type { IParserConfig, TokenVocabulary } from '@traqula/chevrotain';\nimport type { ParseRuleMap } from './builderTypes.js';\nimport type { CstDef, ImplArgs, ParserRule } from './ruleDefTypes.js';\n\nexport class DynamicParser<Context, Names extends string, RuleDefs extends ParseRuleMap<Names>>\n extends EmbeddedActionsParser {\n private context: Context | undefined;\n\n public setContext(context: Context): void {\n this.context = context;\n }\n\n public constructor(rules: RuleDefs, tokenVocabulary: TokenVocabulary, config: IParserConfig = {}) {\n super(tokenVocabulary, {\n // RecoveryEnabled: true,\n maxLookahead: 1,\n skipValidations: true,\n dynamicTokensEnabled: false,\n ...config,\n });\n this.context = undefined;\n const selfRef = this.constructSelfRef();\n const implArgs: ImplArgs = {\n ...selfRef,\n cache: new WeakMap(),\n };\n\n for (const rule of Object.values(<Record<string, ParserRule<Context>>>rules)) {\n // Function implementation itself - this function is called AFTER lexing\n this[<keyof (typeof this)>rule.name] = <any> this.RULE(rule.name, rule.impl(implArgs));\n }\n this.performSelfAnalysis();\n }\n\n private constructSelfRef(): CstDef {\n const subRuleImpl = (chevrotainSubrule: typeof this.SUBRULE): CstDef['SUBRULE'] =>\n ((cstDef, ...arg) =>\n chevrotainSubrule(<any> this[<keyof (typeof this)>cstDef.name], <any>{ ARGS: [ this.context, ...arg ]})\n ) satisfies CstDef['SUBRULE'];\n return {\n CONSUME: (tokenType, option) => this.CONSUME(tokenType, option),\n CONSUME1: (tokenType, option) => this.CONSUME1(tokenType, option),\n CONSUME2: (tokenType, option) => this.CONSUME2(tokenType, option),\n CONSUME3: (tokenType, option) => this.CONSUME3(tokenType, option),\n CONSUME4: (tokenType, option) => this.CONSUME4(tokenType, option),\n CONSUME5: (tokenType, option) => this.CONSUME5(tokenType, option),\n CONSUME6: (tokenType, option) => this.CONSUME6(tokenType, option),\n CONSUME7: (tokenType, option) => this.CONSUME7(tokenType, option),\n CONSUME8: (tokenType, option) => this.CONSUME8(tokenType, option),\n CONSUME9: (tokenType, option) => this.CONSUME9(tokenType, option),\n OPTION: actionORMethodDef => this.OPTION(actionORMethodDef),\n OPTION1: actionORMethodDef => this.OPTION1(actionORMethodDef),\n OPTION2: actionORMethodDef => this.OPTION2(actionORMethodDef),\n OPTION3: actionORMethodDef => this.OPTION3(actionORMethodDef),\n OPTION4: actionORMethodDef => this.OPTION4(actionORMethodDef),\n OPTION5: actionORMethodDef => this.OPTION5(actionORMethodDef),\n OPTION6: actionORMethodDef => this.OPTION6(actionORMethodDef),\n OPTION7: actionORMethodDef => this.OPTION7(actionORMethodDef),\n OPTION8: actionORMethodDef => this.OPTION8(actionORMethodDef),\n OPTION9: actionORMethodDef => this.OPTION9(actionORMethodDef),\n OR: altsOrOpts => this.OR(altsOrOpts),\n OR1: altsOrOpts => this.OR1(altsOrOpts),\n OR2: altsOrOpts => this.OR2(altsOrOpts),\n OR3: altsOrOpts => this.OR3(altsOrOpts),\n OR4: altsOrOpts => this.OR4(altsOrOpts),\n OR5: altsOrOpts => this.OR5(altsOrOpts),\n OR6: altsOrOpts => this.OR6(altsOrOpts),\n OR7: altsOrOpts => this.OR7(altsOrOpts),\n OR8: altsOrOpts => this.OR8(altsOrOpts),\n OR9: altsOrOpts => this.OR9(altsOrOpts),\n MANY: actionORMethodDef => this.MANY(actionORMethodDef),\n MANY1: actionORMethodDef => this.MANY1(actionORMethodDef),\n MANY2: actionORMethodDef => this.MANY2(actionORMethodDef),\n MANY3: actionORMethodDef => this.MANY3(actionORMethodDef),\n MANY4: actionORMethodDef => this.MANY4(actionORMethodDef),\n MANY5: actionORMethodDef => this.MANY5(actionORMethodDef),\n MANY6: actionORMethodDef => this.MANY6(actionORMethodDef),\n MANY7: actionORMethodDef => this.MANY7(actionORMethodDef),\n MANY8: actionORMethodDef => this.MANY8(actionORMethodDef),\n MANY9: actionORMethodDef => this.MANY9(actionORMethodDef),\n MANY_SEP: options => this.MANY_SEP(options),\n MANY_SEP1: options => this.MANY_SEP1(options),\n MANY_SEP2: options => this.MANY_SEP2(options),\n MANY_SEP3: options => this.MANY_SEP3(options),\n MANY_SEP4: options => this.MANY_SEP4(options),\n MANY_SEP5: options => this.MANY_SEP5(options),\n MANY_SEP6: options => this.MANY_SEP6(options),\n MANY_SEP7: options => this.MANY_SEP7(options),\n MANY_SEP8: options => this.MANY_SEP8(options),\n MANY_SEP9: options => this.MANY_SEP9(options),\n AT_LEAST_ONE: actionORMethodDef => this.AT_LEAST_ONE(actionORMethodDef),\n AT_LEAST_ONE1: actionORMethodDef => this.AT_LEAST_ONE1(actionORMethodDef),\n AT_LEAST_ONE2: actionORMethodDef => this.AT_LEAST_ONE2(actionORMethodDef),\n AT_LEAST_ONE3: actionORMethodDef => this.AT_LEAST_ONE3(actionORMethodDef),\n AT_LEAST_ONE4: actionORMethodDef => this.AT_LEAST_ONE4(actionORMethodDef),\n AT_LEAST_ONE5: actionORMethodDef => this.AT_LEAST_ONE5(actionORMethodDef),\n AT_LEAST_ONE6: actionORMethodDef => this.AT_LEAST_ONE6(actionORMethodDef),\n AT_LEAST_ONE7: actionORMethodDef => this.AT_LEAST_ONE7(actionORMethodDef),\n AT_LEAST_ONE8: actionORMethodDef => this.AT_LEAST_ONE8(actionORMethodDef),\n AT_LEAST_ONE9: actionORMethodDef => this.AT_LEAST_ONE9(actionORMethodDef),\n AT_LEAST_ONE_SEP: options => this.AT_LEAST_ONE_SEP(options),\n AT_LEAST_ONE_SEP1: options => this.AT_LEAST_ONE_SEP1(options),\n AT_LEAST_ONE_SEP2: options => this.AT_LEAST_ONE_SEP2(options),\n AT_LEAST_ONE_SEP3: options => this.AT_LEAST_ONE_SEP3(options),\n AT_LEAST_ONE_SEP4: options => this.AT_LEAST_ONE_SEP4(options),\n AT_LEAST_ONE_SEP5: options => this.AT_LEAST_ONE_SEP5(options),\n AT_LEAST_ONE_SEP6: options => this.AT_LEAST_ONE_SEP6(options),\n AT_LEAST_ONE_SEP7: options => this.AT_LEAST_ONE_SEP7(options),\n AT_LEAST_ONE_SEP8: options => this.AT_LEAST_ONE_SEP8(options),\n AT_LEAST_ONE_SEP9: options => this.AT_LEAST_ONE_SEP9(options),\n ACTION: func => this.ACTION(func),\n BACKTRACK: (cstDef, ...args) =>\n this.BACKTRACK(<any> this[<keyof (typeof this)>cstDef.name], <any>{ ARGS: args }),\n SUBRULE: subRuleImpl((rule, args) => this.SUBRULE(rule, args)),\n SUBRULE1: subRuleImpl((rule, args) => this.SUBRULE1(rule, args)),\n SUBRULE2: subRuleImpl((rule, args) => this.SUBRULE2(rule, args)),\n SUBRULE3: subRuleImpl((rule, args) => this.SUBRULE3(rule, args)),\n SUBRULE4: subRuleImpl((rule, args) => this.SUBRULE4(rule, args)),\n SUBRULE5: subRuleImpl((rule, args) => this.SUBRULE5(rule, args)),\n SUBRULE6: subRuleImpl((rule, args) => this.SUBRULE6(rule, args)),\n SUBRULE7: subRuleImpl((rule, args) => this.SUBRULE7(rule, args)),\n SUBRULE8: subRuleImpl((rule, args) => this.SUBRULE8(rule, args)),\n SUBRULE9: subRuleImpl((rule, args) => this.SUBRULE9(rule, args)),\n };\n }\n}\n", "import type {\n ILexerConfig,\n IParserConfig,\n IRecognitionException,\n TokenType,\n TokenVocabulary,\n EmbeddedActionsParser,\n} from '@traqula/chevrotain';\nimport { LexerBuilder } from '../lexer-builder/LexerBuilder.js';\nimport type { CheckOverlap } from '../utils.js';\nimport type {\n ParseMethodsFromRules,\n ParserFromRules,\n ParseRuleMap,\n ParseRulesToObject,\n ParseNamesFromList,\n} from './builderTypes.js';\nimport { DynamicParser } from './dynamicParser.js';\nimport type { ParserRule } from './ruleDefTypes.js';\n\n/**\n * Converts a list of ruledefs to a record mapping a name to the corresponding ruledef.\n */\nfunction listToRuleDefMap<T extends readonly ParserRule[]>(rules: T): ParseRulesToObject<T> {\n const newRules: Record<string, ParserRule> = Object.create(null);\n for (const rule of rules) {\n newRules[rule.name] = rule;\n }\n return <ParseRulesToObject<T>>newRules;\n}\n\n/**\n * Configuration for {@link ParserBuilder.build}. Specifies the token vocabulary,\n * optional Chevrotain parser/lexer configuration, and optional hooks for\n * preprocessing input or handling parse errors.\n */\nexport interface ParserBuildArgs {\n /** The complete token vocabulary the parser and lexer should recognize. */\n tokenVocabulary: readonly TokenType[];\n /** Optional Chevrotain parser configuration (e.g., `maxLookahead`). */\n parserConfig?: IParserConfig;\n /** Optional Chevrotain lexer configuration (e.g., `positionTracking`). */\n lexerConfig?: ILexerConfig;\n /** Optional function to preprocess the input string before lexing. */\n queryPreProcessor?: (input: string) => string;\n /** Optional custom error handler. If omitted, a default handler throws on the first error. */\n errorHandler?: (errors: IRecognitionException[]) => void;\n}\n\n/**\n * The grammar builder. This is the core of traqula (besides using the amazing chevrotain framework).\n * Using the builder you can create a grammar + AST creator.\n * At any point in time, a parser can be constructed from the added rules.\n * Constructing a parser will cause a validation which will validate the correctness of the grammar.\n */\n// This code is wild so other code can be simple.\nexport class ParserBuilder<Context, Names extends string, RuleDefs extends ParseRuleMap<Names>> {\n /**\n * Create a builder from some initial grammar rules or an existing builder.\n * If a builder is provided, a new copy will be created.\n */\n public static create<\n Rules extends readonly ParserRule[] = readonly ParserRule[],\n Context = Rules[0] extends ParserRule<infer context> ? context : never,\n Names extends string = ParseNamesFromList<Rules>,\n RuleDefs extends ParseRuleMap<Names> = ParseRulesToObject<Rules>,\n >(\n start: Rules | ParserBuilder<Context, Names, RuleDefs>,\n ): ParserBuilder<Context, Names, RuleDefs> {\n if (Array.isArray(start)) {\n return <ParserBuilder<Context, Names, RuleDefs>> <unknown> new ParserBuilder(listToRuleDefMap(start));\n }\n return new ParserBuilder({ ...(<ParserBuilder<any, any, any>>start).rules });\n }\n\n private rules: RuleDefs;\n\n private constructor(startRules: RuleDefs) {\n this.rules = startRules;\n }\n\n /**\n * Narrow the builder's context type parameter to a more specific subtype.\n * This is a zero-cost type-level operation — the builder instance is returned as-is\n * but with updated type parameters.\n */\n public widenContext<NewContext extends Context>(): ParserBuilder<\n NewContext,\nNames,\n{[Key in keyof RuleDefs]: Key extends Names ?\n (RuleDefs[Key] extends ParserRule<any, any, infer RT, infer PT> ? ParserRule<NewContext, Key, RT, PT> : never)\n : never }\n> {\n return <any> this;\n }\n\n /**\n * Update the type signatures (return types and/or parameter types) of existing rules\n * without changing their implementations. Use this when a patched rule changes the types\n * flowing through downstream rules that don't need new implementations.\n * This is a zero-cost type-level operation.\n */\n public typePatch<Patch extends {[Key in Names]?: [any] | [any, any[]]}>():\n ParserBuilder<Context, Names, {[Key in Names]: Key extends keyof Patch ? (\n Patch[Key] extends [any, any[]] ? ParserRule<Context, Key, Patch[Key][0], Patch[Key][1]> : (\n // Only one - infer yourself\n Patch[Key] extends [any] ? (\n RuleDefs[Key] extends ParserRule<any, any, any, infer Par> ?\n ParserRule<Context, Key, Patch[Key][0], Par> : never\n ) : never\n )\n ) : (RuleDefs[Key] extends ParserRule<Context, Key> ? RuleDefs[Key] : never) }> {\n return <any> this;\n }\n\n /**\n * Change the implementation of an existing grammar rule.\n */\n public patchRule<U extends Names, RET, ARGS extends any[]>(patch: ParserRule<Context, U, RET, ARGS>):\n ParserBuilder<Context, Names, {[Key in Names]: Key extends U ?\n ParserRule<Context, Key, RET, ARGS> :\n (RuleDefs[Key] extends ParserRule<Context, Key> ? RuleDefs[Key] : never)\n } > {\n const self = <ParserBuilder<Context, Names, {[Key in Names]: Key extends U ?\n ParserRule<Context, Key, RET, ARGS> : (RuleDefs[Key] extends ParserRule<Context, Key> ? RuleDefs[Key] : never) }>>\n <unknown> this;\n self.rules[patch.name] = <any> patch;\n return self;\n }\n\n /**\n * Add a rule to the grammar. If the rule already exists, but the implementation differs, an error will be thrown.\n */\n public addRuleRedundant<U extends string, RET, ARGS extends any[]>(rule: ParserRule<Context, U, RET, ARGS>):\n ParserBuilder<Context, Names | U, {[K in Names | U]: K extends U ?\n ParserRule<Context, K, RET, ARGS> :\n (K extends Names ? (RuleDefs[K] extends ParserRule<Context, K> ? RuleDefs[K] : never) : never)\n }> {\n const self = <ParserBuilder<Context, Names | U, {[K in Names | U]: K extends U ?\n ParserRule<Context, K, RET, ARGS> :\n (K extends Names ? (RuleDefs[K] extends ParserRule<Context, K> ? RuleDefs[K] : never) : never) }>>\n <unknown> this;\n const rules = <Record<string, ParserRule<Context>>> self.rules;\n if (rules[rule.name] !== undefined && rules[rule.name] !== rule) {\n throw new Error(`Rule ${rule.name} already exists in the builder`);\n }\n rules[rule.name] = rule;\n return self;\n }\n\n /**\n * Add a rule to the grammar. Will raise a typescript error if the rule already exists in the grammar.\n */\n public addRule<U extends string, RET, ARGS extends any[]>(\n rule: CheckOverlap<U, Names, ParserRule<Context, U, RET, ARGS>>,\n ): ParserBuilder<Context, Names | U, {[K in Names | U]: K extends U ?\n ParserRule<Context, K, RET, ARGS> :\n (K extends Names ? (RuleDefs[K] extends ParserRule<Context, K> ? RuleDefs[K] : never) : never) }> {\n return this.addRuleRedundant(rule);\n }\n\n /**\n * Add multiple rules at once using rest parameters.\n * Provides better TypeScript type inference than calling {@link addRule} in a loop,\n * but avoid passing too many rules at once as this can cause TypeScript compilation slowdowns.\n * TypeScript errors if any rule name conflicts with an existing one.\n */\n public addMany<U extends readonly ParserRule<Context>[]>(\n ...rules: CheckOverlap<ParseNamesFromList<U>, Names, U>\n ): ParserBuilder<\n Context,\n Names | ParseNamesFromList<U>,\n {[K in Names | ParseNamesFromList<U>]:\n K extends keyof ParseRulesToObject<typeof rules> ? (\n ParseRulesToObject<typeof rules>[K] extends ParserRule<Context, K> ? ParseRulesToObject<typeof rules>[K] : never\n ) : (\n K extends Names ? (RuleDefs[K] extends ParserRule<Context, K> ? RuleDefs[K] : never) : never\n )\n }\n > {\n this.rules = { ...this.rules, ...listToRuleDefMap(rules) };\n return <any> <unknown> this;\n }\n\n /**\n * Delete a grammar rule by its name.\n */\n public deleteRule<U extends Names>(ruleName: U):\n ParserBuilder<Context, Exclude<Names, U>, {[K in Exclude<Names, U>]:\n RuleDefs[K] extends ParserRule<Context, K> ? RuleDefs[K] : never }> {\n delete this.rules[ruleName];\n return <ParserBuilder<Context, Exclude<Names, U>, {[K in Exclude<Names, U>]:\n RuleDefs[K] extends ParserRule<Context, K> ? RuleDefs[K] : never }>>\n <unknown> this;\n }\n\n /**\n * Delete multiple rules by name in a single call.\n * @param ruleNames - Names of the rules to delete.\n */\n public deleteMany<U extends Names>(...ruleNames: U[]):\n ParserBuilder<Context, Exclude<Names, U>, {[K in Exclude<Names, U>]:\n RuleDefs[K] extends ParserRule<Context, K> ? RuleDefs[K] : never }> {\n for (const ruleName of ruleNames) {\n delete this.rules[ruleName];\n }\n return <ParserBuilder<Context, Exclude<Names, U>, {[K in Exclude<Names, U>]:\n RuleDefs[K] extends ParserRule<Context, K> ? RuleDefs[K] : never }>>\n <unknown> this;\n }\n\n /**\n * Retrieve a grammar rule definition by its name.\n * Useful for inspecting or wrapping existing rules when extending a parser.\n * @param ruleName - The name of the rule, type-checked against the builder's known rule names.\n */\n public getRule<U extends Names>(ruleName: U): RuleDefs[U] extends ParserRule<any, U, infer RT, infer PT> ?\n ParserRule<Context, U, RT, PT> : never {\n return <any> this.rules[ruleName];\n }\n\n /**\n * Merge this grammar builder with another.\n * It is best to merge the bigger grammar with the smaller one.\n * If the two builders both have a grammar rule with the same name,\n * no error will be thrown case they map to the same ruledef object.\n * If they map to a different object, an error will be thrown.\n * To fix this problem, the overridingRules array should contain a rule with the same conflicting name,\n * this rule implementation will be used.\n */\n public merge<\n OtherNames extends string,\n OtherRules extends ParseRuleMap<OtherNames>,\n OW extends readonly ParserRule<Context>[],\n >(\n builder: ParserBuilder<Context, OtherNames, OtherRules>,\n overridingRules: OW,\n ):\n ParserBuilder<\n Context,\n Names | OtherNames | ParseNamesFromList<OW>,\n {[K in Names | OtherNames | ParseNamesFromList<OW>]:\n K extends keyof ParseRulesToObject<OW> ? (\n ParseRulesToObject<OW>[K] extends ParserRule<Context, K> ? ParseRulesToObject<OW>[K] : never\n )\n : (\n K extends Names ? (RuleDefs[K] extends ParserRule<Context, K> ? RuleDefs[K] : never)\n : K extends OtherNames ? (OtherRules[K] extends ParserRule<Context, K> ? OtherRules[K] : never) : never\n ) }\n > {\n // Assume the other grammar is bigger than yours. So start from that one and add this one\n const otherRules: Record<string, ParserRule<Context>> = Object.assign(Object.create(null), builder.rules);\n const myRules: Record<string, ParserRule<Context>> = this.rules;\n\n for (const rule of Object.values(myRules)) {\n if (otherRules[rule.name] === undefined) {\n otherRules[rule.name] = rule;\n } else {\n const existingRule = otherRules[rule.name];\n // If same rule, no issue, move on. Else\n if (existingRule !== rule) {\n const override = overridingRules.find(x => x.name === rule.name);\n // If override specified, take override, else, inform user that there is a conflict\n if (override) {\n otherRules[rule.name] = override;\n } else {\n throw new Error(`Rule with name \"${rule.name}\" already exists in the builder, specify an override to resolve conflict`);\n }\n }\n }\n }\n\n this.rules = <any> <unknown> otherRules;\n return <any> <unknown> this;\n }\n\n private defaultErrorHandler(input: string, errors: IRecognitionException[]): void {\n const firstError = errors[0];\n const messageBuilder: string[] = [ 'Parse error' ];\n const lineIdx = firstError.token.startLine;\n if (lineIdx !== undefined && !Number.isNaN(lineIdx)) {\n const errorLine = input.split('\\n')[lineIdx - 1];\n messageBuilder.push(` on line ${lineIdx}\n${errorLine}`);\n const columnIdx = firstError.token.startColumn;\n if (columnIdx !== undefined) {\n messageBuilder.push(`\\n${'-'.repeat(columnIdx - 1)}^`);\n }\n }\n messageBuilder.push(`\\n${firstError.message}`);\n throw new Error(messageBuilder.join(''));\n }\n\n /**\n * Construct a self-sufficient parser from the registered rules and token vocabulary.\n * Building a parser is expensive (Chevrotain performs grammar recording), so the result\n * should be reused across parse calls.\n * @returns An object with a method for each registered rule name.\n */\n public build({\n tokenVocabulary,\n parserConfig = {},\n lexerConfig = {},\n queryPreProcessor = s => s,\n errorHandler,\n }: ParserBuildArgs): ParserFromRules<Context, Names, RuleDefs> {\n const lexer = LexerBuilder.create().add(...tokenVocabulary).build({\n positionTracking: 'onlyOffset',\n recoveryEnabled: false,\n ensureOptimizations: true,\n safeMode: false,\n skipValidations: true,\n ...lexerConfig,\n });\n // Get the chevrotain parser\n const parser = this.consume({\n tokenVocabulary: <TokenType[]> tokenVocabulary,\n config: parserConfig,\n });\n // Start building a parser that does not pass input using a state, but instead gets it as a function argument.\n const selfSufficientParser: Partial<ParserFromRules<Context, Names, RuleDefs>> = {};\n\n // To do that, we need to create a wrapper for each parser rule.\n // eslint-disable-next-line ts/no-unnecessary-type-assertion\n for (const rule of <ParserRule<Context, Names>[]> Object.values(this.rules)) {\n selfSufficientParser[rule.name] = <any> ((input: string, context: Context, ...args: unknown[]) => {\n const processedInput = queryPreProcessor(input);\n const lexResult = lexer.tokenize(processedInput);\n\n if (lexResult.errors.length > 0) {\n throw new Error(lexResult.errors[0].message);\n }\n\n // This also resets the parser\n parser.input = lexResult.tokens;\n parser.setContext(context);\n const result = parser[rule.name](context, ...args);\n if (parser.errors.length > 0) {\n // Console.log(JSON.stringify(lexResult, null, 2));\n if (errorHandler) {\n errorHandler(parser.errors);\n } else {\n this.defaultErrorHandler(processedInput, parser.errors);\n }\n }\n return result;\n });\n }\n return <ParserFromRules<Context, Names, RuleDefs>> selfSufficientParser;\n }\n\n private consume({ tokenVocabulary, config = {}}: {\n tokenVocabulary: TokenVocabulary;\n config?: IParserConfig;\n }): EmbeddedActionsParser & ParseMethodsFromRules<Context, Names, RuleDefs> &\n { setContext: (context: Context) => void } {\n return <EmbeddedActionsParser & ParseMethodsFromRules<Context, Names, RuleDefs> &\n { setContext: (context: Context) => void }><unknown> new DynamicParser(this.rules, tokenVocabulary, config);\n }\n}\n", "/**\n * A value that is either available synchronously, or as a native promise.\n */\nexport type Awaitable<T> = T | Promise<T>;\n\nexport function isPromise(value: unknown): value is Promise<unknown> {\n return value instanceof Promise;\n}\n\nexport interface VisitContext {\n /**\n * Whether you should stop iterating after this object. Default false.\n */\n shortcut?: boolean;\n /**\n * Whether you should continue iterating deeper with this object. Default true.\n */\n continue?: boolean;\n /**\n * Object keys that can be ignored, meaning they do not get visited.\n */\n ignoreKeys?: Set<string>;\n}\n\nexport interface TransformContext extends VisitContext {\n /**\n * Object keys that will be shallowly copied but not traversed.\n * When the same key is included here and in ignoreKeys, the copy will still be made.\n */\n shallowKeys?: Set<string>;\n /**\n * Whether the visited object should be shallowly copied or not. Defaults to true.\n */\n copy?: boolean;\n /**\n * Only used by {@link TransformerObject.transformObjectPreOrder}.\n * Whether to re-call the transform callback onto the result of the current transform callback.\n */\n reTransform?: boolean;\n}\n\nexport type PreOrderMappingReturn = Omit<TransformContext, 'copy'> & {\n /**\n * The value to replace the current one with.\n */\n newValue: unknown;\n};\n\nexport interface SelectiveTraversalContext<Nodes> {\n /**\n * Nodes you should visit next. Defaults to empty list\n */\n next?: Nodes[];\n /**\n * Whether you should stop visiting after visiting this object. Default false.\n */\n shortcut?: boolean;\n}\n\n/**\n * Base transformer class for recursively visiting and transforming object trees.\n * Operates on plain JavaScript objects without requiring specific type structure.\n *\n * Uses an iterative (stack-based) algorithm instead of recursion to handle deep trees safely.\n * {@link transformObject} and {@link visitObject} traverse depth-first, processing\n * deeper objects before their parents (post-order), so a callback sees the already transformed\n * descendants of the object it maps.\n * {@link transformObjectPreOrder} traverses the same tree in the opposite order - transforming an object\n * before its descendants (pre-order) - so a callback decides what the descendants we iterate into are.\n *\n * For type-aware traversal based on `type` and `subType` fields,\n * see {@link TransformerTyped} and {@link TransformerSubTyped}.\n */\nexport class TransformerObject {\n protected maxStackSize = 1_000_000;\n\n /**\n * The number of times {@link transformObjectPreOrder} may hand the same position in the tree back to the\n * traversal - by remapping it, or by wrapping it in an array - before we assume the rules do not converge.\n */\n protected maxNodeRewrites = 1_000;\n\n /**\n * Creates stateless transformer.\n * @param defaultContext\n */\n public constructor(protected readonly defaultContext: TransformContext = {}) {}\n\n public clone(newDefaultContext: TransformContext = {}): TransformerObject {\n return new TransformerObject({ ...this.defaultContext, ...newDefaultContext });\n }\n\n /**\n * Function to shallow clone any type.\n * @param obj\n * @protected\n */\n public cloneObj<T>(obj: T): T {\n if (obj === null || typeof obj !== 'object') {\n return obj;\n }\n\n const proto = Object.getPrototypeOf(obj);\n\n // Fast path: plain object\n if (proto === Object.prototype || proto === null) {\n // Spread or assign preserves fast properties\n return { ...obj };\n }\n\n // Otherwise, preserve prototype for custom objects\n return Object.assign(Object.create(proto), obj);\n }\n\n /**\n * Recursively transforms all objects that are not arrays. Mapper is called on deeper objects first.\n *\n * `transformObject` never inspects the values a mapper returns; a returned promise is stored as-is.\n * `transformObjectAsync` awaits any thenable a mapper returns, so it cannot store one as a value.\n * @param startObject object to start iterating from\n * @param postMapper postMapper to transform the various objects - argument is a copy of the original\n * @param preVisitor callback that is evaluated before iterating deeper.\n * If continues is false, we do not iterate deeper, current object is still mapped. - default: true\n * If shortcut is true, we do not iterate deeper, nor do we branch out, this postMapper will be the last one called.\n * - Default false\n */\n public transformObject(\n startObject: object,\n postMapper: (copy: object, orig: object) => unknown,\n preVisitor: (orig: object) => TransformContext = () => ({}),\n ): unknown {\n return this.runTransformObject(startObject, postMapper, preVisitor, false);\n }\n\n /**\n * Async variant of {@link transformObject}, supporting promise-returning callbacks.\n * The traversal is strictly sequential (depth-first, one suspension point) - it does not parallelise siblings.\n *\n * `transformObject` never inspects the values a mapper returns; a returned promise is stored as-is.\n * `transformObjectAsync` awaits any thenable a mapper returns, so it cannot store one as a value.\n * @param startObject object to start iterating from\n * @param postMapper postMapper to transform the various objects - argument is a copy of the original\n * @param preVisitor callback that is evaluated before iterating deeper.\n */\n public transformObjectAsync(\n startObject: object,\n postMapper: (copy: object, orig: object) => Awaitable<unknown>,\n preVisitor: (orig: object) => Awaitable<TransformContext> = () => ({}),\n ): Promise<unknown> {\n return Promise.resolve(this.runTransformObject(startObject, postMapper, preVisitor, true));\n }\n\n protected runTransformObject(\n startObject: object,\n postMapper: (copy: object, orig: object) => Awaitable<unknown>,\n preVisitor: (orig: object) => Awaitable<TransformContext>,\n allowAsync: boolean,\n ): unknown {\n const defaults = this.defaultContext;\n const defaultCopyFlag = defaults.copy ?? true;\n const defaultContinues = defaults.continue ?? true;\n const defaultIgnoreKeys = defaults.ignoreKeys;\n const defaultShallowKeys = defaults.shallowKeys;\n const defaultDidShortCut = defaults.shortcut ?? false;\n\n // Code handles own stack instead of using recursion - this optimizes it for deep operations.\n let didShortCut = false;\n const resultWrap = { res: startObject };\n\n // Work stack: nodes still to visit. Parallel arrays, length S.\n // stack[i] - original node to visit\n // stackParent[i] - copy to write the result into, under stackParentKey[i]\n // Seeded with the root under resultWrap.res, so the root's mapped value has\n // somewhere to land. S is the DFS frontier (all unvisited siblings on all levels),\n // not the depth — this is what maxStackSize bounds.\n const stack = [ startObject ];\n const stackParent: object[] = [ resultWrap ];\n const stackParentKey: string[] = [ 'res' ];\n\n // Post-map stack: visited, awaiting postMapper. Parallel arrays, length M.\n // handleMapperOnLen[i] - stack.length snapshotted after popping node i, before pushing its children.\n // The frontier returning to this value means i's subtree is done.\n // mapperParent/Key[i] - where postMapper's return value goes (may differ from the copy, hence a separate write)\n // M is the current ancestor chain, so M <= nesting depth and is usually far\n // below S. Watermarks are non-decreasing bottom-to-top; a match at the top\n // flushes and cascades to the parent.\n const handleMapperOnLen: number[] = [];\n const mapperCopyStack: object[] = [];\n const mapperOrigStack: object[] = [];\n const mapperParent: object[] = [];\n const mapperParentKey: string[] = [];\n\n // Returns a promise only when a postMapper suspended - it keeps unwinding itself once that resolves.\n function handleMapper(): PromiseLike<void> | undefined {\n while (stack.length === handleMapperOnLen.at(-1)) {\n handleMapperOnLen.pop();\n const copyToMap = mapperCopyStack.pop()!;\n const origToMap = mapperOrigStack.pop()!;\n const parent = <Record<string, unknown>> mapperParent.pop()!;\n const parentKey = mapperParentKey.pop()!;\n const mapped = postMapper(copyToMap, origToMap);\n if (allowAsync && isPromise(mapped)) {\n return mapped.then((value): PromiseLike<void> | undefined => {\n parent[parentKey] = value;\n return handleMapper();\n });\n }\n parent[parentKey] = mapped;\n }\n return undefined;\n }\n\n // Everything after the preVisitor call - split out so it can also run from inside a resolved promise.\n const expand = (curObject: object, curParent: object, curKey: string, context: TransformContext): void => {\n const copyFlag = context.copy ?? defaultCopyFlag;\n const continues = context.continue ?? defaultContinues;\n const ignoreKeys = context.ignoreKeys ?? defaultIgnoreKeys;\n const shallowKeys = context.shallowKeys ?? defaultShallowKeys;\n didShortCut = context.shortcut ?? defaultDidShortCut;\n\n const copy = copyFlag ? this.cloneObj(curObject) : curObject;\n\n // Register that you want to be visited\n handleMapperOnLen.push(stack.length);\n mapperCopyStack.push(copy);\n mapperOrigStack.push(curObject);\n mapperParent.push(curParent);\n mapperParentKey.push(curKey);\n\n // Extend stack if needed. When shortcutted, should still unwind the stack, but no longer add to it.\n if (continues && !didShortCut) {\n for (const key in copy) {\n if (!Object.hasOwn(copy, key)) {\n continue;\n }\n const val = (<Record<string, unknown>> copy)[key];\n\n // If shallow copy required, do\n const onlyShallow = shallowKeys && shallowKeys?.has(key);\n if (onlyShallow) {\n // Do not add stack entry - assign straight away\n (<Record<string, unknown>> copy)[key] = this.cloneObj(val);\n }\n if (ignoreKeys && ignoreKeys.has(key)) {\n // Do not add stack entry\n continue;\n }\n if (!onlyShallow && val !== null && typeof val === 'object') {\n // Do add stack entry.\n stack.push(val);\n stackParentKey.push(key);\n stackParent.push(copy);\n }\n }\n }\n };\n\n // The loop is wrapped so it can return at a suspension point and be called again to resume.\n const wrappedExecutionLoop = (): unknown => {\n while (stack.length > 0 && stack.length < this.maxStackSize) {\n const curObject = stack.pop()!;\n const curParent = stackParent.pop()!;\n const curKey = stackParentKey.pop()!;\n\n // Only add to the stack when you did not shortcut\n if (!didShortCut) {\n if (Array.isArray(curObject)) {\n const newArr = [ ...curObject ];\n handleMapperOnLen.push(stack.length);\n mapperCopyStack.push(newArr);\n mapperOrigStack.push(curObject);\n mapperParent.push(curParent);\n mapperParentKey.push(curKey);\n\n for (let index = curObject.length - 1; index >= 0; index--) {\n const val = <unknown> curObject[index];\n if (val !== null && typeof val === 'object') {\n stack.push(val);\n stackParent.push(newArr);\n stackParentKey.push(index.toString());\n }\n }\n const pending = handleMapper();\n if (pending) {\n return pending.then(wrappedExecutionLoop);\n }\n continue;\n }\n\n // Perform pre visit before expanding the stack\n const context = preVisitor(<any>curObject);\n if (allowAsync && isPromise(context)) {\n return context.then((context) => {\n expand(curObject, curParent, curKey, context);\n const pending = handleMapper();\n return pending ? pending.then(wrappedExecutionLoop) : wrappedExecutionLoop();\n });\n }\n expand(curObject, curParent, curKey, <TransformContext>context);\n }\n const pending = handleMapper();\n if (pending) {\n return pending.then(wrappedExecutionLoop);\n }\n }\n if (stack.length >= this.maxStackSize) {\n throw new Error('Transform object stack overflowed');\n }\n return resultWrap.res;\n };\n\n return wrappedExecutionLoop();\n }\n\n /**\n * Recursively transforms all objects that are not arrays, calling the preMapper on an object _before_\n * iterating into its descendants, and iterating into the *result* of that preMapper.\n * It should be noted that the preMapper is called using a *shallow* copy of the object.\n * Meaning manipulation of nested objects changes the original!\n * @param startObject object to start iterating from\n * @param preMapper mapper to transform the various objects -\n * first argument is a copy of the original if default setup says to copy.\n * It returns a {@link PreOrderMappingReturn}: the value taking the place of the object - the value we\n * iterate into - together with the {@link TransformContext} steering that iteration. Since the mapper\n * is the one deciding what the descendants of that value are, it hands us that context itself, there is\n * no separate preVisitor. Whether we copy is therefore not up to the mapper either,\n * the default context of this transformer decides that.\n * The returned value is only handed back to the traversal - and thus mapped again - when the mapper\n * asked for {@link TransformContext.reTransform}, in any other case we iterate straight into its\n * descendants. An array is the exception: it is never mapped as a whole, its elements are handed back\n * and mapped in turn. Either way the rules have to settle a position within {@link maxNodeRewrites}\n * hand-backs of that position, or we assume they do not converge and throw.\n * A {@link VisitContext.shortcut} simply ends the traversal - since an object is already mapped when we\n * iterate into it, there is nothing left to unwind - leaving the objects still on the stack in the place\n * they have in the (shallow) copy of their parent.\n *\n * `transformObjectPreOrder` never inspects the values a mapper returns; a returned promise is stored as-is.\n * `transformObjectPreOrderAsync` awaits any thenable a mapper returns, so it cannot store one as a value.\n */\n public transformObjectPreOrder(\n startObject: object,\n preMapper: (copy: object, orig: object) => PreOrderMappingReturn,\n ): unknown {\n return this.runTransformObjectPreOrder(startObject, preMapper, false);\n }\n\n /**\n * Async variant of {@link transformObjectPreOrder}, supporting promise-returning callbacks.\n * The traversal is strictly sequential (depth-first, one suspension point) - it does not parallelise siblings.\n *\n * `transformObjectPreOrder` never inspects the values a mapper returns; a returned promise is stored as-is.\n * `transformObjectPreOrderAsync` awaits any thenable a mapper returns, so it cannot store one as a value.\n * @param startObject object to start iterating from\n * @param preMapper mapper to transform the various objects.\n */\n public transformObjectPreOrderAsync(\n startObject: object,\n preMapper: (copy: object, orig: object) => Awaitable<PreOrderMappingReturn>,\n ): Promise<unknown> {\n return Promise.resolve(this.runTransformObjectPreOrder(startObject, preMapper, true));\n }\n\n protected runTransformObjectPreOrder(\n startObject: object,\n preMapper: (copy: object, orig: object) => Awaitable<PreOrderMappingReturn>,\n allowAsync: boolean,\n ): unknown {\n const defaults = this.defaultContext;\n const defaultCopyFlag = defaults.copy ?? true;\n const defaultContinues = defaults.continue ?? true;\n const defaultIgnoreKeys = defaults.ignoreKeys;\n const defaultShallowKeys = defaults.shallowKeys;\n const defaultDidShortCut = defaults.shortcut ?? false;\n const defaultReTransform = defaults.reTransform ?? false;\n\n // Code handles own stack instead of using recursion - this optimizes it for deep operations.\n // Contrary to {@link transformObject}, an object is mapped when it is popped of the stack,\n // so its result can be assigned to its parent right away - no reverse (post-map) stack needed.\n let didShortCut = false;\n const resultWrap = { res: <unknown> startObject };\n\n // Work stack: nodes still to visit. Parallel arrays, length S.\n // stack[i] - original node to visit\n // stackParent[i] - object to write the mapped value into, under stackParentKey[i]\n // stackRewriteCount[i] - how many times this position was already handed back (remap/array-wrap),\n // bounded by maxNodeRewrites so non-converging rules throw instead of looping forever.\n // Seeded with the root under resultWrap.res. S is the DFS frontier (all unvisited siblings on all\n // levels), not the depth — this is what maxStackSize bounds.\n const stack = [ startObject ];\n const stackParent: object[] = [ resultWrap ];\n const stackParentKey: string[] = [ 'res' ];\n // Counts for ech object how many times it has been rewritten\n const stackRewriteCount: number[] = [ 0 ];\n\n function pushArrayOnStack(array: unknown[], rewriteCount: number): void {\n // Register all containing objects in the stack to be handled.\n // The elements inherit the count of the array: an array is not mapped as a whole, so it does not\n // settle the position it takes, a rule wrapping its argument in one has to keep climbing.\n for (let index = array.length - 1; index >= 0; index--) {\n const val = array[index];\n if (val !== null && typeof val === 'object') {\n stack.push(val);\n stackParent.push(array);\n stackParentKey.push(index.toString());\n stackRewriteCount.push(rewriteCount);\n }\n }\n }\n\n const applyResult = (\n mapperResult: PreOrderMappingReturn,\n curParent: Record<string, unknown>,\n curKey: string,\n rewriteCount: number,\n ): void => {\n const newValue = mapperResult.newValue;\n\n // The object is mapped, the value takes its place in the tree\n curParent[curKey] = newValue;\n\n const continues = mapperResult.continue ?? defaultContinues;\n const ignoreKeys = mapperResult.ignoreKeys ?? defaultIgnoreKeys;\n const shallowKeys = mapperResult.shallowKeys ?? defaultShallowKeys;\n const reTransform = mapperResult.reTransform ?? defaultReTransform;\n didShortCut = mapperResult.shortcut ?? defaultDidShortCut;\n\n // Register values of returned object onto the stack\n // If primitive, or we do not go further, cannot do\n if (!continues || didShortCut || (newValue === null || typeof newValue !== 'object')) {\n return;\n }\n // We cannot retransform an array since the API never gives array to the callback.\n // Its elements are handed back to the traversal instead, and are mapped in turn.\n if (Array.isArray(newValue)) {\n pushArrayOnStack(newValue, rewriteCount + 1);\n return;\n }\n // If we need to re transform, register the object instead of its children.\n if (reTransform) {\n stack.push(newValue);\n stackParent.push(curParent);\n stackParentKey.push(curKey);\n stackRewriteCount.push(rewriteCount + 1);\n return;\n }\n // In any other case, push the children, ignoring ignoreKeys and shallowKeys.\n // Creating shallow copies of shallowKeys.\n const newAsRecord = <Record<string, unknown>> newValue;\n for (const key in newAsRecord) {\n if (!Object.hasOwn(newAsRecord, key) || ignoreKeys?.has(key)) {\n continue;\n }\n const val = newAsRecord[key];\n if (val !== null && typeof val === 'object') {\n if (shallowKeys?.has(key)) {\n newAsRecord[key] = this.cloneObj(val);\n } else {\n stack.push(val);\n stackParent.push(newAsRecord);\n stackParentKey.push(key);\n stackRewriteCount.push(0);\n }\n }\n }\n };\n\n // The loop is wrapped so it can return at a suspension point and be called again to resume.\n // Since there is nothing left to unwind, a shortcut simply ends the traversal.\n // Objects still on the stack keep the place they have in the (shallow) copy of their parent.\n const wrappedExecutionLoop = (): unknown => {\n // The didShortCut flag is flipped inside applyResult (a separate closure), which the rule cannot see.\n // eslint-disable-next-line no-unmodified-loop-condition\n while (!didShortCut && stack.length > 0 && stack.length < this.maxStackSize) {\n const curObject = stack.pop()!;\n // Parent is always a raw object (not an array since we handle that differently)\n const curParent = <Record<string, unknown>> stackParent.pop()!;\n const curKey = stackParentKey.pop()!;\n const rewriteCount = stackRewriteCount.pop()!;\n\n if (rewriteCount >= this.maxNodeRewrites) {\n throw new Error(`Pre order transform did not converge: rewrote the same position ${this.maxNodeRewrites} times.`, { cause: curObject });\n }\n\n if (Array.isArray(curObject)) {\n const newArr = [ ...curObject ];\n curParent[curKey] = newArr;\n pushArrayOnStack(newArr, rewriteCount);\n continue;\n }\n\n // Map the object before its descendants, so that the mapper can decide what its descendants are.\n const copy = defaultCopyFlag ? this.cloneObj(curObject) : curObject;\n const mapperResult = preMapper(copy, curObject);\n if (allowAsync && isPromise(mapperResult)) {\n return mapperResult.then((result): unknown => {\n applyResult(result, curParent, curKey, rewriteCount);\n return wrappedExecutionLoop();\n });\n }\n applyResult(<PreOrderMappingReturn>mapperResult, curParent, curKey, rewriteCount);\n }\n if (stack.length >= this.maxStackSize) {\n throw new Error('Transform object stack overflowed');\n }\n return resultWrap.res;\n };\n\n return wrappedExecutionLoop();\n }\n\n /**\n * Visitor that visits all objects. Visits deeper objects first.\n *\n * `visitObjectAsync` awaits any thenable a visitor returns before visiting the next node.\n */\n public visitObject(\n startObject: object,\n visitor: (orig: object) => void,\n preVisitor: (orig: object) => VisitContext = () => ({}),\n ): void {\n this.runVisitObject(startObject, visitor, preVisitor, false);\n }\n\n /**\n * Async variant of {@link visitObject}, supporting promise-returning callbacks.\n * The traversal is strictly sequential (depth-first, one suspension point) - it does not parallelise siblings.\n */\n public visitObjectAsync(\n startObject: object,\n visitor: (orig: object) => Awaitable<void>,\n preVisitor: (orig: object) => Awaitable<VisitContext> = () => ({}),\n ): Promise<void> {\n return <Promise<void>> Promise.resolve(this.runVisitObject(startObject, visitor, preVisitor, true));\n }\n\n protected runVisitObject(\n startObject: object,\n visitor: (orig: object) => Awaitable<void>,\n preVisitor: (orig: object) => Awaitable<VisitContext>,\n allowAsync: boolean,\n ): unknown {\n const defaults = this.defaultContext;\n const defaultContinues = defaults.continue ?? true;\n const defaultIgnoreKeys = defaults.ignoreKeys;\n const defaultShortcut = defaults.shortcut ?? false;\n\n let didShortCut = false;\n\n // Work stack: nodes still to preVisit. Single array, length S.\n // Unlike {@link transformObject} there is no copying, so a parent/key is not tracked - we only visit.\n // Seeded with the root. S is the DFS frontier (all unvisited siblings on all levels),\n // not the depth — this is what maxStackSize bounds.\n const stack = [ startObject ];\n\n // Visit stack: preVisited, awaiting the actual visitor. Parallel arrays, length M.\n // handleVisitorOnLen[i] - stack.length snapshotted after popping node i, before pushing its children.\n // The frontier returning to this value means i's subtree is done, so i can be visited.\n // visitorStack[i] - the node to hand to the visitor\n // M is the current ancestor chain, so M <= nesting depth and is usually far below S.\n const handleVisitorOnLen: number[] = [];\n const visitorStack: object[] = [];\n\n // Returns a promise only when a visitor suspended - it keeps unwinding itself once that resolves.\n function handleVisitor(): PromiseLike<void> | undefined {\n while (stack.length === handleVisitorOnLen.at(-1)) {\n handleVisitorOnLen.pop();\n const toVisit = visitorStack.pop()!;\n const visited = visitor(toVisit);\n if (allowAsync && isPromise(visited)) {\n return visited.then((): PromiseLike<void> | undefined => handleVisitor());\n }\n }\n return undefined;\n }\n\n // Everything after the preVisitor call - split out so it can also run from inside a resolved promise.\n const expand = (curObject: object, context: VisitContext): void => {\n didShortCut = context.shortcut ?? defaultShortcut;\n const continues = context.continue ?? defaultContinues;\n const ignoreKeys = context.ignoreKeys ?? defaultIgnoreKeys;\n\n // Register that you want to be visited\n handleVisitorOnLen.push(stack.length);\n visitorStack.push(curObject);\n\n // Extend stack if needed. When shortcutted, should still unwind the stack, but no longer add to it.\n if (continues && !didShortCut) {\n for (const key in curObject) {\n if (!Object.hasOwn(curObject, key)) {\n continue;\n }\n if (ignoreKeys && ignoreKeys.has(key)) {\n continue;\n }\n const val = (<Record<string, unknown>> curObject)[key];\n if (val && typeof val === 'object') {\n stack.push(val);\n }\n }\n }\n };\n\n // The loop is wrapped so it can return at a suspension point and be called again to resume.\n const wrappedExecutionLoop = (): unknown => {\n while (stack.length > 0 && stack.length < this.maxStackSize) {\n const curObject = stack.pop()!;\n\n if (!didShortCut) {\n if (Array.isArray(curObject)) {\n for (let i = curObject.length - 1; i >= 0; i--) {\n const val = <unknown> curObject[i];\n if (val !== null && typeof val === 'object') {\n stack.push(val);\n }\n }\n const pending = handleVisitor();\n if (pending) {\n return pending.then(wrappedExecutionLoop);\n }\n continue;\n }\n\n // Perform pre visit before expanding the stack\n const context = preVisitor(curObject);\n if (allowAsync && isPromise(context)) {\n return context.then((ctx): unknown => {\n expand(curObject, ctx);\n const pending = handleVisitor();\n return pending ? pending.then(wrappedExecutionLoop) : wrappedExecutionLoop();\n });\n }\n expand(curObject, <VisitContext>context);\n }\n const pending = handleVisitor();\n if (pending) {\n return pending.then(wrappedExecutionLoop);\n }\n }\n if (stack.length >= this.maxStackSize) {\n throw new Error('Transform object stack overflowed');\n }\n return undefined;\n };\n\n return wrappedExecutionLoop();\n }\n}\n", "import type { Typed } from '../types.js';\nimport type { Awaitable, PreOrderMappingReturn, TransformContext, VisitContext } from './TransformerObject.js';\nimport { isPromise, TransformerObject } from './TransformerObject.js';\n\n/**\n * Controls whether transform callbacks receive fully typed nodes (`'unsafe'`) or\n * nodes where all fields are `unknown` (`'safe'`). Using `'safe'` (the default)\n * forces explicit type narrowing, reducing the risk of incorrect assumptions.\n */\nexport type Safeness = 'safe' | 'unsafe';\n/**\n * Conditionally wraps an object type: in `'safe'` mode, all fields become `unknown`;\n * in `'unsafe'` mode, the original types are preserved.\n */\nexport type SafeWrap<Safe extends Safeness, obj extends object> =\n Safe extends 'safe' ? {[key in keyof obj]: unknown } : obj;\n\n/**\n * Default pre-visitor configuration per node type. Provides default {@link TransformContext}\n * values that apply when no explicit preVisitor is given for a node type.\n */\nexport type DefaultNodePreVisitor<Nodes extends Typed> = {[T in Nodes['type']]?: TransformContext };\n\n/**\n * Type-aware AST transformer that dispatches visit and transform callbacks\n * based on the `type` field of {@link Typed} nodes.\n *\n * Extends {@link TransformerObject} with node-type-specific dispatch, so you can\n * register handlers per node type rather than filtering manually.\n *\n * For even more specific dispatch based on both `type` and `subType`,\n * see {@link TransformerSubTyped}.\n *\n * @typeParam Nodes - Union type of all node types this transformer handles.\n * Each member must extend {@link Typed}.\n */\nexport class TransformerTyped<Nodes extends Typed> extends TransformerObject {\n public constructor(\n defaultContext: TransformContext = {},\n protected defaultNodePreVisitor: DefaultNodePreVisitor<Nodes> = {},\n ) {\n super(defaultContext);\n };\n\n public override clone(\n newDefaultContext: TransformContext = {},\n newDefaultNodePreVisitor: DefaultNodePreVisitor<Nodes> = {},\n ): TransformerTyped<Nodes> {\n return new TransformerTyped(\n { ...this.defaultContext, ...newDefaultContext },\n { ...this.defaultNodePreVisitor, ...newDefaultNodePreVisitor },\n );\n }\n\n /**\n * Transform a single node ({@link Typed}).\n * @param startObject the object from which we will start the transformation,\n * potentially visiting and transforming its descendants along the way.\n * @param nodeCallBacks a dictionary mapping the various node types to objects optionally\n * containing preVisitor and transformer.\n * The preVisitor allows you to provide {@link TransformContext} for the current object,\n * altering how it will be transformed.\n * The transformer allows you to manipulate the copy of the current object,\n * and expects you to return the value that should take the current objects place.\n * @return the result of transforming the requested descendant operations (based on the preVisitor)\n * using a transformer that works its way back up from the descendant to the startObject.\n */\n public transformNode<Safe extends Safeness = 'safe', OutType = unknown>(\n startObject: object,\n nodeCallBacks: {[T in Nodes['type']]?: {\n transform?: (copy: SafeWrap<Safe, Extract<Nodes, Typed<T>>>, orig: Extract<Nodes, Typed<T>>) => unknown;\n preVisitor?: (orig: Extract<Nodes, Typed<T>>) => TransformContext;\n }},\n ): Safe extends 'unsafe' ? OutType : unknown {\n const transformWrapper = (copy: object, orig: object): unknown => {\n let ogTransform: ((copy: any, orig: any) => unknown) | undefined;\n const casted = <Typed<Nodes['type']>>copy;\n if (casted.type) {\n ogTransform = nodeCallBacks[casted.type]?.transform;\n }\n return ogTransform ? ogTransform(casted, orig) : copy;\n };\n const nodeDefaults = this.defaultNodePreVisitor;\n const preVisitWrapper = (curObject: object): VisitContext => {\n let ogPreVisit: ((node: any) => TransformContext) | undefined;\n let nodeContext: TransformContext = {};\n const casted = <Typed<Nodes['type']>>curObject;\n if (casted.type) {\n ogPreVisit = nodeCallBacks[casted.type]?.preVisitor;\n nodeContext = nodeDefaults[casted.type] ?? nodeContext;\n }\n return ogPreVisit ? { ...nodeContext, ...ogPreVisit(casted) } : nodeContext;\n };\n return <any> this.transformObject(startObject, transformWrapper, preVisitWrapper);\n }\n\n /**\n * Async variant of {@link transformNode}, supporting promise-returning callbacks.\n * The traversal is strictly sequential (depth-first) - it does not parallelise siblings.\n */\n public transformNodeAsync<Safe extends Safeness = 'safe', OutType = unknown>(\n startObject: object,\n nodeCallBacks: {[T in Nodes['type']]?: {\n transform?: (\n copy: SafeWrap<Safe, Extract<Nodes, Typed<T>>>,\n orig: Extract<Nodes, Typed<T>>,\n ) => Awaitable<unknown>;\n preVisitor?: (orig: Extract<Nodes, Typed<T>>) => Awaitable<TransformContext>;\n }},\n ): Promise<Safe extends 'unsafe' ? OutType : unknown> {\n const transformWrapper = (copy: object, orig: object): Awaitable<unknown> => {\n let ogTransform: ((copy: any, orig: any) => Awaitable<unknown>) | undefined;\n const casted = <Typed<Nodes['type']>>copy;\n if (casted.type) {\n ogTransform = nodeCallBacks[casted.type]?.transform;\n }\n return ogTransform ? ogTransform(casted, orig) : copy;\n };\n const nodeDefaults = this.defaultNodePreVisitor;\n const preVisitWrapper = (curObject: object): Awaitable<TransformContext> => {\n let ogPreVisit: ((node: any) => Awaitable<TransformContext>) | undefined;\n let nodeContext: TransformContext = {};\n const casted = <Typed<Nodes['type']>>curObject;\n if (casted.type) {\n ogPreVisit = nodeCallBacks[casted.type]?.preVisitor;\n nodeContext = nodeDefaults[casted.type] ?? nodeContext;\n }\n if (!ogPreVisit) {\n return nodeContext;\n }\n const result = ogPreVisit(casted);\n return isPromise(result) ?\n result.then((res): TransformContext => ({ ...nodeContext, ...res })) :\n { ...nodeContext, ...result };\n };\n return <any> this.transformObjectAsync(startObject, transformWrapper, preVisitWrapper);\n }\n\n /**\n * Transform a single node ({@link Typed}) pre-order,\n * the dual of {@link this.transformObjectPreOrder} with the same type specification as {@link this.transformNode}:\n * a node is transformed _before_ its descendants, and we iterate into the result of that transformation.\n * This is what you want when a node has to travel deeper into the tree:\n * the callback only describes how a node swaps places with the node right below it,\n * the copy it sank into is dispatched in turn, and swaps places with the node below that one.\n *\n * Contrary to {@link this.transformNode}, a callback does not just return the value taking the place of\n * the node, it returns a {@link PreOrderMappingReturn}: that value, plus the {@link TransformContext} of\n * that value. Since the callback decides what we iterate into, it is the one telling us how to iterate\n * into it, so there is no separate preVisitor - it only completes the per type defaults of this\n * transformer, which are looked up using the type of the node it was called on.\n * A node without a callback is left alone: it keeps those defaults, but is never re-transformed.\n *\n * Also contrary to {@link this.transformNode}, the descendants of the node given to the callback are not\n * transformed yet: they are the nodes of the input tree itself.\n * @param startObject the object from which we will start the transformation,\n * potentially visiting and transforming its descendants along the way.\n * @param nodeCallBacks a dictionary mapping the various node types to a mapper.\n * The mapper allows you to manipulate the copy of the current node, and expects you to return the\n * value that should take the current nodes place, together with the context of that value.\n * That context steers how we iterate into the returned value.\n * @return the result of transforming the startObject and the descendants of its rewrites.\n */\n public transformNodePreOrder<Safe extends Safeness = 'safe', OutType = unknown>(\n startObject: object,\n nodeCallBacks: {[T in Nodes['type']]?:\n (copy: SafeWrap<Safe, Extract<Nodes, Typed<T>>>, orig: Extract<Nodes, Typed<T>>) => PreOrderMappingReturn;\n },\n ): Safe extends 'unsafe' ? OutType : unknown {\n const nodeDefaults = this.defaultNodePreVisitor;\n const preTransformWrapper = (copy: object, orig: object): PreOrderMappingReturn => {\n let ogPreTransform: ((copy: any, orig: any) => PreOrderMappingReturn) | undefined;\n let nodeContext: TransformContext = {};\n const casted = <Typed<Nodes['type']>>copy;\n if (casted.type) {\n ogPreTransform = nodeCallBacks[casted.type];\n nodeContext = nodeDefaults[casted.type] ?? nodeContext;\n }\n return ogPreTransform ?\n { ...nodeContext, ...ogPreTransform(copy, orig) } :\n { ...nodeContext, newValue: copy, reTransform: false };\n };\n\n return <any> this.transformObjectPreOrder(startObject, preTransformWrapper);\n }\n\n /**\n * Async variant of {@link transformNodePreOrder}, supporting promise-returning callbacks.\n * The traversal is strictly sequential (depth-first) - it does not parallelise siblings.\n */\n public transformNodePreOrderAsync<Safe extends Safeness = 'safe', OutType = unknown>(\n startObject: object,\n nodeCallBacks: {[T in Nodes['type']]?:\n (\n copy: SafeWrap<Safe, Extract<Nodes, Typed<T>>>,\n orig: Extract<Nodes, Typed<T>>,\n ) => Awaitable<PreOrderMappingReturn>;\n },\n ): Promise<Safe extends 'unsafe' ? OutType : unknown> {\n const nodeDefaults = this.defaultNodePreVisitor;\n const preTransformWrapper = (copy: object, orig: object): Awaitable<PreOrderMappingReturn> => {\n let ogPreTransform: ((copy: any, orig: any) => Awaitable<PreOrderMappingReturn>) | undefined;\n let nodeContext: TransformContext = {};\n const casted = <Typed<Nodes['type']>>copy;\n if (casted.type) {\n ogPreTransform = nodeCallBacks[casted.type];\n nodeContext = nodeDefaults[casted.type] ?? nodeContext;\n }\n if (!ogPreTransform) {\n return { ...nodeContext, newValue: copy, reTransform: false };\n }\n const result = ogPreTransform(copy, orig);\n return isPromise(result) ?\n result.then((res): PreOrderMappingReturn => ({ ...nodeContext, ...res })) :\n { ...nodeContext, ...result };\n };\n\n return <any> this.transformObjectPreOrderAsync(startObject, preTransformWrapper);\n }\n\n /**\n * Visit a selected subTree given a startObject, steering the visits based on {@link Typed} nodes.\n * Will first call the preVisitor on the project and notice it should not iterate on its descendants.\n * It then visits the project, and the outermost distinct, printing '21'.\n * The pre-visitor visits starting from the root, going deeper, while the actual visitor goes in reverse.\n * @param startObject the object from which we will start visiting,\n * potentially visiting its descendants along the way.\n * @param nodeCallBacks a dictionary mapping the various operation types to objects optionally\n * containing preVisitor and visitor.\n * The preVisitor allows you to provide {@link VisitContext} for the current object,\n * altering how it will be visited.\n * The visitor allows you to visit the object from deepest to the outermost object.\n * This is useful if you for example want to manipulate the objects you visit during your visits,\n * similar to {@link this.transformNode}.\n */\n public visitNode(\n startObject: object,\n nodeCallBacks: {[T in Nodes['type']]?: {\n visitor?: (op: Extract<Nodes, Typed<T>>) => void;\n preVisitor?: (op: Extract<Nodes, Typed<T>>) => VisitContext;\n }},\n ): void {\n const visitorWrapper = (curObject: object): void => {\n const casted = <Typed<Nodes['type']>>curObject;\n if (casted.type) {\n const ogTransform = nodeCallBacks[casted.type]?.visitor;\n if (ogTransform) {\n ogTransform(<any> casted);\n }\n }\n };\n const nodeDefaults = this.defaultNodePreVisitor;\n const preVisitWrapper = (curObject: object): VisitContext => {\n let ogPreVisit: ((node: any) => VisitContext) | undefined;\n let nodeContext: VisitContext = {};\n const casted = <Typed<Nodes['type']>>curObject;\n if (casted.type) {\n ogPreVisit = nodeCallBacks[casted.type]?.preVisitor;\n nodeContext = nodeDefaults[casted.type] ?? nodeContext;\n }\n return ogPreVisit ? { ...nodeContext, ...ogPreVisit(casted) } : nodeContext;\n };\n return this.visitObject(startObject, visitorWrapper, preVisitWrapper);\n }\n\n /**\n * Async variant of {@link visitNode}, supporting promise-returning callbacks.\n * The traversal is strictly sequential (depth-first) - it does not parallelise siblings.\n */\n public visitNodeAsync(\n startObject: object,\n nodeCallBacks: {[T in Nodes['type']]?: {\n visitor?: (op: Extract<Nodes, Typed<T>>) => Awaitable<void>;\n preVisitor?: (op: Extract<Nodes, Typed<T>>) => Awaitable<VisitContext>;\n }},\n ): Promise<void> {\n const visitorWrapper = (curObject: object): Awaitable<void> => {\n const casted = <Typed<Nodes['type']>>curObject;\n if (casted.type) {\n const ogTransform = nodeCallBacks[casted.type]?.visitor;\n if (ogTransform) {\n return ogTransform(<any> casted);\n }\n }\n };\n const nodeDefaults = this.defaultNodePreVisitor;\n const preVisitWrapper = (curObject: object): Awaitable<VisitContext> => {\n let ogPreVisit: ((node: any) => Awaitable<VisitContext>) | undefined;\n let nodeContext: VisitContext = {};\n const casted = <Typed<Nodes['type']>>curObject;\n if (casted.type) {\n ogPreVisit = nodeCallBacks[casted.type]?.preVisitor;\n nodeContext = nodeDefaults[casted.type] ?? nodeContext;\n }\n if (!ogPreVisit) {\n return nodeContext;\n }\n const result = ogPreVisit(casted);\n return isPromise(result) ?\n result.then((res): VisitContext => ({ ...nodeContext, ...res })) :\n { ...nodeContext, ...result };\n };\n return this.visitObjectAsync(startObject, visitorWrapper, preVisitWrapper);\n }\n}\n", "import type { SubTyped, Typed } from '../types.js';\nimport type {\n Awaitable,\n PreOrderMappingReturn,\n TransformContext,\n VisitContext,\n} from './TransformerObject.js';\nimport type { DefaultNodePreVisitor, Safeness, SafeWrap } from './TransformerTyped.js';\nimport { TransformerTyped } from './TransformerTyped.js';\n\n/**\n * Most specific AST transformer that dispatches visit and transform callbacks\n * based on both the `type` and `subType` fields of {@link SubTyped} nodes.\n *\n * Extends {@link TransformerTyped} with an additional dispatch level. When a callback\n * is registered for a specific `(type, subType)` pair, it takes precedence over\n * the type-only callback from {@link TransformerTyped.transformNode}.\n *\n * This is the recommended transformer for SPARQL ASTs where nodes have both\n * type and subType discriminators (e.g., `{ type: 'term', subType: 'literal' }`).\n *\n * @typeParam Nodes - Union type of all node types this transformer handles.\n */\nexport class TransformerSubTyped<Nodes extends Typed> extends TransformerTyped<Nodes> {\n // TODO(major): these functions here should care about the default pre visitor provided to the constructor!\n public constructor(\n defaultContext: TransformContext = {},\n defaultNodePreVisitor: DefaultNodePreVisitor<Nodes> = {},\n ) {\n super(defaultContext, defaultNodePreVisitor);\n };\n\n public override clone(\n newDefaultContext: TransformContext = {},\n newDefaultNodePreVisitor: DefaultNodePreVisitor<Nodes> = {},\n ): TransformerSubTyped<Nodes> {\n return new TransformerSubTyped(\n { ...this.defaultContext, ...newDefaultContext },\n { ...this.defaultNodePreVisitor, ...newDefaultNodePreVisitor },\n );\n }\n\n /**\n * Transform a single node ({@link Typed}).\n * Similar to {@link this.transformNode} but also allowing you to target the subTypes.\n * @param startObject the object from which we will start the transformation,\n * potentially visiting and transforming its descendants along the way.\n * @param nodeCallBacks a dictionary mapping the various operation types to objects optionally\n * containing preVisitor and transformer.\n * The preVisitor allows you to provide {@link TransformContext} for the current object,\n * altering how it will be transformed.\n * The transformer allows you to manipulate the copy of the current object,\n * and expects you to return the value that should take the current objects place.\n * @param nodeSpecificCallBacks Same as nodeCallBacks but using an additional level of indirection to\n * indicate the subType.\n * @return the result of transforming the requested descendant operations (based on the preVisitor)\n * using a transformer that works its way back up from the descendant to the startObject.\n */\n public transformNodeSpecific<Safe extends Safeness = 'safe', OutType = unknown>(\n startObject: object,\n nodeCallBacks: {[T in Nodes['type']]?: {\n transform?: (copy: SafeWrap<Safe, Extract<Nodes, Typed<T>>>, orig: Extract<Nodes, Typed<T>>) => unknown;\n preVisitor?: (orig: Extract<Nodes, Typed<T>>) => TransformContext;\n }},\n nodeSpecificCallBacks: {[Type in Nodes['type']]?: {\n [SubType in Extract<Nodes, SubTyped<Type>>['subType']]?: {\n transform?: (\n copy: SafeWrap<Safe, Extract<Nodes, SubTyped<Type, SubType>>>,\n orig: Extract<Nodes, SubTyped<Type, SubType>>,\n ) => unknown;\n preVisitor?: (op: Extract<Nodes, SubTyped<Type, SubType>>) => TransformContext;\n }}},\n ): Safe extends 'unsafe' ? OutType : unknown {\n const transformWrapper = (copy: object, orig: object): unknown => {\n let ogTransform: ((copy: any, orig: any) => unknown) | undefined;\n const casted = <SubTyped<Nodes['type']>>copy;\n if (casted.type && casted.subType) {\n const specific = nodeSpecificCallBacks[casted.type];\n if (specific) {\n ogTransform = specific[<keyof typeof specific> casted.subType]?.transform;\n }\n if (!ogTransform) {\n ogTransform = nodeCallBacks[casted.type]?.transform;\n }\n }\n return ogTransform ? ogTransform(casted, orig) : copy;\n };\n const preVisitWrapper = (curObject: object): TransformContext => {\n let ogPreVisit: ((node: any) => TransformContext) | undefined;\n const casted = <SubTyped<Nodes['type']>>curObject;\n if (casted.type && casted.subType) {\n const specific = nodeSpecificCallBacks[casted.type];\n if (specific) {\n ogPreVisit = specific[<keyof typeof specific> casted.subType]?.preVisitor;\n }\n if (!ogPreVisit) {\n ogPreVisit = nodeCallBacks[casted.type]?.preVisitor;\n }\n }\n return ogPreVisit ? ogPreVisit(casted) : {};\n };\n return <any> this.transformObject(startObject, transformWrapper, preVisitWrapper);\n }\n\n /**\n * Async variant of {@link transformNodeSpecific}, supporting promise-returning callbacks.\n * The traversal is strictly sequential (depth-first) - it does not parallelise siblings.\n */\n public transformNodeSpecificAsync<Safe extends Safeness = 'safe', OutType = unknown>(\n startObject: object,\n nodeCallBacks: {[T in Nodes['type']]?: {\n transform?: (\n copy: SafeWrap<Safe, Extract<Nodes, Typed<T>>>,\n orig: Extract<Nodes, Typed<T>>,\n ) => Awaitable<unknown>;\n preVisitor?: (orig: Extract<Nodes, Typed<T>>) => Awaitable<TransformContext>;\n }},\n nodeSpecificCallBacks: {[Type in Nodes['type']]?: {\n [SubType in Extract<Nodes, SubTyped<Type>>['subType']]?: {\n transform?: (\n copy: SafeWrap<Safe, Extract<Nodes, SubTyped<Type, SubType>>>,\n orig: Extract<Nodes, SubTyped<Type, SubType>>,\n ) => Awaitable<unknown>;\n preVisitor?: (op: Extract<Nodes, SubTyped<Type, SubType>>) => Awaitable<TransformContext>;\n }}},\n ): Promise<Safe extends 'unsafe' ? OutType : unknown> {\n const transformWrapper = (copy: object, orig: object): Awaitable<unknown> => {\n let ogTransform: ((copy: any, orig: any) => Awaitable<unknown>) | undefined;\n const casted = <SubTyped<Nodes['type']>>copy;\n if (casted.type && casted.subType) {\n const specific = nodeSpecificCallBacks[casted.type];\n if (specific) {\n ogTransform = specific[<keyof typeof specific> casted.subType]?.transform;\n }\n if (!ogTransform) {\n ogTransform = nodeCallBacks[casted.type]?.transform;\n }\n }\n return ogTransform ? ogTransform(casted, orig) : copy;\n };\n const preVisitWrapper = (curObject: object): Awaitable<TransformContext> => {\n let ogPreVisit: ((node: any) => Awaitable<TransformContext>) | undefined;\n const casted = <SubTyped<Nodes['type']>>curObject;\n if (casted.type && casted.subType) {\n const specific = nodeSpecificCallBacks[casted.type];\n if (specific) {\n ogPreVisit = specific[<keyof typeof specific> casted.subType]?.preVisitor;\n }\n if (!ogPreVisit) {\n ogPreVisit = nodeCallBacks[casted.type]?.preVisitor;\n }\n }\n return ogPreVisit ? ogPreVisit(casted) : {};\n };\n return <any> this.transformObjectAsync(startObject, transformWrapper, preVisitWrapper);\n }\n\n /**\n * Transform a single node pre-order,\n * the dual of {@link this.transformObjectPreOrder} with the same type specification\n * as {@link this.transformNodeSpecific}:\n * Similar to {@link TransformerTyped.transformNodePreOrder}, but also allowing you to target the subTypes:\n * the node is transformed _before_ its descendants, and we iterate into the result of that transformation,\n * making it the tool of choice for nodes that have to travel deeper into the tree, like a filter pushdown.\n *\n * Contrary to {@link this.transformNodeSpecific}, a callback does not just return the value taking the\n * place of the node, it returns a {@link PreOrderMappingReturn}: that value, plus the\n * {@link TransformContext} of that value, so there is no separate preVisitor.\n * Also contrary to {@link this.transformNodeSpecific}, the descendants of the node given to the callback\n * are not transformed yet: they are the nodes of the input tree itself.\n * @param startObject the object from which we will start the transformation,\n * potentially visiting and transforming its descendants along the way.\n * @param nodeCallBacks a dictionary mapping the various node types to a mapper.\n * The mapper allows you to manipulate the copy of the current node, and expects you to return the\n * value that should take the current nodes place, together with the context of that value.\n * That context steers how we iterate into the returned value.\n * @param nodeSpecificCallBacks Same as nodeCallBacks but using an additional level of indirection to\n * indicate the subType.\n * @return the result of transforming the startObject and the descendants of its rewrites.\n */\n public transformNodeSpecificPreOrder<Safe extends Safeness = 'safe', OutType = unknown>(\n startObject: object,\n nodeCallBacks: {[T in Nodes['type']]?:\n (copy: SafeWrap<Safe, Extract<Nodes, Typed<T>>>, orig: Extract<Nodes, Typed<T>>) => PreOrderMappingReturn;\n },\n nodeSpecificCallBacks: {[Type in Nodes['type']]?: {[SubType in Extract<Nodes, SubTyped<Type>>['subType']]?:\n (\n copy: SafeWrap<Safe, Extract<Nodes, SubTyped<Type, SubType>>>,\n orig: Extract<Nodes, SubTyped<Type, SubType>>,\n ) => PreOrderMappingReturn;\n }},\n ): Safe extends 'unsafe' ? OutType : unknown {\n const preTransformWrapper = (copy: object, orig: object): PreOrderMappingReturn => {\n let ogPreTransform: ((copy: any, orig: any) => PreOrderMappingReturn) | undefined;\n const casted = <SubTyped<Nodes['type']>> copy;\n if (casted.type && casted.subType) {\n const specific = nodeSpecificCallBacks[casted.type];\n if (specific) {\n ogPreTransform = specific[<keyof typeof specific> casted.subType];\n }\n if (!ogPreTransform) {\n ogPreTransform = nodeCallBacks[casted.type];\n }\n }\n return ogPreTransform ? ogPreTransform(copy, orig) : { newValue: copy };\n };\n return <any> this.transformObjectPreOrder(startObject, preTransformWrapper);\n }\n\n /**\n * Async variant of {@link transformNodeSpecificPreOrder}, supporting promise-returning callbacks.\n * The traversal is strictly sequential (depth-first) - it does not parallelise siblings.\n */\n public transformNodeSpecificPreOrderAsync<Safe extends Safeness = 'safe', OutType = unknown>(\n startObject: object,\n nodeCallBacks: {[T in Nodes['type']]?:\n (\n copy: SafeWrap<Safe, Extract<Nodes, Typed<T>>>,\n orig: Extract<Nodes, Typed<T>>,\n ) => Awaitable<PreOrderMappingReturn>;\n },\n nodeSpecificCallBacks: {[Type in Nodes['type']]?: {[SubType in Extract<Nodes, SubTyped<Type>>['subType']]?:\n (\n copy: SafeWrap<Safe, Extract<Nodes, SubTyped<Type, SubType>>>,\n orig: Extract<Nodes, SubTyped<Type, SubType>>,\n ) => Awaitable<PreOrderMappingReturn>;\n }},\n ): Promise<Safe extends 'unsafe' ? OutType : unknown> {\n const preTransformWrapper = (copy: object, orig: object): Awaitable<PreOrderMappingReturn> => {\n let ogPreTransform: ((copy: any, orig: any) => Awaitable<PreOrderMappingReturn>) | undefined;\n const casted = <SubTyped<Nodes['type']>> copy;\n if (casted.type && casted.subType) {\n const specific = nodeSpecificCallBacks[casted.type];\n if (specific) {\n ogPreTransform = specific[<keyof typeof specific> casted.subType];\n }\n if (!ogPreTransform) {\n ogPreTransform = nodeCallBacks[casted.type];\n }\n }\n return ogPreTransform ? ogPreTransform(copy, orig) : { newValue: copy };\n };\n return <any> this.transformObjectPreOrderAsync(startObject, preTransformWrapper);\n }\n\n /**\n * Visit a selected subTree given a startObject, steering the visits based on {@link Typed} nodes.\n * Similar to {@link this.visitNode}, but also allowing you to target subTypes.\n * Will call the preVisitor on the outer distinct, then the visitor of the special distinct,\n * followed by the visiting the outer distinct, printing '231'.\n * The pre-visitor visits starting from the root, going deeper, while the actual visitor goes in reverse.\n * @param startObject the object from which we will start visiting,\n * potentially visiting its descendants along the way.\n * @param nodeCallBacks a dictionary mapping the various operation types to objects optionally\n * containing preVisitor and visitor.\n * The preVisitor allows you to provide {@link VisitContext} for the current object,\n * altering how it will be visited.\n * The visitor allows you to visit the object from deepest to the outermost object.\n * This is useful if you for example want to manipulate the objects you visit during your visits,\n * similar to {@link mapOperation}.\n * @param nodeSpecificCallBacks Same as nodeCallBacks but using an additional level of indirection to\n * indicate the subType.\n */\n public visitNodeSpecific(\n startObject: object,\n nodeCallBacks: {[T in Nodes['type']]?: {\n visitor?: (op: Extract<Nodes, Typed<T>>) => void;\n preVisitor?: (op: Extract<Nodes, Typed<T>>) => VisitContext;\n }},\n nodeSpecificCallBacks: {[Type in Nodes['type']]?:\n {[Subtype in Extract<Nodes, SubTyped<Type>>['subType']]?: {\n visitor?: (op: Extract<Nodes, SubTyped<Type, Subtype>>) => void;\n preVisitor?: (op: Extract<Nodes, SubTyped<Type, Subtype>>) => VisitContext;\n }}},\n ): void {\n const visitWrapper = (curObject: object): void => {\n let ogTransform: ((node: any) => void) | undefined;\n const casted = <SubTyped<Nodes['type']>>curObject;\n if (casted.type && casted.subType) {\n const specific = nodeSpecificCallBacks[casted.type];\n if (specific) {\n ogTransform = specific[<keyof typeof specific> casted.subType]?.visitor;\n }\n if (!ogTransform) {\n ogTransform = nodeCallBacks[casted.type]?.visitor;\n }\n }\n if (ogTransform) {\n ogTransform(casted);\n }\n };\n const preVisitWrapper = (curObject: object): VisitContext => {\n let ogPreVisit: ((node: any) => VisitContext) | undefined;\n const casted = <SubTyped<Nodes['type']>>curObject;\n if (casted.type && casted.subType) {\n const specific = nodeSpecificCallBacks[casted.type];\n if (specific) {\n ogPreVisit = specific[<keyof typeof specific> casted.subType]?.preVisitor;\n }\n if (!ogPreVisit) {\n ogPreVisit = nodeCallBacks[casted.type]?.preVisitor;\n }\n }\n return ogPreVisit ? ogPreVisit(casted) : {};\n };\n this.visitObject(startObject, visitWrapper, preVisitWrapper);\n }\n\n /**\n * Async variant of {@link visitNodeSpecific}, supporting promise-returning callbacks.\n * The traversal is strictly sequential (depth-first) - it does not parallelise siblings.\n */\n public visitNodeSpecificAsync(\n startObject: object,\n nodeCallBacks: {[T in Nodes['type']]?: {\n visitor?: (op: Extract<Nodes, Typed<T>>) => Awaitable<void>;\n preVisitor?: (op: Extract<Nodes, Typed<T>>) => Awaitable<VisitContext>;\n }},\n nodeSpecificCallBacks: {[Type in Nodes['type']]?:\n {[Subtype in Extract<Nodes, SubTyped<Type>>['subType']]?: {\n visitor?: (op: Extract<Nodes, SubTyped<Type, Subtype>>) => Awaitable<void>;\n preVisitor?: (op: Extract<Nodes, SubTyped<Type, Subtype>>) => Awaitable<VisitContext>;\n }}},\n ): Promise<void> {\n const visitWrapper = (curObject: object): Awaitable<void> => {\n let ogTransform: ((node: any) => Awaitable<void>) | undefined;\n const casted = <SubTyped<Nodes['type']>>curObject;\n if (casted.type && casted.subType) {\n const specific = nodeSpecificCallBacks[casted.type];\n if (specific) {\n ogTransform = specific[<keyof typeof specific> casted.subType]?.visitor;\n }\n if (!ogTransform) {\n ogTransform = nodeCallBacks[casted.type]?.visitor;\n }\n }\n if (ogTransform) {\n return ogTransform(casted);\n }\n };\n const preVisitWrapper = (curObject: object): Awaitable<VisitContext> => {\n let ogPreVisit: ((node: any) => Awaitable<VisitContext>) | undefined;\n const casted = <SubTyped<Nodes['type']>>curObject;\n if (casted.type && casted.subType) {\n const specific = nodeSpecificCallBacks[casted.type];\n if (specific) {\n ogPreVisit = specific[<keyof typeof specific> casted.subType]?.preVisitor;\n }\n if (!ogPreVisit) {\n ogPreVisit = nodeCallBacks[casted.type]?.preVisitor;\n }\n }\n return ogPreVisit ? ogPreVisit(casted) : {};\n };\n return this.visitObjectAsync(startObject, visitWrapper, preVisitWrapper);\n }\n}\n", "import { symbols } from '../lexer/index.js';\nimport type { SparqlRule } from '../sparql11HelperTypes.js';\nimport type { Query, SparqlQuery, Update } from '../Sparql11types.js';\nimport { updateNoReuseBlankNodeLabels } from '../validation/validators.js';\nimport { prologue } from './general.js';\nimport type { HandledByBase } from './queryUnit.js';\nimport { query, askQuery, constructQuery, describeQuery, selectQuery, valuesClause } from './queryUnit.js';\nimport { update, update1 } from './updateUnit.js';\n\nexport * from './queryUnit.js';\nexport * from './updateUnit.js';\nexport * from './builtIn.js';\nexport * from './dataSetClause.js';\nexport * from './expression.js';\nexport * from '../expressionHelpers.js';\nexport * from './general.js';\nexport * from './literals.js';\nexport * from './propertyPaths.js';\nexport * from './solutionModifier.js';\nexport * from './tripleBlock.js';\nexport * from './whereClause.js';\n\n/**\n * Query or update, optimized for the Query case.\n * One could implement a new rule that does not use BACKTRACK.\n */\nexport const queryOrUpdate: SparqlRule<'queryOrUpdate', SparqlQuery> = {\n name: 'queryOrUpdate',\n impl: ({ ACTION, SUBRULE, OR1, OR2, MANY, OPTION1, CONSUME, SUBRULE2 }) => (C) => {\n const prologueValues = SUBRULE(prologue);\n return OR1<Query | Update>([\n { ALT: () => {\n const subType = OR2<Omit<Query, HandledByBase>>([\n { ALT: () => SUBRULE(selectQuery) },\n { ALT: () => SUBRULE(constructQuery) },\n { ALT: () => SUBRULE(describeQuery) },\n { ALT: () => SUBRULE(askQuery) },\n ]);\n const values = SUBRULE(valuesClause);\n return ACTION(() => (<Query>{\n context: prologueValues,\n ...subType,\n type: 'query',\n ...(values && { values }),\n loc: C.astFactory.sourceLocation(\n prologueValues.at(0),\n subType,\n values,\n ),\n }));\n } },\n { ALT: () => {\n const updates: Update['updates'] = [];\n updates.push({ context: prologueValues });\n let parsedSemi = true;\n MANY({\n GATE: () => parsedSemi,\n DEF: () => {\n parsedSemi = false;\n updates.at(-1)!.operation = SUBRULE(update1);\n\n OPTION1(() => {\n CONSUME(symbols.semi);\n\n parsedSemi = true;\n const innerPrologue = SUBRULE2(prologue);\n updates.push({ context: innerPrologue });\n });\n },\n });\n return ACTION(() => {\n const update = {\n type: 'update',\n updates,\n loc: C.astFactory.sourceLocation(\n ...updates.flatMap(x => [ ...x.context, x.operation ]),\n ),\n } satisfies Update;\n if (!C.skipValidation) {\n updateNoReuseBlankNodeLabels(update);\n }\n return update;\n });\n } },\n ]);\n },\n gImpl: ({ SUBRULE }) => (ast, { astFactory: F }) => {\n if (F.isQuery(ast)) {\n SUBRULE(query, ast);\n } else {\n SUBRULE(update, ast);\n }\n },\n};\n", "export * as builtIn from './BuiltInCalls.js';\nexport * as graph from './graph.js';\nexport * from './lexer.js';\nexport * as patterns from './lexerPatterns.js';\nexport * as symbols from './symbols.js';\nexport * as terminals from './terminals.js';\n", "/* eslint-disable require-unicode-regexp */\n\nimport { LexerBuilder, createToken } from '@traqula/core';\n\nexport enum BuiltInCalls {\n Str = 'builtInStr',\n Lang = 'builtInLang',\n Langmatches = 'builtInLangmatches',\n Datatype = 'builtInDatatype',\n Bound = 'builtInBound',\n Iri = 'builtInIri',\n Uri = 'builtInUri',\n Bnode = 'builtInBnode',\n Rand = 'builtInRand',\n Abs = 'builtInAbs',\n Ceil = 'builtInCeil',\n Floor = 'builtInFloor',\n Round = 'builtInRound',\n Concat = 'builtInConcat',\n Strlen = 'builtInStrlen',\n Ucase = 'builtInUcase',\n Lcase = 'builtInLcase',\n Encode_for_uri = 'builtInEncode_for_uri',\n Contains = 'builtInContains',\n Strstarts = 'builtInStrstarts',\n Strends = 'builtInStrends',\n Strbefore = 'builtInStrbefore',\n Strafter = 'builtInStrafter',\n Year = 'builtInYear',\n Month = 'builtInMonth',\n Day = 'builtInDay',\n Hours = 'builtInHours',\n Minutes = 'builtInMinutes',\n Seconds = 'builtInSeconds',\n Timezone = 'builtInTimezone',\n Tz = 'builtInTz',\n Now = 'builtInNow',\n Uuid = 'builtInUuid',\n Struuid = 'builtInStruuid',\n Md5 = 'builtInMd5',\n Sha1 = 'builtInSha1',\n Sha256 = 'builtInSha256',\n Sha384 = 'builtInSha384',\n Sha512 = 'builtInSha512',\n Coalesce = 'builtInCoalesce',\n If = 'builtInIf',\n Strlang = 'builtInStrlang',\n Strdt = 'builtInStrdt',\n Sameterm = 'builtInSameterm',\n Isiri = 'builtInIsiri',\n Isuri = 'builtInIsuri',\n Isblank = 'builtInIsblank',\n Isliteral = 'builtInIsliteral',\n Isnumeric = 'builtInIsnumeric',\n Regex = 'builtInRegex',\n Substr = 'builtInSubstr',\n Replace = 'builtInReplace',\n Exists = 'builtInExists',\n Notexists = 'builtInNotexists',\n Count = 'builtInCount',\n Sum = 'builtInSum',\n Min = 'builtInMin',\n Max = 'builtInMax',\n Avg = 'builtInAvg',\n Sample = 'builtInSample',\n Group_concat = 'builtInGroup_concat',\n}\n\nfunction capitalize<T extends string>(string: T): Capitalize<T> {\n return <Capitalize<T>> (string.charAt(0).toUpperCase() + string.slice(1));\n}\n\nexport const str = createToken({ name: capitalize(BuiltInCalls.Str), pattern: /str/i, label: 'STR' });\nexport const lang = createToken({ name: capitalize(BuiltInCalls.Lang), pattern: /lang/i, label: 'LANG' });\nexport const langmatches = createToken({\n name: capitalize(BuiltInCalls.Langmatches),\n pattern: /langmatches/i,\n label: 'LANGMATCHES',\n});\nexport const datatype = createToken({\n name: capitalize(BuiltInCalls.Datatype),\n pattern: /datatype/i,\n label: 'DATATYPE',\n});\nexport const bound = createToken({ name: capitalize(BuiltInCalls.Bound), pattern: /bound/i, label: 'BOUND' });\nexport const iri = createToken({ name: capitalize(BuiltInCalls.Iri), pattern: /iri/i, label: 'IRI' });\nexport const uri = createToken({ name: capitalize(BuiltInCalls.Uri), pattern: /uri/i, label: 'URI' });\nexport const bnode = createToken({ name: capitalize(BuiltInCalls.Bnode), pattern: /bnode/i, label: 'BNODE' });\nexport const rand = createToken({ name: capitalize(BuiltInCalls.Rand), pattern: /rand/i, label: 'RAND' });\nexport const abs = createToken({ name: capitalize(BuiltInCalls.Abs), pattern: /abs/i, label: 'ABS' });\nexport const ceil = createToken({ name: capitalize(BuiltInCalls.Ceil), pattern: /ceil/i, label: 'CEIL' });\nexport const floor = createToken({ name: capitalize(BuiltInCalls.Floor), pattern: /floor/i, label: 'FLOOR' });\nexport const round = createToken({ name: capitalize(BuiltInCalls.Round), pattern: /round/i, label: 'ROUND' });\nexport const concat = createToken({ name: capitalize(BuiltInCalls.Concat), pattern: /concat/i, label: 'CONCAT' });\nexport const strlen = createToken({ name: capitalize(BuiltInCalls.Strlen), pattern: /strlen/i, label: 'STRLEN' });\nexport const ucase = createToken({ name: capitalize(BuiltInCalls.Ucase), pattern: /ucase/i, label: 'UCASE' });\nexport const lcase = createToken({ name: capitalize(BuiltInCalls.Lcase), pattern: /lcase/i, label: 'LCASE' });\nexport const encode_for_uri = createToken({\n name: capitalize(BuiltInCalls.Encode_for_uri),\n pattern: /encode_for_uri/i,\n label: 'ENCODE_FOR_URI',\n});\nexport const contains = createToken({\n name: capitalize(BuiltInCalls.Contains),\n pattern: /contains/i,\n label: 'CONTAINS',\n});\nexport const strstarts = createToken({\n name: capitalize(BuiltInCalls.Strstarts),\n pattern: /strstarts/i,\n label: 'STRSTARTS',\n});\nexport const strends = createToken({ name: capitalize(BuiltInCalls.Strends), pattern: /strends/i, label: 'STRENDS' });\nexport const strbefore = createToken({\n name: capitalize(BuiltInCalls.Strbefore),\n pattern: /strbefore/i,\n label: 'STRBEFORE',\n});\nexport const strafter = createToken({\n name: capitalize(BuiltInCalls.Strafter),\n pattern: /strafter/i,\n label: 'STRAFTER',\n});\nexport const year = createToken({ name: capitalize(BuiltInCalls.Year), pattern: /year/i, label: 'YEAR' });\nexport const month = createToken({ name: capitalize(BuiltInCalls.Month), pattern: /month/i, label: 'MONTH' });\nexport const day = createToken({ name: capitalize(BuiltInCalls.Day), pattern: /day/i, label: 'DAY' });\nexport const hours = createToken({ name: capitalize(BuiltInCalls.Hours), pattern: /hours/i, label: 'HOURS' });\nexport const minutes = createToken({ name: capitalize(BuiltInCalls.Minutes), pattern: /minutes/i, label: 'MINUTES' });\nexport const seconds = createToken({ name: capitalize(BuiltInCalls.Seconds), pattern: /seconds/i, label: 'SECONDS' });\nexport const timezone = createToken({\n name: capitalize(BuiltInCalls.Timezone),\n pattern: /timezone/i,\n label: 'TIMEZONE',\n});\nexport const tz = createToken({ name: capitalize(BuiltInCalls.Tz), pattern: /tz/i, label: 'TZ' });\nexport const now = createToken({ name: capitalize(BuiltInCalls.Now), pattern: /now/i, label: 'NOW' });\nexport const uuid = createToken({ name: capitalize(BuiltInCalls.Uuid), pattern: /uuid/i, label: 'UUID' });\nexport const struuid = createToken({ name: capitalize(BuiltInCalls.Struuid), pattern: /struuid/i, label: 'STRUUID' });\nexport const md5 = createToken({ name: capitalize(BuiltInCalls.Md5), pattern: /md5/i, label: 'MD5' });\nexport const sha1 = createToken({ name: capitalize(BuiltInCalls.Sha1), pattern: /sha1/i, label: 'SHA1' });\nexport const sha256 = createToken({ name: capitalize(BuiltInCalls.Sha256), pattern: /sha256/i, label: 'SHA256' });\nexport const sha384 = createToken({ name: capitalize(BuiltInCalls.Sha384), pattern: /sha384/i, label: 'SHA384' });\nexport const sha512 = createToken({ name: capitalize(BuiltInCalls.Sha512), pattern: /sha512/i, label: 'SHA512' });\nexport const coalesce = createToken({\n name: capitalize(BuiltInCalls.Coalesce),\n pattern: /coalesce/i,\n label: 'COALESCE',\n});\nexport const if_ = createToken({ name: capitalize(BuiltInCalls.If), pattern: /if/i, label: 'IF' });\nexport const strlang = createToken({ name: capitalize(BuiltInCalls.Strlang), pattern: /strlang/i, label: 'STRLANG' });\nexport const strdt = createToken({ name: capitalize(BuiltInCalls.Strdt), pattern: /strdt/i, label: 'STRDT' });\nexport const sameterm = createToken({\n name: capitalize(BuiltInCalls.Sameterm),\n pattern: /sameterm/i,\n label: 'SAMETERM',\n});\nexport const isiri = createToken({ name: capitalize(BuiltInCalls.Isiri), pattern: /isiri/i, label: 'ISIRI' });\nexport const isuri = createToken({ name: capitalize(BuiltInCalls.Isuri), pattern: /isuri/i, label: 'ISURI' });\nexport const isblank = createToken({ name: capitalize(BuiltInCalls.Isblank), pattern: /isblank/i, label: 'ISBLANK' });\nexport const isliteral = createToken({\n name: capitalize(BuiltInCalls.Isliteral),\n pattern: /isliteral/i,\n label: 'ISLITERAL',\n});\nexport const isnumeric = createToken({\n name: capitalize(BuiltInCalls.Isnumeric),\n pattern: /isnumeric/i,\n label: 'ISNUMERIC',\n});\nexport const regex = createToken({ name: capitalize(BuiltInCalls.Regex), pattern: /regex/i, label: 'REGEX' });\nexport const substr = createToken({ name: capitalize(BuiltInCalls.Substr), pattern: /substr/i, label: 'SUBSTR' });\nexport const replace = createToken({ name: capitalize(BuiltInCalls.Replace), pattern: /replace/i, label: 'REPLACE' });\nexport const exists = createToken({ name: capitalize(BuiltInCalls.Exists), pattern: /exists/i, label: 'EXISTS' });\nexport const notexists = createToken({\n name: capitalize(BuiltInCalls.Notexists),\n pattern: /not exists/i,\n label: 'NOT EXISTS',\n});\nexport const count = createToken({ name: capitalize(BuiltInCalls.Count), pattern: /count/i, label: 'COUNT' });\nexport const sum = createToken({ name: capitalize(BuiltInCalls.Sum), pattern: /sum/i, label: 'SUM' });\nexport const min = createToken({ name: capitalize(BuiltInCalls.Min), pattern: /min/i, label: 'MIN' });\nexport const max = createToken({ name: capitalize(BuiltInCalls.Max), pattern: /max/i, label: 'MAX' });\nexport const avg = createToken({ name: capitalize(BuiltInCalls.Avg), pattern: /avg/i, label: 'AVG' });\nexport const sample = createToken({ name: capitalize(BuiltInCalls.Sample), pattern: /sample/i, label: 'SAMPLE' });\nexport const groupConcat = createToken({\n name: capitalize(BuiltInCalls.Group_concat),\n pattern: /group_concat/i,\n label: 'GROUP_CONCAT',\n});\n\nexport const allBuiltInCalls = LexerBuilder.create().add(\n langmatches,\n datatype,\n lang,\n bound,\n iri,\n uri,\n bnode,\n rand,\n abs,\n ceil,\n floor,\n round,\n concat,\n strlen,\n ucase,\n lcase,\n encode_for_uri,\n contains,\n strstarts,\n strends,\n strbefore,\n strafter,\n year,\n month,\n day,\n hours,\n minutes,\n seconds,\n timezone,\n tz,\n now,\n uuid,\n struuid,\n md5,\n sha1,\n sha256,\n sha384,\n sha512,\n coalesce,\n if_,\n strlang,\n strdt,\n sameterm,\n isiri,\n isuri,\n isblank,\n isliteral,\n isnumeric,\n regex,\n substr,\n replace,\n exists,\n notexists,\n count,\n sum,\n min,\n max,\n avg,\n sample,\n groupConcat,\n str,\n);\n", "/* eslint-disable require-unicode-regexp */\nimport { LexerBuilder, createToken } from '@traqula/core';\n\nexport const named = createToken({ name: 'NamedGraph', pattern: /named/i, label: 'NAMED' });\nexport const default_ = createToken({ name: 'DefaultGraph', pattern: /default/i, label: 'DEFAULT' });\nexport const graph = createToken({ name: 'Graph', pattern: /graph/i, label: 'GRAPH' });\nexport const graphAll = createToken({ name: 'GraphAll', pattern: /all/i, label: 'ALL' });\n\nexport const allGraphTokens = LexerBuilder.create().add(\n named,\n default_,\n graph,\n graphAll,\n);\n", "/* eslint-disable require-unicode-regexp,no-misleading-character-class,max-len,no-control-regex */\n\nexport const pnCharsBasePattern = /[A-Za-z\\u00C0-\\u00D6\\u00D8-\\u00F6\\u00F8-\\u02FF\\u0370-\\u037D\\u037F-\\u1FFF\\u200C\\u200D\\u2070-\\u218F\\u2C00-\\u2FEF\\u3001-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFFD]|[\\uD800-\\uDB7F][\\uDC00-\\uDFFF]/;\nexport const pnCharsUPattern = new RegExp(`(${pnCharsBasePattern.source})|_`);\nexport const varNamePattern = new RegExp(`((${pnCharsUPattern.source})|[0-9])((${pnCharsUPattern.source})|[0-9]|[\\u00B7\\u0300-\\u036F\\u203F-\\u2040])*`);\nexport const iriRefPattern = /<([^\\u0000-\\u0020\"<>\\\\^`{|}])*>/;\nexport const pnCharsPattern = new RegExp(`(${pnCharsUPattern.source})|[\\\\-0-9\\u00B7\\u0300-\\u036F\\u203F-\\u2040]`);\nexport const pnPrefixPattern = new RegExp(`(${pnCharsBasePattern.source})(((${pnCharsPattern.source})|\\\\.)*(${pnCharsPattern.source}))?`);\nexport const pNameNsPattern = new RegExp(`(${pnPrefixPattern.source})?:`);\nexport const percentPattern = /%[\\dA-Fa-f]{2}/;\n// \"A reserved character escape sequence consists of a \\ followed by one of these characters ~.-!$&'()*+,;=/?#@%_,\n// and represents the character to the right of the \\.\" - https://www.w3.org/TR/sparql12-query/#sec-escapes\n// The backslash itself cannot be escaped: https://www.w3.org/TR/sparql12-query/#rPN_LOCAL_ESC\nexport const pnLocalEscPattern = /\\\\[!#$%&'()*+,./;=?@_~-]/;\nexport const plxPattern = new RegExp(`(${percentPattern.source})|(${pnLocalEscPattern.source})`);\nexport const pnLocalPattern = new RegExp(`((${pnCharsUPattern.source})|:|[0-9]|(${plxPattern.source}))(((${pnCharsPattern.source})|\\\\.|:|(${plxPattern.source}))*((${pnCharsPattern.source})|:|(${plxPattern.source})))?`);\nexport const pNameLnPattern = new RegExp(`(${pNameNsPattern.source})(${pnLocalPattern.source})`);\nexport const blankNodeLabelPattern = new RegExp(`_:((${pnCharsUPattern.source})|[0-9])(((${pnCharsPattern.source})|\\\\.)*(${pnCharsPattern.source}))?`);\nexport const var1Pattern = new RegExp(`\\\\?(${varNamePattern.source})`);\nexport const var2Pattern = new RegExp(`\\\\$(${varNamePattern.source})`);\nexport const langTagPattern = /@[A-Za-z]+(-[\\dA-Za-z]+)*/;\nexport const integerPattern = /\\d+/;\nexport const decimalPattern = /\\d+\\.\\d+/;\nexport const exponentPattern = /[Ee][+-]?\\d+/;\nexport const doublePattern = new RegExp(`([0-9]+\\\\.[0-9]*(${exponentPattern.source}))|(\\\\.[0-9]+(${exponentPattern.source}))|([0-9]+(${exponentPattern.source}))`);\nexport const integerPositivePattern = new RegExp(`\\\\+(${integerPattern.source})`);\nexport const decimalPositivePattern = new RegExp(`\\\\+(${decimalPattern.source})`);\nexport const doublePositivePattern = new RegExp(`\\\\+(${doublePattern.source})`);\nexport const integerNegativePattern = new RegExp(`-(${integerPattern.source})`);\nexport const decimalNegativePattern = new RegExp(`-(${decimalPattern.source})`);\nexport const doubleNegativePattern = new RegExp(`-(${doublePattern.source})`);\nexport const echarPattern = /\\\\[\"'\\\\bfnrt]/;\nexport const stringLiteral1Pattern = new RegExp(`'(([^\\\\u0027\\\\u005C\\\\u000A\\u000D])|(${echarPattern.source}))*'`);\nexport const stringLiteral2Pattern = new RegExp(`\"(([^\\\\u0022\\\\u005C\\\\u000A\\\\u000D])|(${echarPattern.source}))*\"`);\nexport const stringLiteralLong1Pattern = new RegExp(`'''(('|(''))?([^'\\\\\\\\]|(${echarPattern.source})))*'''`);\nexport const stringLiteralLong2Pattern = new RegExp(`\"\"\"((\"|(\"\"))?([^\"\\\\\\\\]|(${echarPattern.source})))*\"\"\"`);\nexport const wsPattern = /[\\u0009\\u000A\\u000D ]/;\nexport const nilPattern = new RegExp(`\\\\((${wsPattern.source})*\\\\)`);\nexport const anonPattern = new RegExp(`\\\\[(${wsPattern.source})*\\\\]`);\nexport const commentPattern = /#[^\\n]*/;\n// Need to ensure the blank closes\nexport const atLeastOneBlankPattern = new RegExp(`(((${wsPattern.source})+)|((${commentPattern.source})\\n))+`);\n", "import { LexerBuilder, createToken } from '@traqula/core';\n\nexport const LCurly = createToken({ name: 'LCurly', pattern: '{', label: '{' });\nexport const RCurly = createToken({ name: 'RCurly', pattern: '}', label: '}' });\nexport const dot = createToken({ name: 'Dot', pattern: '.', label: '.' });\nexport const comma = createToken({ name: 'Comma', pattern: ',', label: ',' });\nexport const semi = createToken({ name: 'Semi', pattern: ';', label: ';' });\nexport const LParen = createToken({ name: 'LParen', pattern: '(', label: '(' });\nexport const RParen = createToken({ name: 'RParen', pattern: ')', label: ')' });\nexport const LSquare = createToken({ name: 'LSquare', pattern: '[', label: '[' });\nexport const RSquare = createToken({ name: 'RSquare', pattern: ']', label: ']' });\nexport const pipe = createToken({ name: 'Pipe', pattern: '|', label: '|' });\nexport const slash = createToken({ name: 'Slash', pattern: '/', label: '/' });\nexport const hat = createToken({ name: 'Hat', pattern: '^', label: '^' });\nexport const question = createToken({ name: 'Question', pattern: '?', label: '?' });\nexport const star = createToken({ name: 'Star', pattern: '*', label: '*' });\nexport const opPlus = createToken({ name: 'OpPlus', pattern: '+', label: '+' });\nexport const opMinus = createToken({ name: 'OpMinus', pattern: '-', label: '-' });\nexport const exclamation = createToken({ name: 'Exclamation', pattern: '!', label: '!' });\nexport const logicAnd = createToken({ name: 'LogicAnd', pattern: '&&', label: '&&' });\nexport const logicOr = createToken({ name: 'LogicOr', pattern: '||', label: '||' });\nexport const equal = createToken({ name: 'Equal', pattern: '=', label: '=' });\nexport const notEqual = createToken({ name: 'NotEqual', pattern: '!=', label: '!=' });\nexport const lessThan = createToken({ name: 'LessThan', pattern: '<', label: '<' });\nexport const greaterThan = createToken({ name: 'GreaterThan', pattern: '>', label: '>' });\nexport const lessThanEqual = createToken({ name: 'LessThanEqual', pattern: '<=', label: '<=' });\nexport const greaterThanEqual = createToken({ name: 'GreaterThanEqual', pattern: '>=', label: '>=' });\nexport const hathat = createToken({ name: 'Hathat', pattern: '^^', label: '^^' });\n\nexport const allSymbols = LexerBuilder.create().add(\n logicAnd,\n logicOr,\n notEqual,\n lessThanEqual,\n greaterThanEqual,\n LCurly,\n RCurly,\n dot,\n comma,\n semi,\n LParen,\n RParen,\n LSquare,\n RSquare,\n pipe,\n slash,\n hathat,\n hat,\n question,\n star,\n opPlus,\n opMinus,\n exclamation,\n equal,\n lessThan,\n greaterThan,\n);\n", "import { Lexer } from '@traqula/chevrotain';\nimport { LexerBuilder, createToken } from '@traqula/core';\nimport {\n anonPattern,\n blankNodeLabelPattern,\n commentPattern,\n decimalNegativePattern,\n decimalPattern,\n decimalPositivePattern,\n doubleNegativePattern,\n doublePattern,\n doublePositivePattern,\n integerNegativePattern,\n integerPattern,\n integerPositivePattern,\n iriRefPattern,\n langTagPattern,\n nilPattern,\n pNameLnPattern,\n pNameNsPattern,\n stringLiteral1Pattern,\n stringLiteral2Pattern,\n stringLiteralLong1Pattern,\n stringLiteralLong2Pattern,\n var1Pattern,\n var2Pattern,\n wsPattern,\n} from './lexerPatterns.js';\n\n/**\n * [[139]](https://www.w3.org/TR/sparql11-query/#rIRIREF)\n */\nexport const iriRef = createToken({ name: 'IriRef', pattern: iriRefPattern });\n/**\n * [[141]](https://www.w3.org/TR/sparql11-query/#rPNAME_LN)\n */\nexport const pNameLn = createToken({ name: 'PNameLn', pattern: pNameLnPattern });\n/**\n * [[140]](https://www.w3.org/TR/sparql11-query/#rPNAME_NS)\n */\nexport const pNameNs = createToken({ name: 'PNameNs', pattern: pNameNsPattern, longer_alt: [ pNameLn ]});\n/**\n * [[142]](https://www.w3.org/TR/sparql11-query/#rBLANK_NODE_LABEL)\n */\nexport const blankNodeLabel = createToken({ name: 'BlankNodeLabel', pattern: blankNodeLabelPattern });\n/**\n * [[143]](https://www.w3.org/TR/sparql11-query/#rVAR1)\n */\nexport const var1 = createToken({ name: 'Var1', pattern: var1Pattern });\n/**\n * [[144]](https://www.w3.org/TR/sparql11-query/#rVAR1)\n */\nexport const var2 = createToken({ name: 'Var2', pattern: var2Pattern });\n/**\n * [[145]](https://www.w3.org/TR/sparql11-query/#rLANGTAG)\n */\nexport const langTag = createToken({ name: 'LangTag', pattern: langTagPattern });\n/**\n * [[146]](https://www.w3.org/TR/sparql11-query/#rINTEGER)\n */\nexport const integer = createToken({ name: 'Integer', pattern: integerPattern });\n/**\n * [[148]](https://www.w3.org/TR/sparql11-query/#rDOUBLE)\n */\nexport const decimal = createToken({ name: 'Decimal', pattern: decimalPattern });\n/**\n * [[148]](https://www.w3.org/TR/sparql11-query/#rDOUBLE)\n */\nexport const double = createToken({ name: 'Double', pattern: doublePattern });\n/**\n * [[149]](https://www.w3.org/TR/sparql11-query/#rINTEGER_POSITIVE)\n */\nexport const integerPositive = createToken({ name: 'IntegerPositive', pattern: integerPositivePattern });\n/**\n * [[150]](https://www.w3.org/TR/sparql11-query/#rDECIMAL_POSITIVE)\n */\nexport const decimalPositive = createToken({ name: 'DecimalPositive', pattern: decimalPositivePattern });\n/**\n * [[151]](https://www.w3.org/TR/sparql11-query/#rDOUBLE_POSITIVE)\n */\nexport const doublePositive = createToken({ name: 'DoublePositive', pattern: doublePositivePattern });\n/**\n * [[152]](https://www.w3.org/TR/sparql11-query/#rINTEGER_NEGATIVE)\n */\nexport const integerNegative = createToken({ name: 'IntegerNegative', pattern: integerNegativePattern });\n/**\n * [[153]](https://www.w3.org/TR/sparql11-query/#rDECIMAL_NEGATIVE)\n */\nexport const decimalNegative = createToken({ name: 'DecimalNegative', pattern: decimalNegativePattern });\n/**\n * [[154]](https://www.w3.org/TR/sparql11-query/#rDOUBLE_NEGATIVE)\n */\nexport const doubleNegative = createToken({ name: 'DoubleNegative', pattern: doubleNegativePattern });\n/**\n * [[156]](https://www.w3.org/TR/sparql11-query/#rSTRING_LITERAL1)\n */\nexport const stringLiteral1 = createToken({ name: 'StringLiteral1', pattern: stringLiteral1Pattern });\n/**\n * [[157]](https://www.w3.org/TR/sparql11-query/#rSTRING_LITERAL1)\n */\nexport const stringLiteral2 = createToken({ name: 'StringLiteral2', pattern: stringLiteral2Pattern });\n/**\n * [[158]](https://www.w3.org/TR/sparql11-query/#rSTRING_LITERAL_LONG1)\n */\nexport const stringLiteralLong1 = createToken({ name: 'StringLiteralLong1', pattern: stringLiteralLong1Pattern });\n/**\n * [[159]]https://www.w3.org/TR/sparql11-query/#rSTRING_LITERAL_LONG2)\n */\nexport const stringLiteralLong2 = createToken({ name: 'StringLiteralLong2', pattern: stringLiteralLong2Pattern });\n/**\n * https://www.w3.org/TR/sparql11-query/#rWS\n */\nexport const ws = createToken({ name: 'Ws', pattern: wsPattern, group: Lexer.SKIPPED });\nexport const comment = createToken({ name: 'Comment', pattern: commentPattern, group: Lexer.SKIPPED });\n/**\n * [[161]](https://www.w3.org/TR/sparql11-query/#rNIL)\n */\nexport const nil = createToken({ name: 'Nil', pattern: nilPattern });\n/**\n * [[163]](https://www.w3.org/TR/sparql11-query/#rANON)\n */\nexport const anon = createToken({ name: 'Anon', pattern: anonPattern });\n\nexport const allTerminals = LexerBuilder.create().add(\n iriRef,\n pNameNs,\n pNameLn,\n blankNodeLabel,\n var1,\n var2,\n langTag,\n double,\n decimal,\n integer,\n doublePositive,\n decimalPositive,\n integerPositive,\n doubleNegative,\n decimalNegative,\n integerNegative,\n stringLiteralLong1,\n stringLiteralLong2,\n stringLiteral1,\n stringLiteral2,\n ws,\n comment,\n nil,\n anon,\n);\n", "/* eslint-disable require-unicode-regexp */\nimport { LexerBuilder, createToken } from '@traqula/core';\nimport { allBuiltInCalls, avg, groupConcat } from './BuiltInCalls.js';\nimport { allGraphTokens, graphAll } from './graph.js';\nimport { atLeastOneBlankPattern } from './lexerPatterns.js';\nimport { allSymbols } from './symbols.js';\nimport { allTerminals } from './terminals.js';\n\nexport const baseDecl = createToken({ name: 'BaseDecl', pattern: /base/i, label: 'BASE' });\nexport const prefixDecl = createToken({ name: 'PrefixDecl', pattern: /prefix/i, label: 'PREFIX' });\nexport const select = createToken({ name: 'Select', pattern: /select/i, label: 'SELECT' });\nexport const distinct = createToken({ name: 'Distinct', pattern: /distinct/i, label: 'DISTINCT' });\nexport const reduced = createToken({ name: 'Reduced', pattern: /reduced/i, label: 'REDUCED' });\nexport const as = createToken({ name: 'As', pattern: /as/i, label: 'AS' });\nexport const construct = createToken({ name: 'Construct', pattern: /construct/i, label: 'CONSTRUCT' });\nexport const describe = createToken({ name: 'Describe', pattern: /describe/i, label: 'DESCRIBE' });\nexport const ask = createToken({ name: 'Ask', pattern: /ask/i, label: 'ASK' });\nexport const from = createToken({ name: 'From', pattern: /from/i, label: 'FROM' });\nexport const where = createToken({ name: 'Where', pattern: /where/i, label: 'WHERE' });\nexport const groupByGroup = createToken({ name: 'GroupByGroup', pattern: /group/i, label: '_GROUP_ BY' });\nexport const by = createToken({ name: 'By', pattern: /by/i, label: 'BY' });\nexport const having = createToken({ name: 'Having', pattern: /having/i, label: 'HAVING' });\nexport const order = createToken({ name: 'Order', pattern: /order/i, label: '_ORDER_ BY' });\nexport const orderAsc = createToken({ name: 'OrderAsc', pattern: /asc/i, label: 'ASC' });\nexport const orderDesc = createToken({ name: 'OrderDesc', pattern: /desc/i, label: 'DESC' });\nexport const limit = createToken({ name: 'Limit', pattern: /limit/i, label: 'LIMIT' });\nexport const offset = createToken({ name: 'Offset', pattern: /offset/i, label: 'OFFSET' });\nexport const values = createToken({ name: 'Values', pattern: /values/i, label: 'VALUES' });\nexport const load = createToken({ name: 'Load', pattern: /load/i, label: 'LOAD' });\nexport const silent = createToken({ name: 'Silent', pattern: /silent/i, label: 'SILENT' });\nexport const loadInto = createToken({ name: 'LoadInto', pattern: /into/i, label: 'INTO' });\nexport const clear = createToken({ name: 'Clear', pattern: /clear/i, label: 'CLEAR' });\nexport const drop = createToken({ name: 'Drop', pattern: /drop/i, label: 'DROP' });\nexport const create = createToken({ name: 'Create', pattern: /create/i, label: 'CREATE' });\nexport const add = createToken({ name: 'Add', pattern: /add/i, label: 'ADD' });\nexport const to = createToken({ name: 'To', pattern: /to/i, label: 'TO' });\nexport const move = createToken({ name: 'Move', pattern: /move/i, label: 'MOVE' });\nexport const copy = createToken({ name: 'Copy', pattern: /copy/i, label: 'COPY' });\nexport const modifyWith = createToken({ name: 'ModifyWith', pattern: /with/i, label: 'WITH' });\nexport const deleteDataClause = createToken({\n name: 'DeleteDataClause',\n pattern: new RegExp(`delete(${atLeastOneBlankPattern.source})data`, 'i'),\n label: 'DELETE DATA',\n});\nexport const deleteWhereClause = createToken({\n name: 'DeleteWhereClause',\n pattern: new RegExp(`delete(${atLeastOneBlankPattern.source})where`, 'i'),\n label: 'DELETE WHERE',\n});\nexport const deleteClause = createToken({ name: 'DeleteClause', pattern: /delete/i, label: 'DELETE' });\nexport const insertDataClause = createToken({\n name: 'InsertDataClause',\n pattern: new RegExp(`insert(${atLeastOneBlankPattern.source})data`, 'i'),\n label: 'INSERT DATA',\n});\nexport const insertClause = createToken({ name: 'InsertClause', pattern: /insert/i, label: 'insert' });\nexport const usingClause = createToken({ name: 'UsingClause', pattern: /using/i, label: 'USING' });\nexport const optional = createToken({ name: 'Optional', pattern: /optional/i, label: 'OPTIONAL' });\nexport const service = createToken({ name: 'Service', pattern: /service/i, label: 'SERVICE' });\nexport const bind = createToken({ name: 'Bind', pattern: /bind/i, label: 'BIND' });\nexport const undef = createToken({ name: 'Undef', pattern: /undef/i, label: 'UNDEF' });\nexport const minus = createToken({ name: 'Minus', pattern: /minus/i, label: 'MINUS' });\nexport const union = createToken({ name: 'Union', pattern: /union/i, label: 'UNION' });\nexport const filter = createToken({ name: 'Filter', pattern: /filter/i, label: 'FILTER' });\nexport const a = createToken({ name: 'a', pattern: 'a', label: 'type declaration \\'a\\'' });\nexport const true_ = createToken({ name: 'True', pattern: /true/i, label: 'true' });\nexport const false_ = createToken({ name: 'False', pattern: /false/i, label: 'false' });\nexport const in_ = createToken({ name: 'In', pattern: /in/i, label: 'IN' });\n// eslint-disable-next-line unicorn/better-regex,no-control-regex\nexport const notIn = createToken({ name: 'NotIn', pattern: /not[\\u0020\\u0009\\u000D\\u000A]+in/i, label: 'NOT IN' });\nexport const separator = createToken({ name: 'Separator', pattern: /separator/i, label: 'SEPARATOR' });\n\nexport const allBaseTokens = LexerBuilder.create().add(\n baseDecl,\n prefixDecl,\n select,\n distinct,\n reduced,\n construct,\n describe,\n ask,\n from,\n where,\n having,\n groupByGroup,\n by,\n order,\n orderAsc,\n orderDesc,\n limit,\n offset,\n values,\n load,\n silent,\n loadInto,\n clear,\n drop,\n create,\n add,\n to,\n move,\n copy,\n modifyWith,\n deleteWhereClause,\n deleteDataClause,\n deleteClause,\n insertDataClause,\n insertClause,\n usingClause,\n optional,\n service,\n bind,\n undef,\n minus,\n union,\n filter,\n as,\n a,\n true_,\n false_,\n in_,\n notIn,\n separator,\n);\n\n/**\n * [!!!ORDER MATTERS!!!](https://chevrotain.io/docs/tutorial/step1_lexing.html#creating-the-lexer)\n */\nexport const sparql11LexerBuilder = LexerBuilder\n .create(allTerminals)\n .merge(allBaseTokens)\n .merge(allBuiltInCalls)\n .merge(allGraphTokens)\n .merge(allSymbols)\n .moveAfter(avg, a)\n .moveBefore(a, graphAll)\n .moveAfter(groupConcat, groupByGroup);\n", "import { AstFactory } from '../astFactory.js';\nimport type {\n Wildcard,\n Expression,\n ExpressionAggregate,\n Pattern,\n PatternBgp,\n QuerySelect,\n TermVariable,\n SolutionModifierGroupBind,\n Update,\n PatternBind,\n Sparql11Nodes,\n} from '../Sparql11types.js';\nimport { AstTransformer } from '../utils.js';\n\nconst F = new AstFactory();\nconst transformer = new AstTransformer();\n\n/**\n * Get all 'aggregate' rules from an expression\n */\nexport function getAggregatesOfExpression(expression: Expression): ExpressionAggregate[] {\n if (F.isExpressionAggregate(expression)) {\n return [ expression ];\n }\n if (F.isExpressionOperator(expression)) {\n const aggregates: ExpressionAggregate[] = [];\n for (const arg of expression.args) {\n aggregates.push(...getAggregatesOfExpression(arg));\n }\n return aggregates;\n }\n return [];\n}\n\n/**\n * Return the variable value id of an expression if bounded\n */\nexport function getExpressionId(expression: SolutionModifierGroupBind | Expression | TermVariable): string | undefined {\n // Check if grouping\n if (F.isTerm(expression) && F.isTermVariable(expression)) {\n return expression.value;\n }\n if (F.isExpression(expression)) {\n if (F.isExpressionAggregate(expression) && F.isTermVariable(expression.expression[0])) {\n return expression.expression[0].value;\n }\n return undefined;\n }\n return expression.variable.value;\n}\n\n/**\n * Get all variables used in an expression\n */\nexport function getVariablesFromExpression(expression: Expression, variables: Set<string>): void {\n if (F.isExpressionOperator(expression)) {\n for (const expr of expression.args) {\n getVariablesFromExpression(expr, variables);\n }\n } else if (F.isTerm(expression) && F.isTermVariable(expression)) {\n variables.add(expression.value);\n }\n}\n\n/**\n * Verify that the projected variables (select head) are allowed:\n * - no group-by on select *\n * - if group-by, selected variables need to be collected by the group-by\n * - 'select ?var as ?other', ?other cannot be in scope\n */\nexport function queryProjectionIsGood(query: Pick<QuerySelect, 'variables' | 'solutionModifiers' | 'where'>): void {\n // NoGroupByOnWildcardSelect\n if (query.variables.length === 1 && F.isWildcard(query.variables[0])) {\n if (query.solutionModifiers.group !== undefined) {\n throw new Error('GROUP BY not allowed with wildcard');\n }\n return;\n }\n\n // CannotProjectUngroupedVars - can be skipped if `SELECT *`\n // Check for projection of ungrouped variable\n // Check can be skipped in case of wildcard select.\n const variables = <Exclude<typeof query.variables, [Wildcard]>> query.variables;\n const hasCountAggregate = variables.flatMap(\n varVal => F.isTerm(varVal) ? [] : getAggregatesOfExpression(varVal.expression),\n ).some(agg => agg.aggregation === 'count' && !agg.expression.some(arg => F.isWildcard(arg)));\n const groupBy = query.solutionModifiers.group;\n if (hasCountAggregate || groupBy) {\n // We have to check whether\n // 1. Variables used in projection are usable given the group by clause\n // 2. A selectCount will create an implicit group by clause.\n for (const selectVar of variables) {\n if (F.isTerm(selectVar)) {\n if (!groupBy || !groupBy.groupings.map(groupvar => getExpressionId(groupvar))\n .includes((getExpressionId(selectVar)))) {\n throw new Error('Variable not allowed in projection');\n }\n } else if (getAggregatesOfExpression(selectVar.expression).length === 0) {\n // Current value binding does not use aggregates\n const usedvars = new Set<string>();\n getVariablesFromExpression(selectVar.expression, usedvars);\n for (const usedvar of usedvars) {\n if (!groupBy || !groupBy.groupings.map(groupVar => getExpressionId(groupVar))\n .includes(usedvar)) {\n throw new Error(`Use of ungrouped variable in projection of operation (?${usedvar})`);\n }\n }\n }\n }\n }\n\n // NOTE 12: Check if id of each AS-selected column is not yet bound by subquery\n const subqueries = query.where.patterns.filter(pattern => pattern.type === 'query');\n if (subqueries.length > 0) {\n const selectBoundedVars = new Set<string>();\n for (const variable of variables) {\n if ('variable' in variable) {\n selectBoundedVars.add(variable.variable.value);\n }\n }\n\n // Look at in scope variables\n const vars = subqueries.flatMap<TermVariable | PatternBind | Wildcard>(sub => sub.variables)\n .map(v => F.isTerm(v) ? v.value : (F.isWildcard(v) ? '*' : v.variable.value));\n const subqueryIds = new Set(vars);\n for (const selectedVarId of selectBoundedVars) {\n if (subqueryIds.has(selectedVarId)) {\n throw new Error(`Target id of 'AS' (?${selectedVarId}) already used in subquery`);\n }\n }\n }\n}\n\nexport function findPatternBoundedVars(\n op: Sparql11Nodes | undefined | (Sparql11Nodes | undefined)[],\n boundedVars: Set<string>,\n): void {\n function recurse(x: Parameters<(typeof findPatternBoundedVars)>[0]): void {\n findPatternBoundedVars(x, boundedVars);\n }\n if (op === undefined) {\n return;\n }\n if (Array.isArray(op)) {\n for (const iter of op) {\n recurse(iter);\n }\n } else if (F.isQuery(op)) {\n if (F.isQuerySelect(op) || F.isQueryDescribe(op)) {\n recurse([\n ...(op.variables.some(x => F.isWildcard(x)) ? [ op.where ] : op.variables),\n op.solutionModifiers.group,\n op.values,\n ]);\n } else {\n recurse(op.solutionModifiers.group);\n }\n } else if (F.isTriple(op)) {\n recurse([ op.subject, op.predicate, op.object ]);\n } else if (F.isPathPure(op)) {\n recurse(op.items);\n } else if (F.isTripleCollection(op)) {\n recurse([ op.identifier, ...op.triples ]);\n } else if (F.isSolutionModifierGroup(op)) {\n recurse(op.groupings.filter(g => 'variable' in g).map(x => x.variable));\n } else if (F.isSolutionModifierHaving(op)) {\n recurse(op.having);\n } else if (F.isSolutionModifierOrder(op)) {\n recurse(op.orderDefs.map(x => x.expression));\n } else if (F.isPatternValues(op)) {\n for (const v of Object.keys(op.values.at(0) ?? {})) {\n boundedVars.add(v);\n }\n } else if (F.isPatternBgp(op)) {\n recurse(op.triples);\n } else if (F.isPatternGroup(op) || F.isPatternUnion(op) || F.isPatternOptional(op)) {\n recurse(op.patterns);\n } else if (F.isPatternService(op) || F.isPatternGraph(op)) {\n recurse([ op.name, ...op.patterns ]);\n } else if (F.isPatternBind(op)) {\n recurse(op.variable);\n } else if (F.isTermVariable(op)) {\n boundedVars.add(op.value);\n }\n}\n\n/**\n * NOTE 13 and https://www.w3.org/TR/sparql11-query/#variableScope\n * > In BIND (expr AS v) requires that the variable v is not in-scope from the preceeding elements in the\n * group graph pattern in which it is used.\n */\nexport function checkNote13(patterns: Pattern[]): void {\n for (const [ index, pattern ] of patterns.entries()) {\n if (F.isPatternBind(pattern) && index > 0 && F.isPatternBgp(patterns[index - 1])) {\n const bgp = patterns[index - 1];\n // Find variables used.\n const variables: TermVariable[] = [];\n // TODO: this is slow! 2.6% self execution\n transformer.visitNodeSpecific(bgp, {}, { term: { variable: { visitor: (var_) => {\n variables.push(var_);\n } }}});\n if (variables.some(var_ => var_.value === pattern.variable.value)) {\n throw new Error(`Variable used to bind is already bound (?${pattern.variable.value})`);\n }\n }\n }\n\n const boundedVars = new Set<string>();\n for (const pattern of patterns) {\n // Element can be bind, in that case, check note 13. If it is not, buildup set of bounded variables.\n if (F.isPatternBind(pattern)) {\n if (boundedVars.has(pattern.variable.value)) {\n throw new Error(`Variable used to bind is already bound (?${pattern.variable.value})`);\n }\n } else {\n findPatternBoundedVars(pattern, boundedVars);\n }\n }\n}\n\n/**\n * https://www.w3.org/TR/sparql11-query/#grammarBNodes\n * > two INSERT DATA operations within a single SPARQL Update request\n */\nexport function updateNoReuseBlankNodeLabels(updateQuery: Update): void {\n const blankLabelsUsedInInsertData = new Set<string>();\n for (const update of updateQuery.updates) {\n if (!update.operation) {\n continue;\n }\n const operation = update.operation;\n if (operation.subType === 'insertdata') {\n const blankNodesHere = new Set<string>();\n transformer.visitNodeSpecific(operation, {}, { term: { blankNode: { visitor: (blankNode) => {\n blankNodesHere.add(blankNode.label);\n if (blankLabelsUsedInInsertData.has(blankNode.label)) {\n throw new Error('Detected reuse blank node across different INSERT DATA clauses');\n }\n } }}});\n for (const blankNode of blankNodesHere) {\n blankLabelsUsedInInsertData.add(blankNode);\n }\n }\n }\n}\n\n/**\n * https://www.w3.org/TR/sparql11-query/#bgpBNodeLabels\n * > A label can be used in only a single basic graph pattern in any query.\n */\nexport function checkBlankNodeBGPScope(patterns: Pattern[]): void {\n const labelOwner = new Map<string, object>();\n\n // Each entry is a unique object used only as an identity marker for \"the current scope\"\n const scopeStack: object[] = [{}];\n const currentScope = (): object => scopeStack.at(-1)!;\n\n function collectBlankNodeLabels(bgp: PatternBgp): Set<string> {\n const labels = new Set<string>();\n transformer.visitNodeSpecific(bgp, {}, { term: { blankNode: { visitor: (blankNode) => {\n labels.add(blankNode.label);\n } }}});\n return labels;\n }\n\n // Introduces a new blank node scope on entry.\n // Pops the introduced scope and resets the parent scope on exit.\n const newBlankNodeScopeHandler = {\n preVisitor: () => {\n scopeStack.push({});\n return {};\n },\n visitor: () => {\n scopeStack.pop();\n // Within a list of patterns, seeing this pattern breaks the scope of the list of patterns.\n // BIND and FILTER do not break the scope since when transforming to algebra, they are collected separately:\n // https://www.w3.org/TR/sparql12-query/#sparqlCollectFilters\n scopeStack[scopeStack.length - 1] = {};\n },\n };\n\n transformer.visitNodeSpecific(\n patterns,\n {\n query: {\n preVisitor: () => ({ continue: false }),\n },\n pattern: newBlankNodeScopeHandler,\n },\n {\n pattern: {\n bgp: {\n preVisitor: (bgp) => {\n const scope = currentScope();\n for (const label of collectBlankNodeLabels(bgp)) {\n const owner = labelOwner.get(label);\n if (owner !== undefined && owner !== scope) {\n throw new Error(\n `Detected reuse of blank node across two different basic graph patterns (_:${\n label.replace(/^[eg]_/u, '')})`,\n );\n }\n labelOwner.set(label, scope);\n }\n return { continue: false };\n },\n visitor: () => {},\n },\n // FILTER (not) EXISTS introduces a new scope.\n // Unlike newBlankScopeHandler, we only pop on exit, we don't reset the parent scope;\n // labels can still be reused after a FILTER or (not) EXISTS.\n filter: {\n preVisitor: () => {\n scopeStack.push({});\n return {};\n },\n visitor: () => {\n scopeStack.pop();\n },\n },\n },\n },\n );\n}\n", "import type { AstCoreFactory, SubTyped, SourceLocation } from '@traqula/core';\nimport type {\n ContextDefinitionBase,\n ContextDefinitionPrefix,\n TermIriFull,\n} from '../Sparql11types.js';\nimport type { Constructor } from './mixins.js';\n\ntype NodeType = 'contextDef';\nconst nodeType: NodeType = 'contextDef';\n\n// eslint-disable-next-line ts/explicit-function-return-type\nexport function ContextFactoryMixin<TBase extends Constructor<AstCoreFactory>>(Base: TBase) {\n return class ContextFactory extends Base {\n public contextDefinitionPrefix(loc: SourceLocation, key: string, value: TermIriFull): ContextDefinitionPrefix {\n return {\n type: nodeType,\n subType: 'prefix',\n key,\n value,\n loc,\n };\n }\n\n public isContextDefinitionPrefix(contextDef: object): contextDef is SubTyped<NodeType, 'prefix'> {\n return this.isOfSubType(contextDef, nodeType, 'prefix');\n }\n\n public contextDefinitionBase(loc: SourceLocation, value: TermIriFull): ContextDefinitionBase {\n return {\n type: 'contextDef',\n subType: 'base',\n value,\n loc,\n };\n }\n\n public isContextDefinitionBase(contextDef: object): contextDef is SubTyped<NodeType, 'base'> {\n return this.isOfSubType(contextDef, nodeType, 'base');\n }\n };\n}\n", "import type { AstCoreFactory, SourceLocation, Typed, SubTyped } from '@traqula/core';\nimport type {\n Expression,\n ExpressionAggregate,\n ExpressionAggregateDefault,\n ExpressionAggregateOnWildcard,\n ExpressionAggregateSeparator,\n ExpressionFunctionCall,\n ExpressionOperation,\n ExpressionPatternOperation,\n PatternGroup,\n TermIri,\n Wildcard,\n} from '../Sparql11types.js';\nimport type { Constructor } from './mixins.js';\n\ntype NodeType = 'expression';\nconst nodeType: NodeType = 'expression';\n\n// eslint-disable-next-line ts/explicit-function-return-type\nexport function ExpressionFactoryMixin<TBase extends Constructor<AstCoreFactory>>(Base: TBase) {\n return class ExpressionFactory extends Base {\n public isExpressionPure(obj: object): obj is Typed<NodeType> {\n return this.isOfType(obj, nodeType);\n }\n\n public formatOperator(operator: string): string {\n return operator.toLowerCase().replaceAll(' ', '');\n }\n\n public expressionOperation<Args extends Expression[]>(\n operator: string,\n args: Args,\n loc: SourceLocation,\n ): ExpressionOperation & { args: Args } {\n return {\n type: nodeType,\n subType: 'operation',\n operator: this.formatOperator(operator),\n args,\n loc,\n };\n }\n\n public isExpressionOperator(obj: object): obj is SubTyped<NodeType, 'operation'> {\n return this.isOfSubType(obj, nodeType, 'operation');\n }\n\n public expressionFunctionCall<Args extends Expression[]>(\n functionOp: TermIri,\n args: Args,\n distinct: boolean,\n loc: SourceLocation,\n ): ExpressionFunctionCall & { args: Args } {\n return {\n type: 'expression',\n subType: 'functionCall',\n function: functionOp,\n args,\n distinct,\n loc,\n };\n }\n\n public isExpressionFunctionCall(obj: object): obj is SubTyped<NodeType, 'functionCall'> {\n return this.isOfSubType(obj, nodeType, 'functionCall');\n }\n\n public expressionPatternOperation(\n operator: string,\n args: PatternGroup,\n loc: SourceLocation,\n ): ExpressionPatternOperation {\n return {\n type: nodeType,\n subType: 'patternOperation',\n operator: this.formatOperator(operator),\n args,\n loc,\n };\n }\n\n public isExpressionPatternOperation(obj: object): obj is SubTyped<NodeType, 'patternOperation'> {\n return this.isOfSubType(obj, nodeType, 'patternOperation');\n }\n\n public aggregate(\n aggregation: string,\n distinct: boolean,\n arg: Expression,\n separator: undefined,\n loc: SourceLocation\n ): ExpressionAggregateDefault;\n public aggregate(\n aggregation: string,\n distinct: boolean,\n arg: Wildcard,\n separator: undefined,\n loc: SourceLocation\n ): ExpressionAggregateOnWildcard;\n public aggregate(\n aggregation: string,\n distinct: boolean,\n arg: Expression,\n separator: string,\n loc: SourceLocation\n ): ExpressionAggregateSeparator;\n public aggregate(\n aggregation: string,\n distinct: boolean,\n arg: Expression | Wildcard,\n separator: string | undefined,\n loc: SourceLocation,\n ): ExpressionAggregate;\n public aggregate(\n aggregation: string,\n distinct: boolean,\n arg: Expression | Wildcard,\n separator: string | undefined,\n loc: SourceLocation,\n ): ExpressionAggregate {\n const base = <const> {\n type: 'expression',\n subType: 'aggregate',\n aggregation: this.formatOperator(aggregation),\n distinct,\n loc,\n };\n if (this.isOfType(arg, 'wildcard')) {\n return { ...base, expression: [ arg ]} satisfies ExpressionAggregateOnWildcard;\n }\n if (separator === undefined) {\n return { ...base, expression: [ arg ]} satisfies ExpressionAggregateDefault;\n }\n return { ...base, expression: [ arg ], separator } satisfies ExpressionAggregateSeparator;\n }\n\n public isExpressionAggregate(obj: object): obj is SubTyped<NodeType, 'aggregate'> {\n return this.isOfSubType(obj, nodeType, 'aggregate');\n }\n\n public isExpressionAggregateSeparator(obj: object): obj is SubTyped<NodeType, 'aggregate'> & { separator: string } {\n return this.isOfSubType(obj, nodeType, 'aggregate') &&\n typeof (<{ separator?: unknown }> obj).separator === 'string';\n }\n\n public isExpressionAggregateOnWildcard(obj: object):\n obj is SubTyped<NodeType, 'aggregate'> & { expression: [Typed<'wildcard'>]} {\n const casted = <{ expression?: unknown }> obj;\n return this.isOfSubType(obj, nodeType, 'aggregate') && Array.isArray(casted.expression) &&\n casted.expression.length === 1 && this.isOfType(casted.expression[0], 'wildcard');\n }\n\n public isExpressionAggregateDefault(obj: object):\n obj is SubTyped<NodeType, 'aggregate'> & { expression: [Expression]} {\n const casted = <{ expression?: unknown }> obj;\n\n return this.isOfSubType(obj, nodeType, 'operation') && Array.isArray(casted.expression) &&\n casted.expression.length === 1 && !this.isOfType(casted.expression[0], 'wildcard');\n }\n };\n}\n", "import type { AstCoreFactory, SubTyped, SourceLocation, Typed } from '@traqula/core';\nimport type {\n GraphRefAll,\n GraphRefDefault,\n GraphRefNamed,\n GraphRefSpecific,\n TermIri,\n} from '../Sparql11types.js';\nimport type { Constructor } from './mixins.js';\n\ntype NodeType = 'graphRef';\nconst nodeType: NodeType = 'graphRef';\n\n// eslint-disable-next-line ts/explicit-function-return-type\nexport function GraphRefFactoryMixin<TBase extends Constructor<AstCoreFactory>>(Base: TBase) {\n return class GraphRefFactory extends Base {\n public isGraphRef(obj: object): obj is Typed<NodeType> {\n return this.isOfType(obj, nodeType);\n }\n\n public graphRefDefault(loc: SourceLocation): GraphRefDefault {\n return {\n type: nodeType,\n subType: 'default',\n loc,\n };\n }\n\n public isGraphRefDefault(graphRef: object): graphRef is SubTyped<NodeType, 'default'> {\n return this.isOfSubType(graphRef, nodeType, 'default');\n }\n\n public graphRefNamed(loc: SourceLocation): GraphRefNamed {\n return {\n type: nodeType,\n subType: 'named',\n loc,\n };\n }\n\n public isGraphRefNamed(graphRef: object): graphRef is SubTyped<NodeType, 'named'> {\n return this.isOfSubType(graphRef, nodeType, 'named');\n }\n\n public graphRefAll(loc: SourceLocation): GraphRefAll {\n return {\n type: nodeType,\n subType: 'all',\n loc,\n };\n }\n\n public isGraphRefAll(graphRef: object): graphRef is SubTyped<NodeType, 'all'> {\n return this.isOfSubType(graphRef, nodeType, 'all');\n }\n\n public graphRefSpecific(graph: TermIri, loc: SourceLocation): GraphRefSpecific {\n return {\n type: nodeType,\n subType: 'specific',\n graph,\n loc,\n };\n }\n\n public isGraphRefSpecific(graphRef: object): graphRef is SubTyped<NodeType, 'specific'> {\n return this.isOfSubType(graphRef, nodeType, 'specific');\n }\n };\n}\n", "/**\n * We use mixins as explained by the official TypeScript documentation:\n * https://www.typescriptlang.org/docs/handbook/mixins.html\n * Mixins are used so we can split into many files.\n * Additionally, it allows type guards and generics, which the is not possible using the indirection builder.\n */\n\nexport type Constructor<T = object> = new (...args: any[]) => T;\n\nexport type Mixin<Base = object, U extends Base = Base> = (superclass: Constructor<Base>) => Constructor<U>;\n\nexport function asArg<T>(arg: T): FlatCall<T> {\n return new FlatCall<T>(arg);\n}\n\nclass FlatCall<Input> {\n public constructor(private input: Input) {}\n public call<Out>(func: (input: Input) => Out): FlatCall<Out> {\n this.input = <Input> <unknown> func(this.input);\n return <FlatCall<Out>> <unknown> this;\n }\n\n public returns(): Input {\n return this.input;\n }\n}\n", "import type { AstCoreFactory, SourceLocation, Typed, SubTyped } from '@traqula/core';\nimport type {\n Path,\n PathAlternativeLimited,\n PathModified,\n PathNegated,\n PathNegatedElt,\n PropertyPathChain,\n TermIri,\n} from '../Sparql11types.js';\nimport type { Constructor } from './mixins.js';\n\ntype NodeType = 'path';\nconst nodeType: NodeType = 'path';\n\ntype RawNegatedElt = SubTyped<NodeType, '^'> & { items: [SubTyped<'term', 'namedNode'>]};\n\n// eslint-disable-next-line ts/explicit-function-return-type\nexport function PathFactoryMixin<TBase extends Constructor<AstCoreFactory>>(Base: TBase) {\n return class PathFactory extends Base {\n public isPathPure(obj: object): obj is Typed<NodeType> {\n return this.isOfType(obj, nodeType);\n }\n\n public path(\n subType: '|',\n items: (TermIri | PathNegatedElt)[],\n loc: SourceLocation\n ): PathAlternativeLimited;\n public path(\n subType: '!',\n items: [TermIri | PathNegatedElt | PathAlternativeLimited],\n loc: SourceLocation\n ): PathNegated;\n public path(subType: '^', items: [TermIri], loc: SourceLocation): PathNegatedElt;\n public path(subType: PathModified['subType'], item: [Path], loc: SourceLocation): PathModified;\n public path(subType: '|' | '/', items: Path[], loc: SourceLocation):\n PropertyPathChain;\n public path(\n subType: (PropertyPathChain | PathModified | PathNegated)['subType'],\n items: Path[],\n loc: SourceLocation,\n ): Path {\n const base = <const>{\n type: nodeType,\n loc,\n items,\n };\n if (subType === '|' || subType === '/') {\n return {\n ...base,\n subType,\n } satisfies PropertyPathChain;\n }\n if ((subType === '?' || subType === '*' || subType === '+' ||\n (subType === '^' && this.isPathPure(items[0]))) && items.length === 1) {\n return {\n ...base,\n subType,\n items: <[Path]>items,\n } satisfies PathModified;\n }\n if (subType === '^' && items.length === 1 && !this.isPathPure(items[0])) {\n return {\n ...base,\n subType,\n items: <[TermIri]>items,\n } satisfies PathNegatedElt;\n }\n if (subType === '!' && items.length === 1 && (\n this.isPathAlternativeLimited(items[0]) || !this.isPathPure(items[0]) || this.isPathNegatedElt(items[0]))) {\n return {\n ...base,\n subType,\n items: <[TermIri | PathNegatedElt | PathAlternativeLimited]>items,\n } satisfies PathNegated;\n }\n throw new Error('Invalid path type');\n }\n\n public isPathOfType<T extends U[], U extends string>(obj: object, subTypes: T): obj is SubTyped<NodeType, U> {\n return this.isOfType(obj, nodeType) && subTypes.includes(<any>(<{ subType?: unknown }>obj).subType);\n }\n\n public isPathChain(obj: object): obj is SubTyped<NodeType, '|' | '/'> {\n return this.isOfSubType(obj, nodeType, '/') || this.isOfSubType(obj, nodeType, '|');\n }\n\n public isPathModified(obj: object): obj is SubTyped<NodeType, '?' | '*' | '+' | '^'> {\n return this.isOfSubType(obj, nodeType, '?') || this.isOfSubType(obj, nodeType, '*') ||\n this.isOfSubType(obj, nodeType, '+') || this.isOfSubType(obj, nodeType, '^');\n }\n\n public isPathNegatedElt(obj: object): obj is RawNegatedElt {\n const casted: { items?: unknown } = obj;\n return this.isOfSubType(obj, nodeType, '^') && Array.isArray(casted.items) && casted.items.length === 1 &&\n casted.items[0] !== null && typeof casted.items[0] === 'object' && !this.isPathPure(casted.items[0]);\n }\n\n public isPathNegated(obj: object): obj is SubTyped<NodeType, '!'> {\n return this.isOfSubType(obj, nodeType, '!');\n }\n\n public isPathAlternativeLimited(obj: object):\n obj is SubTyped<NodeType, '|'> & { items: (SubTyped<'term', 'namedNode'> | RawNegatedElt)[] } {\n const casted: { items?: unknown } = obj;\n return this.isOfSubType(obj, nodeType, '|') && Array.isArray(casted.items) &&\n casted.items.every(item => !this.isPathPure(item) || this.isPathNegatedElt(item));\n }\n };\n}\n", "import type { AstCoreFactory, SourceLocation, Typed, SubTyped } from '@traqula/core';\nimport type {\n BasicGraphPattern,\n Expression,\n Pattern,\n PatternBgp,\n PatternBind,\n PatternFilter,\n PatternGraph,\n PatternGroup,\n PatternMinus,\n PatternOptional,\n PatternService,\n PatternUnion,\n PatternValues,\n TermIri,\n TermVariable,\n ValuePatternRow,\n} from '../Sparql11types.js';\nimport type { Constructor } from './mixins.js';\n\ntype NodeType = 'pattern';\nconst nodeType: NodeType = 'pattern';\n\n// eslint-disable-next-line ts/explicit-function-return-type\nexport function PatternFactoryMixin<TBase extends Constructor<AstCoreFactory>>(Base: TBase) {\n return class PatternFactory extends Base {\n public isPattern(obj: object): obj is Typed<NodeType> {\n return this.isOfType(obj, nodeType);\n }\n\n public patternBgp(triples: BasicGraphPattern, loc: SourceLocation): PatternBgp {\n return { type: nodeType, subType: 'bgp', triples, loc };\n }\n\n public isPatternBgp(obj: object): obj is SubTyped<NodeType, 'bgp'> {\n return this.isOfSubType(obj, nodeType, 'bgp');\n }\n\n public patternGroup(patterns: Pattern[], loc: SourceLocation): PatternGroup {\n return { type: nodeType, subType: 'group', patterns, loc };\n }\n\n public isPatternGroup(obj: object): obj is SubTyped<NodeType, 'group'> {\n return this.isOfSubType(obj, nodeType, 'group');\n }\n\n public patternGraph(name: TermIri | TermVariable, patterns: Pattern[], loc: SourceLocation): PatternGraph {\n return { type: nodeType, subType: 'graph', name, patterns, loc };\n }\n\n public isPatternGraph(obj: object): obj is SubTyped<NodeType, 'graph'> {\n return this.isOfSubType(obj, nodeType, 'graph');\n }\n\n public patternOptional(patterns: Pattern[], loc: SourceLocation): PatternOptional {\n return { type: nodeType, subType: 'optional', patterns, loc };\n }\n\n public isPatternOptional(obj: object): obj is SubTyped<NodeType, 'optional'> {\n return this.isOfSubType(obj, nodeType, 'optional');\n }\n\n public patternValues(variables: TermVariable[], values: ValuePatternRow[], loc: SourceLocation): PatternValues {\n return { type: nodeType, subType: 'values', variables, values, loc };\n }\n\n public isPatternValues(obj: object): obj is SubTyped<NodeType, 'values'> {\n return this.isOfSubType(obj, nodeType, 'values');\n }\n\n public patternFilter(expression: Expression, loc: SourceLocation): PatternFilter {\n return {\n type: nodeType,\n subType: 'filter',\n expression,\n loc,\n };\n }\n\n public isPatternFilter(obj: object): obj is SubTyped<NodeType, 'filter'> {\n return this.isOfSubType(obj, nodeType, 'filter');\n }\n\n public patternBind(\n expression: Expression,\n variable: TermVariable,\n loc: SourceLocation,\n ): PatternBind {\n return {\n type: nodeType,\n subType: 'bind',\n expression,\n variable,\n loc,\n };\n }\n\n public isPatternBind(obj: object): obj is SubTyped<NodeType, 'bind'> {\n return this.isOfSubType(obj, nodeType, 'bind');\n }\n\n public patternUnion(patterns: PatternGroup[], loc: SourceLocation): PatternUnion {\n return {\n type: nodeType,\n subType: 'union',\n patterns,\n loc,\n };\n }\n\n public isPatternUnion(obj: object): obj is SubTyped<NodeType, 'union'> {\n return this.isOfSubType(obj, nodeType, 'union');\n }\n\n public patternMinus(patterns: Pattern[], loc: SourceLocation): PatternMinus {\n return {\n type: nodeType,\n subType: 'minus',\n patterns,\n loc,\n };\n }\n\n public isPatternMinus(obj: object): obj is SubTyped<NodeType, 'minus'> {\n return this.isOfSubType(obj, nodeType, 'minus');\n }\n\n public patternService(\n name: TermIri | TermVariable,\n patterns: Pattern[],\n silent: boolean,\n loc: SourceLocation,\n ): PatternService {\n return {\n type: nodeType,\n subType: 'service',\n silent,\n name,\n patterns,\n loc,\n };\n }\n\n public isPatternService(obj: object): obj is SubTyped<NodeType, 'service'> {\n return this.isOfSubType(obj, nodeType, 'service');\n }\n };\n}\n", "import type { AstCoreFactory, SourceLocation, Typed, SubTyped } from '@traqula/core';\nimport type {\n ContextDefinition,\n DatasetClauses,\n PatternBgp,\n PatternGroup,\n PatternValues,\n QueryConstruct,\n QuerySelect,\n SolutionModifiers,\n} from '../Sparql11types.js';\nimport type { Constructor } from './mixins.js';\n\ntype NodeType = 'query';\nconst nodeType: NodeType = 'query';\n\n// eslint-disable-next-line ts/explicit-function-return-type\nexport function QueryFactoryMixin<TBase extends Constructor<AstCoreFactory>>(Base: TBase) {\n return class QueryFactory extends Base {\n public isQuery(obj: object): obj is Typed<NodeType> {\n return this.isOfType(obj, nodeType);\n }\n\n public isQuerySelect(obj: object): obj is SubTyped<NodeType, 'select'> {\n return this.isOfSubType(obj, nodeType, 'select');\n }\n\n public queryConstruct(\n loc: SourceLocation,\n context: ContextDefinition[],\n template: PatternBgp,\n where: PatternGroup,\n solutionModifiers: SolutionModifiers,\n datasets: DatasetClauses,\n values?: PatternValues,\n ): QueryConstruct {\n return {\n type: 'query',\n subType: 'construct',\n context,\n template,\n where,\n solutionModifiers,\n datasets,\n values,\n loc,\n };\n }\n\n public isQueryConstruct(obj: object): obj is SubTyped<NodeType, 'construct'> {\n return this.isOfSubType(obj, nodeType, 'construct');\n }\n\n public isQueryDescribe(obj: object): obj is SubTyped<NodeType, 'describe'> {\n return this.isOfSubType(obj, nodeType, 'describe');\n }\n\n public isQueryAsk(obj: object): obj is SubTyped<NodeType, 'ask'> {\n return this.isOfSubType(obj, nodeType, 'ask');\n }\n\n public querySelect(arg: Omit<QuerySelect, 'type' | 'subType' | 'loc'>, loc: SourceLocation): QuerySelect {\n return {\n type: nodeType,\n subType: 'select',\n ...arg,\n loc,\n };\n }\n };\n}\n", "import type { AstCoreFactory, SourceLocation, Typed, SubTyped } from '@traqula/core';\nimport type {\n Expression,\n Ordering,\n SolutionModifierGroup,\n SolutionModifierGroupBind,\n SolutionModifierHaving,\n SolutionModifierLimitOffset,\n SolutionModifierOrder,\n} from '../Sparql11types.js';\nimport type { Constructor } from './mixins.js';\n\ntype NodeType = 'solutionModifier';\nconst nodeType: NodeType = 'solutionModifier';\n\n// eslint-disable-next-line ts/explicit-function-return-type\nexport function SolutionModifiersFactoryMixin<TBase extends Constructor<AstCoreFactory>>(Base: TBase) {\n return class SolutionModifiersFactory extends Base {\n public isSolutionModifier(obj: object): obj is Typed<NodeType> {\n return this.isOfType(obj, nodeType);\n }\n\n public solutionModifierHaving(having: Expression[], loc: SourceLocation): SolutionModifierHaving {\n return {\n type: nodeType,\n subType: 'having',\n having,\n loc,\n };\n }\n\n public isSolutionModifierHaving(obj: object): obj is SubTyped<NodeType, 'having'> {\n return this.isOfSubType(obj, nodeType, 'having');\n }\n\n public solutionModifierOrder(orderDefs: Ordering[], loc: SourceLocation): SolutionModifierOrder {\n return {\n type: nodeType,\n subType: 'order',\n orderDefs,\n loc,\n };\n }\n\n public isSolutionModifierOrder(obj: object): obj is SubTyped<NodeType, 'order'> {\n return this.isOfSubType(obj, nodeType, 'order');\n }\n\n public solutionModifierLimitOffset(\n limit: number | undefined,\n offset: number | undefined,\n loc: SourceLocation,\n ): SolutionModifierLimitOffset {\n return {\n type: nodeType,\n subType: 'limitOffset',\n limit,\n offset,\n loc,\n };\n }\n\n public isSolutionModifierLimitOffset(obj: object): obj is SubTyped<NodeType, 'limitOffset'> {\n return this.isOfSubType(obj, nodeType, 'limitOffset');\n }\n\n public solutionModifierGroup(groupings: (Expression | SolutionModifierGroupBind)[], loc: SourceLocation):\n SolutionModifierGroup {\n return {\n type: 'solutionModifier',\n subType: 'group',\n groupings,\n loc,\n };\n }\n\n public isSolutionModifierGroup(obj: object): obj is SubTyped<NodeType, 'group'> {\n return this.isOfSubType(obj, nodeType, 'group');\n }\n };\n}\n", "import type { AstCoreFactory, SourceLocation, Typed, SubTyped } from '@traqula/core';\nimport type {\n TermBlank,\n TermIri,\n TermIriFull,\n TermIriPrefixed,\n TermLiteral,\n TermLiteralLangStr,\n TermLiteralStr,\n TermLiteralTyped,\n TermVariable,\n} from '../Sparql11types.js';\nimport type { Constructor } from './mixins.js';\n\ntype NodeType = 'term';\nconst nodeType: NodeType = 'term';\n\n// eslint-disable-next-line ts/explicit-function-return-type\nexport function TermFactoryMixin<TBase extends Constructor<AstCoreFactory>>(Base: TBase) {\n return class TermFactory extends Base {\n public __blankNodeCounter = 0;\n\n public resetBlankNodeCounter(): void {\n this.__blankNodeCounter = 0;\n }\n\n public isTerm(x: object): x is Typed<'term'> {\n return this.isOfType(x, 'term');\n }\n\n public termBlank(label: undefined | string, loc: SourceLocation): TermBlank {\n const base = <const>{\n type: 'term',\n subType: 'blankNode',\n loc,\n };\n if (label === undefined) {\n return { ...base, label: `g_${this.__blankNodeCounter++}` };\n }\n return { ...base, label: `e_${label}` };\n }\n\n public isTermBlank(obj: object): obj is SubTyped<NodeType, 'blankNode'> {\n return this.isOfSubType(obj, nodeType, 'blankNode');\n }\n\n /**\n * String, no lang, no type\n */\n public termLiteral(loc: SourceLocation, value: string, lang?: undefined): TermLiteralStr;\n /**\n * String with a language tag\n */\n public termLiteral(loc: SourceLocation, value: string, lang: string): TermLiteralLangStr;\n /**\n * Lexical form with a type\n */\n public termLiteral(loc: SourceLocation, value: string, iri: TermIri): TermLiteralTyped;\n public termLiteral(loc: SourceLocation, value: string, langOrIri?: string | TermIri): TermLiteral;\n public termLiteral(loc: SourceLocation, value: string, langOrIri?: string | TermIri): TermLiteral {\n return {\n type: nodeType,\n subType: 'literal',\n value,\n langOrIri,\n loc,\n };\n }\n\n public isTermLiteral(obj: object): obj is SubTyped<NodeType, 'literal'> {\n return this.isOfSubType(obj, nodeType, 'literal');\n }\n\n public isTermLiteralLangStr(obj: object): obj is SubTyped<NodeType, 'literal'> & { langOrIri: string } {\n return this.isTermLiteral(obj) && typeof (<{ langOrIri?: unknown }>obj).langOrIri === 'string';\n }\n\n public isTermLiteralStr(obj: object): obj is SubTyped<NodeType, 'literal'> & { langOrIri: undefined } {\n return this.isTermLiteral(obj) && typeof (<{ langOrIri?: unknown }>obj).langOrIri === 'undefined';\n }\n\n public isTermLiteralTyped(obj: object):\n obj is SubTyped<NodeType, 'literal'> & { langOrIri: SubTyped<NodeType, 'namedNode'> } {\n const casted = <{ langOrIri?: unknown }>obj;\n return this.isTermLiteral(obj) && typeof casted.langOrIri === 'object' &&\n casted.langOrIri !== null && this.isTermNamed(casted.langOrIri);\n }\n\n public termVariable(value: string, loc: SourceLocation): TermVariable {\n return {\n type: nodeType,\n subType: 'variable',\n value,\n loc,\n };\n }\n\n public isTermVariable(obj: object): obj is SubTyped<NodeType, 'variable'> {\n return this.isOfSubType(obj, nodeType, 'variable');\n }\n\n /**\n * A namednode with fully defined with a uri.\n */\n public termNamed(loc: SourceLocation, value: string, prefix?: undefined): TermIriFull;\n /**\n * A namednode defined using a prefix\n */\n public termNamed(loc: SourceLocation, value: string, prefix: string): TermIriPrefixed;\n public termNamed(loc: SourceLocation, value: string, prefix?: string): TermIriFull | TermIriPrefixed {\n const base = <const>{\n type: nodeType,\n subType: 'namedNode',\n value,\n loc,\n };\n if (prefix === undefined) {\n return base;\n }\n return { ...base, prefix };\n }\n\n public isTermNamed(obj: object): obj is SubTyped<NodeType, 'namedNode'> {\n return this.isOfSubType(obj, nodeType, 'namedNode');\n }\n\n public isTermNamedPrefixed(obj: object): obj is SubTyped<NodeType, 'namedNode'> & { prefix: string } {\n const casted = <{ prefix?: unknown }>obj;\n return this.isTermNamed(obj) && typeof casted.prefix === 'string';\n }\n };\n}\n", "import type { AstCoreFactory, SourceLocation, SubTyped, Typed } from '@traqula/core';\nimport type {\n DatasetClauses,\n GraphRef,\n GraphRefDefault,\n GraphRefSpecific,\n PatternGroup,\n Quads,\n TermIri,\n UpdateOperationAdd,\n UpdateOperationClear,\n UpdateOperationCopy,\n UpdateOperationCreate,\n UpdateOperationDeleteData,\n UpdateOperationDeleteWhere,\n UpdateOperationDrop,\n UpdateOperationInsertData,\n UpdateOperationLoad,\n UpdateOperationModify,\n UpdateOperationMove,\n} from '../Sparql11types.js';\nimport type { Constructor } from './mixins.js';\n\ntype NodeType = 'updateOperation';\nconst nodeType: NodeType = 'updateOperation';\n\n// eslint-disable-next-line ts/explicit-function-return-type\nexport function UpdateOperationFactoryMixin<TBase extends Constructor<AstCoreFactory>>(Base: TBase) {\n return class UpdateOperationFactory extends Base {\n public isUpdateOperation(obj: object): obj is Typed<NodeType> {\n return this.isOfType(obj, nodeType);\n }\n\n public updateOperationLoad(\n loc: SourceLocation,\n source: TermIri,\n silent: boolean,\n destination?: GraphRefSpecific | undefined,\n ): UpdateOperationLoad {\n return {\n type: nodeType,\n subType: 'load',\n silent,\n source,\n ...(destination && { destination }),\n loc,\n };\n }\n\n public isUpdateOperationLoad(obj: object): obj is SubTyped<NodeType, 'load'> {\n return this.isOfSubType(obj, nodeType, 'load');\n }\n\n public updateOperationClearDrop(subType: 'clear', silent: boolean, destination: GraphRef, loc: SourceLocation):\n UpdateOperationClear;\n public updateOperationClearDrop(subType: 'drop', silent: boolean, destination: GraphRef, loc: SourceLocation):\n UpdateOperationDrop;\n public updateOperationClearDrop(\n subType: 'clear' | 'drop',\n silent: boolean,\n destination: GraphRef,\n loc: SourceLocation\n ): UpdateOperationClear | UpdateOperationDrop;\n public updateOperationClearDrop(\n subType: 'clear' | 'drop',\n silent: boolean,\n destination: GraphRef,\n loc: SourceLocation,\n ): UpdateOperationClear | UpdateOperationDrop {\n return {\n type: 'updateOperation',\n subType,\n silent,\n destination,\n loc,\n };\n }\n\n public updateOperationClear(\n destination: GraphRef,\n silent: boolean,\n loc: SourceLocation,\n ): UpdateOperationClear {\n return this.updateOperationClearDrop('clear', silent, destination, loc);\n };\n\n public isUpdateOperationClear(obj: object): obj is SubTyped<NodeType, 'clear'> {\n return this.isOfSubType(obj, nodeType, 'clear');\n }\n\n public updateOperationDrop(\n destination: GraphRef,\n silent: boolean,\n loc: SourceLocation,\n ): UpdateOperationDrop {\n return this.updateOperationClearDrop('drop', silent, destination, loc);\n }\n\n public isUpdateOperationDrop(obj: object): obj is SubTyped<NodeType, 'drop'> {\n return this.isOfSubType(obj, nodeType, 'drop');\n }\n\n public updateOperationCreate(\n destination: GraphRefSpecific,\n silent: boolean,\n loc: SourceLocation,\n ): UpdateOperationCreate {\n return {\n type: 'updateOperation',\n subType: 'create',\n silent,\n destination,\n loc,\n };\n }\n\n public isUpdateOperationCreate(obj: object): obj is SubTyped<NodeType, 'create'> {\n return this.isOfSubType(obj, nodeType, 'create');\n }\n\n public updateOperationAddMoveCopy(\n subType: 'add',\n source: GraphRefDefault | GraphRefSpecific,\n destination: GraphRefDefault | GraphRefSpecific,\n silent: boolean,\n loc: SourceLocation,\n ): UpdateOperationAdd;\n public updateOperationAddMoveCopy(\n subType: 'move',\n source: GraphRefDefault | GraphRefSpecific,\n destination: GraphRefDefault | GraphRefSpecific,\n silent: boolean,\n loc: SourceLocation,\n ): UpdateOperationMove ;\n public updateOperationAddMoveCopy(\n subType: 'copy',\n source: GraphRefDefault | GraphRefSpecific,\n destination: GraphRefDefault | GraphRefSpecific,\n silent: boolean,\n loc: SourceLocation,\n ): UpdateOperationCopy;\n public updateOperationAddMoveCopy(\n subType: 'add' | 'move' | 'copy',\n source: GraphRefDefault | GraphRefSpecific,\n destination: GraphRefDefault | GraphRefSpecific,\n silent: boolean,\n loc: SourceLocation,\n ): UpdateOperationAdd | UpdateOperationMove | UpdateOperationCopy;\n public updateOperationAddMoveCopy(\n subType: 'add' | 'move' | 'copy',\n source: GraphRefDefault | GraphRefSpecific,\n destination: GraphRefDefault | GraphRefSpecific,\n silent: boolean,\n loc: SourceLocation,\n ): UpdateOperationAdd | UpdateOperationMove | UpdateOperationCopy {\n return {\n type: 'updateOperation',\n subType,\n silent,\n source,\n destination,\n loc,\n };\n }\n\n public updateOperationAdd(\n source: GraphRefDefault | GraphRefSpecific,\n destination: GraphRefDefault | GraphRefSpecific,\n silent: boolean,\n loc: SourceLocation,\n ): UpdateOperationAdd {\n return this.updateOperationAddMoveCopy('add', source, destination, silent, loc);\n }\n\n public isUpdateOperationAdd(obj: object): obj is SubTyped<NodeType, 'add'> {\n return this.isOfSubType(obj, nodeType, 'add');\n }\n\n public updateOperationMove(\n source: GraphRefDefault | GraphRefSpecific,\n destination: GraphRefDefault | GraphRefSpecific,\n silent: boolean,\n loc: SourceLocation,\n ): UpdateOperationMove {\n return this.updateOperationAddMoveCopy('move', source, destination, silent, loc);\n }\n\n public isUpdateOperationMove(obj: object): obj is SubTyped<NodeType, 'move'> {\n return this.isOfSubType(obj, nodeType, 'move');\n }\n\n public updateOperationCopy(\n source: GraphRefDefault | GraphRefSpecific,\n destination: GraphRefDefault | GraphRefSpecific,\n silent: boolean,\n loc: SourceLocation,\n ): UpdateOperationCopy {\n return this.updateOperationAddMoveCopy('copy', source, destination, silent, loc);\n }\n\n public isUpdateOperationCopy(obj: object): obj is SubTyped<NodeType, 'copy'> {\n return this.isOfSubType(obj, nodeType, 'copy');\n }\n\n public updateOperationInsDelDataWhere(subType: 'insertdata', data: Quads[], loc: SourceLocation):\n UpdateOperationInsertData;\n public updateOperationInsDelDataWhere(subType: 'deletedata', data: Quads[], loc: SourceLocation):\n UpdateOperationDeleteData;\n public updateOperationInsDelDataWhere(subType: 'deletewhere', data: Quads[], loc: SourceLocation):\n UpdateOperationDeleteWhere;\n public updateOperationInsDelDataWhere(\n subType: 'insertdata' | 'deletedata' | 'deletewhere',\n data: Quads[],\n loc: SourceLocation,\n ): UpdateOperationInsertData | UpdateOperationDeleteData | UpdateOperationDeleteWhere;\n public updateOperationInsDelDataWhere(\n subType: 'insertdata' | 'deletedata' | 'deletewhere',\n data: Quads[],\n loc: SourceLocation,\n ): UpdateOperationInsertData | UpdateOperationDeleteData | UpdateOperationDeleteWhere {\n return {\n type: 'updateOperation',\n subType,\n data,\n loc,\n };\n }\n\n public updateOperationInsertData(data: Quads[], loc: SourceLocation): UpdateOperationInsertData {\n return this.updateOperationInsDelDataWhere('insertdata', data, loc);\n }\n\n public isUpdateOperationInsertData(obj: object): obj is SubTyped<NodeType, 'insertdata'> {\n return this.isOfSubType(obj, nodeType, 'insertdata');\n }\n\n public updateOperationDeleteData(data: Quads[], loc: SourceLocation): UpdateOperationDeleteData {\n return this.updateOperationInsDelDataWhere('deletedata', data, loc);\n }\n\n public isUpdateOperationDeleteData(obj: object): obj is SubTyped<NodeType, 'deletedata'> {\n return this.isOfSubType(obj, nodeType, 'deletedata');\n }\n\n public updateOperationDeleteWhere(data: Quads[], loc: SourceLocation): UpdateOperationDeleteWhere {\n return this.updateOperationInsDelDataWhere('deletewhere', data, loc);\n }\n\n public isUpdateOperationDeleteWhere(obj: object): obj is SubTyped<NodeType, 'deletewhere'> {\n return this.isOfSubType(obj, nodeType, 'deletewhere');\n }\n\n public updateOperationModify(\n loc: SourceLocation,\n insert: Quads[] | undefined,\n del: Quads[] | undefined,\n where: PatternGroup,\n from: DatasetClauses,\n graph?: TermIri | undefined,\n ): UpdateOperationModify {\n return {\n type: 'updateOperation',\n subType: 'modify',\n insert: insert ?? [],\n delete: del ?? [],\n graph,\n where,\n from,\n loc,\n };\n }\n\n public isUpdateOperationModify(obj: object): obj is SubTyped<NodeType, 'modify'> {\n return this.isOfSubType(obj, nodeType, 'modify');\n }\n };\n}\n", "import type { SourceLocation, SubTyped, Typed } from '@traqula/core';\nimport { AstCoreFactory } from '@traqula/core';\nimport { ContextFactoryMixin } from './factoryMixins/ContextFactory.js';\nimport { ExpressionFactoryMixin } from './factoryMixins/ExpressionFactory.js';\nimport { GraphRefFactoryMixin } from './factoryMixins/GraphRefFactory.js';\nimport { asArg } from './factoryMixins/mixins.js';\nimport { PathFactoryMixin } from './factoryMixins/PathFactory.js';\nimport { PatternFactoryMixin } from './factoryMixins/Patternfactory.js';\nimport { QueryFactoryMixin } from './factoryMixins/QueryFactory.js';\nimport { SolutionModifiersFactoryMixin } from './factoryMixins/SolutionModifiersFactory.js';\nimport { TermFactoryMixin } from './factoryMixins/TermFactory.js';\nimport { UpdateOperationFactoryMixin } from './factoryMixins/UpdateOperationFactory.js';\nimport type {\n DatasetClauses,\n GraphNode,\n GraphQuads,\n PatternBgp,\n Sparql11Nodes,\n Term,\n TermBlank,\n TermIri,\n TermVariable,\n TripleCollectionBlankNodeProperties,\n TripleCollectionList,\n TripleNesting,\n Update,\n Wildcard,\n} from './Sparql11types.js';\n\n/**\n * A factory that helps you create, and check types for AST nodes for SPARQL 1.1\n */\nexport class AstFactory extends asArg(AstCoreFactory)\n .call(ContextFactoryMixin)\n .call(ExpressionFactoryMixin)\n .call(GraphRefFactoryMixin)\n .call(PathFactoryMixin)\n .call(PatternFactoryMixin)\n .call(QueryFactoryMixin)\n .call(SolutionModifiersFactoryMixin)\n .call(TermFactoryMixin)\n .call(UpdateOperationFactoryMixin)\n .returns() {\n public alwaysSparql11(obj: object): obj is Sparql11Nodes {\n return true;\n }\n\n public isPath(obj: object): obj is SubTyped<'term', 'namedNode'> | Typed<'path'> {\n return this.isPathPure(obj) || this.isTermNamed(obj);\n }\n\n public isExpression(obj: object):\n obj is SubTyped<'term', 'namedNode' | 'variable' | 'literal'> | Typed<'expression'> {\n return this.isExpressionPure(obj) || this.isTermNamed(obj) || this.isTermVariable(obj) || this.isTermLiteral(obj);\n }\n\n public graphNodeIdentifier(graphNode: GraphNode): Term {\n return graphNode.type === 'tripleCollection' ? graphNode.identifier : graphNode;\n }\n\n public triple(\n subject: TripleNesting['subject'],\n predicate: TripleNesting['predicate'],\n object: TripleNesting['object'],\n loc?: SourceLocation,\n ): TripleNesting {\n return {\n type: 'triple',\n subject,\n predicate,\n object,\n loc: loc ?? this.sourceLocation(subject, predicate, object),\n };\n }\n\n public isTriple(obj: object): obj is Typed<'triple'> {\n return this.isOfType(obj, 'triple');\n }\n\n public datasetClauses(clauses: DatasetClauses['clauses'], loc: SourceLocation): DatasetClauses {\n return {\n type: 'datasetClauses',\n clauses,\n loc,\n };\n }\n\n public isDatasetClauses(obj: object): obj is Typed<'datasetClauses'> {\n return this.isOfType(obj, 'datasetClauses');\n }\n\n public wildcard(loc: SourceLocation): Wildcard {\n return { type: 'wildcard', loc };\n }\n\n public isWildcard(obj: object): obj is Typed<'wildcard'> {\n return this.isOfType(obj, 'wildcard');\n }\n\n public isTripleCollection(obj: object): obj is Typed<'tripleCollection'> {\n return this.isOfType(obj, 'tripleCollection');\n }\n\n public tripleCollectionBlankNodeProperties(\n identifier: TermBlank,\n triples: TripleNesting[],\n loc: SourceLocation,\n ): TripleCollectionBlankNodeProperties {\n return {\n type: 'tripleCollection',\n subType: 'blankNodeProperties',\n identifier,\n triples,\n loc,\n };\n }\n\n public isTripleCollectionBlankNodeProperties(obj: object):\n obj is SubTyped<'tripleCollection', 'blankNodeProperties'> {\n return this.isOfSubType(obj, 'tripleCollection', 'blankNodeProperties');\n }\n\n public tripleCollectionList(\n identifier: TermBlank,\n triples: TripleNesting[],\n loc: SourceLocation,\n ): TripleCollectionList {\n return {\n type: 'tripleCollection',\n subType: 'list',\n identifier,\n triples,\n loc,\n };\n }\n\n public isTripleCollectionList(obj: object):\n obj is SubTyped<'tripleCollection', 'list'> {\n return this.isOfSubType(obj, 'tripleCollection', 'list');\n }\n\n public graphQuads(graph: TermIri | TermVariable, triples: PatternBgp, loc: SourceLocation): GraphQuads {\n return {\n type: 'graph',\n graph,\n triples,\n loc,\n };\n }\n\n public isGraphQuads(obj: object): obj is GraphQuads {\n return super.isOfType(obj, 'graph');\n }\n\n public isUpdate(obj: object): obj is Update {\n return super.isOfType(obj, 'update');\n }\n}\n", "import { TransformerSubTyped } from '@traqula/core';\nimport type { Sparql11Nodes } from './Sparql11types.js';\n\n/**\n * Transform input in accordance to [19.2](https://www.w3.org/TR/sparql11-query/#codepointEscape)\n * and validate unicode codepoints.\n */\nexport function sparqlCodepointEscape(input: string): string {\n const sanitizedInput = input.replaceAll(\n /\\\\u([0-9a-fA-F]{4})|\\\\U([0-9a-fA-F]{8})/gu,\n (_, unicode4: string, unicode8: string) => {\n if (unicode4) {\n const charCode = Number.parseInt(unicode4, 16);\n return String.fromCodePoint(charCode);\n }\n const charCode = Number.parseInt(unicode8, 16);\n if (charCode < 0xFFFF) {\n return String.fromCodePoint(charCode);\n }\n const substractedCharCode = charCode - 0x10000;\n return String.fromCodePoint(0xD800 + (substractedCharCode >> 10), 0xDC00 + (substractedCharCode & 0x3FF));\n },\n );\n // Test for invalid unicode surrogate pairs\n if (/[\\uD800-\\uDBFF](?:[^\\uDC00-\\uDFFF]|$)/u.test(sanitizedInput)) {\n throw new Error(`Invalid unicode codepoint of surrogate pair without corresponding codepoint`);\n }\n return sanitizedInput;\n}\n\n/**\n * Common IRI constants used across SPARQL parsing and generation.\n * Includes XSD datatypes (BOOLEAN, INTEGER, DECIMAL, DOUBLE, STRING)\n * and RDF vocabulary (FIRST, REST, NIL, TYPE).\n */\nexport enum CommonIRIs {\n // XSD\n BOOLEAN = 'http://www.w3.org/2001/XMLSchema#boolean',\n INTEGER = 'http://www.w3.org/2001/XMLSchema#integer',\n DECIMAL = 'http://www.w3.org/2001/XMLSchema#decimal',\n DOUBLE = 'http://www.w3.org/2001/XMLSchema#double',\n STRING = 'http://www.w3.org/2001/XMLSchema#string',\n // RDF\n FIRST = 'http://www.w3.org/1999/02/22-rdf-syntax-ns#first',\n REST = 'http://www.w3.org/1999/02/22-rdf-syntax-ns#rest',\n NIL = 'http://www.w3.org/1999/02/22-rdf-syntax-ns#nil',\n TYPE = 'http://www.w3.org/1999/02/22-rdf-syntax-ns#type',\n}\n\n/**\n * A {@link TransformerSubTyped} specialized for the SPARQL 1.1 AST node types.\n * Provides a type-safe visitor/transformer that dispatches based on node `type` and `subType` fields.\n *\n * @example\n * ```typescript\n * const transformer = new AstTransformer();\n * transformer.transformNodeSpecific<'safe', typeof ast>(ast, {\n * query: { select: (node) => { ... } },\n * });\n * ```\n */\nexport class AstTransformer extends TransformerSubTyped<Sparql11Nodes> {}\n", "import type { IToken } from '@traqula/chevrotain';\nimport * as l from '../lexer/index.js';\nimport type { SparqlGrammarRule, SparqlRule } from '../sparql11HelperTypes.js';\nimport type {\n TermBlank,\n TermIri,\n TermIriFull,\n TermIriPrefixed,\n TermLiteral,\n TermLiteralStr,\n TermLiteralTyped,\n} from '../Sparql11types.js';\nimport { CommonIRIs } from '../utils.js';\n\nconst escapeMap: Record<string, string> = {\n '\\t': '\\\\t',\n '\\n': '\\\\n',\n '\\r': '\\\\r',\n '\\b': '\\\\b',\n '\\f': '\\\\f',\n '\"': '\\\\\"',\n '\\\\': '\\\\\\\\',\n};\n\nexport function stringEscapedLexical(str: string): string {\n const lexical = str.replaceAll(/[\"\\\\\\t\\n\\r\\b\\f]/gu, char => escapeMap[char]);\n return `\"${lexical}\"`;\n}\n\n/**\n * [[120]](https://www.w3.org/TR/sparql11-query/#rRDFLiteral)\n */\nexport const rdfLiteral: SparqlRule<'rdfLiteral', TermLiteral> = <const> {\n name: 'rdfLiteral',\n impl: ({ ACTION, SUBRULE1, CONSUME, OPTION, OR }) => (C) => {\n const value = SUBRULE1(string);\n return OPTION(() => OR<TermLiteral>([\n { ALT: () => {\n const lang = CONSUME(l.terminals.langTag);\n return ACTION(() => C.astFactory.termLiteral(\n C.astFactory.sourceLocation(value, lang),\n value.value,\n lang.image.slice(1).toLowerCase(),\n ));\n } },\n { ALT: () => {\n CONSUME(l.symbols.hathat);\n const iriVal = SUBRULE1(iri);\n return ACTION(() => C.astFactory.termLiteral(\n C.astFactory.sourceLocation(value, iriVal),\n value.value,\n iriVal,\n ));\n } },\n ])) ?? value;\n },\n gImpl: ({ SUBRULE, PRINT, PRINT_WORD }) => (ast, { astFactory }) => {\n if (!ast.langOrIri || typeof ast.langOrIri === 'string') {\n // String or langdir string - no sub loc.\n astFactory.printFilter(ast, () => {\n PRINT_WORD('');\n PRINT(stringEscapedLexical(ast.value));\n });\n if (typeof ast.langOrIri === 'string') {\n astFactory.printFilter(ast, () => PRINT('@', ast.langOrIri));\n }\n } else if (astFactory.isSourceLocationNoMaterialize(ast.langOrIri.loc)) {\n // You have a typed literal. -- If type is not materialized, print raw\n astFactory.printFilter(ast, () => {\n PRINT_WORD(ast.value);\n });\n } else {\n astFactory.printFilter(ast, () => {\n PRINT_WORD('');\n PRINT(stringEscapedLexical(ast.value), '^^');\n });\n SUBRULE(iri, ast.langOrIri);\n }\n },\n};\n\n/**\n * Parses a numeric literal.\n * [[130]](https://www.w3.org/TR/sparql11-query/#rNumericLiteral)\n */\nexport const numericLiteral: SparqlGrammarRule<'numericLiteral', TermLiteralTyped> = <const> {\n name: 'numericLiteral',\n impl: ({ SUBRULE, OR }) => () => OR([\n { ALT: () => SUBRULE(numericLiteralUnsigned) },\n { ALT: () => SUBRULE(numericLiteralPositive) },\n { ALT: () => SUBRULE(numericLiteralNegative) },\n ]),\n};\n\n/**\n * Parses an unsigned numeric literal.\n * [[131]](https://www.w3.org/TR/sparql11-query/#rNumericLiteralUnsigned)\n */\nexport const numericLiteralUnsigned: SparqlGrammarRule<'numericLiteralUnsigned', TermLiteralTyped> = <const> {\n name: 'numericLiteralUnsigned',\n impl: ({ ACTION, CONSUME, OR }) => (C) => {\n const parsed = OR<[IToken, string]>([\n { ALT: () => <const> [ CONSUME(l.terminals.integer), CommonIRIs.INTEGER ]},\n { ALT: () => <const> [ CONSUME(l.terminals.decimal), CommonIRIs.DECIMAL ]},\n { ALT: () => <const> [ CONSUME(l.terminals.double), CommonIRIs.DOUBLE ]},\n ]);\n return ACTION(() => C.astFactory.termLiteral(\n C.astFactory.sourceLocation(parsed[0]),\n parsed[0].image,\n C.astFactory.termNamed(C.astFactory.sourceLocation(), parsed[1]),\n ));\n },\n};\n\n/**\n * Parses a positive numeric literal.\n * [[132]](https://www.w3.org/TR/sparql11-query/#rNumericLiteralPositive)\n */\nexport const numericLiteralPositive: SparqlGrammarRule<'numericLiteralPositive', TermLiteralTyped> = <const> {\n name: 'numericLiteralPositive',\n impl: ({ ACTION, CONSUME, OR }) => (C) => {\n const parsed = OR<[IToken, string]>([\n { ALT: () => <const> [ CONSUME(l.terminals.integerPositive), CommonIRIs.INTEGER ]},\n { ALT: () => <const> [ CONSUME(l.terminals.decimalPositive), CommonIRIs.DECIMAL ]},\n { ALT: () => <const> [ CONSUME(l.terminals.doublePositive), CommonIRIs.DOUBLE ]},\n ]);\n return ACTION(() => C.astFactory.termLiteral(\n C.astFactory.sourceLocation(parsed[0]),\n parsed[0].image,\n C.astFactory.termNamed(C.astFactory.sourceLocation(), parsed[1]),\n ));\n },\n};\n\n/**\n * Parses a negative numeric literal.\n * [[133]](https://www.w3.org/TR/sparql11-query/#rNumericLiteralNegative)\n */\nexport const numericLiteralNegative: SparqlGrammarRule<'numericLiteralNegative', TermLiteralTyped> = <const> {\n name: 'numericLiteralNegative',\n impl: ({ ACTION, CONSUME, OR }) => (C) => {\n const parsed = OR<[IToken, string]>([\n { ALT: () => <const> [ CONSUME(l.terminals.integerNegative), CommonIRIs.INTEGER ]},\n { ALT: () => <const> [ CONSUME(l.terminals.decimalNegative), CommonIRIs.DECIMAL ]},\n { ALT: () => <const> [ CONSUME(l.terminals.doubleNegative), CommonIRIs.DOUBLE ]},\n ]);\n return ACTION(() => C.astFactory.termLiteral(\n C.astFactory.sourceLocation(parsed[0]),\n parsed[0].image,\n C.astFactory.termNamed(C.astFactory.sourceLocation(), parsed[1]),\n ));\n },\n};\n\n/**\n * Parses a boolean literal.\n * [[134]](https://www.w3.org/TR/sparql11-query/#rBooleanLiteral)\n */\nexport const booleanLiteral: SparqlGrammarRule<'booleanLiteral', TermLiteralTyped> = <const> {\n name: 'booleanLiteral',\n impl: ({ ACTION, CONSUME, OR }) => (C) => {\n const token = OR([\n { ALT: () => CONSUME(l.true_) },\n { ALT: () => CONSUME(l.false_) },\n ]);\n\n return ACTION(() => C.astFactory.termLiteral(\n C.astFactory.sourceLocation(token),\n token.image.toLowerCase(),\n C.astFactory.termNamed(C.astFactory.sourceLocation(), CommonIRIs.BOOLEAN),\n ));\n },\n};\n\n/**\n * Parses a string literal.\n * [[135]](https://www.w3.org/TR/sparql11-query/#rString)\n */\nexport const string: SparqlGrammarRule<'string', TermLiteralStr> = <const> {\n name: 'string',\n impl: ({ ACTION, CONSUME, OR }) => (C) => {\n const x = OR([\n { ALT: () => {\n const token = CONSUME(l.terminals.stringLiteral1);\n return <const>[ token, token.image.slice(1, -1) ];\n } },\n { ALT: () => {\n const token = CONSUME(l.terminals.stringLiteral2);\n return <const>[ token, token.image.slice(1, -1) ];\n } },\n { ALT: () => {\n const token = CONSUME(l.terminals.stringLiteralLong1);\n return <const>[ token, token.image.slice(3, -3) ];\n } },\n { ALT: () => {\n const token = CONSUME(l.terminals.stringLiteralLong2);\n return <const>[ token, token.image.slice(3, -3) ];\n } },\n ]);\n // Handle string escapes (19.7). (19.2 is handled at input level.)\n return ACTION(() => {\n const F = C.astFactory;\n const value = x[1].replaceAll(/\\\\([tnrbf\"'\\\\])/gu, (_, char: string) => {\n switch (char) {\n case 't':\n return '\\t';\n case 'n':\n return '\\n';\n case 'r':\n return '\\r';\n case 'b':\n return '\\b';\n case 'f':\n return '\\f';\n default:\n return char;\n }\n });\n return F.termLiteral(F.sourceLocation(x[0]), value);\n });\n },\n};\n\n/**\n * Parses a named node, either as an IRI or as a prefixed name.\n * [[136]](https://www.w3.org/TR/sparql11-query/#riri)\n */\nexport const iri: SparqlRule<'iri', TermIri> = <const> {\n name: 'iri',\n impl: ({ SUBRULE, OR }) => () => OR<TermIri>([\n { ALT: () => SUBRULE(iriFull) },\n { ALT: () => SUBRULE(prefixedName) },\n ]),\n gImpl: ({ SUBRULE }) => (ast, { astFactory: F }) =>\n F.isTermNamedPrefixed(ast) ? SUBRULE(prefixedName, ast) : SUBRULE(iriFull, ast),\n};\n\nexport const iriFull: SparqlRule<'iriFull', TermIriFull> = <const> {\n name: 'iriFull',\n impl: ({ ACTION, CONSUME }) => (C) => {\n const iriToken = CONSUME(l.terminals.iriRef);\n return ACTION(() => C.astFactory.termNamed(C.astFactory.sourceLocation(iriToken), iriToken.image.slice(1, -1)));\n },\n gImpl: ({ PRINT }) => (ast, { astFactory: F }) => {\n F.printFilter(ast, () => PRINT('<', ast.value, '>'));\n },\n};\n\n/**\n * Parses a named node with a prefix. Looks up the prefix in the context and returns the full IRI.\n * [[137]](https://www.w3.org/TR/sparql11-query/#rPrefixedName)\n */\nexport const prefixedName: SparqlRule<'prefixedName', TermIriPrefixed> = <const> {\n name: 'prefixedName',\n impl: ({ ACTION, CONSUME, OR }) => (C) => {\n function verifyPrefix(prefix: string): void {\n if (!C.skipValidation && C.prefixes[prefix] === undefined) {\n throw new Error(`Unknown prefix: ${prefix}`);\n }\n }\n return OR([{ ALT: () => {\n const longName = CONSUME(l.terminals.pNameLn);\n return ACTION(() => {\n // The local name may itself contain colons, only the first one ends the prefix.\n // https://www.w3.org/TR/sparql12-query/#rPN_LOCAL\n const colon = longName.image.indexOf(':');\n const prefix = longName.image.slice(0, colon);\n const localName = longName.image.slice(colon + 1);\n verifyPrefix(prefix);\n return C.astFactory.termNamed(C.astFactory.sourceLocation(longName), localName, prefix);\n });\n },\n }, { ALT: () => {\n const shortName = CONSUME(l.terminals.pNameNs);\n return ACTION(() => {\n const prefix = shortName.image.slice(0, -1);\n verifyPrefix(prefix);\n return C.astFactory.termNamed(\n C.astFactory.sourceLocation(shortName),\n '',\n prefix,\n );\n });\n },\n }]);\n },\n gImpl: ({ PRINT }) => (ast, { astFactory: F }) => {\n F.printFilter(ast, () => PRINT(ast.prefix, ':', ast.value));\n },\n};\n\nexport const canCreateBlankNodes = Symbol('canCreateBlankNodes');\n\n/**\n * Parses blank note and throws an error if 'canCreateBlankNodes' is not in the current parserMode.\n * [[138]](https://www.w3.org/TR/sparql11-query/#rBlankNode)\n */\nexport const blankNode: SparqlRule<'blankNode', TermBlank> = <const> {\n name: 'blankNode',\n impl: ({ ACTION, CONSUME, OR }) => (C) => {\n const result = OR([\n { ALT: () => {\n const labelToken = CONSUME(l.terminals.blankNodeLabel);\n return ACTION(() =>\n C.astFactory.termBlank(labelToken.image.slice(2), C.astFactory.sourceLocation(labelToken)));\n } },\n { ALT: () => {\n const anonToken = CONSUME(l.terminals.anon);\n return ACTION(() => C.astFactory.termBlank(undefined, C.astFactory.sourceLocation(anonToken)));\n } },\n ]);\n ACTION(() => {\n if (!C.parseMode.has('canCreateBlankNodes')) {\n throw new Error('Blank nodes are not allowed in this context');\n }\n });\n return result;\n },\n gImpl: ({ PRINT }) => (ast, { astFactory }) => {\n astFactory.printFilter(ast, () => PRINT('_:', ast.label.replace(/^e_/u, '')));\n },\n};\n\nexport const verbA: SparqlGrammarRule<'VerbA', TermIriFull> = <const> {\n name: 'VerbA',\n impl: ({ ACTION, CONSUME }) => (C) => {\n const token = CONSUME(l.a);\n return ACTION(() => C.astFactory.termNamed(C.astFactory.sourceLocation(token), CommonIRIs.TYPE, undefined));\n },\n};\n", "import * as l from '../lexer/index.js';\nimport type { SparqlGrammarRule, SparqlRule } from '../sparql11HelperTypes.js';\nimport type {\n ContextDefinition,\n ContextDefinitionBase,\n ContextDefinitionPrefix,\n GraphTerm,\n Term,\n TermIri,\n TermVariable,\n} from '../Sparql11types.js';\nimport { CommonIRIs } from '../utils.js';\nimport { blankNode, booleanLiteral, iri, iriFull, numericLiteral, rdfLiteral, verbA } from './literals.js';\n\n/**\n * [[4]](https://www.w3.org/TR/sparql11-query/#rPrologue)\n */\nexport const prologue: SparqlRule<'prologue', ContextDefinition[]> = <const> {\n name: 'prologue',\n impl: ({ SUBRULE, MANY, OR }) => () => {\n const result: ContextDefinition[] = [];\n MANY(() => OR([\n { ALT: () => result.push(SUBRULE(baseDecl)) },\n // TODO: the [spec](https://www.w3.org/TR/sparql11-query/#iriRefs) says you cannot redefine prefixes.\n // We might need to check this.\n { ALT: () => result.push(SUBRULE(prefixDecl)) },\n ]));\n return result;\n },\n gImpl: ({ SUBRULE }) => (ast, { astFactory: F }) => {\n for (const context of ast) {\n if (F.isContextDefinitionBase(context)) {\n SUBRULE(baseDecl, context);\n } else {\n SUBRULE(prefixDecl, context);\n }\n }\n },\n};\n\n/**\n * Registers base IRI in the context and returns it.\n * [[5]](https://www.w3.org/TR/sparql11-query/#rBaseDecl)\n */\nexport const baseDecl: SparqlRule<'baseDecl', ContextDefinitionBase> = <const> {\n name: 'baseDecl',\n impl: ({ ACTION, CONSUME, SUBRULE }) => (C) => {\n const base = CONSUME(l.baseDecl);\n const val = SUBRULE(iriFull);\n return ACTION(() => C.astFactory.contextDefinitionBase(C.astFactory.sourceLocation(base, val), val));\n },\n gImpl: ({ SUBRULE, PRINT_ON_EMPTY, NEW_LINE }) => (ast, { astFactory: F }) => {\n F.printFilter(ast, () => PRINT_ON_EMPTY('BASE '));\n SUBRULE(iri, ast.value);\n F.printFilter(ast, () => NEW_LINE());\n },\n};\n\n/**\n * Registers prefix in the context and returns registered key-value-pair.\n * [[6]](https://www.w3.org/TR/sparql11-query/#rPrefixDecl)\n */\nexport const prefixDecl: SparqlRule<'prefixDecl', ContextDefinitionPrefix> = <const> {\n name: 'prefixDecl',\n impl: ({ ACTION, CONSUME, SUBRULE }) => (C) => {\n const prefix = CONSUME(l.prefixDecl);\n const name = CONSUME(l.terminals.pNameNs).image.slice(0, -1);\n const value = SUBRULE(iriFull);\n\n return ACTION(() => {\n C.prefixes[name] = value.value;\n return C.astFactory.contextDefinitionPrefix(C.astFactory.sourceLocation(prefix, value), name, value);\n });\n },\n gImpl: ({ SUBRULE, PRINT_ON_EMPTY, NEW_LINE }) => (ast, { astFactory: F }) => {\n F.printFilter(ast, () => {\n PRINT_ON_EMPTY('PREFIX ', `${ast.key}: `);\n });\n SUBRULE(iri, ast.value);\n F.printFilter(ast, () => NEW_LINE());\n },\n};\n\n/**\n * [[78]](https://www.w3.org/TR/sparql11-query/#rVerb)\n */\nexport const verb: SparqlGrammarRule<'verb', TermVariable | TermIri> = <const> {\n name: 'verb',\n impl: ({ SUBRULE, OR }) => () => OR([\n { ALT: () => SUBRULE(varOrIri) },\n { ALT: () => SUBRULE(verbA) },\n ]),\n};\n\n/**\n * [[106]](https://www.w3.org/TR/sparql11-query/#rVarOrTerm)\n */\nexport const varOrTerm: SparqlRule<'varOrTerm', Term> = <const> {\n name: 'varOrTerm',\n impl: ({ SUBRULE, OR }) => C => OR<Term>([\n { GATE: () => C.parseMode.has('canParseVars'), ALT: () => SUBRULE(var_) },\n { ALT: () => SUBRULE(graphTerm) },\n ]),\n gImpl: ({ SUBRULE }) => (ast, { astFactory: F }) => {\n if (F.isTermVariable(ast)) {\n return SUBRULE(var_, ast);\n }\n return SUBRULE(graphTerm, ast);\n },\n};\n\n/**\n * [[107]](https://www.w3.org/TR/sparql11-query/#rVarOrIri)\n */\nexport const varOrIri: SparqlGrammarRule<'varOrIri', TermIri | TermVariable> = <const> {\n name: 'varOrIri',\n impl: ({ SUBRULE, OR }) => C => OR<TermIri | TermVariable>([\n { GATE: () => C.parseMode.has('canParseVars'), ALT: () => SUBRULE(var_) },\n { ALT: () => SUBRULE(iri) },\n ]),\n};\n\n/**\n * [[108]](https://www.w3.org/TR/sparql11-query/#rVar)\n */\nexport const var_: SparqlRule<'var', TermVariable> = <const> {\n name: 'var',\n impl: ({ ACTION, CONSUME, OR }) => (C) => {\n const varToken = OR([\n { ALT: () => CONSUME(l.terminals.var1) },\n { ALT: () => CONSUME(l.terminals.var2) },\n ]);\n return ACTION(() => C.astFactory.termVariable(varToken.image.slice(1), C.astFactory.sourceLocation(varToken)));\n },\n gImpl: ({ PRINT }) => (ast, { astFactory: F }) => {\n F.printFilter(ast, () => PRINT(`?${ast.value}`));\n },\n};\n\n/**\n * [[109]](https://www.w3.org/TR/sparql11-query/#rGraphTerm)\n */\nexport const graphTerm: SparqlRule<'graphTerm', GraphTerm> = <const> {\n name: 'graphTerm',\n impl: ({ ACTION, SUBRULE, CONSUME, OR }) => C => OR<GraphTerm>([\n { ALT: () => SUBRULE(iri) },\n { ALT: () => SUBRULE(rdfLiteral) },\n { ALT: () => SUBRULE(numericLiteral) },\n { ALT: () => SUBRULE(booleanLiteral) },\n { GATE: () => C.parseMode.has('canCreateBlankNodes'), ALT: () => SUBRULE(blankNode) },\n { ALT: () => {\n const tokenNil = CONSUME(l.terminals.nil);\n return ACTION(() =>\n C.astFactory.termNamed(C.astFactory.sourceLocation(tokenNil), CommonIRIs.NIL));\n } },\n ]),\n gImpl: ({ SUBRULE }) => (ast, { astFactory: F }) => {\n if (F.isTermNamed(ast)) {\n SUBRULE(iri, ast);\n } else if (F.isTermLiteral(ast)) {\n SUBRULE(rdfLiteral, ast);\n } else {\n SUBRULE(blankNode, ast);\n }\n },\n};\n", "import type { TokenType } from '@traqula/chevrotain';\nimport type { RuleDefReturn, Wrap } from '@traqula/core';\nimport * as l from '../lexer/index.js';\nimport type { SparqlGrammarRule, SparqlRule } from '../sparql11HelperTypes.js';\nimport type { DatasetClauses, TermIri } from '../Sparql11types.js';\nimport { iri } from './literals.js';\n\nexport function datasetClauseUsing<RuleName extends 'usingClause' | 'datasetClause'>(\n name: RuleName,\n token: TokenType,\n): SparqlGrammarRule<RuleName, Wrap<DatasetClauses['clauses'][0]>> {\n return {\n name,\n impl: ({ ACTION, SUBRULE, CONSUME, OR }) => (C) => {\n const start = CONSUME(token);\n return OR<RuleDefReturn<typeof datasetClause>>([\n { ALT: () => {\n const iri = SUBRULE(defaultGraphClause);\n return ACTION(() =>\n C.astFactory.wrap({ clauseType: 'default', value: iri }, C.astFactory.sourceLocation(start, iri)));\n } },\n { ALT: () => {\n const namedClause = SUBRULE(namedGraphClause);\n return ACTION(() => C.astFactory.wrap({\n clauseType: 'named',\n value: namedClause.val,\n }, C.astFactory.sourceLocation(start, namedClause)));\n } },\n ]);\n },\n };\n}\n\n/**\n * [[13]](https://www.w3.org/TR/sparql11-query/#rDatasetClause)\n */\nexport const datasetClause = datasetClauseUsing('datasetClause', l.from);\n\n/**\n * [[14]](https://www.w3.org/TR/sparql11-query/#rDefaultGraphClause)\n */\nexport const defaultGraphClause: SparqlGrammarRule<'defaultGraphClause', TermIri> = <const> {\n name: 'defaultGraphClause',\n impl: ({ SUBRULE }) => () => SUBRULE(sourceSelector),\n};\n/**\n * [[44]](https://www.w3.org/TR/sparql11-query/#rUsingClause)\n */\nexport const usingClause = datasetClauseUsing('usingClause', l.usingClause);\n\nexport function datasetClauseUsingStar<RuleName extends string>(\n name: RuleName,\n subRule: ReturnType<typeof datasetClauseUsing<any>>,\n fromUsing: 'FROM' | 'USING',\n): SparqlRule<RuleName, DatasetClauses> {\n return {\n name,\n impl: ({ ACTION, MANY, SUBRULE }) => (C) => {\n const clauses: RuleDefReturn<typeof datasetClause>[] = [];\n\n MANY(() => {\n const clause = SUBRULE(subRule);\n clauses.push(clause);\n });\n\n return ACTION(() => C.astFactory.datasetClauses(\n clauses.map(clause => clause.val),\n C.astFactory.sourceLocation(...clauses),\n ));\n },\n gImpl: ({ SUBRULE, PRINT_WORD }) => (ast, { astFactory: F }) => {\n for (const clause of ast.clauses) {\n F.printFilter(ast, () => PRINT_WORD(fromUsing));\n if (clause.clauseType === 'named') {\n F.printFilter(ast, () => PRINT_WORD('NAMED'));\n }\n SUBRULE(iri, clause.value);\n }\n },\n };\n}\n\nexport const datasetClauseStar = datasetClauseUsingStar(<const> 'datasetClauses', datasetClause, 'FROM');\nexport const usingClauseStar = datasetClauseUsingStar(<const> 'usingClauses', usingClause, 'USING');\n\n/**\n * [[15]](https://www.w3.org/TR/sparql11-query/#rNamedGraphClause)\n */\nexport const namedGraphClause: SparqlGrammarRule<'namedGraphClause', Wrap<TermIri>> = <const> {\n name: 'namedGraphClause',\n impl: ({ ACTION, SUBRULE, CONSUME }) => (C) => {\n const named = CONSUME(l.graph.named);\n const iri = SUBRULE(sourceSelector);\n return ACTION(() => C.astFactory.wrap(iri, C.astFactory.sourceLocation(named, iri)));\n },\n};\n\n/**\n * [[16]](https://www.w3.org/TR/sparql11-query/#rSourceSelector)\n */\nexport const sourceSelector: SparqlGrammarRule<'sourceSelector', TermIri> = <const> {\n name: 'sourceSelector',\n impl: ({ SUBRULE }) => () => SUBRULE(iri),\n};\n", "import type { TokenType } from '@traqula/chevrotain';\nimport { unCapitalize } from '@traqula/core';\nimport { var_, expression, expressionList, groupGraphPattern } from './grammar/index.js';\nimport * as l from './lexer/index.js';\nimport type { SparqlGrammarRule } from './sparql11HelperTypes.js';\nimport type {\n Expression,\n ExpressionAggregateDefault,\n ExpressionOperation,\n ExpressionPatternOperation,\n TermVariable,\n} from './Sparql11types.js';\n\nexport type ExpressionFunctionX<U extends Expression[]> = ExpressionOperation & {\n args: U;\n};\n\nexport type RuleDefExpressionFunctionX<T extends string, U extends Expression[]>\n = SparqlGrammarRule<T, ExpressionFunctionX<U>>;\n\n/**\n * Create a grammar rule for a SPARQL built-in function that takes exactly one expression argument.\n * The rule name is derived from the token name (uncapitalized).\n * @param func - The lexer token for the built-in function keyword.\n */\nexport function funcExpr1<T extends string>(func: TokenType & { name: T }):\nRuleDefExpressionFunctionX<Uncapitalize<T>, [Expression]> {\n return {\n name: unCapitalize(func.name),\n impl: ({ ACTION, SUBRULE, CONSUME }) => (C) => {\n const operator = CONSUME(func);\n CONSUME(l.symbols.LParen);\n const arg = SUBRULE(expression);\n const close = CONSUME(l.symbols.RParen);\n return ACTION(() =>\n C.astFactory.expressionOperation(operator.image, [ arg ], C.astFactory.sourceLocation(operator, close)));\n },\n };\n}\n\n/**\n * Create a grammar rule for a SPARQL built-in function that takes exactly two expression arguments.\n * @param func - The lexer token for the built-in function keyword.\n */\nexport function funcExpr2<T extends string>(func: TokenType & { name: T }):\nRuleDefExpressionFunctionX<Uncapitalize<T>, [Expression, Expression]> {\n return {\n name: unCapitalize(func.name),\n impl: ({ ACTION, CONSUME, SUBRULE1, SUBRULE2 }) => (C) => {\n const operator = CONSUME(func);\n CONSUME(l.symbols.LParen);\n const arg1 = SUBRULE1(expression);\n CONSUME(l.symbols.comma);\n const arg2 = SUBRULE2(expression);\n const close = CONSUME(l.symbols.RParen);\n return ACTION(() =>\n C.astFactory.expressionOperation(operator.image, [ arg1, arg2 ], C.astFactory.sourceLocation(operator, close)));\n },\n };\n}\n\n/**\n * Create a grammar rule for a SPARQL built-in function that takes exactly three expression arguments.\n * @param func - The lexer token for the built-in function keyword.\n */\nexport function funcExpr3<T extends string>(func: TokenType & { name: T }):\nRuleDefExpressionFunctionX<Uncapitalize<T>, [Expression, Expression, Expression]> {\n return {\n name: unCapitalize(func.name),\n impl: ({ ACTION, CONSUME, CONSUME1, CONSUME2, SUBRULE1, SUBRULE2, SUBRULE3 }) => (C) => {\n const operator = CONSUME(func);\n CONSUME(l.symbols.LParen);\n const arg1 = SUBRULE1(expression);\n CONSUME1(l.symbols.comma);\n const arg2 = SUBRULE2(expression);\n CONSUME2(l.symbols.comma);\n const arg3 = SUBRULE3(expression);\n const close = CONSUME(l.symbols.RParen);\n\n return ACTION(() =>\n C.astFactory.expressionOperation(\n operator.image,\n [ arg1, arg2, arg3 ],\n C.astFactory.sourceLocation(operator, close),\n ));\n },\n };\n}\n\n/**\n * Create a grammar rule for a SPARQL built-in function that takes exactly one variable argument.\n * @param func - The lexer token for the built-in function keyword.\n */\nexport function funcVar1<T extends string>(func: TokenType & { name: T }):\nRuleDefExpressionFunctionX<Uncapitalize<T>, [TermVariable]> {\n return {\n name: unCapitalize(func.name),\n impl: ({ ACTION, SUBRULE, CONSUME }) => (C) => {\n const operator = CONSUME(func);\n CONSUME(l.symbols.LParen);\n const arg = SUBRULE(var_);\n const close = CONSUME(l.symbols.RParen);\n return ACTION(() =>\n C.astFactory.expressionOperation(operator.image, [ arg ], C.astFactory.sourceLocation(operator, close)));\n },\n };\n}\n\n/**\n * Create a grammar rule for a SPARQL built-in function that takes zero or one expression argument.\n * Supports both `FUNC(expr)` and `FUNC NIL` syntax.\n * @param func - The lexer token for the built-in function keyword.\n */\nexport function funcExprOrNil1<T extends string>(func: TokenType & { name: T }):\nRuleDefExpressionFunctionX<Uncapitalize<T>, [] | [Expression]> {\n return {\n name: unCapitalize(func.name),\n impl: ({ ACTION, CONSUME, OR, SUBRULE }) => (C) => {\n const operator = CONSUME(func);\n return OR<ExpressionFunctionX<[] | [Expression]>>([\n { ALT: () => {\n CONSUME(l.symbols.LParen);\n const arg = SUBRULE(expression);\n const close = CONSUME(l.symbols.RParen);\n return ACTION(() =>\n C.astFactory.expressionOperation(operator.image, [ arg ], C.astFactory.sourceLocation(operator, close)));\n } },\n { ALT: () => {\n const nil = CONSUME(l.terminals.nil);\n return ACTION(() =>\n C.astFactory.expressionOperation(operator.image, [], C.astFactory.sourceLocation(operator, nil)));\n } },\n ]);\n },\n };\n}\n\n/**\n * Create a grammar rule for a SPARQL built-in function that takes no arguments (NIL syntax only).\n * @param func - The lexer token for the built-in function keyword.\n */\nexport function funcNil1<T extends string>(func: TokenType & { name: T }):\nRuleDefExpressionFunctionX<Uncapitalize<T>, []> {\n return {\n name: unCapitalize(func.name),\n impl: ({ ACTION, CONSUME }) => (C) => {\n const operator = CONSUME(func);\n const nil = CONSUME(l.terminals.nil);\n return ACTION(() =>\n C.astFactory.expressionOperation(operator.image, [], C.astFactory.sourceLocation(operator, nil)));\n },\n };\n}\n\n/**\n * Create a grammar rule for a SPARQL built-in function that takes an expression list argument.\n * @param func - The lexer token for the built-in function keyword.\n */\nexport function funcExprList1<T extends string>(func: TokenType & { name: T }):\nRuleDefExpressionFunctionX<Uncapitalize<T>, Expression[]> {\n return {\n name: unCapitalize(func.name),\n impl: ({ ACTION, CONSUME, SUBRULE }) => (C) => {\n const operator = CONSUME(func);\n const args = SUBRULE(expressionList);\n return ACTION(() =>\n C.astFactory.expressionOperation(operator.image, args.val, C.astFactory.sourceLocation(operator, args)));\n },\n };\n}\n\n/**\n * Create a grammar rule for a SPARQL built-in function that takes two or three expression arguments.\n * @param func - The lexer token for the built-in function keyword.\n */\nexport function funcExpr2or3<T extends string>(func: TokenType & { name: T }):\nRuleDefExpressionFunctionX<Uncapitalize<T>, [Expression, Expression] | [Expression, Expression, Expression]> {\n return {\n name: unCapitalize(func.name),\n impl: ({ ACTION, CONSUME, SUBRULE1, SUBRULE2, SUBRULE3, CONSUME1, OPTION, CONSUME2 }) =>\n (C) => {\n const operator = CONSUME(func);\n CONSUME(l.symbols.LParen);\n const arg1 = SUBRULE1(expression);\n CONSUME1(l.symbols.comma);\n const arg2 = SUBRULE2(expression);\n const arg3 = OPTION(() => {\n CONSUME2(l.symbols.comma);\n return SUBRULE3(expression);\n });\n const close = CONSUME(l.symbols.RParen);\n return ACTION(() => C.astFactory.expressionOperation(\n operator.image,\n arg3 ? <const> [ arg1, arg2, arg3 ] : <const> [ arg1, arg2 ],\n C.astFactory.sourceLocation(operator, close),\n ));\n },\n };\n}\n\n/**\n * Create a grammar rule for a SPARQL built-in function that takes three or four expression arguments.\n * @param func - The lexer token for the built-in function keyword.\n */\nexport function funcExpr3or4<T extends string>(func: TokenType & { name: T }):\nRuleDefExpressionFunctionX<\n Uncapitalize<T>,\n [Expression, Expression, Expression] | [Expression, Expression, Expression, Expression]\n> {\n return {\n name: unCapitalize(func.name),\n impl: ({\n ACTION,\n CONSUME,\n SUBRULE1,\n SUBRULE2,\n SUBRULE3,\n SUBRULE4,\n CONSUME1,\n OPTION,\n CONSUME2,\n CONSUME3,\n }) =>\n (C) => {\n const operator = CONSUME(func);\n CONSUME(l.symbols.LParen);\n const arg1 = SUBRULE1(expression);\n CONSUME1(l.symbols.comma);\n const arg2 = SUBRULE2(expression);\n CONSUME2(l.symbols.comma);\n const arg3 = SUBRULE3(expression);\n const arg4 = OPTION(() => {\n CONSUME3(l.symbols.comma);\n return SUBRULE4(expression);\n });\n const close = CONSUME(l.symbols.RParen);\n return ACTION(() => C.astFactory.expressionOperation(\n operator.image,\n arg4 ? <const> [ arg1, arg2, arg3, arg4 ] : <const> [ arg1, arg2, arg3 ],\n C.astFactory.sourceLocation(operator, close),\n ));\n },\n };\n}\n\n/**\n * Create a grammar rule for a SPARQL built-in function that takes a GroupGraphPattern argument\n * (e.g. EXISTS, NOT EXISTS).\n * @param func - The lexer token for the built-in function keyword.\n */\nexport function funcGroupGraphPattern<T extends string>(func: TokenType & { name: T }):\nSparqlGrammarRule<Uncapitalize<T>, ExpressionPatternOperation> {\n return {\n name: unCapitalize(func.name),\n impl: ({ ACTION, SUBRULE, CONSUME }) => (C) => {\n const operator = CONSUME(func);\n const group = SUBRULE(groupGraphPattern);\n return ACTION(() => C.astFactory.expressionPatternOperation(\n operator.image,\n group,\n C.astFactory.sourceLocation(operator, group),\n ));\n },\n };\n}\n\nexport type RuleDefExpressionAggregatorX<T extends string> = SparqlGrammarRule<T, ExpressionAggregateDefault>;\n\n/**\n * Create a grammar rule for a SPARQL aggregate function (e.g. SUM, AVG, MIN, MAX)\n * that takes a single expression with an optional DISTINCT modifier.\n * @param func - The lexer token for the aggregate function keyword.\n */\nexport function baseAggregateFunc<T extends string>(func: TokenType & { name: T }):\nRuleDefExpressionAggregatorX<Uncapitalize<T>> {\n return {\n name: unCapitalize(func.name),\n impl: ({ ACTION, CONSUME, SUBRULE, OPTION }) => (C) => {\n const operator = CONSUME(func);\n CONSUME(l.symbols.LParen);\n const distinct = OPTION(() => CONSUME(l.distinct));\n const expr1 = SUBRULE(expression);\n const close = CONSUME(l.symbols.RParen);\n\n return ACTION(() => C.astFactory.aggregate(\n operator.image,\n distinct !== undefined,\n expr1,\n undefined,\n C.astFactory.sourceLocation(operator, close),\n ));\n },\n };\n}\n", "import type { IOrAlt } from '@traqula/chevrotain';\nimport type { ImplArgs } from '@traqula/core';\nimport {\n unCapitalize,\n} from '@traqula/core';\nimport {\n funcExprOrNil1,\n baseAggregateFunc,\n funcExpr1,\n funcExpr2,\n funcExpr2or3,\n funcExpr3,\n funcExpr3or4,\n funcExprList1,\n funcGroupGraphPattern,\n funcNil1,\n funcVar1,\n} from '../expressionHelpers.js';\nimport * as l from '../lexer/index.js';\nimport type { SparqlGrammarRule, SparqlRule } from '../sparql11HelperTypes.js';\nimport type {\n Expression,\n ExpressionAggregate,\n ExpressionAggregateDefault,\n ExpressionAggregateOnWildcard,\n ExpressionAggregateSeparator,\n Wildcard,\n} from '../Sparql11types.js';\nimport { expression } from './expression.js';\nimport { string, stringEscapedLexical } from './literals.js';\n\nexport const builtInStr = funcExpr1(l.builtIn.str);\nexport const builtInLang = funcExpr1(l.builtIn.lang);\nexport const builtInLangmatches = funcExpr2(l.builtIn.langmatches);\nexport const builtInDatatype = funcExpr1(l.builtIn.datatype);\nexport const builtInBound = funcVar1(l.builtIn.bound);\nexport const builtInIri = funcExpr1(l.builtIn.iri);\nexport const builtInUri = funcExpr1(l.builtIn.uri);\nexport const builtInBnodeSparqlJs = funcExprOrNil1(l.builtIn.bnode);\nexport const builtInRand = funcNil1(l.builtIn.rand);\nexport const builtInAbs = funcExpr1(l.builtIn.abs);\nexport const builtInCeil = funcExpr1(l.builtIn.ceil);\nexport const builtInFloor = funcExpr1(l.builtIn.floor);\nexport const builtInRound = funcExpr1(l.builtIn.round);\nexport const builtInConcat = funcExprList1(l.builtIn.concat);\nexport const builtInStrlen = funcExpr1(l.builtIn.strlen);\nexport const builtInUcase = funcExpr1(l.builtIn.ucase);\nexport const builtInLcase = funcExpr1(l.builtIn.lcase);\nexport const builtInEncode_for_uri = funcExpr1(l.builtIn.encode_for_uri);\nexport const builtInContains = funcExpr2(l.builtIn.contains);\nexport const builtInStrstarts = funcExpr2(l.builtIn.strstarts);\nexport const builtInStrends = funcExpr2(l.builtIn.strends);\nexport const builtInStrbefore = funcExpr2(l.builtIn.strbefore);\nexport const builtInStrafter = funcExpr2(l.builtIn.strafter);\nexport const builtInYear = funcExpr1(l.builtIn.year);\nexport const builtInMonth = funcExpr1(l.builtIn.month);\nexport const builtInDay = funcExpr1(l.builtIn.day);\nexport const builtInHours = funcExpr1(l.builtIn.hours);\nexport const builtInMinutes = funcExpr1(l.builtIn.minutes);\nexport const builtInSeconds = funcExpr1(l.builtIn.seconds);\nexport const builtInTimezone = funcExpr1(l.builtIn.timezone);\nexport const builtInTz = funcExpr1(l.builtIn.tz);\nexport const builtInNow = funcNil1(l.builtIn.now);\nexport const builtInUuid = funcNil1(l.builtIn.uuid);\nexport const builtInStruuid = funcNil1(l.builtIn.struuid);\nexport const builtInMd5 = funcExpr1(l.builtIn.md5);\nexport const builtInSha1 = funcExpr1(l.builtIn.sha1);\nexport const builtInSha256 = funcExpr1(l.builtIn.sha256);\nexport const builtInSha384 = funcExpr1(l.builtIn.sha384);\nexport const builtInSha512 = funcExpr1(l.builtIn.sha512);\nexport const builtInCoalesce = funcExprList1(l.builtIn.coalesce);\nexport const builtInIf = funcExpr3(l.builtIn.if_);\nexport const builtInStrlang = funcExpr2(l.builtIn.strlang);\nexport const builtInStrdt = funcExpr2(l.builtIn.strdt);\nexport const builtInSameterm = funcExpr2(l.builtIn.sameterm);\nexport const builtInIsiri = funcExpr1(l.builtIn.isiri);\nexport const builtInIsuri = funcExpr1(l.builtIn.isuri);\nexport const builtInIsblank = funcExpr1(l.builtIn.isblank);\nexport const builtInIsliteral = funcExpr1(l.builtIn.isliteral);\nexport const builtInIsnumeric = funcExpr1(l.builtIn.isnumeric);\n\nexport function builtInCallList(SUBRULE: ImplArgs['SUBRULE']): IOrAlt<Expression>[] {\n return [\n { ALT: () => SUBRULE(aggregate) },\n { ALT: () => SUBRULE(builtInStr) },\n { ALT: () => SUBRULE(builtInLang) },\n { ALT: () => SUBRULE(builtInLangmatches) },\n { ALT: () => SUBRULE(builtInDatatype) },\n { ALT: () => SUBRULE(builtInBound) },\n { ALT: () => SUBRULE(builtInIri) },\n { ALT: () => SUBRULE(builtInUri) },\n { ALT: () => SUBRULE(builtInBnodeSparqlJs) },\n { ALT: () => SUBRULE(builtInRand) },\n { ALT: () => SUBRULE(builtInAbs) },\n { ALT: () => SUBRULE(builtInCeil) },\n { ALT: () => SUBRULE(builtInFloor) },\n { ALT: () => SUBRULE(builtInRound) },\n { ALT: () => SUBRULE(builtInConcat) },\n { ALT: () => SUBRULE(substringExpression) },\n { ALT: () => SUBRULE(builtInStrlen) },\n { ALT: () => SUBRULE(strReplaceExpression) },\n { ALT: () => SUBRULE(builtInUcase) },\n { ALT: () => SUBRULE(builtInLcase) },\n { ALT: () => SUBRULE(builtInEncode_for_uri) },\n { ALT: () => SUBRULE(builtInContains) },\n { ALT: () => SUBRULE(builtInStrstarts) },\n { ALT: () => SUBRULE(builtInStrends) },\n { ALT: () => SUBRULE(builtInStrbefore) },\n { ALT: () => SUBRULE(builtInStrafter) },\n { ALT: () => SUBRULE(builtInYear) },\n { ALT: () => SUBRULE(builtInMonth) },\n { ALT: () => SUBRULE(builtInDay) },\n { ALT: () => SUBRULE(builtInHours) },\n { ALT: () => SUBRULE(builtInMinutes) },\n { ALT: () => SUBRULE(builtInSeconds) },\n { ALT: () => SUBRULE(builtInTimezone) },\n { ALT: () => SUBRULE(builtInTz) },\n { ALT: () => SUBRULE(builtInNow) },\n { ALT: () => SUBRULE(builtInUuid) },\n { ALT: () => SUBRULE(builtInStruuid) },\n { ALT: () => SUBRULE(builtInMd5) },\n { ALT: () => SUBRULE(builtInSha1) },\n { ALT: () => SUBRULE(builtInSha256) },\n { ALT: () => SUBRULE(builtInSha384) },\n { ALT: () => SUBRULE(builtInSha512) },\n { ALT: () => SUBRULE(builtInCoalesce) },\n { ALT: () => SUBRULE(builtInIf) },\n { ALT: () => SUBRULE(builtInStrlang) },\n { ALT: () => SUBRULE(builtInStrdt) },\n { ALT: () => SUBRULE(builtInSameterm) },\n { ALT: () => SUBRULE(builtInIsiri) },\n { ALT: () => SUBRULE(builtInIsuri) },\n { ALT: () => SUBRULE(builtInIsblank) },\n { ALT: () => SUBRULE(builtInIsliteral) },\n { ALT: () => SUBRULE(builtInIsnumeric) },\n { ALT: () => SUBRULE(regexExpression) },\n { ALT: () => SUBRULE(existsFunc) },\n { ALT: () => SUBRULE(notExistsFunc) },\n ];\n}\n\n/**\n * [[121]](https://www.w3.org/TR/sparql11-query/#rBuiltInCall)\n */\nexport const builtInCall: SparqlGrammarRule<'builtInCall', Expression> = <const>{\n name: 'builtInCall',\n impl: ({ OR, SUBRULE, cache }) => () => {\n const cached = <IOrAlt<Expression>[]>cache.get(builtInCall);\n if (cached) {\n return OR<Expression>(cached);\n }\n const builtIns = builtInCallList(SUBRULE);\n cache.set(builtInCall, builtIns);\n return OR<Expression>(builtIns);\n },\n};\n\n/**\n * [[122]](https://www.w3.org/TR/sparql11-query/#rBuiltInCall)\n */\nexport const regexExpression = funcExpr2or3(l.builtIn.regex);\n\n/**\n * [[123]](https://www.w3.org/TR/sparql11-query/#rBuiltInCall)\n */\nexport const substringExpression = funcExpr2or3(l.builtIn.substr);\n\n/**\n * [[124]](https://www.w3.org/TR/sparql11-query/#rBuiltInCall)\n */\nexport const strReplaceExpression = funcExpr3or4(l.builtIn.replace);\n\n/**\n * [[125]](https://www.w3.org/TR/sparql11-query/#rBuiltInCall)\n */\nexport const existsFunc = funcGroupGraphPattern(l.builtIn.exists);\n\n/**\n * [[126]](https://www.w3.org/TR/sparql11-query/#rBuiltInCall)\n */\nexport const notExistsFunc = funcGroupGraphPattern(l.builtIn.notexists);\n\nexport const aggregateCount:\nSparqlGrammarRule<'builtInCount', ExpressionAggregateOnWildcard | ExpressionAggregateDefault> = {\n name: unCapitalize(l.builtIn.count.name),\n impl: ({ ACTION, CONSUME, SUBRULE, OR, OPTION }) => (C) => {\n const operatorToken = CONSUME(l.builtIn.count);\n CONSUME(l.symbols.LParen);\n const distinctToken = OPTION(() => CONSUME(l.distinct));\n\n const expressionVal = OR<Expression | Wildcard>([\n { ALT: () => {\n const starToken = CONSUME(l.symbols.star);\n return ACTION(() => C.astFactory.wildcard(C.astFactory.sourceLocation(starToken)));\n } },\n { ALT: () => SUBRULE(expression) },\n ]);\n const closeToken = CONSUME(l.symbols.RParen);\n\n return ACTION(() => {\n const F = C.astFactory;\n if (C.astFactory.isWildcard(expressionVal)) {\n return F.aggregate(\n operatorToken.image,\n Boolean(distinctToken),\n expressionVal,\n undefined,\n C.astFactory.sourceLocation(operatorToken, closeToken),\n );\n }\n return F.aggregate(\n operatorToken.image,\n Boolean(distinctToken),\n expressionVal,\n undefined,\n C.astFactory.sourceLocation(operatorToken, closeToken),\n );\n });\n },\n};\nexport const aggregateSum = baseAggregateFunc(l.builtIn.sum);\nexport const aggregateMin = baseAggregateFunc(l.builtIn.min);\nexport const aggregateMax = baseAggregateFunc(l.builtIn.max);\nexport const aggregateAvg = baseAggregateFunc(l.builtIn.avg);\nexport const aggregateSample = baseAggregateFunc(l.builtIn.sample);\nexport const aggregateGroup_concat:\nSparqlGrammarRule<'builtInGroup_concat', ExpressionAggregateDefault | ExpressionAggregateSeparator> = <const>{\n name: unCapitalize(l.builtIn.groupConcat.name),\n impl: ({ ACTION, CONSUME, OPTION1, SUBRULE, OPTION2 }) =>\n (C) => {\n const operatorToken = CONSUME(l.builtIn.groupConcat);\n CONSUME(l.symbols.LParen);\n const distinctToken = OPTION1(() => CONSUME(l.distinct));\n\n const expr = SUBRULE(expression);\n const sep = OPTION2(() => {\n CONSUME(l.symbols.semi);\n CONSUME(l.separator);\n CONSUME(l.symbols.equal);\n return SUBRULE(string);\n });\n const closeToken = CONSUME(l.symbols.RParen);\n\n return ACTION(() => {\n const F = C.astFactory;\n return F.aggregate(\n operatorToken.image,\n Boolean(distinctToken),\n expr,\n sep?.value ?? ' ',\n F.sourceLocation(operatorToken, closeToken),\n );\n });\n },\n};\n\n/**\n * [[127]](https://www.w3.org/TR/sparql11-query/#rBuiltInCall)\n */\nexport const aggregate: SparqlRule<'aggregate', ExpressionAggregate> = <const>{\n name: 'aggregate',\n impl: ({ ACTION, SUBRULE, OR }) => (C) => {\n // https://www.w3.org/2013/sparql-errata#errata-query-5 - Or note 15 in SPARQL1.2 spec\n // An aggregate function is not allowed within an aggregate function.\n const wasInAggregate = ACTION(() => C.parseMode.has('inAggregate'));\n ACTION(() => C.parseMode.add('inAggregate'));\n const result = OR<ExpressionAggregate>([\n { ALT: () => SUBRULE(aggregateCount) },\n { ALT: () => SUBRULE(aggregateSum) },\n { ALT: () => SUBRULE(aggregateMin) },\n { ALT: () => SUBRULE(aggregateMax) },\n { ALT: () => SUBRULE(aggregateAvg) },\n { ALT: () => SUBRULE(aggregateSample) },\n { ALT: () => SUBRULE(aggregateGroup_concat) },\n ]);\n ACTION(() => !wasInAggregate && C.parseMode.delete('inAggregate'));\n\n ACTION(() => {\n if (!C.parseMode.has('canParseAggregate')) {\n throw new Error('Aggregates are only allowed in SELECT, HAVING, and ORDER BY clauses.');\n }\n if (C.parseMode.has('inAggregate')) {\n throw new Error('An aggregate function is not allowed within an aggregate function.');\n }\n });\n\n return result;\n },\n gImpl: ({ SUBRULE, PRINT_WORD }) => (ast, { astFactory: F }) => {\n F.printFilter(ast, () => {\n PRINT_WORD(ast.aggregation.toUpperCase(), '(');\n if (ast.distinct) {\n PRINT_WORD('DISTINCT');\n }\n });\n const arg = ast.expression[0];\n if (F.isWildcard(arg)) {\n F.printFilter(ast, () => PRINT_WORD('*'));\n } else {\n SUBRULE(expression, arg);\n }\n if (F.isExpressionAggregateSeparator(ast)) {\n F.printFilter(ast, () => PRINT_WORD(';', 'SEPARATOR', '=', stringEscapedLexical(ast.separator)));\n }\n F.printFilter(ast, () => PRINT_WORD(')'));\n },\n};\n", "import type { IToken, TokenType } from '@traqula/chevrotain';\nimport type { RuleDefReturn } from '@traqula/core';\nimport * as l from '../lexer/index.js';\nimport type { SparqlGeneratorRule, SparqlGrammarRule } from '../sparql11HelperTypes.js';\nimport type { TermIri, PathNegatedElt, Path, PathModified, PathNegated } from '../Sparql11types.js';\nimport { iri, verbA } from './literals.js';\n\n/**\n * [[88]](https://www.w3.org/TR/sparql11-query/#rPath)\n */\nexport const path: SparqlGrammarRule<'path', Path> = <const> {\n name: 'path',\n impl: ({ SUBRULE }) => () => SUBRULE(pathAlternative),\n};\n\nexport const pathGenerator: SparqlGeneratorRule<'path', Path, [boolean | undefined]> = {\n name: 'path',\n gImpl: ({ PRINT, SUBRULE }) => (ast, { astFactory: F }, braces = true) => {\n if (F.isTerm(ast) && F.isTermNamed(ast)) {\n SUBRULE(iri, ast);\n } else {\n F.printFilter(ast, () => braces && PRINT('('));\n switch (ast.subType) {\n case '|':\n case '/': {\n const [ head, ...tail ] = ast.items;\n SUBRULE(pathGenerator, head, braces);\n for (const val of tail) {\n F.printFilter(ast, () => PRINT(ast.subType));\n SUBRULE(pathGenerator, val, braces);\n }\n break;\n }\n case '^':\n F.printFilter(ast, () => PRINT('^'));\n SUBRULE(pathGenerator, ast.items[0], braces);\n break;\n case '?':\n case '*':\n case '+':\n SUBRULE(pathGenerator, ast.items[0], braces);\n F.printFilter(ast, () => PRINT(ast.subType));\n break;\n case '!':\n F.printFilter(ast, () => PRINT('!'));\n F.printFilter(ast, () => PRINT('('));\n SUBRULE(pathGenerator, ast.items[0], false);\n F.printFilter(ast, () => PRINT(')'));\n break;\n }\n F.printFilter(ast, () => braces && PRINT(')'));\n }\n },\n};\n\nexport function pathChainHelper<T extends string>(\n name: T,\n SEP: TokenType,\n subType: '|' | '/',\n subRule: SparqlGrammarRule<string, Path>,\n): SparqlGrammarRule<T, Path | TermIri> {\n return {\n name,\n impl: ({ ACTION, CONSUME, SUBRULE1, SUBRULE2, MANY }) => (C) => {\n const head = SUBRULE1(subRule);\n let tailEnd: Path = head;\n const tail: Path[] = [];\n\n MANY(() => {\n CONSUME(SEP);\n tailEnd = SUBRULE2(subRule);\n tail.push(tailEnd);\n });\n\n return ACTION(() => tail.length === 0 ?\n head :\n C.astFactory.path(subType, [ head, ...tail ], C.astFactory.sourceLocation(head, tailEnd)));\n },\n };\n}\n\n/**\n * [[92]](https://www.w3.org/TR/sparql11-query/#rPathEltOrInverse)\n */\nexport const pathEltOrInverse: SparqlGrammarRule<'pathEltOrInverse', PathModified | Path> = <const> {\n name: 'pathEltOrInverse',\n impl: ({ ACTION, CONSUME, SUBRULE1, SUBRULE2, OR }) => C => OR<Path | TermIri>([\n { ALT: () => SUBRULE1(pathElt) },\n { ALT: () => {\n const hat = CONSUME(l.symbols.hat);\n const item = SUBRULE2(pathElt);\n return ACTION(() => C.astFactory.path('^', [ item ], C.astFactory.sourceLocation(hat, item)));\n } },\n ]),\n};\n\n/**\n * [[90]](https://www.w3.org/TR/sparql11-query/#rPathSequence)\n */\nexport const pathSequence = pathChainHelper('pathSequence', l.symbols.slash, '/', pathEltOrInverse);\n\n/**\n * [[89]](https://www.w3.org/TR/sparql11-query/#rPathAlternative)\n */\nexport const pathAlternative = pathChainHelper('pathAlternative', l.symbols.pipe, '|', pathSequence);\n\n/**\n * [[91]](https://www.w3.org/TR/sparql11-query/#rPathElt)\n */\nexport const pathElt: SparqlGrammarRule<'pathElt', PathModified | Path> = <const> {\n name: 'pathElt',\n impl: ({ ACTION, SUBRULE, OPTION }) => (C) => {\n const item = SUBRULE(pathPrimary);\n const modification = OPTION(() => SUBRULE(pathMod));\n return ACTION(() => modification === undefined ?\n item :\n C.astFactory.path(modification.image, [ item ], C.astFactory.sourceLocation(item, modification)));\n },\n};\n\n/**\n * [[93]](https://www.w3.org/TR/sparql11-query/#rPathMod)\n */\nexport const pathMod: SparqlGrammarRule<'pathMod', IToken & { image: '*' | '+' | '?' }> = <const> {\n name: 'pathMod',\n impl: ({ CONSUME, OR }) => () => OR<RuleDefReturn<typeof pathMod>>([\n { ALT: () => <RuleDefReturn<typeof pathMod>> CONSUME(l.symbols.question) },\n { ALT: () => <RuleDefReturn<typeof pathMod>> CONSUME(l.symbols.star) },\n { ALT: () => <RuleDefReturn<typeof pathMod>> CONSUME(l.symbols.opPlus) },\n ]),\n};\n\n/**\n * [[94]](https://www.w3.org/TR/sparql11-query/#rPathPrimary)\n */\nexport const pathPrimary: SparqlGrammarRule<'pathPrimary', Path> = <const> {\n name: 'pathPrimary',\n impl: ({ SUBRULE, CONSUME, OR }) => () => OR<Path>([\n { ALT: () => SUBRULE(iri) },\n { ALT: () => SUBRULE(verbA) },\n { ALT: () => SUBRULE(pathNegatedPropertySet) },\n { ALT: () => {\n CONSUME(l.symbols.LParen);\n const resRecursive = SUBRULE(path);\n CONSUME(l.symbols.RParen);\n return resRecursive;\n } },\n ]),\n};\n\n/**\n * [[95]](https://www.w3.org/TR/sparql11-query/#rPathNegatedPropertySet)\n */\nexport const pathNegatedPropertySet: SparqlGrammarRule<'pathNegatedPropertySet', PathNegated> = <const> {\n name: 'pathNegatedPropertySet',\n impl: ({ ACTION, CONSUME, SUBRULE1, SUBRULE2, SUBRULE3, OR, MANY }) => (C) => {\n const exclamation = CONSUME(l.symbols.exclamation);\n return OR<PathNegated>([\n { ALT: () => {\n const noAlternative = SUBRULE1(pathOneInPropertySet);\n return ACTION(() =>\n C.astFactory.path('!', [ noAlternative ], C.astFactory.sourceLocation(exclamation, noAlternative)));\n } },\n { ALT: () => {\n const open = CONSUME(l.symbols.LParen);\n\n const head = SUBRULE2(pathOneInPropertySet);\n const tail: (TermIri | PathNegatedElt)[] = [];\n MANY(() => {\n CONSUME(l.symbols.pipe);\n const item = SUBRULE3(pathOneInPropertySet);\n tail.push(item);\n });\n\n const close = CONSUME(l.symbols.RParen);\n\n return ACTION(() => {\n const F = C.astFactory;\n if (tail.length === 0) {\n return F.path('!', [ head ], F.sourceLocation(exclamation, close));\n }\n return F.path(\n '!',\n [ F.path('|', [ head, ...tail ], F.sourceLocation(open, close)) ],\n F.sourceLocation(exclamation, close),\n );\n });\n } },\n ]);\n },\n};\n\n/**\n * [[96]](https://www.w3.org/TR/sparql11-query/#rPathOneInPropertySet)\n */\nexport const pathOneInPropertySet: SparqlGrammarRule<'pathOneInPropertySet', TermIri | PathNegatedElt> = <const> {\n name: 'pathOneInPropertySet',\n impl: ({ ACTION, CONSUME, SUBRULE1, SUBRULE2, OR1, OR2 }) => C =>\n OR1<TermIri | PathNegatedElt>([\n { ALT: () => SUBRULE1(iri) },\n { ALT: () => SUBRULE1(verbA) },\n { ALT: () => {\n const hat = CONSUME(l.symbols.hat);\n const item = OR2<TermIri>([\n { ALT: () => SUBRULE2(iri) },\n { ALT: () => SUBRULE2(verbA) },\n ]);\n return ACTION(() =>\n C.astFactory.path('^', [ item ], C.astFactory.sourceLocation(hat, item)));\n } },\n ]),\n};\n", "import type { IToken } from '@traqula/chevrotain';\nimport { traqulaIndentation } from '@traqula/core';\nimport * as l from '../lexer/index.js';\nimport type { SparqlGrammarRule, SparqlRule } from '../sparql11HelperTypes.js';\nimport type {\n BasicGraphPattern,\n GraphNode,\n Path,\n PatternBgp,\n Term,\n TermVariable,\n TripleCollection,\n TripleCollectionBlankNodeProperties,\n TripleCollectionList,\n TripleNesting,\n} from '../Sparql11types.js';\nimport { CommonIRIs } from '../utils.js';\nimport { var_, varOrTerm, verb } from './general.js';\nimport { path, pathGenerator } from './propertyPaths.js';\n\nfunction triplesDotSeperated(triplesSameSubjectSubrule: SparqlGrammarRule<string, BasicGraphPattern>):\nSparqlGrammarRule<string, PatternBgp>['impl'] {\n return ({ ACTION, AT_LEAST_ONE, SUBRULE, CONSUME, OPTION }) => (C) => {\n const triples: BasicGraphPattern = [];\n\n let parsedDot = true;\n let dotToken: undefined | IToken;\n AT_LEAST_ONE({\n GATE: () => parsedDot,\n DEF: () => {\n parsedDot = false;\n const template = SUBRULE(triplesSameSubjectSubrule);\n ACTION(() => {\n triples.push(...template);\n });\n OPTION(() => {\n dotToken = CONSUME(l.symbols.dot);\n parsedDot = true;\n });\n },\n });\n return ACTION(() => C.astFactory.patternBgp(triples, C.astFactory.sourceLocation(...triples, dotToken)));\n };\n}\n\n/**\n * [[55]](https://www.w3.org/TR/sparql11-query/#rTriplesBlock)\n */\nexport const triplesBlock: SparqlRule<'triplesBlock', PatternBgp> = <const>{\n name: 'triplesBlock',\n impl: implArgs => C => triplesDotSeperated(triplesSameSubjectPath)(implArgs)(C),\n gImpl: ({ SUBRULE, PRINT_WORD, HANDLE_LOC, NEW_LINE }) => (ast, { astFactory: F }) => {\n for (const [ index, triple ] of ast.triples.entries()) {\n HANDLE_LOC(triple, () => {\n const nextTriple = ast.triples.at(index + 1);\n if (F.isTripleCollection(triple)) {\n SUBRULE(graphNodePath, triple);\n // A top level tripleCollection block means that it is not used as the subject of another triple\n // (if it were, the grammar would have set it as the subject of the next triple instead of a standalone item).\n F.printFilter(triple, () => {\n PRINT_WORD('.');\n NEW_LINE();\n });\n } else {\n // Subject\n SUBRULE(graphNodePath, triple.subject);\n F.printFilter(triple, () => PRINT_WORD(''));\n // Predicate\n if (F.isTerm(triple.predicate) && F.isTermVariable(triple.predicate)) {\n SUBRULE(varOrTerm, triple.predicate);\n } else {\n SUBRULE(pathGenerator, triple.predicate, undefined);\n }\n F.printFilter(triple, () => PRINT_WORD(''));\n // Object\n SUBRULE(graphNodePath, triple.object);\n\n // If no more things, or a top level collection (only possible if new block was part), or new subject: add DOT\n if (nextTriple === undefined || F.isTripleCollection(nextTriple) ||\n !F.isSourceLocationNoMaterialize(nextTriple.subject.loc)) {\n F.printFilter(ast, () => {\n PRINT_WORD('.');\n NEW_LINE();\n });\n } else if (F.isSourceLocationNoMaterialize(nextTriple.predicate.loc)) {\n F.printFilter(ast, () => PRINT_WORD(','));\n } else {\n F.printFilter(ast, () => {\n PRINT_WORD(';');\n NEW_LINE();\n });\n }\n }\n });\n }\n },\n};\n\n/**\n * [[75]](https://www.w3.org/TR/sparql11-query/#rTriplesSameSubject)\n * [[81]](https://www.w3.org/TR/sparql11-query/#rTriplesSameSubjectPath)\n * CONTRACT: triples generated from the subject come first, then comes the main triple,\n * and then come the triples from the object. Only the first occurrence of a term has `SourceLocationType = source`\n */\nfunction triplesSameSubjectImpl<T extends string>(name: T, allowPaths: boolean):\nSparqlGrammarRule<T, BasicGraphPattern> {\n return <const> {\n name,\n impl: ({ ACTION, SUBRULE, OR }) => C => OR<BasicGraphPattern>([\n { ALT: () => {\n const subject = SUBRULE(varOrTerm);\n const res = SUBRULE(\n allowPaths ? propertyListPathNotEmpty : propertyListNotEmpty,\n ACTION(() => C.astFactory.dematerialized(subject)),\n );\n // Only the first occurrence of a subject is actually materialized.\n return ACTION(() => {\n res[0].subject = subject;\n res[0].loc = C.astFactory.sourceLocation(subject, res[0]);\n return res;\n });\n } },\n { ALT: () => {\n const subjectNode = SUBRULE(allowPaths ? triplesNodePath : triplesNode);\n const restNode = SUBRULE(\n allowPaths ? propertyListPath : propertyList,\n ACTION(() => C.astFactory.graphNodeIdentifier(subjectNode)),\n );\n return ACTION(() => {\n if (restNode.length === 0) {\n return [ subjectNode ];\n }\n restNode[0].subject = subjectNode;\n restNode[0].loc = C.astFactory.sourceLocation(subjectNode, restNode[0]);\n return restNode;\n });\n } },\n ]),\n };\n}\nexport const triplesSameSubject = triplesSameSubjectImpl('triplesSameSubject', false);\nexport const triplesSameSubjectPath = triplesSameSubjectImpl('triplesSameSubjectPath', true);\n\n/**\n * [[52]](https://www.w3.org/TR/sparql11-query/#rTriplesTemplate)\n */\nexport const triplesTemplate: SparqlGrammarRule<'triplesTemplate', PatternBgp> = <const> {\n name: 'triplesTemplate',\n impl: triplesDotSeperated(triplesSameSubject),\n};\n\n/**\n * [[76]](https://www.w3.org/TR/sparql11-query/#rPropertyList)\n * [[82]](https://www.w3.org/TR/sparql11-query/#rPropertyListPath)\n */\nfunction propertyListImpl<T extends string>(name: T, allowPaths: boolean):\nSparqlGrammarRule<T, TripleNesting[], [TripleNesting['subject']]> {\n return {\n name,\n impl: ({ SUBRULE, OPTION }) => (_, subject) =>\n OPTION(() => SUBRULE(allowPaths ? propertyListPathNotEmpty : propertyListNotEmpty, subject)) ?? [],\n };\n}\nexport const propertyList = propertyListImpl('propertyList', false);\nexport const propertyListPath = propertyListImpl('propertyListPath', true);\n\n// We could use gates for this, but in that case,\n// a grammar not in need of paths would still have to include the path rules\n/**\n * [[77]](https://www.w3.org/TR/sparql11-query/#rPropertyListNotEmpty)\n * [[83]](https://www.w3.org/TR/sparql11-query/#rPropertyListPathNotEmpty)\n */\nfunction propertyListNotEmptyImplementation<T extends string>(\n name: T,\n allowPaths: boolean,\n): SparqlGrammarRule<T, TripleNesting[], [TripleNesting['subject']]> {\n return {\n name,\n impl: ({ ACTION, CONSUME, AT_LEAST_ONE, SUBRULE1, MANY2, OR1 }) => (_, subject) => {\n const result: TripleNesting[] = [];\n let parsedSemi = true;\n\n AT_LEAST_ONE({\n GATE: () => parsedSemi,\n DEF: () => {\n parsedSemi = false;\n const predicate = allowPaths ?\n OR1<TermVariable | Path>([\n { ALT: () => SUBRULE1(verbPath) },\n { ALT: () => SUBRULE1(verbSimple) },\n ]) :\n SUBRULE1(verb);\n const triples = SUBRULE1(\n allowPaths ? objectListPath : objectList,\n subject,\n predicate,\n );\n\n MANY2(() => {\n CONSUME(l.symbols.semi);\n parsedSemi = true;\n });\n\n ACTION(() => {\n result.push(...triples);\n });\n },\n });\n return result;\n },\n };\n}\nexport const propertyListNotEmpty = propertyListNotEmptyImplementation('propertyListNotEmpty', false);\nexport const propertyListPathNotEmpty = propertyListNotEmptyImplementation('propertyListPathNotEmpty', true);\n\n/**\n * [[84]](https://www.w3.org/TR/sparql11-query/#rVerbPath)\n */\nexport const verbPath: SparqlGrammarRule<'verbPath', Path> = <const> {\n name: 'verbPath',\n impl: ({ SUBRULE }) => () => SUBRULE(path),\n};\n\n/**\n * [[85]](https://www.w3.org/TR/sparql11-query/#rVerbSimple)\n */\nexport const verbSimple: SparqlGrammarRule<'verbSimple', TermVariable> = <const> {\n name: 'verbSimple',\n impl: ({ SUBRULE }) => () => SUBRULE(var_),\n};\n\n/**\n * [[79]](https://www.w3.org/TR/sparql11-query/#rObjectList)\n * [[86]](https://www.w3.org/TR/sparql11-query/#rObjectListPath)\n */\nfunction objectListImpl<T extends string>(name: T, allowPaths: boolean):\nSparqlGrammarRule<T, TripleNesting[], [TripleNesting['subject'], TripleNesting['predicate']]> {\n return <const> {\n name,\n impl: ({ ACTION, SUBRULE, AT_LEAST_ONE_SEP }) => (_, subj, pred) => {\n const objects: TripleNesting[] = [];\n AT_LEAST_ONE_SEP({\n SEP: l.symbols.comma,\n DEF: () => {\n const objectTriple = SUBRULE(allowPaths ? objectPath : object, subj, pred);\n ACTION(() => {\n objects.push(objectTriple);\n });\n },\n });\n return objects;\n },\n };\n}\nexport const objectList = objectListImpl('objectList', false);\nexport const objectListPath = objectListImpl('objectListPath', true);\n\n/**\n * [[80]](https://www.w3.org/TR/sparql11-query/#rObject)\n * [[87]](https://www.w3.org/TR/sparql11-query/#rObjectPath)\n */\nfunction objectImpl<T extends string>(name: T, allowPaths: boolean):\nSparqlGrammarRule<T, TripleNesting, [TripleNesting['subject'], TripleNesting['predicate']]> {\n return {\n name,\n impl: ({ ACTION, SUBRULE }) => (C, subject, predicate) => {\n const node = SUBRULE(allowPaths ? graphNodePath : graphNode);\n return ACTION(() =>\n C.astFactory.triple(subject, predicate, node));\n },\n };\n}\nexport const object = objectImpl('object', false);\nexport const objectPath = objectImpl('objectPath', true);\n\n/**\n * [[102]](https://www.w3.org/TR/sparql11-query/#rCollection)\n * [[103]](https://www.w3.org/TR/sparql11-query/#rCollectionPath)\n */\nfunction collectionImpl<T extends string>(name: T, allowPaths: boolean): SparqlRule<T, TripleCollectionList> {\n return {\n name,\n impl: ({ ACTION, AT_LEAST_ONE, SUBRULE, CONSUME }) => (C) => {\n // Construct a [cons list](https://en.wikipedia.org/wiki/Cons#Lists),\n // here called a [RDF collection](https://www.w3.org/TR/sparql11-query/#collections).\n const terms: GraphNode[] = [];\n\n const startToken = CONSUME(l.symbols.LParen);\n\n AT_LEAST_ONE(() => {\n terms.push(SUBRULE(allowPaths ? graphNodePath : graphNode));\n });\n const endToken = CONSUME(l.symbols.RParen);\n\n return ACTION(() => {\n const F = C.astFactory;\n const triples: TripleNesting[] = [];\n // The triples created in your recursion\n const predFirst = F.termNamed(F.sourceLocation(), CommonIRIs.FIRST, undefined);\n const predRest = F.termNamed(F.sourceLocation(), CommonIRIs.REST, undefined);\n const predNil = F.termNamed(F.sourceLocation(), CommonIRIs.NIL, undefined);\n\n const listHead = F.termBlank(undefined, F.sourceLocation());\n let iterHead: TripleNesting['object'] = listHead;\n for (const [ index, term ] of terms.entries()) {\n const lastInList = index === terms.length - 1;\n\n const headTriple: TripleNesting = F.triple(\n iterHead,\n predFirst,\n term,\n );\n triples.push(headTriple);\n\n // If not the last, create new iterHead, otherwise, close list\n if (lastInList) {\n const nilTriple: TripleNesting = F.triple(iterHead, predRest, predNil);\n triples.push(nilTriple);\n } else {\n const tail = F.termBlank(undefined, F.sourceLocation());\n const linkTriple: TripleNesting = F.triple(iterHead, predRest, tail);\n triples.push(linkTriple);\n iterHead = tail;\n }\n }\n return F.tripleCollectionList(listHead, triples, F.sourceLocation(startToken, endToken));\n });\n },\n gImpl: ({ SUBRULE, PRINT_WORD }) => (ast, { astFactory: F }) => {\n F.printFilter(ast, () => PRINT_WORD('('));\n // Only every 2 triple is relevant. The odd triples are linking triples.\n for (const [ idx, triple ] of ast.triples.entries()) {\n if (idx % 2 === 0) {\n // Separate the items, otherwise `( ?a ex:b )` would be generated as `( ?aex:b )`\n F.printFilter(ast, () => PRINT_WORD(''));\n SUBRULE(graphNodePath, triple.object);\n }\n }\n F.printFilter(ast, () => PRINT_WORD(')'));\n },\n };\n}\nexport const collection = collectionImpl('collection', false);\nexport const collectionPath = collectionImpl('collectionPath', true);\n\n/**\n * [[98]](https://www.w3.org/TR/sparql11-query/#rTriplesNode)\n * [[100]](https://www.w3.org/TR/sparql11-query/#rTriplesNodePath)\n */\nfunction triplesNodeImpl<T extends string>(name: T, allowPaths: boolean): SparqlRule<T, TripleCollection> {\n return <const>{\n name,\n impl: ({ SUBRULE, OR }) => () => OR<TripleCollection>([\n { ALT: () => SUBRULE(allowPaths ? collectionPath : collection) },\n { ALT: () => SUBRULE(allowPaths ? blankNodePropertyListPath : blankNodePropertyList) },\n ]),\n gImpl: ({ SUBRULE }) => ast => ast.subType === 'list' ?\n SUBRULE(collectionPath, ast) :\n SUBRULE(blankNodePropertyListPath, ast),\n };\n}\nexport const triplesNode = triplesNodeImpl('triplesNode', false);\nexport const triplesNodePath = triplesNodeImpl('triplesNodePath', true);\n\n/**\n * [[99]](https://www.w3.org/TR/sparql11-query/#rBlankNodePropertyList)\n * [[101]](https://www.w3.org/TR/sparql11-query/#rBlankNodePropertyListPath)\n */\nfunction blankNodePropertyListImpl<T extends string>(name: T, allowPaths: boolean):\nSparqlRule<T, TripleCollectionBlankNodeProperties> {\n const propertyPathNotEmptyImpl = allowPaths ? propertyListPathNotEmpty : propertyListNotEmpty;\n return {\n name,\n impl: ({ ACTION, SUBRULE, CONSUME }) => (C) => {\n const startToken = CONSUME(l.symbols.LSquare);\n\n const blankNode = ACTION(() =>\n C.astFactory.termBlank(undefined, C.astFactory.sourceLocation()));\n\n const propList = SUBRULE(propertyPathNotEmptyImpl, blankNode);\n const endToken = CONSUME(l.symbols.RSquare);\n\n return ACTION(() => C.astFactory.tripleCollectionBlankNodeProperties(\n blankNode,\n propList,\n C.astFactory.sourceLocation(startToken, endToken),\n ));\n },\n gImpl: ({ SUBRULE, PRINT, PRINT_WORD, HANDLE_LOC, PRINT_ON_EMPTY, NEW_LINE }) => (ast, c) => {\n const { astFactory: F, indentInc } = c;\n F.printFilter(ast, () => {\n c[traqulaIndentation] += indentInc;\n PRINT('[');\n NEW_LINE();\n });\n for (const triple of ast.triples) {\n HANDLE_LOC(triple, () => {\n // Predicate\n if (F.isTerm(triple.predicate) && F.isTermVariable(triple.predicate)) {\n SUBRULE(varOrTerm, triple.predicate);\n } else {\n SUBRULE(pathGenerator, triple.predicate, undefined);\n }\n F.printFilter(triple, () => PRINT_WORD(''));\n // Object\n SUBRULE(graphNodePath, triple.object);\n\n F.printFilter(ast, () => {\n PRINT_WORD(';');\n NEW_LINE();\n });\n });\n }\n F.printFilter(ast, () => {\n c[traqulaIndentation] -= indentInc;\n PRINT_ON_EMPTY(']');\n });\n },\n };\n}\nexport const blankNodePropertyList = blankNodePropertyListImpl('blankNodePropertyList', false);\nexport const blankNodePropertyListPath = blankNodePropertyListImpl('blankNodePropertyListPath', true);\n\n/**\n * [[103]](https://www.w3.org/TR/sparql11-query/#rGraphNode)\n * [[105]](https://www.w3.org/TR/sparql11-query/#rGraphNodePath)\n */\nfunction graphNodeImpl<T extends string>(name: T, allowPaths: boolean): SparqlRule<T, Term | TripleCollection> {\n const triplesNodeRule = allowPaths ? triplesNodePath : triplesNode;\n return {\n name,\n impl: ({ SUBRULE, OR }) => C => OR<Term | TripleCollection>([\n { ALT: () => SUBRULE(varOrTerm) },\n {\n GATE: () => C.parseMode.has('canCreateBlankNodes'),\n ALT: () => SUBRULE(triplesNodeRule),\n },\n ]),\n gImpl: ({ SUBRULE }) => (ast, { astFactory: F }) => {\n if (F.isTerm(ast)) {\n SUBRULE(varOrTerm, ast);\n } else {\n SUBRULE(triplesNodeRule, ast);\n }\n },\n };\n}\nexport const graphNode = graphNodeImpl('graphNode', false);\nexport const graphNodePath = graphNodeImpl('graphNodePath', true);\n", "import type { RuleDefReturn, Wrap } from '@traqula/core';\nimport { traqulaIndentation } from '@traqula/core';\nimport * as l from '../lexer/index.js';\nimport type { SparqlGeneratorRule, SparqlGrammarRule, SparqlRule } from '../sparql11HelperTypes.js';\nimport type {\n Expression,\n ExpressionFunctionCall,\n Pattern,\n PatternBgp,\n PatternBind,\n PatternFilter,\n PatternGraph,\n PatternGroup,\n PatternMinus,\n PatternOptional,\n PatternService,\n PatternUnion,\n PatternValues,\n SubSelect,\n TermIri,\n TermLiteral,\n TermVariable,\n ValuePatternRow,\n} from '../Sparql11types.js';\nimport { checkBlankNodeBGPScope, checkNote13 } from '../validation/validators.js';\nimport { builtInCall } from './builtIn.js';\nimport { argList, brackettedExpression, expression } from './expression.js';\nimport { var_, varOrIri, varOrTerm } from './general.js';\nimport { booleanLiteral, iri, numericLiteral, rdfLiteral } from './literals.js';\nimport { query, subSelect } from './queryUnit.js';\nimport { graphNodePath, triplesBlock } from './tripleBlock.js';\n\n/**\n * [[17]](https://www.w3.org/TR/sparql11-query/#rWhereClause)\n */\nexport const whereClause: SparqlRule<'whereClause', Wrap<PatternGroup>> = <const> {\n name: 'whereClause',\n impl: ({ ACTION, SUBRULE, CONSUME, OPTION }) => (C) => {\n const where = OPTION(() => CONSUME(l.where));\n const group = SUBRULE(groupGraphPattern);\n return ACTION(() => C.astFactory.wrap(group, C.astFactory.sourceLocation(where, group)));\n },\n gImpl: ({ SUBRULE, PRINT_WORD }) => (ast, { astFactory: F }) => {\n F.printFilter(ast, () => PRINT_WORD('WHERE'));\n SUBRULE(groupGraphPattern, ast.val);\n },\n};\n\n/**\n * [[53]](https://www.w3.org/TR/sparql11-query/#rGroupGraphPattern)\n */\nexport const groupGraphPattern: SparqlRule<'groupGraphPattern', PatternGroup> = <const> {\n name: 'groupGraphPattern',\n impl: ({ ACTION, SUBRULE, CONSUME, OR }) => (C) => {\n const open = CONSUME(l.symbols.LCurly);\n const patterns = OR<Pattern[]>([\n { ALT: () => [ SUBRULE(subSelect) ]},\n { ALT: () => SUBRULE(groupGraphPatternSub) },\n ]);\n const close = CONSUME(l.symbols.RCurly);\n\n ACTION(() => !C.skipValidation && checkBlankNodeBGPScope(patterns));\n\n return ACTION(() => C.astFactory.patternGroup(patterns, C.astFactory.sourceLocation(open, close)));\n },\n gImpl: ({ SUBRULE, PRINT_WORD, NEW_LINE, PRINT_ON_OWN_LINE }) => (ast, C) => {\n const { astFactory: F, indentInc } = C;\n F.printFilter(ast, () => {\n C[traqulaIndentation] += indentInc;\n PRINT_WORD('{');\n NEW_LINE();\n });\n\n for (const pattern of ast.patterns) {\n SUBRULE(generatePattern, pattern);\n }\n\n F.printFilter(ast, () => {\n C[traqulaIndentation] -= indentInc;\n PRINT_ON_OWN_LINE('}');\n });\n },\n};\n\nexport const generatePattern: SparqlGeneratorRule<'generatePattern', Pattern> = {\n name: 'generatePattern',\n gImpl: ({ SUBRULE }) => (ast, { astFactory: F }) => {\n if (ast.type === 'query') {\n SUBRULE(query, F.querySelect({\n context: [],\n datasets: F.datasetClauses([], F.sourceLocation()),\n where: ast.where,\n variables: ast.variables,\n solutionModifiers: ast.solutionModifiers,\n values: ast.values,\n distinct: ast.distinct,\n reduced: ast.reduced,\n }, ast.loc));\n } else if (ast.subType === 'group') {\n SUBRULE(groupGraphPattern, ast);\n } else if (ast.subType === 'bgp') {\n SUBRULE(triplesBlock, ast);\n } else {\n SUBRULE(graphPatternNotTriples, ast);\n }\n },\n};\n\n/**\n * [[54]](https://www.w3.org/TR/sparql11-query/#rGroupGraphPatternSub)\n */\nexport const groupGraphPatternSub:\nSparqlGrammarRule<'groupGraphPatternSub', Pattern[]> = <const> {\n name: 'groupGraphPatternSub',\n impl: ({ ACTION, SUBRULE, CONSUME, MANY, SUBRULE1, SUBRULE2, OPTION1, OPTION2, OPTION3 }) => (C) => {\n const patterns: Pattern[] = [];\n\n const bgpPattern = OPTION1(() => SUBRULE1(triplesBlock));\n if (bgpPattern) {\n patterns.push(bgpPattern);\n }\n MANY(() => {\n const notTriples = SUBRULE(graphPatternNotTriples);\n patterns.push(notTriples);\n\n OPTION2(() => CONSUME(l.symbols.dot));\n\n const moreTriples = OPTION3(() => SUBRULE2(triplesBlock));\n if (moreTriples) {\n patterns.push(moreTriples);\n }\n });\n\n ACTION(() => !C.skipValidation && checkNote13(patterns));\n\n return patterns;\n },\n};\n\n/**\n * [[56]](https://www.w3.org/TR/sparql11-query/#rGraphPatternNotTriples)\n */\nexport const graphPatternNotTriples: SparqlRule<'graphPatternNotTriples', Exclude<Pattern, SubSelect | PatternBgp>> = {\n name: 'graphPatternNotTriples',\n impl: ({ SUBRULE, OR }) => () => OR<RuleDefReturn<typeof graphPatternNotTriples>>([\n { ALT: () => SUBRULE(groupOrUnionGraphPattern) },\n { ALT: () => SUBRULE(optionalGraphPattern) },\n { ALT: () => SUBRULE(minusGraphPattern) },\n { ALT: () => SUBRULE(graphGraphPattern) },\n { ALT: () => SUBRULE(serviceGraphPattern) },\n { ALT: () => SUBRULE(filter) },\n { ALT: () => SUBRULE(bind) },\n { ALT: () => SUBRULE(inlineData) },\n ]),\n gImpl: ({ SUBRULE }) => (ast) => {\n switch (ast.subType) {\n case 'group':\n case 'union':\n SUBRULE(groupOrUnionGraphPattern, ast);\n break;\n case 'optional':\n SUBRULE(optionalGraphPattern, ast);\n break;\n case 'minus':\n SUBRULE(minusGraphPattern, ast);\n break;\n case 'graph':\n SUBRULE(graphGraphPattern, ast);\n break;\n case 'service':\n SUBRULE(serviceGraphPattern, ast);\n break;\n case 'filter':\n SUBRULE(filter, ast);\n break;\n case 'bind':\n SUBRULE(bind, ast);\n break;\n case 'values':\n SUBRULE(inlineData, ast);\n break;\n }\n },\n};\n\n/**\n * [[57]](https://www.w3.org/TR/sparql11-query/#rOptionalGraphPattern)\n */\nexport const optionalGraphPattern: SparqlRule<'optionalGraphPattern', PatternOptional> = <const> {\n name: 'optionalGraphPattern',\n impl: ({ ACTION, SUBRULE, CONSUME }) => (C) => {\n const optional = CONSUME(l.optional);\n const group = SUBRULE(groupGraphPattern);\n\n return ACTION(() => C.astFactory.patternOptional(group.patterns, C.astFactory.sourceLocation(optional, group)));\n },\n gImpl: ({ SUBRULE, PRINT_WORD }) => (ast, { astFactory: F }) => {\n F.printFilter(ast, () => PRINT_WORD('OPTIONAL'));\n SUBRULE(groupGraphPattern, F.patternGroup(ast.patterns, ast.loc));\n },\n};\n\n/**\n * [[58]](https://www.w3.org/TR/sparql11-query/#rGraphGraphPattern)\n */\nexport const graphGraphPattern: SparqlRule<'graphGraphPattern', PatternGraph> = <const> {\n name: 'graphGraphPattern',\n impl: ({ ACTION, SUBRULE, CONSUME }) => (C) => {\n const graph = CONSUME(l.graph.graph);\n const name = SUBRULE(varOrIri);\n const group = SUBRULE(groupGraphPattern);\n\n return ACTION(() => C.astFactory.patternGraph(name, group.patterns, C.astFactory.sourceLocation(graph, group)));\n },\n gImpl: ({ SUBRULE, PRINT_WORD }) => (ast, { astFactory: F }) => {\n F.printFilter(ast, () => PRINT_WORD('GRAPH'));\n SUBRULE(varOrTerm, ast.name);\n SUBRULE(groupGraphPattern, F.patternGroup(ast.patterns, ast.loc));\n },\n};\n\n/**\n * [[59]](https://www.w3.org/TR/sparql11-query/#rServiceGraphPattern)\n */\nexport const serviceGraphPattern: SparqlRule<'serviceGraphPattern', PatternService> = <const> {\n name: 'serviceGraphPattern',\n impl: ({ ACTION, SUBRULE1, CONSUME, OPTION }) => (C) => {\n const service = CONSUME(l.service);\n const silent = OPTION(() => {\n CONSUME(l.silent);\n return true;\n }) ?? false;\n const name = SUBRULE1(varOrIri);\n const group = SUBRULE1(groupGraphPattern);\n\n return ACTION(() =>\n C.astFactory.patternService(name, group.patterns, silent, C.astFactory.sourceLocation(service, group)));\n },\n gImpl: ({ SUBRULE, PRINT_WORD }) => (ast, { astFactory: F }) => {\n F.printFilter(ast, () => {\n PRINT_WORD('SERVICE');\n if (ast.silent) {\n PRINT_WORD('SILENT');\n }\n });\n SUBRULE(varOrTerm, ast.name);\n SUBRULE(groupGraphPattern, F.patternGroup(ast.patterns, ast.loc));\n },\n};\n\n/**\n * [[60]](https://www.w3.org/TR/sparql11-query/#rBind)\n */\nexport const bind: SparqlRule<'bind', PatternBind> = <const> {\n name: 'bind',\n impl: ({ ACTION, SUBRULE, CONSUME }) => (C) => {\n const bind = CONSUME(l.bind);\n CONSUME(l.symbols.LParen);\n const expressionVal = SUBRULE(expression);\n CONSUME(l.as);\n const variable = SUBRULE(var_);\n const close = CONSUME(l.symbols.RParen);\n\n return ACTION(() => C.astFactory.patternBind(expressionVal, variable, C.astFactory.sourceLocation(bind, close)));\n },\n gImpl: ({ SUBRULE, PRINT_WORD, NEW_LINE }) => (ast, { astFactory: F }) => {\n F.printFilter(ast, () => PRINT_WORD('BIND', '('));\n SUBRULE(expression, ast.expression);\n F.printFilter(ast, () => PRINT_WORD('AS'));\n SUBRULE(var_, ast.variable);\n F.printFilter(ast, () => {\n PRINT_WORD(')');\n NEW_LINE();\n });\n },\n};\n\n/**\n * [[61]](https://www.w3.org/TR/sparql11-query/#rInlineData)\n */\nexport const inlineData: SparqlRule<'inlineData', PatternValues> = <const> {\n name: 'inlineData',\n impl: ({ ACTION, SUBRULE, CONSUME }) => (C) => {\n const values = CONSUME(l.values);\n const datablock = SUBRULE(dataBlock);\n\n return ACTION(() => {\n datablock.loc = C.astFactory.sourceLocation(values, datablock);\n return datablock;\n });\n },\n gImpl: ({ SUBRULE, PRINT_WORD, PRINT_ON_EMPTY, NEW_LINE, PRINT_ON_OWN_LINE }) => (ast, C) => {\n const { astFactory: F, indentInc } = C;\n const variables = ast.variables;\n const singleVar = variables.length === 1;\n F.printFilter(ast, () => {\n PRINT_ON_EMPTY('VALUES', singleVar ? '' : '( ');\n });\n for (const variable of variables) {\n F.printFilter(ast, () => PRINT_WORD(''));\n SUBRULE(varOrTerm, variable);\n F.printFilter(ast, () => PRINT_WORD(''));\n }\n F.printFilter(ast, () => {\n C[traqulaIndentation] += indentInc;\n PRINT_WORD(singleVar ? '' : ')', '{');\n NEW_LINE();\n });\n\n for (const mapping of ast.values) {\n F.printFilter(ast, () => !singleVar && PRINT_WORD('('));\n for (const variable of variables) {\n const var_ = variable.value;\n if (mapping[var_] === undefined) {\n F.printFilter(ast, () => PRINT_WORD('UNDEF'));\n } else {\n SUBRULE(graphNodePath, mapping[var_]);\n F.printFilter(ast, () => PRINT_WORD(''));\n }\n }\n F.printFilter(ast, () => {\n PRINT_WORD(singleVar ? '' : ')');\n NEW_LINE();\n });\n }\n F.printFilter(ast, () => {\n C[traqulaIndentation] -= indentInc;\n PRINT_ON_OWN_LINE('}');\n });\n },\n};\n\n/**\n * [[62]](https://www.w3.org/TR/sparql11-query/#rDataBlock)\n */\nexport const dataBlock: SparqlGrammarRule<'dataBlock', PatternValues> = <const> {\n name: 'dataBlock',\n impl: ({ SUBRULE, OR }) => () => OR([\n { ALT: () => SUBRULE(inlineDataOneVar) },\n { ALT: () => SUBRULE(inlineDataFull) },\n ]),\n};\n\n/**\n * [[63]](https://www.w3.org/TR/sparql11-query/#rInlineDataOneVar)\n */\nexport const inlineDataOneVar: SparqlGrammarRule<'inlineDataOneVar', PatternValues> = <const> {\n name: 'inlineDataOneVar',\n impl: ({ ACTION, SUBRULE, CONSUME, MANY }) => (C) => {\n const res: ValuePatternRow[] = [];\n const varVal = SUBRULE(var_);\n CONSUME(l.symbols.LCurly);\n MANY(() => {\n const value = SUBRULE(dataBlockValue);\n ACTION(() => {\n res.push(Object.assign(Object.create(null), { [varVal.value]: value }));\n });\n });\n const close = CONSUME(l.symbols.RCurly);\n\n return ACTION(() => C.astFactory.patternValues([ varVal ], res, C.astFactory.sourceLocation(varVal, close)));\n },\n};\n\n/**\n * [[64]](https://www.w3.org/TR/sparql11-query/#rInlineDataFull)\n */\nexport const inlineDataFull: SparqlGrammarRule<'inlineDataFull', PatternValues> = <const> {\n name: 'inlineDataFull',\n impl: ({\n ACTION,\n OR,\n MANY1,\n MANY2,\n MANY3,\n MANY4,\n SUBRULE,\n CONSUME1,\n CONSUME2,\n }) => (C) => {\n const res: ValuePatternRow[] = [];\n const vars: TermVariable[] = [];\n return OR<RuleDefReturn<typeof inlineDataFull>>([\n { ALT: () => {\n // Grammar rule 64 together with note 11 learns us that a nil should be followed by a nil in DataBlock.\n const nil = CONSUME1(l.terminals.nil);\n CONSUME1(l.symbols.LCurly);\n MANY1(() => {\n CONSUME2(l.terminals.nil);\n res.push(Object.create(null));\n });\n const close = CONSUME1(l.symbols.RCurly);\n\n return ACTION(() => C.astFactory.patternValues(vars, res, C.astFactory.sourceLocation(nil, close)));\n } },\n { ALT: () => {\n const open = CONSUME1(l.symbols.LParen);\n MANY2(() => {\n vars.push(SUBRULE(var_));\n });\n CONSUME1(l.symbols.RParen);\n CONSUME2(l.symbols.LCurly);\n MANY3(() => {\n let parsedValues = 0;\n const currentRow: ValuePatternRow = Object.create(null);\n CONSUME2(l.symbols.LParen);\n MANY4(() => {\n ACTION(() => {\n if (!C.skipValidation && parsedValues >= vars.length) {\n throw new Error('Number of dataBlockValues does not match number of variables. Too much values.');\n }\n });\n const value = SUBRULE(dataBlockValue);\n ACTION(() => {\n currentRow[vars[parsedValues].value] = value;\n parsedValues++;\n });\n });\n CONSUME2(l.symbols.RParen);\n ACTION(() => {\n res.push(currentRow);\n if (!C.skipValidation && vars.length !== parsedValues) {\n throw new Error('Number of dataBlockValues does not match number of variables. Too few values.');\n }\n });\n });\n const close = CONSUME2(l.symbols.RCurly);\n return ACTION(() => C.astFactory.patternValues(vars, res, C.astFactory.sourceLocation(open, close)));\n } },\n ]);\n },\n};\n\n/**\n * [[65]](https://www.w3.org/TR/sparql11-query/#rDataBlockValue)\n */\nexport const dataBlockValue: SparqlGrammarRule<'dataBlockValue', TermIri | TermLiteral | undefined> = {\n name: 'dataBlockValue',\n impl: ({ SUBRULE, CONSUME, OR }) => () => OR<RuleDefReturn<typeof dataBlockValue>>([\n { ALT: () => SUBRULE(iri) },\n { ALT: () => SUBRULE(rdfLiteral) },\n { ALT: () => SUBRULE(numericLiteral) },\n { ALT: () => SUBRULE(booleanLiteral) },\n { ALT: () => {\n CONSUME(l.undef);\n // eslint-disable-next-line unicorn/no-useless-undefined\n return undefined;\n } },\n ]),\n};\n\n/**\n * [[66]](https://www.w3.org/TR/sparql11-query/#rMinusGraphPattern)\n */\nexport const minusGraphPattern: SparqlRule<'minusGraphPattern', PatternMinus> = <const> {\n name: 'minusGraphPattern',\n impl: ({ ACTION, SUBRULE, CONSUME }) => (C) => {\n const minus = CONSUME(l.minus);\n const group = SUBRULE(groupGraphPattern);\n\n return ACTION(() => C.astFactory.patternMinus(group.patterns, C.astFactory.sourceLocation(minus, group)));\n },\n gImpl: ({ SUBRULE, PRINT_WORD }) => (ast, { astFactory: F }) => {\n F.printFilter(ast, () => PRINT_WORD('MINUS'));\n SUBRULE(groupGraphPattern, F.patternGroup(ast.patterns, ast.loc));\n },\n};\n\n/**\n * [[67]](https://www.w3.org/TR/sparql11-query/#rGroupOrUnionGraphPattern)\n */\nexport const groupOrUnionGraphPattern: SparqlRule<'groupOrUnionGraphPattern', PatternGroup | PatternUnion> =\n <const> {\n name: 'groupOrUnionGraphPattern',\n impl: ({ ACTION, MANY, SUBRULE1, SUBRULE2, CONSUME }) => (C) => {\n const groups: PatternGroup[] = [];\n\n const group = SUBRULE1(groupGraphPattern);\n groups.push(group);\n MANY(() => {\n CONSUME(l.union);\n const group = SUBRULE2(groupGraphPattern);\n groups.push(group);\n });\n\n return ACTION(() => groups.length === 1 ?\n groups[0] :\n C.astFactory.patternUnion(\n groups,\n C.astFactory.sourceLocation(group, groups.at(-1)),\n ));\n },\n gImpl: ({ SUBRULE, PRINT_WORD }) => (ast, { astFactory: F }) => {\n if (F.isPatternUnion(ast)) {\n const [ head, ...tail ] = ast.patterns;\n SUBRULE(groupGraphPattern, head);\n for (const pattern of tail) {\n F.printFilter(ast, () => PRINT_WORD('UNION'));\n SUBRULE(groupGraphPattern, pattern);\n }\n } else {\n SUBRULE(groupGraphPattern, ast);\n }\n },\n };\n\n/**\n * [[68]](https://www.w3.org/TR/sparql11-query/#rFilter)\n */\nexport const filter: SparqlRule<'filter', PatternFilter> = <const> {\n name: 'filter',\n impl: ({ ACTION, SUBRULE, CONSUME }) => (C) => {\n const filterToken = CONSUME(l.filter);\n const expression = SUBRULE(constraint);\n\n return ACTION(() => C.astFactory.patternFilter(expression, C.astFactory.sourceLocation(filterToken, expression)));\n },\n gImpl: ({ SUBRULE, PRINT_WORD, NEW_LINE }) => (ast, { astFactory: F }) => {\n F.printFilter(ast, () => PRINT_WORD('FILTER ('));\n SUBRULE(expression, ast.expression);\n F.printFilter(ast, () => {\n PRINT_WORD(')');\n NEW_LINE();\n });\n },\n};\n\n/**\n * [[69]](https://www.w3.org/TR/sparql11-query/#rConstraint)\n */\nexport const constraint: SparqlGrammarRule<'constraint', Expression> = <const> {\n name: 'constraint',\n impl: ({ SUBRULE, OR }) => () => OR([\n { ALT: () => SUBRULE(brackettedExpression) },\n { ALT: () => SUBRULE(builtInCall) },\n { ALT: () => SUBRULE(functionCall) },\n ]),\n};\n\n/**\n * [[70]](https://www.w3.org/TR/sparql11-query/#rFunctionCall)\n */\nexport const functionCall: SparqlGrammarRule<'functionCall', ExpressionFunctionCall> = <const> {\n name: 'functionCall',\n impl: ({ ACTION, SUBRULE }) => (C) => {\n const func = SUBRULE(iri);\n const args = SUBRULE(argList);\n return ACTION(() => C.astFactory.expressionFunctionCall(\n func,\n args.val.args,\n args.val.distinct,\n C.astFactory.sourceLocation(func, args),\n ));\n },\n};\n", "import type { ImplArgs, RuleDefReturn, Wrap } from '@traqula/core';\nimport * as l from '../lexer/index.js';\nimport type { SparqlGrammarRule, SparqlRule } from '../sparql11HelperTypes.js';\nimport type {\n Expression,\n ExpressionFunctionCall,\n ExpressionOperation,\n TermIri,\n TermLiteral,\n} from '../Sparql11types.js';\nimport { aggregate, builtInCall } from './builtIn.js';\nimport {\n var_,\n varOrTerm,\n} from './general.js';\nimport {\n booleanLiteral,\n iri,\n numericLiteral,\n numericLiteralNegative,\n numericLiteralPositive,\n rdfLiteral,\n} from './literals.js';\nimport { groupGraphPattern } from './whereClause.js';\n\n/**\n * [[71]](https://www.w3.org/TR/sparql11-query/#rArgList)\n */\nexport interface IArgList {\n args: Expression[];\n distinct: boolean;\n}\nexport const argList: SparqlRule<'argList', Wrap<IArgList>> = <const> {\n name: 'argList',\n impl: ({ ACTION, CONSUME, SUBRULE1, OPTION, OR, AT_LEAST_ONE_SEP }) => C =>\n OR<RuleDefReturn<typeof argList>>([\n { ALT: () => {\n const nil = CONSUME(l.terminals.nil);\n return ACTION(() =>\n C.astFactory.wrap({ args: [], distinct: false }, C.astFactory.sourceLocation(nil)));\n } },\n { ALT: () => {\n const args: Expression[] = [];\n const open = CONSUME(l.symbols.LParen);\n const distinct = OPTION(() => {\n CONSUME(l.distinct);\n return true;\n }) ?? false;\n\n AT_LEAST_ONE_SEP({\n SEP: l.symbols.comma,\n DEF: () => {\n const arg = SUBRULE1(expression);\n args.push(arg);\n },\n });\n const close = CONSUME(l.symbols.RParen);\n return ACTION(() =>\n C.astFactory.wrap({ args, distinct }, C.astFactory.sourceLocation(open, close)));\n } },\n ]),\n gImpl: ({ SUBRULE, PRINT_WORD }) => (ast, { astFactory: F }) => {\n F.printFilter(ast, () => {\n PRINT_WORD('(');\n if (ast.val.distinct) {\n PRINT_WORD('DISTINCT');\n }\n });\n const [ head, ...tail ] = ast.val.args;\n if (head) {\n SUBRULE(expression, head);\n }\n for (const expr of tail) {\n F.printFilter(ast, () => PRINT_WORD(','));\n SUBRULE(expression, expr);\n }\n F.printFilter(ast, () => PRINT_WORD(')'));\n },\n};\n\n/**\n * [[72]](https://www.w3.org/TR/sparql11-query/#rConstructTemplate)\n */\nexport const expressionList: SparqlGrammarRule<'expressionList', Wrap<Expression[]>> = <const> {\n name: 'expressionList',\n impl: ({ ACTION, CONSUME, MANY, OR, SUBRULE1, SUBRULE2 }) => C => OR([\n { ALT: () => {\n const nil = CONSUME(l.terminals.nil);\n return ACTION(() => C.astFactory.wrap([], C.astFactory.sourceLocation(nil)));\n } },\n { ALT: () => {\n const open = CONSUME(l.symbols.LParen);\n const expr1 = SUBRULE1(expression);\n const args: Expression[] = [ expr1 ];\n MANY(() => {\n CONSUME(l.symbols.comma);\n const expr = SUBRULE2(expression);\n args.push(expr);\n });\n const close = CONSUME(l.symbols.RParen);\n return ACTION(() => C.astFactory.wrap(args, C.astFactory.sourceLocation(open, close)));\n } },\n ]),\n};\n\nconst optimizedBracketsInfixOperator = new Set([ '||', '&&', '=', '!=', '<', '>', '<=', '>=', '+', '-', '*', '/' ]);\nconst infixOperators = new Set([ 'in', 'notin', '||', '&&', '=', '!=', '<', '>', '<=', '>=', '+', '-', '*', '/' ]);\nconst prefixOperator: Record<string, string> = { '!': '', uplus: '+', uminus: '-' };\n\n/**\n * [[110]](https://www.w3.org/TR/sparql11-query/#rExpression)\n */\nexport const expression: SparqlRule<'expression', Expression> = <const> {\n name: 'expression',\n impl: ({ SUBRULE }) => () => SUBRULE(conditionalOrExpression),\n gImpl: ({ SUBRULE, PRINT_WORD }) => (ast, { astFactory: F }) => {\n if (F.isTerm(ast)) {\n SUBRULE(varOrTerm, ast);\n } else if (F.isExpressionPatternOperation(ast)) {\n const patterns = ast.args;\n F.printFilter(ast, () => PRINT_WORD(ast.operator === 'exists' ? 'EXISTS' : 'NOT EXISTS'));\n SUBRULE(groupGraphPattern, patterns);\n } else if (F.isExpressionFunctionCall(ast)) {\n SUBRULE(iriOrFunction, ast);\n } else if (F.isExpressionAggregate(ast)) {\n SUBRULE(aggregate, ast);\n } else if (infixOperators.has(ast.operator)) {\n // We know it will be expressionOperator\n const [ left, ...right ] = ast.args;\n F.printFilter(ast, () => PRINT_WORD('('));\n SUBRULE(expression, left);\n F.printFilter(ast, () => {\n if (ast.operator === 'notin') {\n PRINT_WORD('NOT IN');\n } else if (ast.operator === 'in') {\n PRINT_WORD('IN');\n } else {\n PRINT_WORD(ast.operator.toUpperCase());\n }\n });\n if (right.length === 1 && optimizedBracketsInfixOperator.has(ast.operator)) {\n SUBRULE(expression, right[0]);\n } else {\n SUBRULE(argList, F.wrap({ args: right, distinct: false }, ast.loc));\n }\n F.printFilter(ast, () => PRINT_WORD(')'));\n } else if (typeof prefixOperator[ast.operator] === 'string') {\n const [ expr ] = <[Expression]>ast.args;\n F.printFilter(ast, () => PRINT_WORD(prefixOperator[ast.operator] || ast.operator.toUpperCase()));\n SUBRULE(expression, expr);\n } else {\n F.printFilter(ast, () => PRINT_WORD(ast.operator.toUpperCase(), '('));\n const [ head, ...tail ] = ast.args;\n if (head) {\n SUBRULE(expression, head);\n }\n for (const arg of tail) {\n F.printFilter(ast, () => PRINT_WORD(','));\n SUBRULE(expression, arg);\n }\n F.printFilter(ast, () => PRINT_WORD(')'));\n }\n },\n};\n\ntype LeftDeepBuildArgs = (left: Expression) => ExpressionOperation;\n\nfunction constructLeftDeep(\n startGenerator: () => Expression,\n restGenerator: () => LeftDeepBuildArgs,\n ACTION: ImplArgs['ACTION'],\n MANY: ImplArgs['MANY'],\n): ExpressionOperation | Expression {\n // By using iterExpression, we avoid creating unnecessary arrays\n let iterExpr = startGenerator();\n MANY(() => {\n const res = restGenerator();\n ACTION(() => {\n iterExpr = res(iterExpr);\n });\n });\n return iterExpr;\n}\n\n/**\n * [[111]](https://www.w3.org/TR/sparql11-query/#rConditionalOrExpression)\n */\nexport const conditionalOrExpression: SparqlGrammarRule<'conditionalOrExpression', ExpressionOperation | Expression> =\n <const> {\n name: 'conditionalOrExpression',\n impl: ({ ACTION, MANY, CONSUME, SUBRULE1, SUBRULE2 }) => C => constructLeftDeep(\n () => SUBRULE1(conditionalAndExpression),\n () => {\n CONSUME(l.symbols.logicOr);\n const args = SUBRULE2(conditionalAndExpression);\n return left => ACTION(() =>\n C.astFactory.expressionOperation('||', [ left, args ], C.astFactory.sourceLocation(left, args)));\n },\n ACTION,\n MANY,\n ),\n };\n\n/**\n * [[112]](https://www.w3.org/TR/sparql11-query/#rConditionalAndExpression)\n */\nexport const conditionalAndExpression: SparqlGrammarRule<'conditionalAndExpression', Expression> = <const> {\n name: 'conditionalAndExpression',\n impl: ({ ACTION, MANY, SUBRULE1, SUBRULE2, CONSUME }) => C => constructLeftDeep(\n () => SUBRULE1(valueLogical),\n () => {\n CONSUME(l.symbols.logicAnd);\n const arg = SUBRULE2(valueLogical);\n return left => ACTION(() =>\n C.astFactory.expressionOperation('&&', [ left, arg ], C.astFactory.sourceLocation(left, arg)));\n },\n ACTION,\n MANY,\n ),\n};\n\n/**\n * [[113]](https://www.w3.org/TR/sparql11-query/#rValueLogical)\n */\nexport const valueLogical: SparqlGrammarRule<'valueLogical', Expression> = <const> {\n name: 'valueLogical',\n impl: ({ SUBRULE }) => () => SUBRULE(relationalExpression),\n};\n\n/**\n * [[114]](https://www.w3.org/TR/sparql11-query/#rRelationalExpression)\n */\nexport const relationalExpression:\nSparqlGrammarRule<'relationalExpression', ExpressionOperation | Expression> = <const>{\n name: 'relationalExpression',\n impl: ({ ACTION, CONSUME, SUBRULE1, SUBRULE2, OPTION, OR1, OR2, OR3 }) => (C) => {\n const args1 = SUBRULE1(numericExpression);\n const expression = OPTION<ExpressionOperation>(() =>\n OR1<ExpressionOperation>([\n { ALT: () => {\n // Stay in numeric;\n const operator = OR2([\n { ALT: () => CONSUME(l.symbols.equal) },\n { ALT: () => CONSUME(l.symbols.notEqual) },\n { ALT: () => CONSUME(l.symbols.lessThan) },\n { ALT: () => CONSUME(l.symbols.greaterThan) },\n { ALT: () => CONSUME(l.symbols.lessThanEqual) },\n { ALT: () => CONSUME(l.symbols.greaterThanEqual) },\n ]);\n const expr = SUBRULE2(numericExpression);\n return ACTION(() => C.astFactory.expressionOperation(\n operator.image,\n [ args1, expr ],\n C.astFactory.sourceLocation(args1, expr),\n ));\n } },\n { ALT: () => {\n const operator = OR3([\n { ALT: () => CONSUME(l.in_) },\n { ALT: () => CONSUME(l.notIn) },\n ]);\n const args = SUBRULE1(expressionList);\n return ACTION(() => C.astFactory.expressionOperation(\n operator.image,\n [ args1, ...args.val ],\n C.astFactory.sourceLocation(args1, args),\n ));\n } },\n ]));\n return expression ?? args1;\n },\n};\n\n/**\n * [[115]](https://www.w3.org/TR/sparql11-query/#rNumericExpression)\n */\nexport const numericExpression: SparqlGrammarRule<'numericExpression', Expression> = <const> {\n name: 'numericExpression',\n impl: ({ SUBRULE }) => () => SUBRULE(additiveExpression),\n};\n\n/**\n * [[116]](https://www.w3.org/TR/sparql11-query/#rAdditiveExpression)\n */\nexport const additiveExpression: SparqlGrammarRule<'additiveExpression', Expression> = <const> {\n name: 'additiveExpression',\n impl: ({ ACTION, SUBRULE, CONSUME, SUBRULE1, SUBRULE2, MANY1, MANY2, OR1, OR2, OR3, OR4 }) => C =>\n constructLeftDeep(\n () => SUBRULE1(multiplicativeExpression),\n () => OR1<(left: Expression) => ExpressionOperation>([\n { ALT: () => {\n // Multiplicative expression as 2nd argument\n const operator = OR2([\n { ALT: () => CONSUME(l.symbols.opPlus) },\n { ALT: () => CONSUME(l.symbols.opMinus) },\n ]);\n const arg = SUBRULE2(multiplicativeExpression);\n return ACTION(() => left =>\n C.astFactory.expressionOperation(operator.image, [ left, arg ], C.astFactory.sourceLocation(left, arg)));\n } },\n { ALT: () => {\n // The operator of this alternative is actually parsed as part of the signed numeric literal. (note #6)\n const { operator, startInt } = OR3<{ operator: '+' | '-'; startInt: TermLiteral }>([\n { ALT: () => {\n // Note #6. No spaces are allowed between the sign and a number.\n // In this rule however, we do not want to care about this.\n const integer = SUBRULE(numericLiteralPositive);\n return ACTION(() => {\n integer.value = integer.value.replace(/^\\+/u, '');\n return <const> {\n operator: '+',\n startInt: integer,\n };\n });\n } },\n { ALT: () => {\n const integer = SUBRULE(numericLiteralNegative);\n return ACTION(() => {\n integer.value = integer.value.replace(/^-/u, '');\n return <const> {\n operator: '-',\n startInt: integer,\n };\n });\n } },\n ]);\n const multiplicativeExpr = constructLeftDeep(\n () => ACTION(() => startInt),\n () => {\n const innerOperator = OR4([\n { ALT: () => CONSUME(l.symbols.star) },\n { ALT: () => CONSUME(l.symbols.slash) },\n ]);\n const innerExpr = SUBRULE1(unaryExpression);\n return (leftInner: Expression) => ACTION(() =>\n C.astFactory.expressionOperation(\n innerOperator.image,\n [ leftInner, innerExpr ],\n C.astFactory.sourceLocation(leftInner, innerExpr),\n ));\n },\n ACTION,\n MANY2,\n );\n return left => C.astFactory.expressionOperation(\n operator,\n [ left, multiplicativeExpr ],\n C.astFactory.sourceLocation(left, multiplicativeExpr),\n );\n } },\n ]),\n ACTION,\n MANY1,\n ),\n};\n\n/**\n * [[117]](https://www.w3.org/TR/sparql11-query/#rMultiplicativeExpression)\n */\nexport const multiplicativeExpression: SparqlGrammarRule<'multiplicativeExpression', Expression> = <const> {\n name: 'multiplicativeExpression',\n impl: ({ ACTION, CONSUME, MANY, SUBRULE1, SUBRULE2, OR }) => C => constructLeftDeep(\n () => SUBRULE1(unaryExpression),\n () => {\n const operator = OR([\n { ALT: () => CONSUME(l.symbols.star) },\n { ALT: () => CONSUME(l.symbols.slash) },\n ]);\n const expr = SUBRULE2(unaryExpression);\n return (left: Expression) => ({\n type: 'expression',\n subType: 'operation',\n operator: operator.image,\n args: [ left, expr ],\n loc: C.astFactory.sourceLocation(left, expr),\n });\n },\n ACTION,\n MANY,\n ),\n};\n\n/**\n * [[118]](https://www.w3.org/TR/sparql11-query/#rUnaryExpression)\n */\nexport const unaryExpression: SparqlGrammarRule<'unaryExpression', Expression> = <const> {\n name: 'unaryExpression',\n impl: ({ ACTION, CONSUME, SUBRULE1, SUBRULE2, OR1, OR2 }) => C => OR1<Expression>([\n { ALT: () => SUBRULE1(primaryExpression) },\n { ALT: () => {\n const operator = OR2([\n { ALT: () => CONSUME(l.symbols.exclamation) },\n { ALT: () => CONSUME(l.symbols.opPlus) },\n { ALT: () => CONSUME(l.symbols.opMinus) },\n ]);\n const expr = SUBRULE2(primaryExpression);\n return ACTION(() => C.astFactory.expressionOperation(\n operator.image === '!' ? '!' : (operator.image === '+' ? 'UPLUS' : 'UMINUS'),\n [ expr ],\n C.astFactory.sourceLocation(operator, expr),\n ));\n } },\n ]),\n};\n\n/**\n * [[119]](https://www.w3.org/TR/sparql11-query/#rPrimaryExpression)\n */\nexport const primaryExpression: SparqlGrammarRule<'primaryExpression', Expression> = <const> {\n name: 'primaryExpression',\n impl: ({ SUBRULE, OR }) => () => OR([\n { ALT: () => SUBRULE(brackettedExpression) },\n { ALT: () => SUBRULE(builtInCall) },\n { ALT: () => SUBRULE(iriOrFunction) },\n { ALT: () => SUBRULE(rdfLiteral) },\n { ALT: () => SUBRULE(numericLiteral) },\n { ALT: () => SUBRULE(booleanLiteral) },\n { ALT: () => SUBRULE(var_) },\n ]),\n};\n\n/**\n * [[120]](https://www.w3.org/TR/sparql11-query/#rBrackettedExpression)\n */\nexport const brackettedExpression: SparqlGrammarRule<'brackettedExpression', Expression> = <const> {\n name: 'brackettedExpression',\n impl: ({ ACTION, SUBRULE, CONSUME }) => (C) => {\n const open = CONSUME(l.symbols.LParen);\n const expr = SUBRULE(expression);\n const close = CONSUME(l.symbols.RParen);\n return ACTION(() => {\n expr.loc = C.astFactory.sourceLocation(open, close);\n return expr;\n });\n },\n};\n\n/**\n * [[128]](https://www.w3.org/TR/sparql11-query/#ririOrFunction)\n */\nexport const iriOrFunction: SparqlRule<'iriOrFunction', TermIri | ExpressionFunctionCall> = <const> {\n name: 'iriOrFunction',\n impl: ({ ACTION, SUBRULE, OPTION }) => (C) => {\n const iriVal = SUBRULE(iri);\n const functionCall = OPTION<ExpressionFunctionCall>(() => {\n const args = SUBRULE(argList);\n return ACTION(() => {\n const distinct = args.val.distinct;\n if (!C.parseMode.has('canParseAggregate') && distinct) {\n throw new Error(`DISTINCT implies that this function is an aggregated function, which is not allowed in this context.`);\n }\n return {\n type: 'expression',\n subType: 'functionCall',\n function: iriVal,\n args: args.val.args,\n distinct,\n loc: C.astFactory.sourceLocation(iriVal, args),\n };\n });\n });\n return functionCall ?? iriVal;\n },\n gImpl: ({ SUBRULE }) => (ast, { astFactory: F }) => {\n if (F.isTermNamed(ast)) {\n SUBRULE(iri, ast);\n } else {\n SUBRULE(iri, ast.function);\n SUBRULE(argList, F.wrap({ args: ast.args, distinct: ast.distinct }, ast.loc));\n }\n },\n};\n", "import type { IToken } from '@traqula/chevrotain';\nimport type { Wrap } from '@traqula/core';\nimport * as l from '../lexer/index.js';\nimport type { SparqlGrammarRule, SparqlRule } from '../sparql11HelperTypes.js';\nimport type {\n Expression,\n SolutionModifierGroup,\n SolutionModifierGroupBind,\n SolutionModifierHaving,\n SolutionModifierOrder,\n Ordering,\n SolutionModifierLimitOffset,\n SolutionModifiers,\n} from '../Sparql11types.js';\nimport { builtInCall } from './builtIn.js';\nimport { brackettedExpression, expression } from './expression.js';\nimport { var_ } from './general.js';\nimport { constraint, functionCall } from './whereClause.js';\n\n/**\n * [[18]](https://www.w3.org/TR/sparql11-query/#rSolutionModifier)\n */\nexport const solutionModifier: SparqlRule<'solutionModifier', SolutionModifiers> = <const> {\n name: 'solutionModifier',\n impl: ({ ACTION, SUBRULE, OPTION1, OPTION2, OPTION3, OPTION4 }) => () => {\n const group = OPTION1(() => SUBRULE(groupClause));\n const having = OPTION2(() => SUBRULE(havingClause));\n const order = OPTION3(() => SUBRULE(orderClause));\n const limitOffset = OPTION4(() => SUBRULE(limitOffsetClauses));\n return ACTION(() => ({\n ...(limitOffset && { limitOffset }),\n ...(group && { group }),\n ...(having && { having }),\n ...(order && { order }),\n }));\n },\n gImpl: ({ SUBRULE }) => (ast) => {\n if (ast.group) {\n SUBRULE(groupClause, ast.group);\n }\n if (ast.having) {\n SUBRULE(havingClause, ast.having);\n }\n if (ast.order) {\n SUBRULE(orderClause, ast.order);\n }\n if (ast.limitOffset) {\n SUBRULE(limitOffsetClauses, ast.limitOffset);\n }\n },\n};\n\n/**\n * [[19]](https://www.w3.org/TR/sparql11-query/#rGroupClause)\n */\nexport const groupClause: SparqlRule<'groupClause', SolutionModifierGroup> = <const> {\n name: 'groupClause',\n impl: ({ ACTION, AT_LEAST_ONE, SUBRULE1, CONSUME }) => (C) => {\n const groupings: (Expression | SolutionModifierGroupBind)[] = [];\n const start = CONSUME(l.groupByGroup);\n CONSUME(l.by);\n AT_LEAST_ONE(() => {\n groupings.push(SUBRULE1(groupCondition));\n });\n\n return ACTION(() => ({\n type: 'solutionModifier',\n subType: 'group',\n groupings,\n loc: C.astFactory.sourceLocation(start, groupings.at(-1)),\n }));\n },\n gImpl: ({ PRINT_WORDS, SUBRULE, PRINT_ON_EMPTY }) => (ast, { astFactory: F }) => {\n F.printFilter(ast, () => {\n PRINT_ON_EMPTY('GROUP BY ');\n });\n for (const grouping of ast.groupings) {\n // Separate the conditions, otherwise `GROUP BY ?a ex:f(?b)` would be generated as `GROUP BY ?aex:f(?b)`\n F.printFilter(ast, () => PRINT_WORDS(''));\n if (F.isExpression(grouping)) {\n SUBRULE(expression, grouping);\n } else {\n F.printFilter(ast, () => PRINT_WORDS('('));\n SUBRULE(expression, grouping.value);\n F.printFilter(ast, () => PRINT_WORDS('AS'));\n SUBRULE(var_, grouping.variable);\n F.printFilter(ast, () => PRINT_WORDS(')'));\n }\n }\n },\n};\n\n/**\n * [[20]](https://www.w3.org/TR/sparql11-query/#rGroupCondition)\n */\nexport const groupCondition: SparqlGrammarRule<'groupCondition', Expression | SolutionModifierGroupBind> = <const>{\n name: 'groupCondition',\n impl: ({ ACTION, SUBRULE, CONSUME, SUBRULE1, SUBRULE2, OPTION, OR }) => C =>\n OR<Expression | SolutionModifierGroupBind>([\n { ALT: () => SUBRULE(builtInCall) },\n { ALT: () => SUBRULE(functionCall) },\n { ALT: () => SUBRULE2(var_) },\n {\n ALT: () => {\n // Creates a bracketted expression or a Bind.\n const open = CONSUME(l.symbols.LParen);\n const expressionValue = SUBRULE(expression);\n const variable = OPTION(() => {\n CONSUME(l.as);\n return SUBRULE1(var_);\n });\n const close = CONSUME(l.symbols.RParen);\n return ACTION(() => {\n if (variable !== undefined) {\n return {\n variable,\n value: expressionValue,\n loc: C.astFactory.sourceLocation(open, close),\n } satisfies SolutionModifierGroupBind;\n }\n return expressionValue;\n });\n },\n },\n ]),\n};\n\n/**\n * [[21]](https://www.w3.org/TR/sparql11-query/#rHavingClause)\n */\nexport const havingClause: SparqlRule<'havingClause', SolutionModifierHaving> = <const> {\n name: 'havingClause',\n impl: ({ ACTION, AT_LEAST_ONE, SUBRULE, CONSUME }) => (C) => {\n const having = CONSUME(l.having);\n const expressions: Expression[] = [];\n\n const couldParseAgg = ACTION(() =>\n C.parseMode.has('canParseAggregate') || !C.parseMode.add('canParseAggregate'));\n AT_LEAST_ONE(() => {\n expressions.push(SUBRULE(havingCondition));\n });\n ACTION(() => !couldParseAgg && C.parseMode.delete('canParseAggregate'));\n\n return ACTION(() =>\n C.astFactory.solutionModifierHaving(expressions, C.astFactory.sourceLocation(having, expressions.at(-1))));\n },\n gImpl: ({ PRINT_ON_EMPTY, SUBRULE }) => (ast, { astFactory: F }) => {\n F.printFilter(ast, () => {\n PRINT_ON_EMPTY('HAVING ');\n });\n for (const having of ast.having) {\n SUBRULE(expression, having);\n }\n },\n};\n\n/**\n * [[22]](https://www.w3.org/TR/sparql11-query/#rHavingCondition)\n */\nexport const havingCondition: SparqlGrammarRule<'havingCondition', Expression> = <const> {\n name: 'havingCondition',\n impl: ({ SUBRULE }) => () => SUBRULE(constraint),\n};\n\n/**\n * [[23]](https://www.w3.org/TR/sparql11-query/#rOrderClause)\n */\nexport const orderClause: SparqlRule<'orderClause', SolutionModifierOrder> = <const> {\n name: 'orderClause',\n impl: ({ ACTION, AT_LEAST_ONE, SUBRULE1, CONSUME }) => (C) => {\n const order = CONSUME(l.order);\n CONSUME(l.by);\n const orderings: Ordering[] = [];\n\n const couldParseAgg = ACTION(() =>\n C.parseMode.has('canParseAggregate') || !C.parseMode.add('canParseAggregate'));\n AT_LEAST_ONE(() => {\n orderings.push(SUBRULE1(orderCondition));\n });\n ACTION(() => !couldParseAgg && C.parseMode.delete('canParseAggregate'));\n\n return ACTION(() =>\n C.astFactory.solutionModifierOrder(orderings, C.astFactory.sourceLocation(order, orderings.at(-1))));\n },\n gImpl: ({ PRINT_WORDS, PRINT_ON_EMPTY, SUBRULE }) => (ast, { astFactory: F }) => {\n F.printFilter(ast, () => {\n PRINT_ON_EMPTY('ORDER BY ');\n });\n for (const ordering of ast.orderDefs) {\n if (ordering.descending) {\n F.printFilter(ast, () => PRINT_WORDS('DESC'));\n } else {\n F.printFilter(ast, () => PRINT_WORDS('ASC'));\n }\n F.printFilter(ast, () => PRINT_WORDS('('));\n SUBRULE(expression, ordering.expression);\n F.printFilter(ast, () => PRINT_WORDS(')'));\n }\n },\n};\n\n/**\n * [[24]](https://www.w3.org/TR/sparql11-query/#rOrderCondition)\n */\nexport const orderCondition: SparqlGrammarRule<'orderCondition', Ordering> = <const> {\n name: 'orderCondition',\n impl: ({ ACTION, SUBRULE, CONSUME, OR1, OR2 }) => C => OR1<Ordering>([\n { ALT: () => {\n const descending = OR2<[boolean, IToken]>([\n { ALT: () => {\n const token = CONSUME(l.orderAsc);\n return <const>[ false, token ];\n } },\n { ALT: () => {\n const token = CONSUME(l.orderDesc);\n return <const> [ true, token ];\n } },\n ]);\n\n const expr = SUBRULE(brackettedExpression);\n\n return ACTION(() => ({\n expression: expr,\n descending: descending[0],\n loc: C.astFactory.sourceLocation(descending[1], expr),\n }));\n } },\n { ALT: () => {\n const expr = SUBRULE(constraint);\n return ACTION(() => ({ expression: expr, descending: false, loc: expr.loc }));\n } },\n { ALT: () => {\n const expr = SUBRULE(var_);\n return ACTION(() => ({ expression: expr, descending: false, loc: expr.loc }));\n } },\n ]),\n};\n\n/**\n * Parses limit and or offset in any order.\n * [[25]](https://www.w3.org/TR/sparql11-query/#rLimitOffsetClauses)\n */\nexport const limitOffsetClauses: SparqlRule<'limitOffsetClauses', SolutionModifierLimitOffset> = <const> {\n name: 'limitOffsetClauses',\n impl: ({ ACTION, SUBRULE1, SUBRULE2, OPTION1, OPTION2, OR }) => C => OR([\n { ALT: () => {\n const limit = SUBRULE1(limitClause);\n const offset = OPTION1(() => SUBRULE1(offsetClause));\n return ACTION(() => C.astFactory.solutionModifierLimitOffset(\n limit.val,\n offset?.val,\n C.astFactory.sourceLocation(limit, ...(offset ? [ offset ] : [])),\n ));\n } },\n { ALT: () => {\n const offset = SUBRULE2(offsetClause);\n const limit = OPTION2(() => SUBRULE2(limitClause));\n return ACTION(() => C.astFactory.solutionModifierLimitOffset(\n limit?.val,\n offset.val,\n C.astFactory.sourceLocation(offset, limit),\n ));\n } },\n ]),\n gImpl: ({ PRINT_WORDS, NEW_LINE }) => (ast, { astFactory: F }) => {\n F.printFilter(ast, () => {\n NEW_LINE();\n if (ast.limit !== undefined) {\n PRINT_WORDS('LIMIT', String(ast.limit));\n }\n if (ast.offset) {\n PRINT_WORDS('OFFSET', String(ast.offset));\n }\n });\n },\n};\n\n/**\n * [[26]](https://www.w3.org/TR/sparql11-query/#rLimitClause)\n */\nexport const limitClause: SparqlGrammarRule<'limitClause', Wrap<number>> = <const> {\n name: 'limitClause',\n impl: ({ ACTION, CONSUME }) => (C) => {\n const offset = CONSUME(l.limit);\n const value = CONSUME(l.terminals.integer);\n const val = Number.parseInt(value.image, 10);\n return ACTION(() => C.astFactory.wrap(val, C.astFactory.sourceLocation(offset, value)));\n },\n};\n\n/**\n * [[27]](https://www.w3.org/TR/sparql11-query/#rWhereClause)\n */\nexport const offsetClause: SparqlGrammarRule<'offsetClause', Wrap<number>> = <const> {\n name: <const> 'offsetClause',\n impl: ({ CONSUME, ACTION }) => (C) => {\n const offset = CONSUME(l.offset);\n const value = CONSUME(l.terminals.integer);\n const val = Number.parseInt(value.image, 10);\n return ACTION(() => C.astFactory.wrap(val, C.astFactory.sourceLocation(offset, value)));\n },\n};\n", "import type { IToken } from '@traqula/chevrotain';\nimport type { Localized, RuleDefReturn, Wrap } from '@traqula/core';\nimport { traqulaIndentation } from '@traqula/core';\nimport * as l from '../lexer/index.js';\nimport type { SparqlGrammarRule, SparqlRule } from '../sparql11HelperTypes.js';\nimport type {\n PatternBgp,\n PatternBind,\n PatternValues,\n Query,\n QueryAsk,\n QueryConstruct,\n QueryDescribe,\n QuerySelect,\n SubSelect,\n TermIri,\n TermVariable,\n Wildcard,\n} from '../Sparql11types.js';\nimport { queryProjectionIsGood } from '../validation/validators.js';\nimport { datasetClauseStar } from './dataSetClause.js';\nimport { expression } from './expression.js';\nimport { prologue, var_, varOrIri, varOrTerm } from './general.js';\nimport { solutionModifier } from './solutionModifier.js';\nimport { triplesBlock, triplesTemplate } from './tripleBlock.js';\nimport { inlineData, whereClause } from './whereClause.js';\n\n/**\n * [[1]](https://www.w3.org/TR/sparql11-query/#rQueryUnit)\n */\nexport const queryUnit: SparqlGrammarRule<'queryUnit', Query> = <const> {\n name: 'queryUnit',\n impl: ({ SUBRULE }) => () => SUBRULE(query),\n};\n\nexport type HandledByBase = 'type' | 'context' | 'values';\n\n/**\n * [[2]](https://www.w3.org/TR/sparql11-query/#rQuery)\n */\nexport const query: SparqlRule<'query', Query> = <const> {\n name: 'query',\n impl: ({ ACTION, SUBRULE, OR }) => (C) => {\n const prologueValues = SUBRULE(prologue);\n const subType = OR<Omit<Query, HandledByBase>>([\n { ALT: () => SUBRULE(selectQuery) },\n { ALT: () => SUBRULE(constructQuery) },\n { ALT: () => SUBRULE(describeQuery) },\n { ALT: () => SUBRULE(askQuery) },\n ]);\n const values = SUBRULE(valuesClause);\n\n return ACTION(() => {\n const q = <Query> {\n context: prologueValues,\n ...subType,\n type: 'query',\n loc: C.astFactory.sourceLocation(\n prologueValues.at(0),\n subType,\n values,\n ),\n };\n if (values) {\n q.values = values;\n }\n return q;\n });\n },\n gImpl: ({ SUBRULE }) => (ast, { astFactory: F }) => {\n SUBRULE(prologue, ast.context);\n if (F.isQuerySelect(ast)) {\n SUBRULE(selectQuery, ast);\n } else if (F.isQueryConstruct(ast)) {\n SUBRULE(constructQuery, ast);\n } else if (F.isQueryDescribe(ast)) {\n SUBRULE(describeQuery, ast);\n } else {\n SUBRULE(askQuery, ast);\n }\n if (ast.values) {\n SUBRULE(inlineData, ast.values);\n }\n },\n};\n\n/**\n * [[7]](https://www.w3.org/TR/sparql11-query/#rSelectQuery)\n */\nexport const selectQuery: SparqlRule<'selectQuery', Omit<QuerySelect, HandledByBase>> = <const> {\n name: 'selectQuery',\n impl: ({ ACTION, SUBRULE }) => (C) => {\n const selectVal = SUBRULE(selectClause);\n const from = SUBRULE(datasetClauseStar);\n const where = SUBRULE(whereClause);\n const modifiers = SUBRULE(solutionModifier);\n\n return ACTION(() => {\n const ret = {\n subType: 'select',\n where: where.val,\n solutionModifiers: modifiers,\n datasets: from,\n ...selectVal.val,\n loc: C.astFactory.sourceLocation(\n selectVal,\n where,\n modifiers.group,\n modifiers.having,\n modifiers.order,\n modifiers.limitOffset,\n ),\n } satisfies RuleDefReturn<typeof selectQuery>;\n if (!C.skipValidation) {\n queryProjectionIsGood(ret);\n }\n return ret;\n });\n },\n gImpl: ({ SUBRULE }) => (ast, { astFactory: F }) => {\n SUBRULE(selectClause, F.wrap({\n variables: ast.variables,\n distinct: ast.distinct,\n reduced: ast.reduced,\n }, F.sourceLocation(...ast.variables)));\n SUBRULE(datasetClauseStar, ast.datasets);\n SUBRULE(whereClause, F.wrap(ast.where, ast.where.loc));\n SUBRULE(solutionModifier, ast.solutionModifiers);\n },\n};\n\n/**\n * [[8]](https://www.w3.org/TR/sparql11-query/#rSubSelect)\n */\nexport const subSelect: SparqlGrammarRule<'subSelect', SubSelect> = <const> {\n name: 'subSelect',\n impl: ({ ACTION, SUBRULE }) => (C) => {\n const selectVal = SUBRULE(selectClause);\n const where = SUBRULE(whereClause);\n const modifiers = SUBRULE(solutionModifier);\n const values = SUBRULE(valuesClause);\n\n return ACTION(() => C.astFactory.querySelect({\n where: where.val,\n datasets: C.astFactory.datasetClauses([], C.astFactory.sourceLocation()),\n context: [],\n solutionModifiers: modifiers,\n ...selectVal.val,\n ...(values && { values }),\n }, C.astFactory.sourceLocation(\n selectVal,\n where,\n modifiers.group,\n modifiers.having,\n modifiers.order,\n modifiers.limitOffset,\n values,\n )));\n },\n};\n\n/**\n * [[9]](https://www.w3.org/TR/sparql11-query/#rSelectClause)\n */\nexport const selectClause: SparqlRule<'selectClause', Wrap<Pick<QuerySelect, 'variables' | 'distinct' | 'reduced'>>> = {\n name: 'selectClause',\n impl: ({\n ACTION,\n AT_LEAST_ONE,\n SUBRULE1,\n SUBRULE2,\n CONSUME,\n OPTION,\n OR1,\n OR2,\n OR3,\n }) => (C) => {\n const select = CONSUME(l.select);\n const couldParseAgg = ACTION(() => C.parseMode.has('canParseAggregate') || !C.parseMode.add('canParseAggregate'));\n\n const distinctAndReduced = OPTION(() => OR1<[boolean, boolean]>([\n { ALT: () => {\n CONSUME(l.distinct);\n return <const> [ true, false ];\n } },\n { ALT: () => {\n CONSUME(l.reduced);\n return <const> [ false, true ];\n } },\n ])) ?? [ false, false ];\n const distRed = ACTION(() => {\n const [ distinct, reduced ] = distinctAndReduced;\n return {\n ...(distinct && { distinct }),\n ...(reduced && { reduced }),\n };\n });\n\n let last: Localized | IToken;\n const val = OR2<RuleDefReturn<typeof selectClause>['val']>([\n { ALT: () => {\n const star = CONSUME(l.symbols.star);\n return ACTION(() => {\n last = star;\n return { variables: [ C.astFactory.wildcard(C.astFactory.sourceLocation(star)) ], ...distRed };\n });\n } },\n { ALT: () => {\n const usedVars: TermVariable[] = [];\n const variables: (TermVariable | PatternBind)[] = [];\n AT_LEAST_ONE(() => OR3([\n { ALT: () => {\n const raw = SUBRULE1(var_);\n ACTION(() => {\n if (!C.skipValidation && usedVars.some(v => v.value === raw.value)) {\n throw new Error(`Variable ${raw.value} used more than once in SELECT clause`);\n }\n usedVars.push(raw);\n variables.push(raw);\n last = raw;\n });\n } },\n { ALT: () => {\n const open = CONSUME(l.symbols.LParen);\n const expr = SUBRULE1(expression);\n CONSUME(l.as);\n const variable = SUBRULE2(var_);\n const close = CONSUME(l.symbols.RParen);\n ACTION(() => {\n last = close;\n if (!C.skipValidation && usedVars.some(v => v.value === variable.value)) {\n throw new Error(`Variable ${variable.value} used more than once in SELECT clause`);\n }\n usedVars.push(variable);\n variables.push(C.astFactory.patternBind(expr, variable, C.astFactory.sourceLocation(open, last)));\n });\n } },\n ]));\n return { variables, ...distRed };\n } },\n ]);\n ACTION(() => !couldParseAgg && C.parseMode.delete('canParseAggregate'));\n return ACTION(() => C.astFactory.wrap(val, C.astFactory.sourceLocation(select, last)));\n },\n gImpl: ({ SUBRULE, PRINT_WORD, PRINT_ON_EMPTY }) => (ast, { astFactory: F }) => {\n F.printFilter(ast, () => {\n PRINT_ON_EMPTY('SELECT ');\n if (ast.val.distinct) {\n PRINT_WORD('DISTINCT');\n } else if (ast.val.reduced) {\n PRINT_WORD('REDUCED');\n }\n });\n for (const variable of ast.val.variables) {\n if (F.isWildcard(variable)) {\n F.printFilter(ast, () => PRINT_WORD('*'));\n } else if (F.isTerm(variable)) {\n SUBRULE(var_, variable);\n } else {\n F.printFilter(ast, () => PRINT_WORD('('));\n SUBRULE(expression, variable.expression);\n F.printFilter(ast, () => PRINT_WORD('AS'));\n SUBRULE(var_, variable.variable);\n F.printFilter(ast, () => PRINT_WORD(')'));\n }\n F.printFilter(ast, () => PRINT_WORD(''));\n }\n F.printFilter(ast, () => PRINT_WORD(''));\n },\n\n};\n\n/**\n * [[10]](https://www.w3.org/TR/sparql11-query/#rConstructQuery)\n */\nexport const constructQuery: SparqlRule<'constructQuery', Omit<QueryConstruct, HandledByBase>> = <const> {\n name: 'constructQuery',\n impl: ({ ACTION, SUBRULE1, SUBRULE2, CONSUME, OR }) => (C) => {\n const construct = CONSUME(l.construct);\n return OR<Omit<QueryConstruct, HandledByBase>>([\n { ALT: () => {\n const template = SUBRULE1(constructTemplate);\n const from = SUBRULE1(datasetClauseStar);\n const where = SUBRULE1(whereClause);\n const modifiers = SUBRULE1(solutionModifier);\n return ACTION(() => ({\n subType: 'construct',\n template: template.val,\n datasets: from,\n where: where.val,\n solutionModifiers: modifiers,\n loc: C.astFactory.sourceLocation(\n construct,\n where,\n modifiers.group,\n modifiers.having,\n modifiers.order,\n modifiers.limitOffset,\n ),\n } satisfies Omit<QueryConstruct, HandledByBase>));\n } },\n { ALT: () => {\n const from = SUBRULE2(datasetClauseStar);\n CONSUME(l.where);\n // ConstructTemplate is same as '{' TriplesTemplate? '}'\n const template = SUBRULE2(constructTemplate);\n const modifiers = SUBRULE2(solutionModifier);\n\n return ACTION(() => ({\n subType: 'construct',\n template: template.val,\n datasets: from,\n where: C.astFactory.patternGroup([ template.val ], C.astFactory.sourceLocation()),\n solutionModifiers: modifiers,\n loc: C.astFactory.sourceLocation(\n construct,\n template,\n modifiers.group,\n modifiers.having,\n modifiers.order,\n modifiers.limitOffset,\n ),\n }));\n } },\n ]);\n },\n gImpl: ({ SUBRULE, PRINT_WORD, PRINT_ON_EMPTY, PRINT_ON_OWN_LINE, NEW_LINE }) => (ast, C) => {\n const { astFactory: F, indentInc } = C;\n F.printFilter(ast, () => PRINT_ON_EMPTY('CONSTRUCT '));\n if (!F.isSourceLocationNoMaterialize(ast.where.loc)) {\n // You are NOT in second case construct\n F.printFilter(ast, () => {\n C[traqulaIndentation] += indentInc;\n PRINT_WORD('{');\n NEW_LINE();\n });\n SUBRULE(triplesBlock, ast.template);\n F.printFilter(ast, () => {\n C[traqulaIndentation] -= indentInc;\n PRINT_ON_OWN_LINE('}');\n });\n }\n SUBRULE(datasetClauseStar, ast.datasets);\n if (F.isSourceLocationNoMaterialize(ast.where.loc)) {\n SUBRULE(whereClause, F.wrap(F.patternGroup([ ast.template ], ast.template.loc), ast.template.loc));\n } else {\n SUBRULE(whereClause, F.wrap(ast.where, ast.where.loc));\n }\n SUBRULE(solutionModifier, ast.solutionModifiers);\n },\n};\n\n/**\n * [[11]](https://www.w3.org/TR/sparql11-query/#rDescribeQuery)\n */\nexport const describeQuery: SparqlRule<'describeQuery', Omit<QueryDescribe, HandledByBase>> = <const> {\n name: 'describeQuery',\n impl: ({ ACTION, AT_LEAST_ONE, SUBRULE1, CONSUME, OPTION, OR }) => (C) => {\n const describe = CONSUME(l.describe);\n const variables = OR<QueryDescribe['variables']>([\n { ALT: () => {\n const variables: (TermVariable | TermIri)[] = [];\n AT_LEAST_ONE(() => {\n variables.push(SUBRULE1(varOrIri));\n });\n return variables;\n } },\n { ALT: () => {\n const star = CONSUME(l.symbols.star);\n return [ ACTION(() => C.astFactory.wildcard(C.astFactory.sourceLocation(star))) ];\n } },\n ]);\n const from = SUBRULE1(datasetClauseStar);\n const where = OPTION(() => SUBRULE1(whereClause));\n const modifiers = SUBRULE1(solutionModifier);\n return ACTION(() => ({\n subType: 'describe',\n variables,\n datasets: from,\n ...(where && { where: where.val }),\n solutionModifiers: modifiers,\n loc: C.astFactory.sourceLocation(\n describe,\n ...variables,\n from,\n where,\n modifiers.group,\n modifiers.having,\n modifiers.order,\n modifiers.limitOffset,\n ),\n }));\n },\n gImpl: ({ SUBRULE, PRINT_WORD, PRINT_ON_EMPTY }) => (ast, { astFactory: F }) => {\n F.printFilter(ast, () => PRINT_ON_EMPTY('DESCRIBE '));\n if (F.isWildcard(ast.variables[0])) {\n F.printFilter(ast, () => PRINT_WORD('*'));\n } else {\n for (const variable of (<Exclude<QueryDescribe['variables'], [Wildcard]>> ast.variables)) {\n // Separate the targets, otherwise `DESCRIBE ?s ex:a` would be generated as `DESCRIBE ?sex:a`\n F.printFilter(ast, () => PRINT_WORD(''));\n SUBRULE(varOrTerm, variable);\n }\n }\n SUBRULE(datasetClauseStar, ast.datasets);\n if (ast.where) {\n SUBRULE(whereClause, F.wrap(ast.where, ast.loc));\n }\n SUBRULE(solutionModifier, ast.solutionModifiers);\n },\n};\n\n/**\n * [[12]](https://www.w3.org/TR/sparql11-query/#rAskQuery)\n */\nexport const askQuery: SparqlRule<'askQuery', Omit<QueryAsk, HandledByBase>> = <const> {\n name: 'askQuery',\n impl: ({ ACTION, SUBRULE, CONSUME }) => (C) => {\n const ask = CONSUME(l.ask);\n const from = SUBRULE(datasetClauseStar);\n const where = SUBRULE(whereClause);\n const modifiers = SUBRULE(solutionModifier);\n\n return ACTION(() => ({\n subType: 'ask',\n datasets: from,\n where: where.val,\n solutionModifiers: modifiers,\n loc: C.astFactory.sourceLocation(\n ask,\n from,\n where,\n modifiers.group,\n modifiers.having,\n modifiers.order,\n modifiers.limitOffset,\n ),\n } satisfies RuleDefReturn<typeof askQuery>));\n },\n gImpl: ({ SUBRULE, PRINT_ON_EMPTY }) => (ast, { astFactory: F }) => {\n F.printFilter(ast, () => PRINT_ON_EMPTY('ASK '));\n SUBRULE(datasetClauseStar, ast.datasets);\n SUBRULE(whereClause, F.wrap(ast.where, ast.loc));\n SUBRULE(solutionModifier, ast.solutionModifiers);\n },\n};\n\n/**\n * [[28]](https://www.w3.org/TR/sparql11-query/#rValuesClause)\n */\nexport const valuesClause: SparqlGrammarRule<'valuesClause', PatternValues | undefined> = <const> {\n name: 'valuesClause',\n impl: ({ OPTION, SUBRULE }) => () => OPTION(() => SUBRULE(inlineData)),\n};\n\n/**\n * [[73]](https://www.w3.org/TR/sparql11-query/#ConstructTemplate)\n */\nexport const constructTemplate: SparqlGrammarRule<'constructTemplate', Wrap<PatternBgp>> = <const> {\n name: 'constructTemplate',\n impl: ({ ACTION, SUBRULE1, CONSUME, OPTION }) => (C) => {\n const open = CONSUME(l.symbols.LCurly);\n const triples = OPTION(() => SUBRULE1(constructTriples));\n const close = CONSUME(l.symbols.RCurly);\n\n return ACTION(() => C.astFactory.wrap(\n triples ?? C.astFactory.patternBgp([], C.astFactory.sourceLocation()),\n C.astFactory.sourceLocation(open, close),\n ));\n },\n};\n\n/**\n * [[12]](https://www.w3.org/TR/sparql11-query/#rConstructTriples)\n */\nexport const constructTriples: SparqlGrammarRule<'constructTriples', PatternBgp> = <const> {\n name: 'constructTriples',\n impl: triplesTemplate.impl,\n};\n", "import type { IToken, TokenType } from '@traqula/chevrotain';\nimport type { Localized, RuleDefReturn, Wrap } from '@traqula/core';\nimport { traqulaIndentation, unCapitalize } from '@traqula/core';\nimport * as l from '../lexer/index.js';\nimport type { SparqlGrammarRule, SparqlRule } from '../sparql11HelperTypes.js';\nimport type {\n GraphQuads,\n GraphRef,\n GraphRefDefault,\n GraphRefSpecific,\n Quads,\n Update,\n UpdateOperation,\n UpdateOperationAdd,\n UpdateOperationClear,\n UpdateOperationCopy,\n UpdateOperationCreate,\n UpdateOperationDeleteData,\n UpdateOperationDeleteWhere,\n UpdateOperationDrop,\n UpdateOperationInsertData,\n UpdateOperationLoad,\n UpdateOperationModify,\n UpdateOperationMove,\n} from '../Sparql11types.js';\nimport { updateNoReuseBlankNodeLabels } from '../validation/validators.js';\nimport { usingClauseStar } from './dataSetClause.js';\nimport { prologue, varOrIri, varOrTerm } from './general.js';\nimport { iri } from './literals.js';\nimport { triplesBlock, triplesTemplate } from './tripleBlock.js';\nimport { groupGraphPattern } from './whereClause.js';\n\n/**\n * [[3]](https://www.w3.org/TR/sparql11-query/#rUpdateUnit)\n */\nexport const updateUnit: SparqlGrammarRule<'updateUnit', Update> = <const> {\n name: 'updateUnit',\n impl: ({ SUBRULE }) => () => SUBRULE(update),\n};\n\n/**\n * [[29]](https://www.w3.org/TR/sparql11-query/#rUpdate)\n */\nexport const update: SparqlRule<'update', Update> = <const> {\n name: 'update',\n impl: ({ ACTION, SUBRULE, SUBRULE1, SUBRULE2, CONSUME, OPTION1, MANY }) => (C) => {\n // Override prologueValues on new reads of prologue and sink them into updates later\n const updates: Update['updates'] = [];\n const prologueValues = SUBRULE1(prologue);\n updates.push({ context: prologueValues });\n\n let parsedSemi = true;\n MANY({\n GATE: () => parsedSemi,\n DEF: () => {\n parsedSemi = false;\n updates.at(-1)!.operation = SUBRULE(update1);\n\n OPTION1(() => {\n CONSUME(l.symbols.semi);\n\n parsedSemi = true;\n const innerPrologue = SUBRULE2(prologue);\n updates.push({ context: innerPrologue });\n });\n },\n });\n return ACTION(() => {\n const update = {\n type: 'update',\n updates,\n loc: C.astFactory.sourceLocation(\n ...updates.flatMap(x => [ ...x.context, x.operation ]),\n ),\n } satisfies Update;\n if (!C.skipValidation) {\n updateNoReuseBlankNodeLabels(update);\n }\n return update;\n });\n },\n gImpl: ({ SUBRULE, PRINT, NEW_LINE }) => (ast, { astFactory: F }) => {\n const [ head, ...tail ] = ast.updates;\n if (head) {\n SUBRULE(prologue, head.context);\n if (head.operation) {\n SUBRULE(update1, head.operation);\n }\n }\n for (const update of tail) {\n F.printFilter(ast, () => {\n PRINT(';');\n NEW_LINE();\n });\n SUBRULE(prologue, update.context);\n if (update.operation) {\n SUBRULE(update1, update.operation);\n }\n }\n },\n};\n\n/**\n * [[30]](https://www.w3.org/TR/sparql11-query/#rUpdate1)\n */\nexport const update1: SparqlRule<'update1', UpdateOperation> = <const> {\n name: 'update1',\n impl: ({ SUBRULE, OR }) => () => OR<UpdateOperation>([\n { ALT: () => SUBRULE(load) },\n { ALT: () => SUBRULE(clear) },\n { ALT: () => SUBRULE(drop) },\n { ALT: () => SUBRULE(add) },\n { ALT: () => SUBRULE(move) },\n { ALT: () => SUBRULE(copy) },\n { ALT: () => SUBRULE(create) },\n { ALT: () => SUBRULE(insertData) },\n { ALT: () => SUBRULE(deleteData) },\n { ALT: () => SUBRULE(deleteWhere) },\n { ALT: () => SUBRULE(modify) },\n ]),\n gImpl: ({ SUBRULE }) => (ast) => {\n switch (ast.subType) {\n case ('load'):\n SUBRULE(load, ast);\n break;\n case ('clear'):\n SUBRULE(clear, ast);\n break;\n case ('drop'):\n SUBRULE(drop, ast);\n break;\n case ('add'):\n SUBRULE(add, ast);\n break;\n case ('move'):\n SUBRULE(move, ast);\n break;\n case ('copy'):\n SUBRULE(copy, ast);\n break;\n case ('create'):\n SUBRULE(create, ast);\n break;\n case ('insertdata'):\n SUBRULE(insertData, ast);\n break;\n case ('deletedata'):\n SUBRULE(deleteData, ast);\n break;\n case ('deletewhere'):\n SUBRULE(deleteWhere, ast);\n break;\n case ('modify'):\n SUBRULE(modify, ast);\n break;\n }\n },\n};\n\n/**\n * [[31]](https://www.w3.org/TR/sparql11-query/#rLoad)\n */\nexport const load: SparqlRule<'load', UpdateOperationLoad> = <const> {\n name: 'load',\n impl: ({ ACTION, SUBRULE1, CONSUME, OPTION1, OPTION2 }) => (C) => {\n const loadToken = CONSUME(l.load);\n const silent = OPTION1(() => CONSUME(l.silent));\n const source = SUBRULE1(iri);\n const destination = OPTION2(() => {\n CONSUME(l.loadInto);\n return SUBRULE1(graphRef);\n });\n return ACTION(() => C.astFactory.updateOperationLoad(\n C.astFactory.sourceLocation(loadToken, source, destination),\n source,\n Boolean(silent),\n destination,\n ));\n },\n gImpl: ({ SUBRULE, PRINT_WORD, PRINT_ON_EMPTY }) => (ast, { astFactory: F }) => {\n F.printFilter(ast, () => {\n PRINT_ON_EMPTY('LOAD ');\n if (ast.silent) {\n PRINT_WORD('SILENT');\n }\n });\n SUBRULE(iri, ast.source);\n if (ast.destination) {\n F.printFilter(ast, () => PRINT_WORD('INTO'));\n SUBRULE(graphRefAll, ast.destination);\n }\n },\n};\n\nfunction clearOrDrop<T extends 'Clear' | 'Drop'>(operation: TokenType & { name: T }):\nSparqlRule<Uncapitalize<T>, UpdateOperationClear | UpdateOperationDrop> {\n return {\n name: unCapitalize(operation.name),\n impl: ({ ACTION, SUBRULE1, CONSUME, OPTION }) => (C) => {\n const opToken = CONSUME(operation);\n const silent = OPTION(() => CONSUME(l.silent));\n const destination = SUBRULE1(graphRefAll);\n return ACTION(() => C.astFactory.updateOperationClearDrop(\n unCapitalize(operation.name),\n Boolean(silent),\n destination,\n C.astFactory.sourceLocation(opToken, destination),\n ));\n },\n gImpl: ({ SUBRULE, PRINT_WORD, PRINT_ON_EMPTY }) => (ast, { astFactory: F }) => {\n F.printFilter(ast, () => {\n PRINT_ON_EMPTY(operation.name.toUpperCase(), ' ');\n if (ast.silent) {\n PRINT_WORD('SILENT');\n }\n });\n SUBRULE(graphRefAll, ast.destination);\n },\n };\n}\n\n/**\n * [[32]](https://www.w3.org/TR/sparql11-query/#rClear)\n */\nexport const clear = clearOrDrop(l.clear);\n\n/**\n * [[33]](https://www.w3.org/TR/sparql11-query/#rDrop)\n */\nexport const drop = clearOrDrop(l.drop);\n\n/**\n * [[34]](https://www.w3.org/TR/sparql11-query/#rCreate)\n */\nexport const create: SparqlRule<'create', UpdateOperationCreate> = <const> {\n name: 'create',\n impl: ({ ACTION, SUBRULE1, CONSUME, OPTION }) => (C) => {\n const createToken = CONSUME(l.create);\n const silent = OPTION(() => CONSUME(l.silent));\n const destination = SUBRULE1(graphRef);\n\n return ACTION(() => C.astFactory.updateOperationCreate(\n destination,\n Boolean(silent),\n C.astFactory.sourceLocation(createToken, destination),\n ));\n },\n gImpl: ({ SUBRULE, PRINT_WORD, PRINT_ON_EMPTY }) => (ast, { astFactory: F }) => {\n F.printFilter(ast, () => {\n PRINT_ON_EMPTY('CREATE ');\n if (ast.silent) {\n PRINT_WORD('SILENT');\n }\n });\n SUBRULE(graphRefAll, ast.destination);\n },\n};\n\nfunction copyMoveAddOperation<T extends 'Copy' | 'Move' | 'Add'>(operation: TokenType & { name: T }):\nSparqlRule<Uncapitalize<T>, UpdateOperationAdd | UpdateOperationMove | UpdateOperationCopy> {\n return {\n name: unCapitalize(operation.name),\n impl: ({ ACTION, CONSUME, SUBRULE1, SUBRULE2, OPTION }) => (C) => {\n const op = CONSUME(operation);\n const silent = OPTION(() => CONSUME(l.silent));\n const source = SUBRULE1(graphOrDefault);\n CONSUME(l.to);\n const destination = SUBRULE2(graphOrDefault);\n\n return ACTION(() => C.astFactory.updateOperationAddMoveCopy(\n unCapitalize(operation.name),\n source,\n destination,\n Boolean(silent),\n C.astFactory.sourceLocation(op, destination),\n ));\n },\n gImpl: ({ SUBRULE, PRINT_WORD, PRINT_ON_EMPTY }) => (ast, { astFactory: F }) => {\n F.printFilter(ast, () => {\n PRINT_ON_EMPTY(operation.name.toUpperCase(), ' ');\n if (ast.silent) {\n PRINT_WORD('SILENT');\n }\n });\n SUBRULE(graphRefAll, ast.source);\n F.printFilter(ast, () => PRINT_WORD('TO'));\n SUBRULE(graphRefAll, ast.destination);\n },\n };\n}\n\n/**\n * [[35]](https://www.w3.org/TR/sparql11-query/#rAdd)\n */\nexport const add = copyMoveAddOperation(l.add);\n\n/**\n * [[36]](https://www.w3.org/TR/sparql11-query/#rMove)\n */\nexport const move = copyMoveAddOperation(l.move);\n\n/**\n * [[37]](https://www.w3.org/TR/sparql11-query/#rCopy)\n */\nexport const copy = copyMoveAddOperation(l.copy);\n\n/**\n * [[48]](https://www.w3.org/TR/sparql11-query/#rQuadPattern)\n */\nexport const quadPattern: SparqlGrammarRule<'quadPattern', Wrap<Quads[]>> = <const> {\n name: 'quadPattern',\n impl: ({ ACTION, SUBRULE1, CONSUME }) => (C) => {\n const open = CONSUME(l.symbols.LCurly);\n const val = SUBRULE1(quads);\n const close = CONSUME(l.symbols.RCurly);\n return ACTION(() => C.astFactory.wrap(val.val, C.astFactory.sourceLocation(open, close)));\n },\n};\n\n/**\n * [[49]](https://www.w3.org/TR/sparql11-query/#rQuadData)\n */\nexport const quadData: SparqlGrammarRule<'quadData', Wrap<Quads[]>> = <const> {\n name: 'quadData',\n impl: ({ ACTION, SUBRULE1, CONSUME }) => (C) => {\n const open = CONSUME(l.symbols.LCurly);\n\n const couldParseVars = ACTION(() => C.parseMode.delete('canParseVars'));\n const val = SUBRULE1(quads);\n ACTION(() => couldParseVars && C.parseMode.add('canParseVars'));\n\n const close = CONSUME(l.symbols.RCurly);\n return ACTION(() => C.astFactory.wrap(val.val, C.astFactory.sourceLocation(open, close)));\n },\n};\n\nfunction insertDeleteDelWhere<T extends string>(\n name: T,\n subType: 'insertdata' | 'deletedata' | 'deletewhere',\n cons1: TokenType,\n dataRule: SparqlGrammarRule<any, Wrap<Quads[]>>,\n): SparqlRule<T, UpdateOperationInsertData | UpdateOperationDeleteData | UpdateOperationDeleteWhere> {\n return {\n name,\n impl: ({ ACTION, SUBRULE1, CONSUME }) => (C) => {\n const insDelToken = CONSUME(cons1);\n\n let couldCreateBlankNodes = true;\n if (name !== 'insertData') {\n couldCreateBlankNodes = ACTION(() => C.parseMode.delete('canCreateBlankNodes'));\n }\n const data = SUBRULE1(dataRule);\n if (name !== 'insertData') {\n ACTION(() => couldCreateBlankNodes && C.parseMode.add('canCreateBlankNodes'));\n }\n\n return ACTION(() =>\n C.astFactory.updateOperationInsDelDataWhere(subType, data.val, C.astFactory.sourceLocation(insDelToken, data)));\n },\n gImpl: ({ SUBRULE, PRINT_WORD, PRINT_ON_EMPTY, PRINT_ON_OWN_LINE, NEW_LINE }) => (ast, C) => {\n const { astFactory: F, indentInc } = C;\n F.printFilter(ast, () => {\n if (subType === 'insertdata') {\n PRINT_ON_EMPTY('INSERT DATA ');\n } else if (subType === 'deletedata') {\n PRINT_ON_EMPTY('DELETE DATA ');\n } else {\n PRINT_ON_EMPTY('DELETE WHERE ');\n }\n C[traqulaIndentation] += indentInc;\n PRINT_WORD('{');\n NEW_LINE();\n });\n SUBRULE(quads, F.wrap(ast.data, ast.loc));\n F.printFilter(ast, () => {\n C[traqulaIndentation] -= indentInc;\n PRINT_ON_OWN_LINE('}');\n });\n },\n };\n}\n\n/**\n * [[38]](https://www.w3.org/TR/sparql11-query/#rInsertData)\n */\nexport const insertData = insertDeleteDelWhere('insertData', 'insertdata', l.insertDataClause, quadData);\n\n/**\n * [[39]](https://www.w3.org/TR/sparql11-query/#rDeleteData)\n */\nexport const deleteData = insertDeleteDelWhere('deleteData', 'deletedata', l.deleteDataClause, quadData);\n\n/**\n * [[40]](https://www.w3.org/TR/sparql11-query/#rDeleteWhere)\n */\nexport const deleteWhere = insertDeleteDelWhere('deleteWhere', 'deletewhere', l.deleteWhereClause, quadPattern);\n\n/**\n * [[41]](https://www.w3.org/TR/sparql11-query/#rModify)\n */\nexport const modify: SparqlRule<'modify', UpdateOperationModify> = <const> {\n name: 'modify',\n impl: ({ ACTION, CONSUME, SUBRULE1, SUBRULE2, OPTION1, OPTION2, OR }) => (C) => {\n const graph = OPTION1(() => {\n const withToken = CONSUME(l.modifyWith);\n const graph = SUBRULE1(iri);\n return { withToken, graph };\n });\n const { insert, del } = OR<{\n del: RuleDefReturn<typeof deleteClause> | undefined;\n insert: RuleDefReturn<typeof insertClause> | undefined;\n }>([\n { ALT: () => {\n const del = SUBRULE1(deleteClause);\n const insert = OPTION2(() => SUBRULE1(insertClause));\n return { del, insert };\n } },\n { ALT: () => {\n const insert = SUBRULE2(insertClause);\n return { insert, del: undefined };\n } },\n ]);\n const using = SUBRULE1(usingClauseStar);\n CONSUME(l.where);\n const where = SUBRULE1(groupGraphPattern);\n\n return ACTION(() => C.astFactory.updateOperationModify(\n C.astFactory.sourceLocation(graph?.withToken, del, insert, where),\n insert?.val ?? [],\n del?.val ?? [],\n where,\n using,\n graph?.graph,\n ));\n },\n gImpl: ({ SUBRULE, PRINT_WORDS, PRINT_ON_EMPTY, NEW_LINE }) => (ast, C) => {\n const { astFactory: F, indentInc } = C;\n if (ast.graph) {\n F.printFilter(ast, () => PRINT_WORDS('WITH'));\n SUBRULE(iri, ast.graph);\n }\n if (ast.delete.length > 0) {\n F.printFilter(ast, () => {\n C[traqulaIndentation] += indentInc;\n PRINT_WORDS('DELETE', '{');\n NEW_LINE();\n });\n SUBRULE(quads, F.wrap(ast.delete, ast.loc));\n F.printFilter(ast, () => {\n C[traqulaIndentation] -= indentInc;\n PRINT_ON_EMPTY('}');\n NEW_LINE();\n });\n }\n if (ast.insert.length > 0) {\n F.printFilter(ast, () => {\n C[traqulaIndentation] += indentInc;\n PRINT_WORDS('INSERT', '{');\n NEW_LINE();\n });\n SUBRULE(quads, F.wrap(ast.insert, ast.loc));\n F.printFilter(ast, () => {\n C[traqulaIndentation] -= indentInc;\n PRINT_ON_EMPTY('} ');\n NEW_LINE();\n });\n }\n SUBRULE(usingClauseStar, ast.from);\n F.printFilter(ast, () => PRINT_WORDS('WHERE'));\n SUBRULE(groupGraphPattern, ast.where);\n },\n};\n\n/**\n * [[42]](https://www.w3.org/TR/sparql11-query/#rDeleteClause)\n */\nexport const deleteClause: SparqlGrammarRule<'deleteClause', Wrap<Quads[]>> = <const> {\n name: 'deleteClause',\n impl: ({ ACTION, SUBRULE, CONSUME }) => (C) => {\n const delToken = CONSUME(l.deleteClause);\n const couldCreateBlankNodes = ACTION(() => C.parseMode.delete('canCreateBlankNodes'));\n const del = SUBRULE(quadPattern);\n ACTION(() => couldCreateBlankNodes && C.parseMode.add('canCreateBlankNodes'));\n\n return ACTION(() => C.astFactory.wrap(del.val, C.astFactory.sourceLocation(delToken, del)));\n },\n};\n\n/**\n * [[43]](https://www.w3.org/TR/sparql11-query/#rInsertClause)\n */\nexport const insertClause: SparqlGrammarRule<'insertClause', Wrap<Quads[]>> = <const> {\n name: 'insertClause',\n impl: ({ ACTION, SUBRULE, CONSUME }) => (C) => {\n const insertToken = CONSUME(l.insertClause);\n const insert = SUBRULE(quadPattern);\n\n return ACTION(() => C.astFactory.wrap(insert.val, C.astFactory.sourceLocation(insertToken, insert)));\n },\n};\n\n/**\n * [[45]](https://www.w3.org/TR/sparql11-query/#rGraphOrDefault)\n */\nexport const graphOrDefault: SparqlGrammarRule<'graphOrDefault', GraphRefDefault | GraphRefSpecific> = <const> {\n name: 'graphOrDefault',\n impl: ({ ACTION, SUBRULE1, CONSUME, OPTION, OR }) => C => OR<GraphRefDefault | GraphRefSpecific>([\n { ALT: () => {\n const def = CONSUME(l.graph.default_);\n return ACTION(() => C.astFactory.graphRefDefault(C.astFactory.sourceLocation(def)));\n } },\n { ALT: () => {\n const graph = OPTION(() => CONSUME(l.graph.graph));\n const name = SUBRULE1(iri);\n return ACTION(() =>\n C.astFactory.graphRefSpecific(name, C.astFactory.sourceLocation(graph, name)));\n } },\n ]),\n};\n\n/**\n * [[46]](https://www.w3.org/TR/sparql11-query/#rGraphRef)\n */\nexport const graphRef: SparqlRule<'graphRef', GraphRefSpecific> = <const> {\n name: 'graphRef',\n impl: ({ ACTION, SUBRULE, CONSUME }) => (C) => {\n const graph = CONSUME(l.graph.graph);\n const val = SUBRULE(iri);\n return ACTION(() => C.astFactory.graphRefSpecific(val, C.astFactory.sourceLocation(graph, val)));\n },\n gImpl: ({ SUBRULE, PRINT_WORD }) => (ast, { astFactory: F }) => {\n F.printFilter(ast, () => PRINT_WORD('GRAPH'));\n SUBRULE(iri, ast.graph);\n },\n};\n\n/**\n * [[47]](https://www.w3.org/TR/sparql11-query/#rGraphRefAll)\n */\nexport const graphRefAll: SparqlRule<'graphRefAll', GraphRef> = <const> {\n name: 'graphRefAll',\n impl: ({ ACTION, SUBRULE, CONSUME, OR }) => C => OR<GraphRef>([\n { ALT: () => SUBRULE(graphRef) },\n { ALT: () => {\n const def = CONSUME(l.graph.default_);\n return ACTION(() => C.astFactory.graphRefDefault(C.astFactory.sourceLocation(def)));\n } },\n { ALT: () => {\n const named = CONSUME(l.graph.named);\n return ACTION(() => C.astFactory.graphRefNamed(C.astFactory.sourceLocation(named)));\n } },\n { ALT: () => {\n const graphAll = CONSUME(l.graph.graphAll);\n return ACTION(() => C.astFactory.graphRefAll(C.astFactory.sourceLocation(graphAll)));\n } },\n ]),\n gImpl: ({ SUBRULE, PRINT_WORD }) => (ast, { astFactory: F }) => {\n if (F.isGraphRefSpecific(ast)) {\n SUBRULE(graphRef, ast);\n } else if (F.isGraphRefDefault(ast)) {\n F.printFilter(ast, () => PRINT_WORD('DEFAULT'));\n } else if (F.isGraphRefNamed(ast)) {\n F.printFilter(ast, () => PRINT_WORD('NAMED'));\n } else {\n F.printFilter(ast, () => PRINT_WORD('ALL'));\n }\n },\n};\n\n/**\n * [[50]](https://www.w3.org/TR/sparql11-query/#rQuads)\n */\nexport const quads: SparqlRule<'quads', Wrap<Quads[]>> = <const> {\n name: 'quads',\n impl: ({ ACTION, SUBRULE, CONSUME, MANY, SUBRULE1, SUBRULE2, OPTION1, OPTION2, OPTION3 }) => (C) => {\n const quads: Quads[] = [];\n let last: IToken | Localized | undefined;\n\n OPTION1(() => {\n const triples = SUBRULE1(triplesTemplate);\n last = triples;\n ACTION(() => quads.push(triples));\n });\n\n MANY(() => {\n const notTriples = SUBRULE(quadsNotTriples);\n last = notTriples;\n quads.push(notTriples);\n OPTION2(() => {\n const dotToken = CONSUME(l.symbols.dot);\n last = dotToken;\n return dotToken;\n });\n OPTION3(() => {\n const triples = SUBRULE2(triplesTemplate);\n last = triples;\n ACTION(() => quads.push(triples));\n });\n });\n\n return ACTION(() => C.astFactory.wrap(quads, C.astFactory.sourceLocation(quads.at(0), last)));\n },\n gImpl: ({ SUBRULE }) => (ast, { astFactory: F }) => {\n for (const quad of ast.val) {\n if (F.isPattern(quad)) {\n SUBRULE(triplesBlock, quad);\n } else {\n SUBRULE(quadsNotTriples, quad);\n }\n }\n },\n};\n\n/**\n * [[51]](https://www.w3.org/TR/sparql11-query/#rQuadsNotTriples)\n */\nexport const quadsNotTriples: SparqlRule<'quadsNotTriples', GraphQuads> = <const> {\n name: 'quadsNotTriples',\n impl: ({ ACTION, SUBRULE1, CONSUME, OPTION }) => (C) => {\n const graph = CONSUME(l.graph.graph);\n const name = SUBRULE1(varOrIri);\n CONSUME(l.symbols.LCurly);\n const triples = OPTION(() => SUBRULE1(triplesTemplate));\n const close = CONSUME(l.symbols.RCurly);\n\n return ACTION(() => C.astFactory.graphQuads(\n name,\n triples ?? C.astFactory.patternBgp([], C.astFactory.sourceLocation()),\n C.astFactory.sourceLocation(graph, close),\n ));\n },\n gImpl: ({ SUBRULE, PRINT_WORD, NEW_LINE, PRINT_ON_OWN_LINE }) => (ast, C) => {\n const { astFactory: F, indentInc } = C;\n F.printFilter(ast, () => PRINT_WORD('GRAPH'));\n SUBRULE(varOrTerm, ast.graph);\n F.printFilter(ast, () => {\n C[traqulaIndentation] += indentInc;\n PRINT_WORD('{');\n NEW_LINE();\n });\n SUBRULE(triplesBlock, ast.triples);\n F.printFilter(ast, () => {\n C[traqulaIndentation] -= indentInc;\n PRINT_ON_OWN_LINE('}');\n });\n },\n};\n", "import { ParserBuilder } from '@traqula/core';\nimport { gram } from '@traqula/rules-sparql-1-1';\n\nconst rulesNoBuiltIn = <const> [\n gram.expression,\n gram.conditionalOrExpression,\n gram.conditionalAndExpression,\n gram.valueLogical,\n gram.relationalExpression,\n gram.numericExpression,\n gram.expressionList,\n gram.additiveExpression,\n gram.multiplicativeExpression,\n gram.unaryExpression,\n gram.primaryExpression,\n gram.brackettedExpression,\n // BuiltInCall,\n gram.iriOrFunction,\n gram.rdfLiteral,\n gram.numericLiteral,\n gram.numericLiteralUnsigned,\n gram.numericLiteralPositive,\n gram.numericLiteralNegative,\n gram.booleanLiteral,\n gram.var_,\n gram.builtInStr,\n gram.builtInLang,\n gram.builtInLangmatches,\n gram.builtInDatatype,\n gram.builtInBound,\n gram.builtInIri,\n gram.builtInUri,\n gram.builtInBnodeSparqlJs,\n gram.builtInRand,\n gram.builtInAbs,\n gram.builtInCeil,\n gram.builtInFloor,\n gram.builtInRound,\n gram.builtInConcat,\n gram.builtInStrlen,\n gram.builtInUcase,\n gram.builtInLcase,\n gram.builtInEncode_for_uri,\n];\n\nconst builtInPatch: typeof gram.builtInCall = {\n name: 'builtInCall',\n impl: ({ OR, SUBRULE }) => () => OR(gram.builtInCallList(SUBRULE).slice(0, -2)),\n};\n\nexport const expressionParserBuilder = ParserBuilder.create(rulesNoBuiltIn)\n .addMany(\n gram.builtInContains,\n gram.builtInStrstarts,\n gram.builtInStrends,\n gram.builtInStrbefore,\n gram.builtInStrafter,\n gram.builtInYear,\n gram.builtInMonth,\n gram.builtInDay,\n gram.builtInHours,\n gram.builtInMinutes,\n gram.builtInSeconds,\n gram.builtInTimezone,\n gram.builtInTz,\n gram.builtInNow,\n gram.builtInUuid,\n gram.builtInStruuid,\n gram.builtInMd5,\n gram.builtInSha1,\n gram.builtInSha256,\n gram.builtInSha384,\n gram.builtInSha512,\n gram.builtInCoalesce,\n gram.builtInIf,\n gram.builtInStrlang,\n gram.builtInStrdt,\n gram.builtInSameterm,\n gram.builtInIsiri,\n gram.builtInIsuri,\n gram.builtInIsblank,\n gram.builtInIsliteral,\n gram.builtInIsnumeric,\n gram.regexExpression,\n gram.substringExpression,\n gram.strReplaceExpression,\n gram.aggregateCount,\n gram.aggregateSum,\n gram.aggregateMin,\n gram.aggregateMax,\n gram.aggregateAvg,\n gram.aggregateSample,\n gram.aggregateGroup_concat,\n gram.aggregate,\n gram.iri,\n gram.iriFull,\n gram.prefixedName,\n gram.argList,\n gram.string,\n )\n .addRule(builtInPatch);\n\nexport type ExpressionParser = ReturnType<typeof expressionParserBuilder.build>;\n", "import { ParserBuilder } from '@traqula/core';\nimport { gram } from '@traqula/rules-sparql-1-1';\n\nconst rules = <const> [\n gram.objectList,\n gram.object,\n gram.graphNode,\n gram.varOrTerm,\n gram.triplesNode,\n gram.collection,\n gram.blankNodePropertyList,\n gram.propertyListNotEmpty,\n // PropertyListNotEmpty\n gram.verb,\n gram.verbA,\n gram.varOrIri,\n gram.var_,\n gram.iri,\n gram.iriFull,\n gram.prefixedName,\n gram.graphTerm,\n gram.rdfLiteral,\n gram.numericLiteral,\n gram.booleanLiteral,\n gram.blankNode,\n gram.string,\n gram.numericLiteralUnsigned,\n gram.numericLiteralPositive,\n gram.numericLiteralNegative,\n];\n\nexport const objectListParserBuilder = ParserBuilder.create(rules);\n\nexport type ObjectListParser = ReturnType<typeof objectListParserBuilder.build>;\n", "import { ParserBuilder } from '@traqula/core';\nimport { gram } from '@traqula/rules-sparql-1-1';\nimport { objectListParserBuilder } from './objectListParser.js';\n\nexport const triplesBlockParserBuilder = ParserBuilder.create(<const> [\n gram.triplesBlock,\n gram.triplesSameSubjectPath,\n // VarOrTerm is included in the required ObjectList rule\n gram.propertyListPathNotEmpty,\n gram.triplesNodePath,\n gram.propertyListPath,\n // PropertyListNotEmpty\n gram.verbPath,\n gram.verbSimple,\n gram.objectListPath,\n])\n .merge(objectListParserBuilder, <const> [])\n // Verb path\n .addMany(\n gram.path,\n gram.pathAlternative,\n gram.pathSequence,\n gram.pathEltOrInverse,\n gram.pathElt,\n gram.pathPrimary,\n gram.pathMod,\n gram.pathNegatedPropertySet,\n gram.pathOneInPropertySet,\n // ObjectListPath\n gram.objectPath,\n gram.graphNodePath,\n gram.collectionPath,\n gram.blankNodePropertyListPath,\n );\n\nexport type triplesBlockParser = ReturnType<typeof triplesBlockParserBuilder.build>;\n", "import { ParserBuilder } from '@traqula/core';\nimport { gram } from '@traqula/rules-sparql-1-1';\nimport { expressionParserBuilder } from './expressionParser.js';\nimport { triplesBlockParserBuilder } from './triplesBlockParser.js';\n\nconst rules = <const> [\n gram.subSelect,\n gram.selectClause,\n gram.whereClause,\n gram.solutionModifier,\n gram.valuesClause,\n];\n\nexport const subSelectParserBuilder = ParserBuilder.create(rules)\n .merge(expressionParserBuilder, <const> [])\n .patchRule(gram.builtInCall)\n .addMany(\n gram.existsFunc,\n gram.notExistsFunc,\n gram.groupGraphPattern,\n gram.groupGraphPatternSub,\n )\n .merge(triplesBlockParserBuilder, <const> [])\n .addMany(\n gram.graphPatternNotTriples,\n gram.groupOrUnionGraphPattern,\n gram.optionalGraphPattern,\n gram.minusGraphPattern,\n gram.graphGraphPattern,\n gram.serviceGraphPattern,\n gram.filter,\n gram.bind,\n gram.inlineData,\n gram.constraint,\n gram.functionCall,\n gram.dataBlock,\n gram.inlineDataOneVar,\n gram.inlineDataFull,\n gram.dataBlockValue,\n // Solution modifier\n gram.groupClause,\n gram.havingClause,\n gram.orderClause,\n gram.limitOffsetClauses,\n gram.groupCondition,\n gram.havingCondition,\n gram.orderCondition,\n gram.limitClause,\n gram.offsetClause,\n );\n\nexport type SubSelectParser = ReturnType<typeof subSelectParserBuilder.build>;\n", "import { ParserBuilder } from '@traqula/core';\nimport { gram } from '@traqula/rules-sparql-1-1';\n\nconst rules = <const> [\n gram.triplesTemplate,\n gram.triplesSameSubject,\n gram.varOrTerm,\n gram.propertyListNotEmpty,\n gram.triplesNode,\n gram.propertyList,\n gram.var_,\n gram.graphTerm,\n gram.iri,\n gram.iriFull,\n gram.prefixedName,\n gram.rdfLiteral,\n gram.string,\n gram.numericLiteral,\n gram.numericLiteralUnsigned,\n gram.numericLiteralPositive,\n gram.numericLiteralNegative,\n gram.booleanLiteral,\n gram.blankNode,\n gram.verb,\n gram.verbA,\n gram.varOrIri,\n gram.objectList,\n gram.object,\n gram.collection,\n gram.blankNodePropertyList,\n gram.graphNode,\n];\n\nexport const triplesTemplateParserBuilder = ParserBuilder.create(rules);\n\nexport type TriplesTemplateParser = ReturnType<typeof triplesTemplateParserBuilder.build>;\n", "import { ParserBuilder } from '@traqula/core';\nimport { gram } from '@traqula/rules-sparql-1-1';\nimport { subSelectParserBuilder } from './subSelectParser.js';\nimport { triplesTemplateParserBuilder } from './triplesTemplateParserBuilder.js';\n\nconst rules = <const> [\n gram.queryUnit,\n gram.query,\n gram.prologue,\n gram.selectQuery,\n gram.constructQuery,\n gram.describeQuery,\n gram.askQuery,\n gram.valuesClause,\n gram.baseDecl,\n gram.prefixDecl,\n];\n\nexport const queryUnitParserBuilder = ParserBuilder.create(rules)\n // Select Query\n .merge(subSelectParserBuilder, <const> [])\n .addRule(gram.datasetClause)\n .addRule(gram.datasetClauseStar)\n .addRule(gram.defaultGraphClause)\n .addRule(gram.namedGraphClause)\n .addRule(gram.sourceSelector)\n // Construct Query\n .addRule(gram.constructTemplate)\n .merge(triplesTemplateParserBuilder, <const> [])\n .addRule(gram.constructTriples);\n\nexport type QueryUnitParser = ReturnType<typeof queryUnitParserBuilder.build>;\n", "import { ParserBuilder } from '@traqula/core';\nimport type { UpdateOperation } from '@traqula/rules-sparql-1-1';\nimport { gram } from '@traqula/rules-sparql-1-1';\nimport { triplesTemplateParserBuilder } from './triplesTemplateParserBuilder.js';\n\nconst update1Patch: typeof gram.update1 = {\n name: 'update1',\n impl: ({ SUBRULE, OR }) => () => OR<UpdateOperation>([\n { ALT: () => SUBRULE(gram.load) },\n { ALT: () => SUBRULE(gram.clear) },\n { ALT: () => SUBRULE(gram.drop) },\n { ALT: () => SUBRULE(gram.add) },\n { ALT: () => SUBRULE(gram.move) },\n { ALT: () => SUBRULE(gram.copy) },\n { ALT: () => SUBRULE(gram.create) },\n { ALT: () => SUBRULE(gram.insertData) },\n { ALT: () => SUBRULE(gram.deleteData) },\n { ALT: () => SUBRULE(gram.deleteWhere) },\n ]),\n gImpl: gram.update1.gImpl,\n};\n\nconst rulesNoUpdate1 = <const>[\n gram.updateUnit,\n gram.update,\n gram.prologue,\n // Update1,\n gram.baseDecl,\n gram.prefixDecl,\n gram.load,\n gram.clear,\n gram.drop,\n gram.add,\n gram.move,\n gram.copy,\n gram.create,\n gram.insertData,\n gram.deleteData,\n gram.deleteWhere,\n gram.iri,\n gram.prefixedName,\n gram.graphRef,\n gram.graphRefAll,\n gram.graphOrDefault,\n gram.quadData,\n gram.quads,\n];\n\n/**\n * Simple SPARQL 1.1 Update parser excluding MODIFY operations.\n * Top enable MODIFY, you need to path the update1 rule.\n */\nexport const updateNoModifyParserBuilder = ParserBuilder\n .create(rulesNoUpdate1)\n .addRule(update1Patch)\n .merge(triplesTemplateParserBuilder, <const> [])\n .addRule(gram.quadPattern)\n .addRule(gram.quadsNotTriples);\n\nexport type updateNoModifyParser = ReturnType<typeof updateNoModifyParserBuilder.build>;\n", "import { ParserBuilder } from '@traqula/core';\nimport { gram } from '@traqula/rules-sparql-1-1';\nimport { objectListParserBuilder } from './objectListParser.js';\nimport { subSelectParserBuilder } from './subSelectParser.js';\nimport { updateNoModifyParserBuilder } from './updateNoModifyParser.js';\n\nexport const updateParserBuilder = ParserBuilder.create(updateNoModifyParserBuilder)\n .patchRule(gram.update1)\n .addMany(\n gram.modify,\n gram.deleteClause,\n gram.insertClause,\n gram.usingClause,\n gram.defaultGraphClause,\n gram.namedGraphClause,\n gram.sourceSelector,\n gram.usingClauseStar,\n gram.groupGraphPattern,\n )\n // This substitutes all of propertyListNotEmpty\n .merge(objectListParserBuilder, <const> [])\n .merge(subSelectParserBuilder, <const> []);\n\nexport type UpdateUnitParser = ReturnType<typeof updateParserBuilder.build>;\n", "import type { ParserBuildArgs } from '@traqula/core';\nimport { ParserBuilder } from '@traqula/core';\nimport type * as T11 from '@traqula/rules-sparql-1-1';\nimport { gram, lex as l, MinimalSparqlParser, sparqlCodepointEscape } from '@traqula/rules-sparql-1-1';\nimport { queryUnitParserBuilder } from './queryUnitParser.js';\nimport { updateParserBuilder } from './updateUnitParser.js';\n\n/**\n * Pre-configured {@link ParserBuilder} for SPARQL 1.1 that combines query and update grammar rules.\n * Use {@link ParserBuilder.create ParserBuilder.create(sparql11ParserBuilder)} to extend it\n * with additional rules.\n */\nexport const sparql11ParserBuilder = ParserBuilder.create(queryUnitParserBuilder)\n .merge(updateParserBuilder, <const> [])\n .addRule(gram.queryOrUpdate);\n\nexport type SparqlParser = ReturnType<typeof sparql11ParserBuilder.build>;\n\n/**\n * Parser that can parse a SPARQL 1.1 string into a SPARQL 1.1 AST.\n */\nexport class Parser extends MinimalSparqlParser<T11.SparqlQuery> {\n public constructor(\n args: Pick<ParserBuildArgs, 'parserConfig' | 'lexerConfig'> & { defaultContext?: Partial<T11.SparqlContext> } = {},\n ) {\n const parser: SparqlParser = sparql11ParserBuilder.build({\n ...args,\n tokenVocabulary: l.sparql11LexerBuilder.tokenVocabulary,\n queryPreProcessor: sparqlCodepointEscape,\n });\n super(parser, args.defaultContext);\n }\n}\n", "import { getAggregatesOfExpression, getExpressionId, getVariablesFromExpression } from '@traqula/rules-sparql-1-1';\nimport type * as T11 from '@traqula/rules-sparql-1-1';\nimport { AstFactory } from './AstFactory.js';\nimport type {\n Path,\n Pattern,\n PatternBind,\n QuerySelect,\n SparqlQuery,\n Term,\n TermLiteral,\n TermVariable,\n TripleCollection,\n TripleNesting,\n Wildcard,\n} from './sparql12Types.js';\n\nconst F = new AstFactory();\n\nfunction isLangDir(dir: string): dir is 'ltr' | 'rtl' {\n return dir === 'ltr' || dir === 'rtl';\n}\n\nexport function langTagHasCorrectRange(literal: TermLiteral): void {\n if (F.isTermLiteralLangStr(literal)) {\n const dirSplit = literal.langOrIri.split('--');\n if (dirSplit.length > 1) {\n const [ _, direction ] = dirSplit;\n if (!isLangDir(direction)) {\n throw new Error(`language direction \"${direction}\" of literal \"${JSON.stringify(literal)}\" is not is required range 'ltr' | 'rtl'.`);\n }\n }\n }\n}\n\nexport function findPatternBoundedVars(\n iter: SparqlQuery | Pattern | TripleNesting | TripleCollection | Path | Term | Wildcard,\n boundedVars: Set<string>,\n): void {\n if (F.isQuery(iter) || F.isUpdate(iter)) {\n if (F.isQuerySelect(iter) || F.isQueryDescribe(iter)) {\n if (iter.where && iter.variables.some(x => F.isWildcard(x))) {\n findPatternBoundedVars(iter.where, boundedVars);\n } else {\n for (const v of iter.variables) {\n findPatternBoundedVars(v, boundedVars);\n }\n }\n if (iter.solutionModifiers.group) {\n const grouping = iter.solutionModifiers.group;\n for (const g of grouping.groupings) {\n if ('variable' in g) {\n findPatternBoundedVars(g.variable, boundedVars);\n }\n }\n }\n if (iter.values?.values && iter.values.values.length > 0) {\n const values = iter.values.values;\n for (const v of Object.keys(values[0])) {\n boundedVars.add(v);\n }\n }\n }\n } else if (F.isTerm(iter)) {\n if (F.isTermVariable(iter)) {\n boundedVars.add(iter.value);\n }\n if (F.isTermTriple(iter)) {\n findPatternBoundedVars(iter.subject, boundedVars);\n findPatternBoundedVars(iter.predicate, boundedVars);\n findPatternBoundedVars(iter.object, boundedVars);\n }\n } else if (F.isTriple(iter)) {\n findPatternBoundedVars(iter.subject, boundedVars);\n findPatternBoundedVars(iter.predicate, boundedVars);\n findPatternBoundedVars(iter.object, boundedVars);\n for (const annotation of iter.annotations ?? []) {\n findPatternBoundedVars(\n F.isTripleCollection(annotation) ? annotation : annotation.val,\n boundedVars,\n );\n }\n } else if (F.isPath(iter)) {\n for (const item of iter.items) {\n findPatternBoundedVars(item, boundedVars);\n }\n } else if (F.isTripleCollection(iter) || F.isPatternBgp(iter)) {\n for (const triple of iter.triples) {\n findPatternBoundedVars(triple, boundedVars);\n }\n } else if (\n F.isPatternGroup(iter) || F.isPatternUnion(iter) || F.isPatternOptional(iter) || F.isPatternService(iter)) {\n for (const pattern of iter.patterns) {\n findPatternBoundedVars(pattern, boundedVars);\n }\n if (F.isPatternService(iter)) {\n findPatternBoundedVars(iter.name, boundedVars);\n }\n } else if (F.isPatternBind(iter)) {\n findPatternBoundedVars(iter.variable, boundedVars);\n } else if (F.isPatternValues(iter)) {\n for (const variable of Object.keys(iter.values.at(0) ?? {})) {\n boundedVars.add(variable);\n }\n } else if (F.isPatternGraph(iter)) {\n findPatternBoundedVars(iter.name, boundedVars);\n for (const pattern of iter.patterns) {\n findPatternBoundedVars(pattern, boundedVars);\n }\n }\n}\n\n/**\n * Verify that the projected variables (select head) are allowed:\n * - no group-by on select *\n * - if group-by, selected variables need to be collected by the group-by\n * - 'select ?var as ?other', ?other cannot be in scope\n */\nexport function queryProjectionIsGood(query: Pick<QuerySelect, 'variables' | 'solutionModifiers' | 'where'>): void {\n // NoGroupByOnWildcardSelect\n if (query.variables.length === 1 && F.isWildcard(query.variables[0])) {\n if (query.solutionModifiers.group !== undefined) {\n throw new Error('GROUP BY not allowed with wildcard');\n }\n return;\n }\n\n // CannotProjectUngroupedVars - can be skipped if `SELECT *`\n // Check for projection of ungrouped variable\n // Check can be skipped in case of wildcard select.\n const variables = <Exclude<typeof query.variables, [Wildcard]>> query.variables;\n const hasCountAggregate = variables.flatMap(\n varVal => F.isTerm(varVal) ? [] : getAggregatesOfExpression(<T11.Expression> varVal.expression),\n ).some(agg => agg.aggregation === 'count' && !agg.expression.some(arg => F.isWildcard(arg)));\n const groupBy = query.solutionModifiers.group;\n if (hasCountAggregate || groupBy) {\n // We have to check whether\n // 1. Variables used in projection are usable given the group by clause\n // 2. A selectCount will create an implicit group by clause.\n // Variables bound by preceding (expr AS ?var) expressions are in scope for later expressions.\n const asBoundVars = new Set<string>();\n for (const selectVar of variables) {\n if (F.isTerm(selectVar)) {\n if (!groupBy || !groupBy.groupings.map(groupvar =>\n getExpressionId(<T11.Expression | T11.SolutionModifierGroupBind> groupvar))\n .includes((getExpressionId(selectVar)))) {\n throw new Error('Variable not allowed in projection');\n }\n } else if (getAggregatesOfExpression(<T11.Expression> selectVar.expression).length === 0) {\n // Current value binding does not use aggregates\n const usedvars = new Set<string>();\n getVariablesFromExpression(<T11.Expression> selectVar.expression, usedvars);\n for (const usedvar of usedvars) {\n // If the var is created within the select, it is fine.\n if (asBoundVars.has(usedvar)) {\n continue;\n }\n if (!groupBy || !groupBy.groupings.map(groupVar =>\n getExpressionId(<T11.Expression | T11.SolutionModifierGroupBind>groupVar)).includes(usedvar)) {\n throw new Error(`Use of ungrouped variable in projection of operation (?${usedvar})`);\n }\n }\n }\n if (!F.isTerm(selectVar)) {\n // Register a var is created by a bind\n asBoundVars.add(selectVar.variable.value);\n }\n }\n }\n\n // NOTE 12: Check if id of each AS-selected column is not yet bound by subquery\n const subqueries = query.where.patterns.filter(pattern => pattern.type === 'query');\n if (subqueries.length > 0) {\n const selectBoundedVars = new Set<string>();\n for (const variable of variables) {\n if ('variable' in variable) {\n selectBoundedVars.add(variable.variable.value);\n }\n }\n\n // Look at in scope variables\n const vars = subqueries.flatMap<TermVariable | PatternBind | Wildcard>(sub => sub.variables)\n .map(v => F.isTerm(v) ? v.value : (F.isWildcard(v) ? '*' : v.variable.value));\n const subqueryIds = new Set(vars);\n for (const selectedVarId of selectBoundedVars) {\n if (subqueryIds.has(selectedVarId)) {\n throw new Error(`Target id of 'AS' (?${selectedVarId}) already used in subquery`);\n }\n }\n }\n}\n", "import type { SourceLocation, SubTyped } from '@traqula/core';\nimport { AstFactory as Sparql11Factory } from '@traqula/rules-sparql-1-1';\nimport type * as T11 from '@traqula/rules-sparql-1-1';\nimport type {\n Annotation,\n ContextDefinitionVersion,\n TermBlank,\n TermIri,\n TermTriple,\n TermVariable,\n TripleCollectionBlankNodeProperties,\n TripleCollectionReifiedTriple,\n TripleNesting,\n} from './sparql12Types.js';\n\n/**\n * A factory that helps you create, and check types for AST nodes for SPARQL 1.2\n */\nexport class AstFactory extends Sparql11Factory {\n public termTriple(\n subject: TermTriple['subject'],\n predicate: TermTriple['predicate'],\n object: TermTriple['object'],\n loc: SourceLocation,\n ): TermTriple {\n return {\n type: 'term',\n subType: 'triple',\n subject,\n predicate,\n object,\n loc,\n };\n }\n\n public isTermTriple(obj: object): obj is SubTyped<'term', 'triple'> {\n return this.isOfSubType(obj, 'term', 'triple');\n }\n\n public tripleCollectionReifiedTriple(\n loc: SourceLocation,\n subject: TripleNesting['subject'],\n predicate: TripleNesting['predicate'],\n object: TripleNesting['object'],\n reifier?: TripleCollectionReifiedTriple['identifier'],\n ): TripleCollectionReifiedTriple {\n return {\n type: 'tripleCollection',\n subType: 'reifiedTriple',\n triples: [ this.triple(<T11.TripleNesting['subject']>subject, predicate, <T11.TripleNesting['object']>object) ],\n identifier: reifier ?? this.termBlank(undefined, this.sourceLocation()),\n loc,\n };\n }\n\n public isTripleCollectionReifiedTriple(obj: object): obj is SubTyped<'tripleCollection', 'reifiedTriple'> {\n return this.isOfSubType(obj, 'tripleCollection', 'reifiedTriple');\n }\n\n public override tripleCollectionBlankNodeProperties(\n identifier: TermBlank | TermVariable | TermIri,\n triples: TripleNesting[],\n loc: SourceLocation,\n ): T11.TripleCollectionBlankNodeProperties {\n return <T11.TripleCollectionBlankNodeProperties> {\n type: 'tripleCollection',\n subType: 'blankNodeProperties',\n triples,\n identifier,\n loc,\n } satisfies TripleCollectionBlankNodeProperties;\n }\n\n /**\n * Overwritten triple constructor to always contain an empty annotations list\n */\n public override triple: Sparql11Factory['triple'] =\n (subject, predicate, object, loc) => <T11.TripleNesting> {\n type: 'triple',\n subject,\n predicate,\n object,\n annotations: [],\n loc: loc ?? this.sourceLocation(subject, predicate, object),\n } satisfies TripleNesting;\n\n public annotatedTriple(\n subject: TripleNesting['subject'],\n predicate: TripleNesting['predicate'],\n object: TripleNesting['object'],\n annotations?: Annotation[],\n loc?: SourceLocation,\n ): TripleNesting {\n return {\n type: 'triple',\n subject,\n predicate,\n object,\n annotations: annotations ?? [],\n loc: loc ?? this.sourceLocation(subject, predicate, object, ...annotations ?? []),\n };\n }\n\n public contextDefinitionVersion(version: string, loc: SourceLocation): ContextDefinitionVersion {\n return {\n type: 'contextDef',\n subType: 'version',\n version,\n loc,\n };\n }\n\n public isContextDefinitionVersion(obj: object): obj is SubTyped<'contextDef', 'version'> {\n return this.isOfSubType(obj, 'contextDef', 'version');\n }\n}\n", "/**\n * This module will define patch rules that should be used in combination with the sparql11 grammar to create\n * a sparql12 grammar.\n * Rules in this module redefine the return type of core grammar rules.\n * It is therefore essential that the parser retypes the rules from the core grammar.\n */\nimport type { RuleDefReturn, Wrap } from '@traqula/core';\nimport { traqulaIndentation } from '@traqula/core';\nimport { CommonIRIs, funcExpr1, funcExpr3, gram as S11, lex as l11 } from '@traqula/rules-sparql-1-1';\nimport type * as T11 from '@traqula/rules-sparql-1-1';\nimport * as l12 from './lexer.js';\nimport { decodeUchar } from './parserUtils.js';\nimport type { SparqlGeneratorRule, SparqlGrammarRule, SparqlRule } from './sparql12HelperTypes.js';\nimport type {\n Annotation,\n ContextDefinition,\n ContextDefinitionVersion,\n Expression,\n GraphNode,\n GraphTerm,\n PatternBgp,\n QuerySelect,\n Term,\n TermBlank,\n TermIri,\n TermLiteral,\n TermTriple,\n TermVariable,\n TripleCollectionBlankNodeProperties,\n TripleCollectionReifiedTriple,\n TripleNesting,\n} from './sparql12Types.js';\nimport { langTagHasCorrectRange, queryProjectionIsGood } from './validators.js';\n\n/**\n *[[7]](https://www.w3.org/TR/sparql12-query/#rVersionDecl)\n */\nexport const versionDecl: SparqlRule<'versionDecl', ContextDefinitionVersion> = {\n name: 'versionDecl',\n impl: ({ ACTION, SUBRULE, CONSUME }) => (C) => {\n const versionToken = CONSUME(l12.version);\n const identifier = SUBRULE(versionSpecifier);\n return ACTION(() =>\n C.astFactory.contextDefinitionVersion(identifier.val, C.astFactory.sourceLocation(versionToken, identifier)));\n },\n gImpl: ({ PRINT_ON_OWN_LINE }) => (ast, { astFactory: F }) => {\n F.printFilter(ast, () => {\n PRINT_ON_OWN_LINE('VERSION ', `${S11.stringEscapedLexical(ast.version)}`);\n });\n },\n};\n\n/**\n * [[9]](https://www.w3.org/TR/sparql12-query/#rSelectQuery)\n * (Validator has changed: https://github.com/w3c/sparql-query/pull/380)\n */\nexport const selectQuery: SparqlGrammarRule<'selectQuery', Omit<QuerySelect, 'type' | 'context' | 'values'>> = <const> {\n name: 'selectQuery',\n impl: ({ ACTION, SUBRULE }) => (C) => {\n const selectVal = SUBRULE(S11.selectClause);\n const from = SUBRULE(S11.datasetClauseStar);\n const where = SUBRULE(S11.whereClause);\n const modifiers = SUBRULE(S11.solutionModifier);\n\n return ACTION(() => {\n const ret = {\n subType: 'select',\n where: where.val,\n solutionModifiers: modifiers,\n datasets: from,\n ...selectVal.val,\n loc: C.astFactory.sourceLocation(\n selectVal,\n where,\n modifiers.group,\n modifiers.having,\n modifiers.order,\n modifiers.limitOffset,\n ),\n } satisfies RuleDefReturn<typeof selectQuery>;\n if (!C.skipValidation) {\n queryProjectionIsGood(ret);\n }\n return ret;\n });\n },\n};\n\n/**\n * [[8]](https://www.w3.org/TR/sparql12-query/#rVersionSpecifier)\n */\nexport const versionSpecifier: SparqlGrammarRule<'versionSpecifier', Wrap<string>> = {\n name: 'versionSpecifier',\n impl: ({ ACTION, CONSUME, OR }) => (C) => {\n const token = OR([\n { ALT: () => CONSUME(l12.stringLiteral1) },\n { ALT: () => CONSUME(l12.stringLiteral2) },\n ]);\n return ACTION(() => C.astFactory.wrap(token.image.slice(1, -1), C.astFactory.sourceLocation(token)));\n },\n};\n\n/**\n * OVERRIDING RULE {@link S11.prologue}\n * [[4]](https://www.w3.org/TR/sparql12-query/#rPrologue)\n */\nexport const prologue: SparqlRule<'prologue', ContextDefinition[]> = {\n name: 'prologue',\n impl: ({ SUBRULE, MANY, OR }) => () => {\n const result: ContextDefinition[] = [];\n MANY(() => OR([\n { ALT: () => result.push(SUBRULE(S11.baseDecl)) },\n // TODO: the [spec](https://www.w3.org/TR/sparql11-query/#iriRefs) says you cannot redefine prefixes.\n // We might need to check this.\n { ALT: () => result.push(SUBRULE(S11.prefixDecl)) },\n { ALT: () => result.push(SUBRULE(versionDecl)) },\n ]));\n return result;\n },\n gImpl: ({ SUBRULE }) => (ast, { astFactory: F }) => {\n for (const context of ast) {\n if (F.isContextDefinitionBase(context)) {\n SUBRULE(S11.baseDecl, context);\n } else if (F.isContextDefinitionPrefix(context)) {\n SUBRULE(S11.prefixDecl, context);\n } else {\n SUBRULE(versionDecl, context);\n }\n }\n },\n};\n\nfunction reifiedTripleBlockImpl<T extends string>(name: T, allowPath: boolean):\nSparqlGrammarRule<T, T11.BasicGraphPattern> {\n return <const> {\n name,\n impl: ({ ACTION, SUBRULE }) => (C) => {\n const triple = SUBRULE(reifiedTriple);\n const properties = SUBRULE(\n allowPath ? S11.propertyListPath : S11.propertyList,\n ACTION(() => C.astFactory.dematerialized(triple.identifier)),\n );\n\n return ACTION(() => <T11.BasicGraphPattern> [ triple, ...properties ]);\n },\n };\n}\n/**\n * [[58]](https://www.w3.org/TR/sparql12-query/#rReifiedTripleBlock) Used by triplesSameSubject\n */\nexport const reifiedTripleBlock = reifiedTripleBlockImpl('reifiedTripleBlock', false);\n/**\n * [[59]](https://www.w3.org/TR/sparql12-query/#rReifiedTripleBlockPath) Used by TriplesSameSubjectPath\n */\nexport const reifiedTripleBlockPath = reifiedTripleBlockImpl('reifiedTripleBlockPath', true);\n\n/**\n * OVERRIDING RULE: {@link S11.dataBlockValue}.\n * [[69]](https://www.w3.org/TR/sparql12-query/#rDataBlockValue)\n */\nexport const dataBlockValue:\nSparqlGrammarRule<'dataBlockValue', RuleDefReturn<typeof S11.dataBlockValue> | TermTriple> = <const> {\n name: 'dataBlockValue',\n impl: $ => C => $.OR2<RuleDefReturn<typeof dataBlockValue>>([\n { ALT: () => S11.dataBlockValue.impl($)(C) },\n { ALT: () => $.SUBRULE(tripleTermData) },\n ]),\n};\n\n/**\n * [[70]](https://www.w3.org/TR/sparql12-query/#rReifier)\n */\nexport const reifier: SparqlGrammarRule<'reifier', Wrap<RuleDefReturn<typeof varOrReifierId>>> = <const> {\n name: 'reifier',\n impl: ({ ACTION, CONSUME, SUBRULE, OPTION }) => (C) => {\n const tildeToken = CONSUME(l12.tilde);\n const reifier = OPTION(() => SUBRULE(varOrReifierId));\n return ACTION(() => {\n if (reifier === undefined && !C.parseMode.has('canCreateBlankNodes')) {\n throw new Error('Cannot create blanknodes in current parse mode');\n }\n return C.astFactory.wrap(\n reifier ?? C.astFactory.termBlank(undefined, C.astFactory.sourceLocation()),\n C.astFactory.sourceLocation(tildeToken, reifier),\n );\n });\n },\n};\n\n/**\n * [[71]](https://www.w3.org/TR/sparql12-query/#rVarOrReifierId)\n */\nexport const varOrReifierId: SparqlGrammarRule<'varOrReifierId', TermVariable | TermIri | TermBlank> =\n <const> {\n name: 'varOrReifierId',\n impl: ({ SUBRULE, OR }) => C => OR<RuleDefReturn<typeof varOrReifierId>>([\n { GATE: () => C.parseMode.has('canParseVars'), ALT: () => SUBRULE(S11.var_) },\n { ALT: () => SUBRULE(S11.iri) },\n { ALT: () => SUBRULE(S11.blankNode) },\n ]),\n };\n\nfunction triplesSameSubjectImpl<T extends string>(name: T, allowPaths: boolean):\nSparqlGrammarRule<T, T11.BasicGraphPattern> {\n return <const> {\n name,\n impl: $ => C => $.OR2([\n { ALT: () => allowPaths ?\n S11.triplesSameSubjectPath.impl($)(C) :\n S11.triplesSameSubject.impl($)(C) },\n { ALT: () => $.SUBRULE(allowPaths ? reifiedTripleBlockPath : reifiedTripleBlock) },\n ]),\n };\n}\n/**\n * OVERRIDING RULE {@link S11.triplesSameSubject}\n * [[81]](https://www.w3.org/TR/sparql12-query/#rTriplesSameSubject)\n */\nexport const triplesSameSubject = triplesSameSubjectImpl('triplesSameSubject', false);\n/**\n * OVERRIDING RULE {@link S11.triplesSameSubjectPath}\n * [[87]](https://www.w3.org/TR/sparql12-query/#rTriplesSameSubjectPath)\n */\nexport const triplesSameSubjectPath = triplesSameSubjectImpl('triplesSameSubjectPath', true);\n\nfunction objectImpl<T extends string>(name: T, allowPaths: boolean):\nSparqlGrammarRule<T, TripleNesting, [TripleNesting['subject'], TripleNesting['predicate']]> {\n return <const>{\n name,\n impl: ({ ACTION, SUBRULE }) => (C, subject, predicate) => {\n const objectVal = SUBRULE(allowPaths ? graphNodePath : graphNode);\n const annotationVal = SUBRULE(allowPaths ? annotationPath : annotation);\n\n return ACTION(() => {\n const F = C.astFactory;\n if (F.isPathPure(predicate) && annotationVal.length > 0) {\n throw new Error('Note 17 violation');\n }\n return F.annotatedTriple(\n subject,\n predicate,\n objectVal,\n annotationVal,\n );\n });\n },\n };\n}\n/**\n * OVERRIDING RULE: {@link S11.object}.\n * [[86]](https://www.w3.org/TR/sparql12-query/#rObject) Used by ObjectList\n */\nexport const object = objectImpl('object', false);\n/**\n * OVERRIDING RULE: {@link S11.objectPath}.\n * [[87]](https://www.w3.org/TR/sparql12-query/#rTriplesSameSubjectPath) Used by ObjectListPath\n */\nexport const objectPath = objectImpl('objectPath', true);\n\nfunction annotationImpl<T extends string>(name: T, allowPaths: boolean): SparqlRule<T, Annotation[]> {\n return <const> {\n name,\n impl: ({ ACTION, SUBRULE, OR, MANY }) => (C) => {\n const annotations: Annotation[] = [];\n let currentReifier: TermBlank | TermVariable | TermIri | undefined;\n\n MANY(() => {\n OR([\n { ALT: () => {\n const node = SUBRULE(reifier);\n annotations.push(node);\n currentReifier = node.val;\n } },\n { ALT: () => {\n ACTION(() => {\n if (!currentReifier && !C.parseMode.has('canCreateBlankNodes')) {\n throw new Error('Cannot create blanknodes in current parse mode');\n }\n currentReifier = currentReifier ?? C.astFactory.termBlank(undefined, C.astFactory.sourceLocation());\n });\n const block = SUBRULE(\n allowPaths ? annotationBlockPath : annotationBlock,\n currentReifier!,\n );\n ACTION(() => {\n annotations.push(block);\n currentReifier = undefined;\n });\n } },\n ]);\n });\n return annotations;\n },\n gImpl: ({ SUBRULE, PRINT_WORD }) => (ast, { astFactory: F }) => {\n for (const annotation of ast) {\n if (F.isTripleCollectionBlankNodeProperties(annotation)) {\n SUBRULE(annotationBlockPath, annotation);\n } else {\n F.printFilter(annotation, () => PRINT_WORD('~'));\n SUBRULE(graphNodePath, annotation.val);\n }\n }\n },\n };\n}\n/**\n * [[109]](https://www.w3.org/TR/sparql12-query/#rAnnotationPath)\n */\nexport const annotationPath = annotationImpl('annotationPath', true);\n/**\n * [[111]](https://www.w3.org/TR/sparql12-query/#rAnnotation)\n */\nexport const annotation = annotationImpl('annotation', false);\n\nfunction annotationBlockImpl<T extends string>(name: T, allowPaths: boolean):\n SparqlGrammarRule<T, TripleCollectionBlankNodeProperties, [TripleCollectionBlankNodeProperties['identifier']]> &\n SparqlGeneratorRule<T, TripleCollectionBlankNodeProperties> {\n return <const> {\n name,\n impl: ({ ACTION, SUBRULE, CONSUME }) => (C, arg) => {\n const open = CONSUME(l12.annotationOpen);\n const res = SUBRULE(\n allowPaths ? S11.propertyListPathNotEmpty : S11.propertyListNotEmpty,\n arg,\n );\n const close = CONSUME(l12.annotationClose);\n\n return ACTION(() => C.astFactory.tripleCollectionBlankNodeProperties(\n arg,\n res,\n C.astFactory.sourceLocation(open, close),\n ));\n },\n gImpl: ({ SUBRULE, PRINT_WORD, HANDLE_LOC, NEW_LINE, PRINT_ON_OWN_LINE }) => (ast, C) => {\n const { astFactory: F, indentInc } = C;\n F.printFilter(ast, () => {\n PRINT_WORD('{|');\n if (ast.triples.length > 1) {\n C[traqulaIndentation] += indentInc;\n NEW_LINE();\n }\n });\n\n function printTriple(triple: TripleNesting): void {\n HANDLE_LOC(triple, () => {\n if (F.isTerm(triple.predicate)) {\n SUBRULE(graphNodePath, triple.predicate);\n } else {\n SUBRULE(S11.pathGenerator, triple.predicate, undefined);\n }\n F.printFilter(triple, () => PRINT_WORD(''));\n SUBRULE(graphNodePath, triple.object);\n });\n }\n\n const [ head, ...tail ] = ast.triples;\n printTriple(head);\n for (const triple of tail) {\n F.printFilter(ast, () => {\n PRINT_WORD(';');\n NEW_LINE();\n });\n printTriple(triple);\n }\n\n F.printFilter(ast, () => {\n if (ast.triples.length > 1) {\n PRINT_ON_OWN_LINE('|}');\n } else {\n PRINT_WORD('|}');\n }\n });\n },\n };\n}\n/**\n * [[110]](https://www.w3.org/TR/sparql12-query/#rAnnotationBlockPath)\n */\nexport const annotationBlockPath = annotationBlockImpl('annotationBlockPath', true);\n/**\n * [[112]](https://www.w3.org/TR/sparql12-query/#rAnnotationBlock)\n */\nexport const annotationBlock = annotationBlockImpl('annotationBlock', false);\n\n/**\n * OVERRIDING RULE: {@link S11.graphNode}.\n * [[113]](https://www.w3.org/TR/sparql12-query/#rGraphNode)\n */\nexport const graphNode: SparqlGrammarRule<'graphNode', GraphNode> = <const> {\n name: 'graphNode',\n impl: $ => C => $.OR2<RuleDefReturn<typeof graphNode>>([\n { ALT: () => S11.graphNode.impl($)(C) },\n { ALT: () => $.SUBRULE(reifiedTriple) },\n ]),\n};\n/**\n * OVERRIDING RULE: {@link S11.graphNodePath}.\n * [[114]](https://www.w3.org/TR/sparql12-query/#rGraphNodePath)\n */\nexport const graphNodePath: SparqlRule<'graphNodePath', GraphNode> = <const> {\n name: 'graphNodePath',\n impl: $ => C => $.OR2<RuleDefReturn<typeof graphNodePath>>([\n { ALT: () => S11.graphNodePath.impl($)(C) },\n { ALT: () => $.SUBRULE(reifiedTriple) },\n ]),\n gImpl: $ => (ast, C) => {\n if (C.astFactory.isTripleCollectionReifiedTriple(ast)) {\n $.SUBRULE(reifiedTriple, ast);\n } else {\n S11.graphNodePath.gImpl($)(<T11.Term | T11.TripleCollection> ast, C);\n }\n },\n};\n\n/**\n * OVERRIDING RULE: {@link S11.varOrTerm}.\n * [[115]](https://www.w3.org/TR/sparql12-query/#rVarOrTerm)\n */\nexport const varOrTerm: SparqlGrammarRule<'varOrTerm', Term> = <const> {\n name: 'varOrTerm',\n impl: ({ ACTION, SUBRULE, OR, CONSUME }) => C => OR<Term>([\n { GATE: () => C.parseMode.has('canParseVars'), ALT: () => SUBRULE(S11.var_) },\n { ALT: () => SUBRULE(S11.iri) },\n { ALT: () => SUBRULE(rdfLiteral) },\n { ALT: () => SUBRULE(S11.numericLiteral) },\n { ALT: () => SUBRULE(S11.booleanLiteral) },\n { ALT: () => SUBRULE(S11.blankNode) },\n { ALT: () => {\n const token = CONSUME(l11.terminals.nil);\n return ACTION(() => C.astFactory.termNamed(C.astFactory.sourceLocation(token), CommonIRIs.NIL));\n } },\n { ALT: () => SUBRULE(tripleTerm) },\n ]),\n // Generation remains untouched - go through graphTerm\n};\n\n/**\n * [[116]](https://www.w3.org/TR/sparql12-query/#rReifiedTriple)\n */\nexport const reifiedTriple: SparqlRule<'reifiedTriple', TripleCollectionReifiedTriple> = <const> {\n name: 'reifiedTriple',\n impl: ({ ACTION, CONSUME, SUBRULE, OPTION }) => (C) => {\n const open = CONSUME(l12.reificationOpen);\n const subject = SUBRULE(reifiedTripleSubject);\n const predicate = SUBRULE(S11.verb);\n const object = SUBRULE(reifiedTripleObject);\n const reifierVal = OPTION(() => SUBRULE(reifier));\n const close = CONSUME(l12.reificationClose);\n\n return ACTION(() => {\n // A reifier would be auto generated in this case, but we are not allowed to use them.\n if (reifierVal === undefined && !C.parseMode.has('canCreateBlankNodes')) {\n throw new Error('Cannot create blanknodes in current parse mode');\n }\n return C.astFactory.tripleCollectionReifiedTriple(\n C.astFactory.sourceLocation(open, close),\n subject,\n predicate,\n object,\n reifierVal?.val,\n );\n });\n },\n gImpl: ({ SUBRULE, PRINT_WORD }) => (ast, { astFactory: F }) => {\n F.printFilter(ast, () => PRINT_WORD('<<'));\n const triple = ast.triples[0];\n SUBRULE(graphNodePath, triple.subject);\n\n F.printFilter(ast, () => PRINT_WORD(''));\n if (F.isPathPure(triple.predicate)) {\n SUBRULE(S11.pathGenerator, triple.predicate, undefined);\n } else {\n SUBRULE(graphNodePath, triple.predicate);\n }\n\n F.printFilter(ast, () => PRINT_WORD(''));\n SUBRULE(graphNodePath, triple.object);\n\n SUBRULE(annotationPath, [ F.wrap(ast.identifier, ast.identifier.loc) ]);\n F.printFilter(ast, () => PRINT_WORD('>>'));\n },\n};\n\n/**\n * [[117]](https://www.w3.org/TR/sparql12-query/#rReifiedTripleSubject)\n */\nexport const reifiedTripleSubject:\nSparqlGrammarRule<'reifiedTripleSubject', Term | TripleCollectionReifiedTriple> = <const> {\n name: 'reifiedTripleSubject',\n impl: ({ OR, SUBRULE }) => C => OR<RuleDefReturn<typeof reifiedTripleSubject>>([\n { GATE: () => C.parseMode.has('canParseVars'), ALT: () => SUBRULE(S11.var_) },\n { ALT: () => SUBRULE(S11.iri) },\n { ALT: () => SUBRULE(rdfLiteral) },\n { ALT: () => SUBRULE(S11.numericLiteral) },\n { ALT: () => SUBRULE(S11.booleanLiteral) },\n { ALT: () => SUBRULE(S11.blankNode) },\n { ALT: () => SUBRULE(reifiedTriple) },\n { ALT: () => SUBRULE(tripleTerm) },\n ]),\n};\n\n/**\n * [[118]](https://www.w3.org/TR/sparql12-query/#rReifiedTripleObject)\n */\nexport const reifiedTripleObject:\nSparqlGrammarRule<'reifiedTripleObject', RuleDefReturn<typeof reifiedTripleSubject>> =\n <const> {\n name: 'reifiedTripleObject',\n impl: reifiedTripleSubject.impl,\n };\n\n/**\n * [[119]](https://www.w3.org/TR/sparql12-query/#rTripleTerm)\n */\nexport const tripleTerm: SparqlRule<'tripleTerm', TermTriple> = <const> {\n name: 'tripleTerm',\n impl: ({ ACTION, CONSUME, SUBRULE }) => (C) => {\n const open = CONSUME(l12.tripleTermOpen);\n const subject = SUBRULE(tripleTermSubject);\n const predicate = SUBRULE(S11.verb);\n const object = SUBRULE(tripleTermObject);\n const close = CONSUME(l12.tripleTermClose);\n return ACTION(() => C.astFactory.termTriple(subject, predicate, object, C.astFactory.sourceLocation(open, close)));\n },\n gImpl: ({ SUBRULE, PRINT_WORD }) => (ast, { astFactory: F }) => {\n F.printFilter(ast, () => PRINT_WORD('<<('));\n SUBRULE(graphNodePath, ast.subject);\n F.printFilter(ast, () => PRINT_WORD(''));\n SUBRULE(graphNodePath, ast.predicate);\n F.printFilter(ast, () => PRINT_WORD(''));\n SUBRULE(graphNodePath, ast.object);\n F.printFilter(ast, () => PRINT_WORD(')>>'));\n },\n};\n\n/**\n * [[120]](https://www.w3.org/TR/sparql12-query/#rTripleTermSubject)\n */\nexport const tripleTermSubject:\nSparqlGrammarRule<'tripleTermSubject', TermVariable | TermIri | TermLiteral | TermBlank | TermTriple> = <const> {\n name: 'tripleTermSubject',\n impl: ({ SUBRULE, OR }) => C => OR<RuleDefReturn<typeof tripleTermSubject>>([\n { GATE: () => C.parseMode.has('canParseVars'), ALT: () => SUBRULE(S11.var_) },\n { ALT: () => SUBRULE(S11.iri) },\n { ALT: () => SUBRULE(rdfLiteral) },\n { ALT: () => SUBRULE(S11.numericLiteral) },\n { ALT: () => SUBRULE(S11.booleanLiteral) },\n { ALT: () => SUBRULE(S11.blankNode) },\n { ALT: () => SUBRULE(tripleTerm) },\n ]),\n};\n\n/**\n * [[121]](https://www.w3.org/TR/sparql12-query/#rTripleTermObject)\n */\nexport const tripleTermObject:\nSparqlGrammarRule<'tripleTermObject', RuleDefReturn<typeof tripleTermSubject>> = <const> {\n name: 'tripleTermObject',\n impl: tripleTermSubject.impl,\n};\n\n/**\n * [[122]](https://www.w3.org/TR/sparql12-query/#rTripleTermData)\n */\nexport const tripleTermData: SparqlGrammarRule<'tripleTermData', TermTriple> = <const> {\n name: 'tripleTermData',\n impl: ({ ACTION, CONSUME, OR, SUBRULE }) => (C) => {\n const open = CONSUME(l12.tripleTermOpen);\n const subject = SUBRULE(tripleTermDataSubject);\n const predicate = OR([\n { ALT: () => SUBRULE(S11.iri) },\n { ALT: () => {\n const token = CONSUME(l11.a);\n return ACTION(() => C.astFactory.termNamed(C.astFactory.sourceLocation(token), CommonIRIs.TYPE));\n } },\n ]);\n const object = SUBRULE(tripleTermDataObject);\n const close = CONSUME(l12.tripleTermClose);\n\n return ACTION(() => C.astFactory.termTriple(subject, predicate, object, C.astFactory.sourceLocation(open, close)));\n },\n};\n\n/**\n * [[123]](https://www.w3.org/TR/sparql12-query/#rTripleTermDataSubject)\n */\nexport const tripleTermDataSubject: SparqlGrammarRule<'tripleTermDataSubject', TermIri | TermLiteral | TermTriple> =\n <const> {\n name: 'tripleTermDataSubject',\n impl: ({ OR, SUBRULE }) => () => OR<RuleDefReturn<typeof tripleTermDataSubject>>([\n { ALT: () => SUBRULE(S11.iri) },\n ]),\n };\n\n/**\n * [[124]](https://www.w3.org/TR/sparql12-query/#rTripleTermDataObject)\n */\nexport const tripleTermDataObject:\nSparqlGrammarRule<'tripleTermDataObject', RuleDefReturn<typeof tripleTermDataSubject>> = <const> {\n name: 'tripleTermDataObject',\n impl: ({ OR, SUBRULE }) => () => OR<RuleDefReturn<typeof tripleTermDataSubject>>([\n { ALT: () => SUBRULE(S11.iri) },\n { ALT: () => SUBRULE(rdfLiteral) },\n { ALT: () => SUBRULE(S11.numericLiteral) },\n { ALT: () => SUBRULE(S11.booleanLiteral) },\n { ALT: () => SUBRULE(tripleTermData) },\n ]),\n};\n\n/**\n * OVERRIDING RULE: {@link S11.primaryExpression}.\n * [[136]](https://www.w3.org/TR/sparql12-query/#rPrimaryExpression)\n */\nexport const primaryExpression: SparqlGrammarRule<'primaryExpression', Expression> = <const> {\n name: 'primaryExpression',\n impl: $ => C => $.OR2<Expression>([\n { ALT: () => S11.primaryExpression.impl($)(C) },\n { ALT: () => $.SUBRULE(exprTripleTerm) },\n ]),\n};\n\n/**\n * [[137]](https://www.w3.org/TR/sparql12-query/#rExprTripleTerm)\n */\nexport const exprTripleTerm: SparqlGrammarRule<'exprTripleTerm', TermTriple> = <const> {\n name: 'exprTripleTerm',\n impl: ({ ACTION, CONSUME, SUBRULE }) => (C) => {\n const open = CONSUME(l12.tripleTermOpen);\n const subject = SUBRULE(exprTripleTermSubject);\n const predicate = SUBRULE(S11.verb);\n const object = SUBRULE(exprTripleTermObject);\n const close = CONSUME(l12.tripleTermClose);\n\n return ACTION(() => C.astFactory.termTriple(\n subject,\n predicate,\n object,\n C.astFactory.sourceLocation(open, close),\n ));\n },\n};\n\n/**\n * [[138]](https://www.w3.org/TR/sparql12-query/#rExprTripleTermSubject)\n */\nexport const exprTripleTermSubject:\nSparqlGrammarRule<'exprTripleTermSubject', TermIri | TermVariable | TermLiteral | TermTriple> = <const> {\n name: 'exprTripleTermSubject',\n impl: ({ OR, SUBRULE }) => C =>\n OR<RuleDefReturn<typeof exprTripleTermSubject>>([\n { ALT: () => SUBRULE(S11.iri) },\n { GATE: () => C.parseMode.has('canParseVars'), ALT: () => SUBRULE(S11.var_) },\n ]),\n};\n\n/**\n * [[139]](https://www.w3.org/TR/sparql12-query/#rExprTripleTermObject)\n */\nexport const exprTripleTermObject:\nSparqlGrammarRule<'exprTripleTermObject', RuleDefReturn<typeof exprTripleTermSubject> | TermTriple> = <const> {\n name: 'exprTripleTermObject',\n impl: ({ OR, SUBRULE }) => C =>\n OR<RuleDefReturn<typeof exprTripleTermSubject>>([\n { ALT: () => SUBRULE(S11.iri) },\n { ALT: () => SUBRULE(rdfLiteral) },\n { ALT: () => SUBRULE(S11.numericLiteral) },\n { ALT: () => SUBRULE(S11.booleanLiteral) },\n { GATE: () => C.parseMode.has('canParseVars'), ALT: () => SUBRULE(S11.var_) },\n { ALT: () => SUBRULE(exprTripleTerm) },\n ]),\n};\n\n// TODO next major: fix builtIn\nexport const buildInLangDir = funcExpr1(l12.buildInLangDir);\nexport const buildInLangStrDir = funcExpr3(l12.buildInStrLangDir);\nexport const buildInHasLang = funcExpr1(l12.buildInHasLang);\nexport const buildInHasLangDir = funcExpr1(l12.buildInHasLangDir);\nexport const buildInIsTriple = funcExpr1(l12.buildInIsTRIPLE);\nexport const buildInTriple = funcExpr3(l12.buildInTRIPLE);\nexport const buildInSubject = funcExpr1(l12.buildInSUBJECT);\nexport const buildInPredicate = funcExpr1(l12.buildInPREDICATE);\nexport const buildInObject = funcExpr1(l12.buildInOBJECT);\n\n/**\n * OVERRIDING RULE: {@link S11.builtInCall}.\n * [[141]](https://www.w3.org/TR/sparql12-query/#rBuiltInCall)\n */\nexport const builtInCall: typeof S11.builtInCall = <const> {\n name: 'builtInCall',\n impl: $ => C => $.OR2<T11.Expression>([\n { ALT: () => S11.builtInCall.impl($)(C) },\n { ALT: () => $.SUBRULE(buildInLangDir) },\n { ALT: () => $.SUBRULE(buildInLangStrDir) },\n { ALT: () => $.SUBRULE(buildInHasLang) },\n { ALT: () => $.SUBRULE(buildInHasLangDir) },\n { ALT: () => $.SUBRULE(buildInIsTriple) },\n { ALT: () => $.SUBRULE(buildInTriple) },\n { ALT: () => $.SUBRULE(buildInSubject) },\n { ALT: () => $.SUBRULE(buildInPredicate) },\n { ALT: () => $.SUBRULE(buildInObject) },\n ]),\n};\n\n/**\n * OVERRIDING RULE: {@link S11.rdfLiteral}.\n * No retyping is needed since the return type is the same\n * [[149]](https://www.w3.org/TR/sparql12-query/#rRDFLiteral)\n */\nexport const rdfLiteral: SparqlGrammarRule<'rdfLiteral', RuleDefReturn<typeof S11.rdfLiteral>> = <const> {\n name: 'rdfLiteral',\n impl: ({ ACTION, SUBRULE, OPTION, CONSUME, OR }) => (C) => {\n const value = SUBRULE(S11.string);\n return OPTION(() => OR<RuleDefReturn<typeof rdfLiteral>>([\n { ALT: () => {\n const langTag = CONSUME(l12.LANG_DIR);\n return ACTION(() => {\n const literal = C.astFactory.termLiteral(\n C.astFactory.sourceLocation(value, langTag),\n value.value,\n langTag.image.slice(1).toLowerCase(),\n );\n langTagHasCorrectRange(literal);\n return literal;\n });\n } },\n { ALT: () => {\n CONSUME(l11.symbols.hathat);\n const iriVal = SUBRULE(S11.iri);\n return ACTION(() => C.astFactory.termLiteral(\n C.astFactory.sourceLocation(value, iriVal),\n value.value,\n iriVal,\n ));\n } },\n ])) ?? value;\n },\n};\n\n/**\n * OVERRIDING RULE: {@link S11.string}.\n * [[155]](https://www.w3.org/TR/sparql12-query/#rString)\n *\n * Uses the SPARQL 1.2 string tokens (which include UCHAR in their patterns).\n * Applies single-pass decoding of UCHAR and ECHAR sequences so that a backslash\n * produced by a UCHAR (e.g. \\u005C → \\) is never re-interpreted as an ECHAR prefix.\n * Per the SPARQL 1.2 spec exapmles: \\u005Cn -> \\n\n */\nexport const string: SparqlGrammarRule<'string', T11.TermLiteralStr> = {\n name: 'string',\n impl: ({ ACTION, CONSUME, OR }) => (C) => {\n const tuple = OR([\n { ALT: () => {\n const token = CONSUME(l12.stringLiteral1);\n return <const>[ token, token.image.slice(1, -1) ];\n } },\n { ALT: () => {\n const token = CONSUME(l12.stringLiteral2);\n return <const>[ token, token.image.slice(1, -1) ];\n } },\n { ALT: () => {\n const token = CONSUME(l12.stringLiteralLong1);\n return <const>[ token, token.image.slice(3, -3) ];\n } },\n { ALT: () => {\n const token = CONSUME(l12.stringLiteralLong2);\n return <const>[ token, token.image.slice(3, -3) ];\n } },\n ]);\n return ACTION(() => {\n const [ token, raw ] = tuple;\n const F = C.astFactory;\n // Single-pass: decode UCHAR and ECHAR together so a backslash from a UCHAR\n // is never re-processed as an ECHAR prefix.\n const ecmap: Record<string, string> = {\n t: '\\t',\n n: '\\n',\n r: '\\r',\n b: '\\b',\n f: '\\f',\n '\"': '\"',\n '\\'': '\\'',\n '\\\\': '\\\\',\n };\n const value = raw.replaceAll(\n /\\\\u([\\dA-Fa-f]{4})|\\\\U([\\dA-Fa-f]{8})|\\\\(.)/gsu,\n (_, u4: string | undefined, u8: string | undefined, echar: string | undefined) => {\n if (u4 !== undefined || u8 !== undefined) {\n return decodeUchar((u4 ?? u8)!);\n }\n return ecmap[echar!];\n },\n );\n // Catch literal surrogate code units embedded directly in the query (not via \\uXXXX).\n if (/[\\uD800-\\uDBFF](?:[^\\uDC00-\\uDFFF]|$)/u.test(value)) {\n throw new Error(`Invalid unicode codepoint of surrogate pair without corresponding codepoint`);\n }\n return F.termLiteral(F.sourceLocation(token), value);\n });\n },\n};\n\n/**\n * OVERRIDING RULE: {@link S11.iriFull}.\n * [[160]](https://www.w3.org/TR/sparql12-query/#rIRIREF)\n *\n * Uses the SPARQL 1.2 IRI token (which includes UCHAR in its pattern) and applies\n * codepoint escape decoding via {@link SparqlContext.codepointEscape}.\n */\nexport const iriFull: SparqlGrammarRule<'iriFull', T11.TermIriFull> = {\n name: 'iriFull',\n impl: ({ ACTION, CONSUME }) => (C) => {\n const iriToken = CONSUME(l12.iriRef);\n return ACTION(() => {\n const raw = iriToken.image.slice(1, -1);\n return C.astFactory.termNamed(\n C.astFactory.sourceLocation(iriToken),\n // TODO: next major replace with implementation of codePointEscape.\n // The function no longer serves the intended purpose since it is not reusable for `string`.\n C.codepointEscape(raw),\n );\n });\n },\n};\n\nexport const unaryExpression: SparqlGrammarRule<(typeof S11.unaryExpression)['name'], Expression> = {\n name: 'unaryExpression',\n impl: ({ ACTION, CONSUME, SUBRULE1, SUBRULE2, OR1, OR2 }) => C => OR1<Expression>([\n { ALT: () => SUBRULE1(primaryExpression) },\n { ALT: () => {\n const operator = CONSUME(l11.symbols.exclamation);\n const expr = SUBRULE1(unaryExpression);\n return ACTION(() => C.astFactory.expressionOperation(\n '!',\n [ <T11.Expression> expr ],\n C.astFactory.sourceLocation(operator, expr),\n ));\n } },\n { ALT: () => {\n const operator = OR2([\n { ALT: () => CONSUME(l11.symbols.opPlus) },\n { ALT: () => CONSUME(l11.symbols.opMinus) },\n ]);\n const expr = SUBRULE2(primaryExpression);\n return ACTION(() => C.astFactory.expressionOperation(\n operator.image === '+' ? 'UPLUS' : 'UMINUS',\n [ <T11.Expression> expr ],\n C.astFactory.sourceLocation(operator, expr),\n ));\n } },\n ]),\n};\n\n/**\n * OVERRIDING RULE: {@link S11.triplesBlock}.\n */\nexport const generateTriplesBlock: SparqlGeneratorRule<'triplesBlock', PatternBgp> = {\n name: 'triplesBlock',\n gImpl: ({ SUBRULE, PRINT_WORD, NEW_LINE, HANDLE_LOC }) => (ast, { astFactory: F }) => {\n for (const [ index, triple ] of ast.triples.entries()) {\n HANDLE_LOC(triple, () => {\n const nextTriple = ast.triples.at(index + 1);\n if (F.isTripleCollection(triple)) {\n SUBRULE(graphNodePath, triple);\n // A top level tripleCollection block means that it is either not used in a triple\n // - or is the subject of a triple. In case it is the subject,\n // the identifier of the block will be the subject of the next triple and that subject is not materialized.\n const isSubjectOfTriple = nextTriple?.type === 'triple' &&\n F.isSourceLocationNoMaterialize(nextTriple.subject.loc);\n if (!isSubjectOfTriple) {\n F.printFilter(triple, () => {\n PRINT_WORD('.');\n NEW_LINE();\n });\n }\n } else {\n // Subject\n SUBRULE(graphNodePath, triple.subject);\n F.printFilter(ast, () => PRINT_WORD(''));\n // Predicate\n if (F.isPathPure(triple.predicate)) {\n SUBRULE(S11.pathGenerator, triple.predicate, undefined);\n } else {\n SUBRULE(graphNodePath, triple.predicate);\n }\n F.printFilter(ast, () => PRINT_WORD(''));\n // Object\n SUBRULE(graphNodePath, triple.object);\n SUBRULE(annotationPath, triple.annotations ?? []);\n\n // If no more things, or a top level collection (only possible if new block was part), or new subject: add DOT\n if (nextTriple === undefined || F.isTripleCollection(nextTriple) ||\n !F.isSourceLocationNoMaterialize(nextTriple.subject.loc)) {\n F.printFilter(ast, () => {\n PRINT_WORD('.');\n NEW_LINE();\n });\n } else if (F.isSourceLocationNoMaterialize(nextTriple.predicate.loc)) {\n F.printFilter(ast, () => PRINT_WORD(','));\n } else {\n F.printFilter(ast, () => {\n PRINT_WORD(';');\n NEW_LINE();\n });\n }\n }\n });\n }\n },\n};\n\n/**\n * OVERRIDING RULE: {@link S11.graphTerm}.\n * No retyping is needed since the return type is the same\n * [[149]](https://www.w3.org/TR/sparql12-query/#rRDFLiteral)\n */\nexport const generateGraphTerm: SparqlGeneratorRule<'graphTerm', GraphTerm> = {\n name: 'graphTerm',\n gImpl: $ => (ast, C) => {\n if (C.astFactory.isTermTriple(ast)) {\n $.SUBRULE(tripleTerm, ast);\n } else {\n S11.graphTerm.gImpl($)(ast, C);\n }\n },\n};\n", "/* eslint-disable require-unicode-regexp,no-control-regex */\nimport { LexerBuilder, createToken } from '@traqula/core';\nimport { lex as l11 } from '@traqula/rules-sparql-1-1';\n\nexport const version = createToken({ name: 'Version', pattern: /version/i, label: 'version identifier' });\nexport const tilde = createToken({ name: 'Tilde', pattern: '~', label: '~' });\nexport const annotationOpen = createToken({ name: 'AnnotationOpen', pattern: '{|', label: `Annotation Open: {|` });\nexport const annotationClose = createToken({ name: 'AnnotationClose', pattern: '|}', label: 'Annotation Close |}' });\nexport const reificationOpen = createToken({ name: 'ReificationOpen', pattern: '<<', label: 'Reification open <<' });\nexport const reificationClose = createToken({ name: 'ReificationClose', pattern: '>>', label: 'Reification close >>' });\nexport const tripleTermOpen = createToken({ name: 'TripleTermOpen', pattern: '<<(', label: 'Triple Term Open <<(' });\nexport const tripleTermClose = createToken({ name: 'TripleTermClose', pattern: ')>>', label: 'Triple Term Close )>>' });\n\n// TODO next major: fix builtIn\nexport const buildInLangDir = createToken({ name: 'BuiltInLangdir', pattern: /langdir/i, label: 'LANGDIR' });\nexport const buildInStrLangDir = createToken({\n name: 'BuiltInStrLangdir',\n pattern: /strlangdir/i,\n label: 'STRLANGDIR',\n});\nexport const buildInHasLang = createToken({ name: 'BuiltInHasLang', pattern: /haslang/i, label: 'hasLANG' });\nexport const buildInHasLangDir = createToken({\n name: 'BuiltInHasLangdir',\n pattern: /haslangdir/i,\n label: 'hasLANGDIR',\n});\nexport const buildInIsTRIPLE = createToken({ name: 'BuiltInIsTriple', pattern: /istriple/i, label: 'isTRIPLE' });\nexport const buildInTRIPLE = createToken({ name: 'BuiltInTriple', pattern: /triple/i, label: 'TRIPLE' });\nexport const buildInSUBJECT = createToken({ name: 'BuiltInSubject', pattern: /subject/i, label: 'SUBJECT' });\nexport const buildInPREDICATE = createToken({ name: 'BuiltInPredicate', pattern: /predicate/i, label: 'PREDICATE' });\nexport const buildInOBJECT = createToken({ name: 'BuiltInObject', pattern: /object/i, label: 'OBJECT' });\n\nexport const LANG_DIR = createToken({\n name: 'LANG_DIR',\n pattern: /@[a-z]+(?:-[\\da-z]+)*(?:--[a-z]+)?/i,\n label: 'LANG_DIR',\n});\n\n/**\n * UCHAR: \\uXXXX or \\UXXXXXXXX (SPARQL 1.2 §19.2)\n * Used inside IRI references and string literals only.\n */\nconst ucharSource = /\\\\u[\\dA-Fa-f]{4}|\\\\U[\\dA-Fa-f]{8}/.source;\n/**\n * ECHAR source !(same as sparql-1-1 echarPattern)\n */\nconst echarSource = /\\\\[\"'\\\\bfnrt]/.source;\n/**\n * Character class for valid IRI characters (excluding backslash to allow UCHAR alternation)\n * Same as SPARQL 1.1\n */\nconst iriCharSource = /[^\\u0000-\\u0020\"<>\\\\^`{|}]/.source;\n\n/**\n * [[161]](https://www.w3.org/TR/sparql12-query/#rIRIREF)\n * Extends the SPARQL 1.1 IRI token to allow UCHAR codepoint escapes inside angle-bracket IRIs.\n */\nexport const iriRef = createToken({\n name: 'IriRef',\n pattern: new RegExp(`<((${iriCharSource})|(${ucharSource}))*>`),\n});\n\n/**\n * [[163]](https://www.w3.org/TR/sparql12-query/#rSTRING_LITERAL1)\n * Extends the SPARQL 1.1 string token to allow UCHAR codepoint escapes.\n */\nexport const stringLiteral1 = createToken({\n name: 'StringLiteral1',\n pattern: new RegExp(`'(([^\\\\u0027\\\\u005C\\\\u000A\\u000D])|(${echarSource})|(${ucharSource}))*'`),\n});\n\n/**\n * [[164]](https://www.w3.org/TR/sparql12-query/#rSTRING_LITERAL2)\n * Extends the SPARQL 1.1 string token to allow UCHAR codepoint escapes.\n */\nexport const stringLiteral2 = createToken({\n name: 'StringLiteral2',\n pattern: new RegExp(`\"(([^\\\\u0022\\\\u005C\\\\u000A\\\\u000D])|(${echarSource})|(${ucharSource}))*\"`),\n});\n\n/**\n * [[165]](https://www.w3.org/TR/sparql12-query/#rSTRING_LITERAL_LONG1)\n * Extends the SPARQL 1.1 string token to allow UCHAR codepoint escapes.\n */\nexport const stringLiteralLong1 = createToken({\n name: 'StringLiteralLong1',\n pattern: new RegExp(`'''(('|(''))?([^'\\\\\\\\]|(${echarSource})|(${ucharSource})))*'''`),\n});\n\n/**\n * [[166]](https://www.w3.org/TR/sparql12-query/#rSTRING_LITERAL_LONG2)\n * Extends the SPARQL 1.1 string token to allow UCHAR codepoint escapes.\n */\nexport const stringLiteralLong2 = createToken({\n name: 'StringLiteralLong2',\n pattern: new RegExp(`\"\"\"((\"|(\"\"))?([^\"\\\\\\\\]|(${echarSource})|(${ucharSource})))*\"\"\"`),\n});\n\nexport const sparql12LexerBuilder = LexerBuilder\n .create(l11.sparql11LexerBuilder)\n .addBefore(\n l11.symbols.logicAnd,\n tilde,\n annotationOpen,\n annotationClose,\n tripleTermOpen,\n tripleTermClose,\n reificationOpen,\n reificationClose,\n version,\n )\n .addBefore(\n l11.builtIn.langmatches,\n buildInLangDir,\n buildInStrLangDir,\n buildInHasLangDir,\n buildInHasLang,\n buildInIsTRIPLE,\n buildInTRIPLE,\n buildInSUBJECT,\n buildInPREDICATE,\n buildInOBJECT,\n )\n .addBefore(l11.terminals.langTag, LANG_DIR)\n .deleteToken(l11.terminals.langTag.name)\n // Replace IRI and string tokens with UCHAR-aware versions for SPARQL 1.2.\n .replace(iriRef)\n .replace(stringLiteral1)\n .replace(stringLiteral2)\n .replace(stringLiteralLong1)\n .replace(stringLiteralLong2);\n", "import { TransformerSubTyped, traqulaIndentation, traqulaNewlineAlternative } from '@traqula/core';\nimport { AstFactory } from './AstFactory.js';\nimport type { SparqlContext, SparqlGeneratorContext } from './sparql12HelperTypes.js';\nimport type { Sparql12Nodes } from './sparql12Types.js';\n\n/**\n * Decode UCHAR codepoint escapes (\\\\uXXXX / \\\\UXXXXXXXX) within a string according to\n * [SPARQL 1.2 §19.2](https://www.w3.org/TR/sparql12-query/#sec-escapes).\n *\n * Unlike the SPARQL 1.1 variant, this function rejects surrogate code points (U+D800–U+DFFF)\n * even when they would form a valid surrogate pair.\n * @deprecated will be removed in next MAJOR in favor of the less usecase dependent {@link decodeUchar}.\n */\nexport function sparql12CodepointEscape(input: string): string {\n return input.replaceAll(\n /\\\\u([0-9a-fA-F]{4})|\\\\U([0-9a-fA-F]{8})/gu,\n (_, unicode4: string | undefined, unicode8: string | undefined) =>\n decodeUchar((unicode4 ?? unicode8)!),\n );\n}\n\nexport function decodeUchar(hex: string): string {\n const codePoint = Number.parseInt(hex, 16);\n if (codePoint >= 0xD800 && codePoint <= 0xDFFF) {\n throw new Error(`Illegal codepoint escape: surrogate code point U+${hex.toUpperCase()}`);\n }\n return String.fromCodePoint(codePoint);\n}\n\nexport function completeParseContext(\n context: Partial<SparqlContext>,\n): SparqlContext {\n return {\n astFactory: context.astFactory ?? new AstFactory({ tracksSourceLocation: false }),\n baseIRI: context.baseIRI,\n prefixes: Object.assign(Object.create(null), context.prefixes),\n parseMode: context.parseMode ? new Set(context.parseMode) : new Set([ 'canParseVars', 'canCreateBlankNodes' ]),\n skipValidation: context.skipValidation ?? false,\n /**\n * @deprecated since it cannot be used for string decoding.\n */\n codepointEscape: context.codepointEscape ?? sparql12CodepointEscape,\n };\n}\n\nexport function completeGeneratorContext(\n context: Partial<SparqlGeneratorContext & { offset?: number }>,\n): SparqlGeneratorContext & { offset?: number } {\n return {\n astFactory: context.astFactory ?? new AstFactory(),\n origSource: context.origSource ?? '',\n offset: context.offset,\n indentInc: context.indentInc ?? 2,\n [traqulaIndentation]: context[traqulaIndentation] ?? 0,\n [traqulaNewlineAlternative]: context[traqulaNewlineAlternative] ?? ' ',\n };\n}\n\nexport function copyParseContext<T extends\nPartial<SparqlContext & SparqlGeneratorContext & { origSource: string; offset?: number }>>(\n context: T,\n): T {\n return {\n ...context,\n prefixes: Object.assign(Object.create(null), context.prefixes),\n parseMode: new Set(context.parseMode),\n };\n}\n\nexport class AstTransformer extends TransformerSubTyped<Sparql12Nodes> {}\n", "import {\n validation as validation11,\n} from '@traqula/rules-sparql-1-1';\nimport * as validation12 from './validators.js';\n\nexport * as gram from './grammar.js';\nexport * as lex from './lexer.js';\nexport * from './sparql12Types.js';\nexport * from './sparql12HelperTypes.js';\nexport * from './parserUtils.js';\nexport * from './AstFactory.js';\n// TODO: deprecate this export\nexport * from './validators.js';\n\ntype OverriddenKeys = keyof typeof validation11 & keyof typeof validation12;\nexport const validation = <Omit<typeof validation11, OverriddenKeys> & typeof validation12> {\n ...validation11,\n ...validation12,\n};\n", "import { ParserBuilder } from '@traqula/core';\nimport type { Patch, Wrap, ParserBuildArgs } from '@traqula/core';\nimport { sparql11ParserBuilder } from '@traqula/parser-sparql-1-1';\nimport {\n gram as g11,\n} from '@traqula/rules-sparql-1-1';\nimport type {\n TermIri,\n} from '@traqula/rules-sparql-1-1';\nimport { completeParseContext, copyParseContext, gram as S12, lex as l12 } from '@traqula/rules-sparql-1-2';\nimport type * as T12 from '@traqula/rules-sparql-1-2';\n\n/**\n * Pre-configured {@link ParserBuilder} for SPARQL 1.2, extending the SPARQL 1.1 parser builder\n * with SPARQL 1.2 grammar rules (e.g. reified triples, triple terms, VERSION declaration).\n * Use {@link ParserBuilder.create ParserBuilder.create(sparql12ParserBuilder)} to extend it\n * with additional rules.\n */\nexport const sparql12ParserBuilder = ParserBuilder.create(sparql11ParserBuilder)\n .widenContext<T12.SparqlContext>()\n .typePatch<{\n /// GeneralFile\n queryOrUpdate: [ T12.SparqlQuery];\n /// Query Unit file\n [g11.selectQuery.name]: [Omit<T12.QuerySelect, g11.HandledByBase>];\n [g11.subSelect.name]: [ Omit<T12.SubSelect, 'prefixes'>];\n [g11.selectClause.name]: [Wrap<Pick<T12.QuerySelect, 'variables' | 'distinct' | 'reduced'>>];\n [g11.constructQuery.name]: [Omit<T12.QueryConstruct, g11.HandledByBase>];\n [g11.describeQuery.name]: [Omit<T12.QueryDescribe, g11.HandledByBase>];\n [g11.askQuery.name]: [Omit<T12.QueryAsk, g11.HandledByBase>];\n [g11.valuesClause.name]: [T12.PatternValues[] | undefined];\n [g11.constructTemplate.name]: [Wrap<T12.PatternBgp>];\n [g11.constructTriples.name]: [T12.PatternBgp];\n /// Update Unit file\n [g11.update1.name]: [T12.UpdateOperation];\n [g11.load.name]: [T12.UpdateOperationLoad];\n [g11.clear.name]: [T12.UpdateOperationClear];\n [g11.drop.name]: [T12.UpdateOperationDrop];\n [g11.create.name]: [T12.UpdateOperationCreate];\n [g11.add.name]: [T12.UpdateOperationAdd];\n [g11.move.name]: [T12.UpdateOperationMove];\n [g11.copy.name]: [T12.UpdateOperationCopy];\n [g11.quadPattern.name]: [Wrap<T12.Quads[]>];\n [g11.quadData.name]: [Wrap<T12.Quads[]>];\n [g11.insertData.name]: [T12.UpdateOperationInsertData];\n [g11.deleteData.name]: [T12.UpdateOperationDeleteData];\n [g11.deleteWhere.name]: [T12.UpdateOperationDeleteWhere];\n [g11.modify.name]: [T12.UpdateOperationModify];\n [g11.deleteClause.name]: [Wrap<T12.Quads[]>];\n [g11.insertClause.name]: [Wrap<T12.Quads[]>];\n [g11.graphOrDefault.name]: [T12.GraphRefDefault | T12.GraphRefSpecific];\n [g11.graphRef.name]: [T12.GraphRefSpecific];\n [g11.graphRefAll.name]: [T12.GraphRef];\n [g11.quads.name]: [Wrap<T12.Quads[]>];\n [g11.quadsNotTriples.name]: [T12.GraphQuads];\n /// Built-in functions\n [g11.builtInStr.name]: [T12.ExpressionOperation];\n [g11.builtInLang.name]: [T12.ExpressionOperation];\n [g11.builtInLangmatches.name]: [T12.ExpressionOperation];\n [g11.builtInDatatype.name]: [T12.ExpressionOperation];\n [g11.builtInBound.name]: [T12.ExpressionOperation];\n [g11.builtInIri.name]: [T12.ExpressionOperation];\n [g11.builtInUri.name]: [T12.ExpressionOperation];\n [g11.builtInBnodeSparqlJs.name]: [T12.ExpressionOperation];\n [g11.builtInRand.name]: [T12.ExpressionOperation];\n [g11.builtInAbs.name]: [T12.ExpressionOperation];\n [g11.builtInCeil.name]: [T12.ExpressionOperation];\n [g11.builtInFloor.name]: [T12.ExpressionOperation];\n [g11.builtInRound.name]: [T12.ExpressionOperation];\n [g11.builtInConcat.name]: [T12.ExpressionOperation];\n [g11.substringExpression.name]: [T12.ExpressionOperation];\n [g11.builtInStrlen.name]: [T12.ExpressionOperation];\n [g11.strReplaceExpression.name]: [T12.ExpressionOperation];\n [g11.builtInUcase.name]: [T12.ExpressionOperation];\n [g11.builtInLcase.name]: [T12.ExpressionOperation];\n [g11.builtInEncode_for_uri.name]: [T12.ExpressionOperation];\n [g11.builtInContains.name]: [T12.ExpressionOperation];\n [g11.builtInStrstarts.name]: [T12.ExpressionOperation];\n [g11.builtInStrends.name]: [T12.ExpressionOperation];\n [g11.builtInStrbefore.name]: [T12.ExpressionOperation];\n [g11.builtInStrafter.name]: [T12.ExpressionOperation];\n [g11.builtInYear.name]: [T12.ExpressionOperation];\n [g11.builtInMonth.name]: [T12.ExpressionOperation];\n [g11.builtInDay.name]: [T12.ExpressionOperation];\n [g11.builtInHours.name]: [T12.ExpressionOperation];\n [g11.builtInMinutes.name]: [T12.ExpressionOperation];\n [g11.builtInSeconds.name]: [T12.ExpressionOperation];\n [g11.builtInTimezone.name]: [T12.ExpressionOperation];\n [g11.builtInTz.name]: [T12.ExpressionOperation];\n [g11.builtInNow.name]: [T12.ExpressionOperation];\n [g11.builtInUuid.name]: [T12.ExpressionOperation];\n [g11.builtInStruuid.name]: [T12.ExpressionOperation];\n [g11.builtInMd5.name]: [T12.ExpressionOperation];\n [g11.builtInSha1.name]: [T12.ExpressionOperation];\n [g11.builtInSha256.name]: [T12.ExpressionOperation];\n [g11.builtInSha384.name]: [T12.ExpressionOperation];\n [g11.builtInSha512.name]: [T12.ExpressionOperation];\n [g11.builtInCoalesce.name]: [T12.ExpressionOperation];\n [g11.builtInIf.name]: [T12.ExpressionOperation];\n [g11.builtInStrlang.name]: [T12.ExpressionOperation];\n [g11.builtInStrdt.name]: [T12.ExpressionOperation];\n [g11.builtInSameterm.name]: [T12.ExpressionOperation];\n [g11.builtInIsiri.name]: [T12.ExpressionOperation];\n [g11.builtInIsuri.name]: [T12.ExpressionOperation];\n [g11.builtInIsblank.name]: [T12.ExpressionOperation];\n [g11.builtInIsliteral.name]: [T12.ExpressionOperation];\n [g11.builtInIsnumeric.name]: [T12.ExpressionOperation];\n [g11.existsFunc.name]: [T12.ExpressionPatternOperation];\n [g11.notExistsFunc.name]: [T12.ExpressionPatternOperation];\n [g11.aggregateCount.name]: [T12.ExpressionAggregateOnWildcard | T12.ExpressionAggregateDefault];\n [g11.aggregateSum.name]: [T12.ExpressionAggregateDefault];\n [g11.aggregateMin.name]: [T12.ExpressionAggregateDefault];\n [g11.aggregateMax.name]: [T12.ExpressionAggregateDefault];\n [g11.aggregateAvg.name]: [T12.ExpressionAggregateDefault];\n [g11.aggregateSample.name]: [T12.ExpressionAggregateDefault];\n [g11.aggregateGroup_concat.name]: [T12.ExpressionAggregateDefault | T12.ExpressionAggregateSeparator];\n [g11.aggregate.name]: [T12.ExpressionAggregate];\n [g11.builtInCall.name]: [T12.Expression];\n /// DatasetClause\n [g11.datasetClause.name]: [Wrap<T12.DatasetClauses['clauses'][0]>];\n [g11.defaultGraphClause.name]: [T12.TermIri];\n [g11.usingClause.name]: [Wrap<T12.DatasetClauses['clauses'][0]>];\n [g11.datasetClauseStar.name]: [T12.DatasetClauses];\n [g11.usingClauseStar.name]: [T12.DatasetClauses];\n [g11.namedGraphClause.name]: [Wrap<T12.TermIri>];\n [g11.sourceSelector.name]: [T12.TermIri];\n // Expression file\n [g11.argList.name]: [Wrap<Patch<g11.IArgList, { args: T12.Expression[] }>>];\n [g11.expressionList.name]: [Wrap<T12.Expression[]>];\n [g11.expression.name]: [T12.Expression];\n [g11.conditionalOrExpression.name]: [T12.ExpressionOperation | T12.Expression];\n [g11.conditionalAndExpression.name]: [T12.Expression];\n [g11.valueLogical.name]: [T12.Expression];\n [g11.relationalExpression.name]: [T12.ExpressionOperation | T12.Expression];\n [g11.numericExpression.name]: [T12.Expression];\n [g11.additiveExpression.name]: [T12.Expression];\n [g11.multiplicativeExpression.name]: [T12.Expression];\n [g11.unaryExpression.name]: [T12.Expression];\n [g11.primaryExpression.name]: [T12.Expression];\n [g11.brackettedExpression.name]: [T12.Expression];\n [g11.iriOrFunction.name]: [T12.TermIri | T12.ExpressionFunctionCall];\n /// General\n [g11.prologue.name]: [T12.ContextDefinition[]];\n [g11.baseDecl.name]: [T12.ContextDefinition];\n [g11.prefixDecl.name]: [T12.ContextDefinition];\n [g11.verb.name]: [T12.TermVariable | T12.TermIri];\n [g11.varOrTerm.name]: [T12.Term];\n [g11.varOrIri.name]: [T12.TermIri | T12.TermVariable];\n [g11.var_.name]: [T12.TermVariable];\n [g11.graphTerm.name]: [T12.GraphTerm];\n /// Literals\n [g11.rdfLiteral.name]: [T12.TermLiteral];\n [g11.numericLiteral.name]: [T12.TermLiteralTyped];\n [g11.numericLiteralUnsigned.name]: [T12.TermLiteralTyped];\n [g11.numericLiteralPositive.name]: [T12.TermLiteralTyped];\n [g11.numericLiteralNegative.name]: [T12.TermLiteralTyped];\n [g11.booleanLiteral.name]: [T12.TermLiteralTyped];\n [g11.string.name]: [T12.TermLiteralStr];\n [g11.iri.name]: [T12.TermIri];\n [g11.iriFull.name]: [T12.TermIriFull];\n [g11.prefixedName.name]: [T12.TermIriPrefixed];\n [g11.blankNode.name]: [T12.TermBlank];\n [g11.verbA.name]: [T12.TermIriFull];\n /// / Paths: unchanged\n /// / SolutionModifiers\n [g11.solutionModifier.name]: [T12.SolutionModifiers];\n [g11.groupClause.name]: [T12.SolutionModifierGroup];\n [g11.groupCondition.name]: [T12.Expression | T12.SolutionModifierGroupBind];\n [g11.havingClause.name]: [T12.SolutionModifierHaving];\n [g11.havingCondition.name]: [T12.Expression];\n [g11.orderClause.name]: [T12.SolutionModifierOrder];\n [g11.orderCondition.name]: [T12.Ordering];\n [g11.limitOffsetClauses.name]: [T12.SolutionModifierLimitOffset];\n [g11.limitClause.name]: [Wrap<number>];\n [g11.offsetClause.name]: [ Wrap<number>];\n /// tripleBlock\n [g11.triplesBlock.name]: [T12.PatternBgp];\n [g11.triplesSameSubject.name]: [T12.BasicGraphPattern];\n [g11.triplesSameSubjectPath.name]: [T12.BasicGraphPattern];\n [g11.triplesTemplate.name]: [T12.PatternBgp];\n [g11.propertyList.name]: [T12.TripleNesting[]];\n [g11.propertyListPath.name]: [T12.TripleNesting[]];\n [g11.propertyListNotEmpty.name]: [T12.TripleNesting[]];\n [g11.propertyListPathNotEmpty.name]: [T12.TripleNesting[]];\n [g11.verbPath.name]: [T12.Path];\n [g11.verbSimple.name]: [T12.TermVariable];\n [g11.objectList.name]: [T12.TripleNesting[], [ T12.TripleNesting['subject'], T12.TripleNesting['predicate'] ]];\n [g11.objectListPath.name]: [T12.TripleNesting, [ T12.TripleNesting['subject'], T12.TripleNesting['predicate'] ]];\n [g11.object.name]: [T12.TripleNesting, [ T12.TripleNesting['subject'], T12.TripleNesting['predicate'] ]];\n [g11.objectPath.name]: [T12.TripleNesting[], [ T12.TripleNesting['subject'], T12.TripleNesting['predicate'] ]];\n [g11.collection.name]: [T12.TripleCollectionList];\n [g11.collectionPath.name]: [T12.TripleCollectionList];\n [g11.triplesNode.name]: [T12.TripleCollection];\n [g11.triplesNodePath.name]: [T12.TripleCollection];\n [g11.blankNodePropertyList.name]: [T12.TripleCollectionBlankNodeProperties];\n [g11.blankNodePropertyListPath.name]: [T12.TripleCollectionBlankNodeProperties];\n [g11.graphNode.name]: [T12.Term | T12.TripleCollection];\n [g11.graphNodePath.name]: [T12.Term | T12.TripleCollection];\n /// WhereClause\n [g11.whereClause.name]: [Wrap<T12.PatternGroup>];\n [g11.groupGraphPattern.name]: [T12.PatternGroup];\n [g11.groupGraphPatternSub.name]: [T12.Pattern[]];\n [g11.graphPatternNotTriples.name]: [Exclude<T12.Pattern, T12.SubSelect | T12.PatternBgp>];\n [g11.optionalGraphPattern.name]: [T12.PatternOptional];\n [g11.graphGraphPattern.name]: [T12.PatternGraph];\n [g11.serviceGraphPattern.name]: [T12.PatternService];\n [g11.bind.name]: [T12.PatternBind];\n [g11.inlineData.name]: [T12.PatternValues];\n [g11.dataBlock.name]: [T12.PatternValues];\n [g11.inlineDataOneVar.name]: [T12.PatternValues];\n [g11.inlineDataFull.name]: [T12.PatternValues];\n [g11.dataBlockValue.name]: [T12.TermIri | T12.TermLiteral | undefined];\n [g11.minusGraphPattern.name]: [T12.PatternMinus];\n [g11.groupOrUnionGraphPattern.name]: [T12.PatternGroup | T12.PatternUnion];\n [g11.filter.name]: [T12.PatternFilter];\n [g11.constraint.name]: [T12.Expression];\n [g11.functionCall.name]: [T12.ExpressionFunctionCall];\n }>()\n .addMany(\n S12.reifiedTripleBlock,\n S12.reifiedTripleBlockPath,\n S12.reifier,\n S12.varOrReifierId,\n S12.annotation,\n S12.annotationPath,\n S12.annotationBlockPath,\n S12.annotationBlock,\n S12.reifiedTriple,\n S12.reifiedTripleSubject,\n S12.reifiedTripleObject,\n S12.tripleTerm,\n S12.tripleTermSubject,\n S12.tripleTermObject,\n S12.tripleTermData,\n S12.tripleTermDataSubject,\n S12.tripleTermDataObject,\n S12.exprTripleTerm,\n S12.exprTripleTermSubject,\n S12.exprTripleTermObject,\n )\n .addMany(\n S12.versionDecl,\n S12.versionSpecifier,\n )\n .addMany(\n S12.buildInLangDir,\n S12.buildInLangStrDir,\n S12.buildInHasLang,\n S12.buildInHasLangDir,\n S12.buildInIsTriple,\n S12.buildInTriple,\n S12.buildInSubject,\n S12.buildInPredicate,\n S12.buildInObject,\n )\n .patchRule(S12.selectQuery)\n .patchRule(S12.dataBlockValue)\n .patchRule(S12.triplesSameSubject)\n .patchRule(S12.triplesSameSubjectPath)\n .patchRule(S12.object)\n .patchRule(S12.objectPath)\n .patchRule(S12.graphNode)\n .patchRule(S12.graphNodePath)\n .patchRule(S12.varOrTerm)\n .patchRule(S12.primaryExpression)\n .patchRule(S12.builtInCall)\n .patchRule(S12.rdfLiteral)\n .patchRule(S12.unaryExpression)\n .patchRule(S12.prologue)\n .patchRule(S12.string)\n .patchRule(S12.iriFull)\n .deleteRule(g11.graphTerm.name);\n\nexport type SparqlParser = ReturnType<typeof sparql12ParserBuilder.build>;\n\n/**\n * Parser that can parse a SPARQL 1.2 string into a SPARQL 1.2 AST.\n */\nexport class Parser {\n private readonly parser: SparqlParser;\n protected readonly defaultContext: T12.SparqlContext;\n\n public constructor(\n args: Pick<ParserBuildArgs, 'parserConfig' | 'lexerConfig'> & { defaultContext?: Partial<T12.SparqlContext> } = {},\n ) {\n this.parser = sparql12ParserBuilder.build({\n ...args,\n tokenVocabulary: l12.sparql12LexerBuilder.tokenVocabulary,\n });\n this.defaultContext = completeParseContext(args.defaultContext ?? {});\n }\n\n /**\n * Parse a query string starting from the\n * [QueryUnit](https://www.w3.org/TR/sparql12-query/#rQueryUnit)\n * or [QueryUpdate](https://www.w3.org/TR/sparql12-query/#rUpdateUnit) rules.\n * @param query\n * @param context\n */\n public parse(query: string, context: Partial<T12.SparqlContext> = {}): T12.SparqlQuery {\n const ast = this.parser.queryOrUpdate(query, copyParseContext({ ...this.defaultContext, ...context }));\n ast.loc = this.defaultContext.astFactory.sourceLocationInlinedSource(query, ast.loc, 0, Number.MAX_SAFE_INTEGER);\n return ast;\n }\n\n /**\n * Parse a query string starting from the [Path](https://www.w3.org/TR/sparql12-query/#rPath) grammar rule.\n * @param query\n * @param context\n */\n public parsePath(\n query: string,\ncontext: Partial<T12.SparqlContext> = {},\n ): (T12.Path & { prefixes: object }) | TermIri {\n const ast = this.parser.path(query, copyParseContext({ ...this.defaultContext, ...context }));\n ast.loc = this.defaultContext.astFactory.sourceLocationInlinedSource(query, ast.loc, 0, Number.MAX_SAFE_INTEGER);\n if (this.defaultContext.astFactory.isPathPure(ast)) {\n return {\n ...ast,\n prefixes: Object.create(null),\n };\n }\n return ast;\n }\n}\n", "import type * as RDF from '@rdfjs/types';\nimport type {\n Expression,\n ExpressionAggregate,\n Ordering,\n PatternBind,\n Query,\n TermIri,\n TermVariable,\n Wildcard,\n} from '@traqula/rules-sparql-1-1';\nimport equal from 'fast-deep-equal';\nimport type { Algebra } from '../index.js';\nimport type { AlgebraIndir, FlattenedTriple } from './core.js';\nimport {\n type AstToRdfTerm,\n generateFreshVar,\n inScopeVariables,\n translateDatasetClause,\n translateInlineData,\n translateTerm,\n} from './general.js';\nimport { translateExpression } from './patterns.js';\nimport { translateBasicGraphPattern, translateQuad } from './tripleAndQuad.js';\n\n/**\n * 18.2.4\n */\nexport const translateAggregates: AlgebraIndir<'translateAggregates', Algebra.Operation, [Query, Algebra.Operation]> = {\n name: 'translateAggregates',\n fun: ({ SUBRULE }) => ({ astFactory: F, algebraFactory: AF, dataFactory: DF }, query, res) => {\n const bindPatterns: PatternBind[] = [];\n\n const varAggrMap: Record<string, ExpressionAggregate> = {};\n const variables = F.isQuerySelect(query) || F.isQueryDescribe(query) ?\n query.variables.map(x => SUBRULE(mapAggregate, x, varAggrMap)) :\n undefined;\n const having = query.solutionModifiers.having ?\n query.solutionModifiers.having.having.map(x => <typeof x>SUBRULE(mapAggregate, x, varAggrMap)) :\n undefined;\n const order = query.solutionModifiers.order ?\n query.solutionModifiers.order.orderDefs.map(x => <typeof x>SUBRULE(mapAggregate, x, varAggrMap)) :\n undefined;\n\n // Step: GROUP BY - If we found an aggregate, in group by or implicitly, do Group function.\n // 18.2.4.1 Grouping and Aggregation\n if (query.solutionModifiers.group ?? Object.keys(varAggrMap).length > 0) {\n const aggregates = Object.keys(varAggrMap).map(var_ =>\n SUBRULE(translateBoundAggregate, varAggrMap[var_], DF.variable(var_)));\n const vars: RDF.Variable[] = [];\n if (query.solutionModifiers.group) {\n for (const expression of query.solutionModifiers.group.groupings) {\n // https://www.w3.org/TR/sparql11-query/#rGroupCondition\n if (F.isTerm(expression)) {\n // This will always be a var, otherwise sparql would be invalid\n vars.push(<RDF.Variable>SUBRULE(translateTerm, expression));\n } else {\n let var_: RDF.Variable;\n let expr: Expression;\n if ('variable' in expression) {\n var_ = <AstToRdfTerm<typeof expression.variable>>SUBRULE(translateTerm, expression.variable);\n expr = expression.value;\n } else {\n var_ = SUBRULE(generateFreshVar);\n expr = expression;\n }\n res = AF.createExtend(res, var_, SUBRULE(translateExpression, expr));\n vars.push(var_);\n }\n }\n }\n res = AF.createGroup(res, vars, aggregates);\n }\n\n // 18.2.4.2\n if (having) {\n for (const filter of having) {\n res = AF.createFilter(res, SUBRULE(translateExpression, filter));\n }\n }\n\n // 18.2.4.3\n if (query.values) {\n res = AF.createJoin([ res, SUBRULE(translateInlineData, query.values) ]);\n }\n\n // 18.2.4.4\n let PatternValues: (RDF.Variable | RDF.NamedNode)[] = [];\n\n if (variables) {\n // Sort variables for consistent output\n if (variables.some(wild => F.isWildcard(wild))) {\n PatternValues = [ ...SUBRULE(inScopeVariables, query).values() ].map(x => DF.variable(x))\n .sort((left, right) => left.value.localeCompare(right.value));\n } else {\n // Wildcard has been filtered out above\n for (const var_ of <(TermVariable | TermIri | PatternBind)[]> variables) {\n // Can have non-variables with DESCRIBE\n if (F.isTerm(var_)) {\n PatternValues.push(<AstToRdfTerm<typeof var_>>SUBRULE(translateTerm, var_));\n } else {\n // ... AS ?x\n PatternValues.push(<AstToRdfTerm<typeof var_.variable>>SUBRULE(translateTerm, var_.variable));\n bindPatterns.push(var_);\n }\n }\n }\n }\n\n // TODO: Jena simplifies by having a list of extends\n for (const bind of bindPatterns) {\n res = AF.createExtend(\n res,\n <AstToRdfTerm<typeof bind.variable>>SUBRULE(translateTerm, bind.variable),\n SUBRULE(translateExpression, bind.expression),\n );\n }\n\n // 18.2.5\n // not using toList and toMultiset\n\n // 18.2.5.1\n if (order) {\n res = AF.createOrderBy(res, order.map((expr) => {\n let result = SUBRULE(translateExpression, expr.expression);\n if (expr.descending) {\n result = AF.createOperatorExpression('desc', [ result ]);\n }\n return result;\n }));\n }\n\n // 18.2.5.2\n // construct does not need a project (select, ask and describe do)\n if (F.isQuerySelect(query)) {\n // Named nodes are only possible in a DESCRIBE so this cast is safe\n res = AF.createProject(res, <RDF.Variable[]> PatternValues);\n }\n\n // 18.2.5.3\n if ((<{ distinct?: unknown }>query).distinct) {\n res = AF.createDistinct(res);\n }\n\n // 18.2.5.4\n if ((<{ reduced?: unknown }>query).reduced) {\n res = AF.createReduced(res);\n }\n\n if (F.isQueryConstruct(query)) {\n const triples: FlattenedTriple[] = [];\n SUBRULE(translateBasicGraphPattern, query.template.triples, triples);\n res = AF.createConstruct(res, triples.map(quad => SUBRULE(translateQuad, quad)));\n } else if (F.isQueryAsk(query)) {\n res = AF.createAsk(res);\n } else if (F.isQueryDescribe(query)) {\n res = AF.createDescribe(res, PatternValues);\n }\n\n // Slicing needs to happen after construct/describe\n // 18.2.5.5\n const limitOffset = query.solutionModifiers.limitOffset;\n if (limitOffset?.limit !== undefined || limitOffset?.offset) {\n res = AF.createSlice(res, limitOffset.offset ?? 0, limitOffset.limit);\n }\n\n if (query.datasets.clauses.length > 0) {\n const clauses = SUBRULE(translateDatasetClause, query.datasets);\n res = AF.createFrom(res, clauses.default, clauses.named);\n }\n\n return res;\n },\n};\n\nexport type MapAggregateType = Wildcard | Expression | Ordering | PatternBind;\n\n/**\n * Rewrites some of the input sparql object to make use of aggregate variables\n * It thus replaces aggregates by their representative variable and registers the mapping.\n */\nexport const mapAggregate:\nAlgebraIndir<'mapAggregate', MapAggregateType, [MapAggregateType, Record<string, ExpressionAggregate>]> = {\n name: 'mapAggregate',\n fun: ({ SUBRULE }) => ({ astFactory: F }, thingy, aggregates): MapAggregateType => {\n if (F.isExpressionAggregate(thingy)) {\n // Needed to take away the difference in the various `loc` descriptions\n const canonicalAggregate = F.forcedAutoGenTree<ExpressionAggregate>(thingy);\n let val: TermVariable | undefined;\n // Look for the matching aggregate\n for (const [ key, aggregate ] of Object.entries(aggregates)) {\n if (equal(aggregate, canonicalAggregate)) {\n val = F.termVariable(key, F.sourceLocation());\n break;\n }\n }\n if (val !== undefined) {\n return val;\n }\n const freshVar = SUBRULE(generateFreshVar);\n aggregates[freshVar.value] = canonicalAggregate;\n return F.termVariable(freshVar.value, F.sourceLocation());\n }\n\n if (F.isExpressionPure(thingy) && !F.isExpressionPatternOperation(thingy)) {\n return { ...thingy, args: thingy.args.map(x => <typeof x>SUBRULE(mapAggregate, x, aggregates)) };\n }\n // Non-aggregate expression\n if ('expression' in thingy && thingy.expression) {\n return { ...thingy, expression: <typeof thingy.expression>SUBRULE(mapAggregate, thingy.expression, aggregates) };\n }\n return thingy;\n },\n};\n\nexport const translateBoundAggregate:\nAlgebraIndir<'translateBoundAggregate', Algebra.BoundAggregate, [ExpressionAggregate, RDF.Variable]> = {\n name: 'translateBoundAggregate',\n fun: ({ SUBRULE }) => (_, thingy, variable) => {\n const A = <Algebra.AggregateExpression> SUBRULE(translateExpression, thingy);\n return { ...A, variable };\n },\n};\n", "import type * as RDF from '@rdfjs/types';\nimport type { Typed, SubTyped } from '@traqula/core';\n\n/**\n * Enum type listing the type strings for Traqula's SPARQL algebra operations.\n */\nexport enum Types {\n ASK = 'ask',\n BGP = 'bgp',\n CONSTRUCT = 'construct',\n DESCRIBE = 'describe',\n DISTINCT = 'distinct',\n EXPRESSION = 'expression',\n EXTEND = 'extend',\n FILTER = 'filter',\n FROM = 'from',\n GRAPH = 'graph',\n GROUP = 'group',\n JOIN = 'join',\n LEFT_JOIN = 'leftjoin',\n MINUS = 'minus',\n NOP = 'nop',\n ORDER_BY = 'orderby',\n PATTERN = 'pattern',\n PROJECT = 'project',\n REDUCED = 'reduced',\n SERVICE = 'service',\n SLICE = 'slice',\n UNION = 'union',\n VALUES = 'values',\n\n // Update\n COMPOSITE_UPDATE = 'compositeupdate',\n DELETE_INSERT = 'deleteinsert',\n LOAD = 'load',\n CLEAR = 'clear',\n CREATE = 'create',\n DROP = 'drop',\n ADD = 'add',\n MOVE = 'move',\n COPY = 'copy',\n\n // Paths\n PATH = 'path',\n ALT = 'alt',\n INV = 'inv',\n LINK = 'link',\n ONE_OR_MORE_PATH = 'OneOrMorePath',\n SEQ = 'seq',\n NPS = 'nps',\n ZERO_OR_MORE_PATH = 'ZeroOrMorePath',\n ZERO_OR_ONE_PATH = 'ZeroOrOnePath',\n}\n\nexport enum ExpressionTypes {\n AGGREGATE = 'aggregate',\n EXISTENCE = 'existence',\n NAMED = 'named',\n OPERATOR = 'operator',\n TERM = 'term',\n WILDCARD = 'wildcard',\n}\n\n// ----------------------- OPERATIONS -----------------------\n/**\n * Union type of all known SPARQL 1.1 operations.\n */\nexport type Operation = Ask | Expression | Bgp | Construct | Describe | Distinct | Extend | From | Filter\n | Graph | Group | Join | LeftJoin | Minus | Nop | OrderBy | Path | Pattern | Project | PropertyPathSymbol\n | Reduced | Service | Slice | Union | Values | Update | CompositeUpdate;\n\n/**\n * Union type of all known SPARQL 1.1 expression operations.\n */\nexport type Expression = AggregateExpression | GroupConcatExpression | ExistenceExpression | NamedExpression |\n OperatorExpression | TermExpression | WildcardExpression | BoundAggregate;\n\n/**\n * Union type of all known SPARQL 1.1 Property Path symbols.\n */\nexport type PropertyPathSymbol = Alt | Inv | Link | Nps | OneOrMorePath | Seq | ZeroOrMorePath | ZeroOrOnePath;\n\n/**\n * Union type of all known SPARQL 1.1 update operations.\n */\nexport type Update = DeleteInsert | Load | Clear | Create | Drop | Add | Move | Copy;\n\n/**\n * Returns the correct type based on the type enum\n */\nexport type TypedOperation<T extends Types> = Extract<Operation, { type: T }>;\n/**\n * Returns the correct subType based on the type enum\n */\nexport type TypedExpression<T extends ExpressionTypes> = Extract<Expression, { subType: T }>;\n\n// ----------------------- ABSTRACTS -----------------------\n\n/**\n * All SPARQL operations are typed nodes, allowing them to be altered using the transformers in @traqula/core\n */\nexport interface BaseOperation extends Typed { }\n\n/**\n * Open interface describing an expression\n */\nexport interface BaseExpression extends BaseOperation, SubTyped<Types.EXPRESSION> {\n type: Types.EXPRESSION;\n subType: string;\n}\n\n// ----------------------- ABSTRACTS -----------------------\n\n/**\n * Algebra operation taking a single operation as input.\n */\nexport interface Single extends BaseOperation {\n input: Operation;\n}\n\n/**\n * Algebra operation taking multiple operations as input.\n */\nexport interface Multi extends BaseOperation {\n input: Operation[];\n}\n\n/**\n * Algebra operation taking exactly two input operations.\n */\nexport interface Double extends Multi {\n input: [Operation, Operation];\n}\n\n/**\n * [Aggregate Algebra expression](https://www.w3.org/TR/sparql11-query/#aggregateAlgebra)\n */\nexport interface AggregateExpression extends BaseExpression {\n subType: ExpressionTypes.AGGREGATE;\n aggregator: 'avg' | 'count' | 'group_concat' | 'max' | 'min' | 'sample' | 'sum';\n distinct: boolean;\n expression: Expression;\n separator?: string;\n}\n\n/**\n * @inheritDoc\n */\nexport interface GroupConcatExpression extends AggregateExpression {\n aggregator: 'group_concat';\n separator?: string;\n}\n\n/**\n * [Exists / Not Exists Algebra expression](https://www.w3.org/TR/sparql11-query/#defn_evalExists)\n */\nexport interface ExistenceExpression extends BaseExpression {\n subType: ExpressionTypes.EXISTENCE;\n not: boolean;\n input: Operation;\n}\n\nexport interface NamedExpression extends BaseExpression {\n subType: ExpressionTypes.NAMED;\n name: RDF.NamedNode;\n args: Expression[];\n}\n\nexport interface OperatorExpression extends BaseExpression {\n subType: ExpressionTypes.OPERATOR;\n operator: string;\n args: Expression[];\n}\n\nexport interface TermExpression extends BaseExpression {\n subType: ExpressionTypes.TERM;\n term: RDF.Term;\n}\n\nexport interface WildcardExpression extends BaseExpression {\n subType: ExpressionTypes.WILDCARD;\n wildcard: {\n type: 'wildcard';\n };\n}\n\n// TODO: currently not differentiating between lists and multisets\n\n// ----------------------- ACTUAL FUNCTIONS -----------------------\n\n/**\n * [Alternative Property Path algebra operation](https://www.w3.org/TR/sparql11-query/#defn_evalPP_alternative) representing the [Property path](https://www.w3.org/TR/sparql11-query/#propertypaths) alternative (`|`).\n * Property paths have a specific [SPARQL definition](https://www.w3.org/TR/sparql11-query/#sparqlPropertyPaths)\n */\nexport interface Alt extends Multi {\n type: Types.ALT;\n input: PropertyPathSymbol[];\n}\n\nexport interface Ask extends Single {\n type: Types.ASK;\n}\n\nexport interface Bgp extends BaseOperation {\n type: Types.BGP;\n patterns: Pattern[];\n}\n\nexport interface Construct extends Single {\n type: Types.CONSTRUCT;\n template: Pattern[];\n}\n\nexport interface Describe extends Single {\n type: Types.DESCRIBE;\n terms: (RDF.Variable | RDF.NamedNode)[];\n}\n\n/**\n * [Distinct algebra operation](https://www.w3.org/TR/sparql11-query/#defn_evalDistinct)\n */\nexport interface Distinct extends Single {\n type: Types.DISTINCT;\n}\n\n/**\n * [Extend algebra operation](https://www.w3.org/TR/sparql11-query/#defn_evalExtend)\n */\nexport interface Extend extends Single {\n type: Types.EXTEND;\n variable: RDF.Variable;\n expression: Expression;\n}\n\nexport interface From extends Single {\n type: Types.FROM;\n default: RDF.NamedNode[];\n named: RDF.NamedNode[];\n}\n\n/**\n * [Filter algebra operation](https://www.w3.org/TR/sparql11-query/#defn_evalFilter)\n */\nexport interface Filter extends Single {\n type: Types.FILTER;\n expression: Expression;\n}\n\n/**\n * [Graph algebra operation](https://www.w3.org/TR/sparql11-query/#defn_evalGraph)\n */\nexport interface Graph extends Single {\n type: Types.GRAPH;\n name: RDF.Variable | RDF.NamedNode;\n}\n\n// Also an expression\nexport interface BoundAggregate extends AggregateExpression {\n variable: RDF.Variable;\n}\n\n/**\n * [Group algebra operation](https://www.w3.org/TR/sparql11-query/#defn_evalGroup)\n */\nexport interface Group extends Single {\n type: Types.GROUP;\n variables: RDF.Variable[];\n aggregates: BoundAggregate[];\n}\n\n/**\n * Algebra operation representing the [Property path](https://www.w3.org/TR/sparql11-query/#propertypaths) inverse (`^`).\n * Having a specific [SPARQL definition](https://www.w3.org/TR/sparql11-query/#sparqlPropertyPaths)\n * This operation, besides basic mode is the reason SPARQL can contain literals in the subject position.\n */\nexport interface Inv extends BaseOperation {\n type: Types.INV;\n path: PropertyPathSymbol;\n}\n\n/**\n * [Join algebra operation](https://www.w3.org/TR/sparql11-query/#defn_evalJoin)\n */\nexport interface Join extends Multi {\n type: Types.JOIN;\n}\n\n/**\n * [Leftjoin algebra operation](https://www.w3.org/TR/sparql11-query/#defn_evalLeftJoin)\n */\nexport interface LeftJoin extends Double {\n type: Types.LEFT_JOIN;\n expression?: Expression;\n}\n\n/**\n * Algebra operation representing the property of a [Property path](https://www.w3.org/TR/sparql11-query/#propertypaths).\n * Property paths have a specific [SPARQL definition](https://www.w3.org/TR/sparql11-query/#sparqlPropertyPaths)\n * This operation, is just a way of saying to a Propery Path operation that nothing fancy is going on,\n * and it should just match this property.\n */\nexport interface Link extends BaseOperation {\n type: Types.LINK;\n iri: RDF.NamedNode;\n}\n\n/**\n * [Algebra operation minus](https://www.w3.org/TR/sparql11-query/#defn_algMinus)\n */\nexport interface Minus extends Double {\n type: Types.MINUS;\n /**\n * Since our graph translation is not really part of the spec,\n * there is a MINUS edge case we need to consider with GRAPH ?g.\n * If left and right of MINUS have disjoint variables, the whole left solution sequence must be kept.\n * If GRAPH is defined outside of an operator (e.g. MINUS), then the spec says that evaluation of the operators\n * must be done as union over the evaluation of that operator within each graph separately,\n * and that the variable of ?g must only be bound **after** that evaluation.\n * As such, MINUS will not be aware of this variable ?g, and the disjoint case will apply.\n * The code below adds metadata to the operation so that engines can special-case this.\n */\n graphScopeVar?: RDF.Variable;\n}\n\n/**\n * An empty operation.\n * For example used for the algebra representation of a query string that does not contain any operation.\n */\nexport interface Nop extends BaseOperation {\n type: Types.NOP;\n}\n\n/**\n * [NegatedPropertySet algebra operation](https://www.w3.org/TR/sparql11-query/#eval_negatedPropertySet) representing the [Property path](https://www.w3.org/TR/sparql11-query/#propertypaths) negated property set (`!`).\n * Property paths have a specific [SPARQL definition](https://www.w3.org/TR/sparql11-query/#sparqlPropertyPaths)\n */\nexport interface Nps extends BaseOperation {\n type: Types.NPS;\n iris: RDF.NamedNode[];\n}\n\n/**\n * [OneOrMorePath algebra operation](https://www.w3.org/TR/sparql11-query/#defn_evalOneOrMorePath) representing the [Property path](https://www.w3.org/TR/sparql11-query/#propertypaths) one or more (`+`).\n * Property paths have a specific [SPARQL definition](https://www.w3.org/TR/sparql11-query/#sparqlPropertyPaths)\n */\nexport interface OneOrMorePath extends BaseOperation {\n type: Types.ONE_OR_MORE_PATH;\n path: PropertyPathSymbol;\n}\n\n/**\n * [OrderBy algebra operation](https://www.w3.org/TR/sparql11-query/#defn_evalOrderBy)\n */\nexport interface OrderBy extends Single {\n type: Types.ORDER_BY;\n expressions: Expression[];\n}\n\nexport interface Path extends BaseOperation {\n type: Types.PATH;\n subject: RDF.Term;\n predicate: PropertyPathSymbol;\n object: RDF.Term;\n graph: RDF.Term;\n}\n\n/**\n * Simple BGP entry (triple)\n */\nexport interface Pattern extends BaseOperation, RDF.BaseQuad {\n type: Types.PATTERN;\n}\n\n/**\n * [Project algebra operation](https://www.w3.org/TR/sparql11-query/#defn_evalProject)\n */\nexport interface Project extends Single {\n type: Types.PROJECT;\n variables: RDF.Variable[];\n}\n\n/**\n * [Reduced algebra operation](https://www.w3.org/TR/sparql11-query/#defn_evalReduced)\n */\nexport interface Reduced extends Single {\n type: Types.REDUCED;\n}\n\n/**\n * Algebra operation representing the [Property path](https://www.w3.org/TR/sparql11-query/#propertypaths) sequence (`/`).\n * Property paths have a specific [SPARQL definition](https://www.w3.org/TR/sparql11-query/#sparqlPropertyPaths)\n */\nexport interface Seq extends Multi {\n type: Types.SEQ;\n input: PropertyPathSymbol[];\n}\n\nexport interface Service extends Single {\n type: Types.SERVICE;\n name: RDF.Variable | RDF.NamedNode;\n silent: boolean;\n}\n\n/**\n * [Slice algebra operation](https://www.w3.org/TR/sparql11-query/#defn_evalSlice)\n */\nexport interface Slice extends Single {\n type: Types.SLICE;\n start: number;\n length?: number;\n}\n\n/**\n * [Union algebra operation](https://www.w3.org/TR/sparql11-query/#defn_evalUnion)\n */\nexport interface Union extends Multi {\n type: Types.UNION;\n}\n\n/**\n * Algebra operation representing the [VALUES pattern](https://www.w3.org/TR/sparql11-query/#inline-data)\n * Has a list of variables that will be assigned.\n * The assignments are represented as a list of object containing bindings.\n * Each binging links the variable value to the appropriate Term for this binding.\n * Does not take any input.\n */\nexport interface Values extends BaseOperation {\n type: Types.VALUES;\n variables: RDF.Variable[];\n bindings: Record<string, RDF.Literal | RDF.NamedNode>[];\n}\n\n/**\n * [ZeroOrMore algebra operation](https://www.w3.org/TR/sparql11-query/#defn_evalZeroOrMorePath) representing the [Property path](https://www.w3.org/TR/sparql11-query/#propertypaths) zero or more (`*`).\n * The having specific [SPARQL definition](https://www.w3.org/TR/sparql11-query/#sparqlPropertyPaths)\n */\nexport interface ZeroOrMorePath extends BaseOperation {\n type: Types.ZERO_OR_MORE_PATH;\n path: PropertyPathSymbol;\n}\n\n/**\n * [ZeroOrOnePath algebra operation](https://www.w3.org/TR/sparql11-query/#defn_evalPP_ZeroOrOnePath) representing the [Property path](https://www.w3.org/TR/sparql11-query/#propertypaths) zero or one (`?`).\n * The having specific [SPARQL definition](https://www.w3.org/TR/sparql11-query/#sparqlPropertyPaths)\n */\nexport interface ZeroOrOnePath extends BaseOperation {\n type: Types.ZERO_OR_ONE_PATH;\n path: PropertyPathSymbol;\n}\n\n// ----------------------- UPDATE FUNCTIONS -----------------------\nexport interface CompositeUpdate extends BaseOperation {\n type: Types.COMPOSITE_UPDATE;\n updates: (Update | Nop)[];\n}\n\nexport interface DeleteInsert extends BaseOperation {\n type: Types.DELETE_INSERT;\n delete?: Pattern[];\n insert?: Pattern[];\n where?: Operation;\n}\n\nexport interface UpdateGraph extends BaseOperation {\n silent?: boolean;\n}\n\nexport interface Load extends UpdateGraph {\n type: Types.LOAD;\n source: RDF.NamedNode;\n destination?: RDF.NamedNode;\n}\n\nexport interface Clear extends UpdateGraph {\n type: Types.CLEAR;\n source: 'DEFAULT' | 'NAMED' | 'ALL' | RDF.NamedNode;\n}\n\nexport interface Create extends UpdateGraph {\n type: Types.CREATE;\n source: RDF.NamedNode;\n}\n\nexport interface Drop extends UpdateGraph {\n type: Types.DROP;\n source: 'DEFAULT' | 'NAMED' | 'ALL' | RDF.NamedNode;\n}\n\nexport interface UpdateGraphShortcut extends UpdateGraph {\n source: 'DEFAULT' | RDF.NamedNode;\n destination: 'DEFAULT' | RDF.NamedNode;\n}\n\nexport interface Add extends UpdateGraphShortcut {\n type: Types.ADD;\n}\n\nexport interface Move extends UpdateGraphShortcut {\n type: Types.MOVE;\n}\n\nexport interface Copy extends UpdateGraphShortcut {\n type: Types.COPY;\n}\n", "import type * as RDF from '@rdfjs/types';\nimport type { TransformContext, VisitContext } from '@traqula/core';\nimport { TransformerSubTyped } from '@traqula/core';\nimport type * as A from './algebra.js';\nimport { ExpressionTypes, Types } from './algebra.js';\n\nconst transformer = new TransformerSubTyped<A.Operation>({}, {\n // Optimization that causes search tree pruning -- do not step into RDF.Term objects, they are outside the algebra.\n [Types.PATTERN]: { ignoreKeys: new Set([ 'subject', 'predicate', 'object', 'graph' ]) } satisfies TransformContext,\n [Types.EXPRESSION]: { ignoreKeys: new Set([ 'name', 'term', 'wildcard', 'variable' ]) } satisfies VisitContext,\n [Types.DESCRIBE]: { ignoreKeys: new Set([ 'terms' ]) },\n [Types.EXTEND]: { ignoreKeys: new Set([ 'variable' ]) },\n [Types.FROM]: { ignoreKeys: new Set([ 'default', 'named' ]) },\n [Types.GRAPH]: { ignoreKeys: new Set([ 'name' ]) },\n [Types.GROUP]: { ignoreKeys: new Set([ 'variables' ]) },\n [Types.LINK]: { ignoreKeys: new Set([ 'iri' ]) },\n [Types.NPS]: { ignoreKeys: new Set([ 'iris' ]) },\n [Types.PATH]: { ignoreKeys: new Set([ 'subject', 'object', 'graph' ]) },\n [Types.PROJECT]: { ignoreKeys: new Set([ 'variables' ]) },\n [Types.SERVICE]: { ignoreKeys: new Set([ 'name' ]) },\n [Types.VALUES]: { ignoreKeys: new Set([ 'variables', 'bindings' ]) },\n [Types.LOAD]: { ignoreKeys: new Set([ 'source', 'destination' ]) },\n [Types.CLEAR]: { ignoreKeys: new Set([ 'source' ]) },\n [Types.CREATE]: { ignoreKeys: new Set([ 'source' ]) },\n [Types.DROP]: { ignoreKeys: new Set([ 'source' ]) },\n [Types.ADD]: { ignoreKeys: new Set([ 'source', 'destination' ]) },\n [Types.MOVE]: { ignoreKeys: new Set([ 'source', 'destination' ]) },\n [Types.COPY]: { ignoreKeys: new Set([ 'source', 'destination' ]) },\n});\n\n/**\n * Transform a single operation.\n * e.g. wrapping a distinct around the outermost project:\n * ```ts\n * mapOperation({\n * type: Algebra.Types.SLICE,\n * input: {\n * type: Algebra.Types.PROJECT,\n * input: {\n * type: Algebra.Types.JOIN,\n * input: [{ type: Algebra.Types.PROJECT }, { type: Algebra.Types.BGP }],\n * },\n * },\n * }, {\n * [Algebra.Types.PROJECT]: {\n * preVisitor: () => ({ continue: false }),\n * transform: projection => algebraFactory.createDistinct(projection),\n * },\n * });\n * const returns = {\n * type: Algebra.Types.SLICE,\n * input: {\n * type: Algebra.Types.DISTINCT,\n * input: {\n * type: Algebra.Types.PROJECT,\n * input: {\n * type: Algebra.Types.JOIN,\n * input: [{ type: Algebra.Types.PROJECT }, { type: Algebra.Types.BGP }],\n * },\n * },\n * },\n * };\n * ```\n * @param startObject the object from which we will start the transformation,\n * potentially visiting and transforming its descendants along the way.\n * @param nodeCallBacks a dictionary mapping the various operation types to objects optionally\n * containing preVisitor and transformer.\n * The preVisitor allows you to provide {@link TransformContext} for the current object,\n * altering how it will be transformed.\n * The transformer allows you to manipulate the copy of the current object,\n * and expects you to return the value that should take the current objects place.\n * @return the result of transforming the requested descendant operations (based on the preVisitor)\n * using a transformer that works its way back up from the descendant to the startObject.\n */\nexport const mapOperation = transformer.transformNode.bind(transformer);\n\n/**\n * Async variant of {@link mapOperation}, accepting promise-returning callbacks and returning a Promise.\n * The traversal stays strictly sequential (depth-first); see {@link TransformerTyped.transformNodeAsync}.\n */\nexport const mapOperationAsync = transformer.transformNodeAsync.bind(transformer);\n\n/**\n * Transform a single operation pre-order, the dual of {@link mapOperation}: an operation is mapped\n * _before_ its descendants, and we iterate into the result of that mapping.\n * This is what you want for an operation that has to travel deeper into the tree,\n * like a filter pushdown: the callback only describes how the filter swaps places with the operation right\n * below it, and the filters it sank into are mapped in turn.\n * e.g. sinking a filter into every branch of the unions below it:\n * ```ts\n * mapOperationPreOrder({\n * type: Algebra.Types.FILTER,\n * expression,\n * input: {\n * type: Algebra.Types.UNION,\n * input: [{ type: Algebra.Types.BGP }, { type: Algebra.Types.BGP }],\n * },\n * }, {\n * [Algebra.Types.FILTER]: (filter) => {\n * if (filter.input.type === Algebra.Types.UNION) {\n * return { newValue: algebraFactory.createUnion(\n * filter.input.input.map(branch => algebraFactory.createFilter(branch, filter.expression)),\n * false,\n * ) };\n * }\n * // Any other operation is a barrier for this filter\n * return { newValue: filter };\n * },\n * });\n * const returns = {\n * type: Algebra.Types.UNION,\n * input: [\n * { type: Algebra.Types.FILTER, expression, input: { type: Algebra.Types.BGP }},\n * { type: Algebra.Types.FILTER, expression, input: { type: Algebra.Types.BGP }},\n * ],\n * };\n * ```\n * Contrary to {@link mapOperation}, a callback returns the value taking the place of the operation together\n * with the {@link TransformContext} of that value, so there is no separate preVisitor. The descendants of\n * the operation it is called on are not mapped yet either - they are the operations of the input tree\n * itself - so changing the properties _of a descendant_ writes straight into that tree.\n * Both are documented in detail on {@link TransformerTyped.transformNodePreOrder}.\n * @param startObject the object from which we will start the transformation,\n * potentially visiting and transforming its descendants along the way.\n * @param nodeCallBacks a dictionary mapping the various operation types to a mapper.\n * The mapper allows you to manipulate the copy of the current operation, and expects you to return the\n * value that should take the current operations place, together with the context of that value.\n * That context steers how we iterate into the returned value.\n * @return the result of transforming the startObject and the descendants of its rewrites.\n */\nexport const mapOperationPreOrder = transformer.transformNodePreOrder.bind(transformer);\n\n/**\n * Async variant of {@link mapOperationPreOrder}, accepting promise-returning callbacks and returning a\n * Promise. The traversal stays strictly sequential (depth-first);\n * see {@link TransformerTyped.transformNodePreOrderAsync}.\n */\nexport const mapOperationPreOrderAsync = transformer.transformNodePreOrderAsync.bind(transformer);\n\n/**\n * Transform a single operation, similar to {@link mapOperation}, but also allowing you to target subTypes.\n * e.g. wrapping a distinct around the all project operations not contained in an aggregate expression\n * (invalid algebra anyway):\n * ```ts\n * mapOperationSub({\n * type: Algebra.Types.SLICE,\n * input: {\n * type: Algebra.Types.PROJECT,\n * input: {\n * type: Algebra.Types.JOIN,\n * input: [{\n * type: Algebra.Types.EXPRESSION,\n * subType: Algebra.ExpressionTypes.AGGREGATE,\n * input: { type: Algebra.Types.PROJECT },\n * }, { type: Algebra.Types.BGP }],\n * },\n * },\n * }, { [Algebra.Types.PROJECT]: {\n * transform: projection => algebraFactory.createDistinct(projection),\n * }}, { [Algebra.Types.EXPRESSION]: { [Algebra.ExpressionTypes.AGGREGATE]: {\n * preVisitor: () => ({ continue: false }),\n * }}});\n * const returns = {\n * type: Algebra.Types.SLICE,\n * input: {\n * type: Algebra.Types.DISTINCT,\n * input: {\n * type: Algebra.Types.PROJECT,\n * input: {\n * type: Algebra.Types.JOIN,\n * input: [{\n * type: Algebra.Types.EXPRESSION,\n * subType: Algebra.ExpressionTypes.AGGREGATE,\n * input: { type: Algebra.Types.PROJECT },\n * }, { type: Algebra.Types.BGP }],\n * },\n * },\n * },\n * };\n * ```\n * @param startObject the object from which we will start the transformation,\n * potentially visiting and transforming its descendants along the way.\n * @param nodeCallBacks a dictionary mapping the various operation types to objects optionally\n * containing preVisitor and transformer.\n * The preVisitor allows you to provide {@link TransformContext} for the current object,\n * altering how it will be transformed.\n * The transformer allows you to manipulate the copy of the current object,\n * and expects you to return the value that should take the current objects place.\n * @param nodeSpecificCallBacks Same as nodeCallBacks but using an additional level of indirection to\n * indicate the subType.\n * @return the result of transforming the requested descendant operations (based on the preVisitor)\n * using a transformer that works its way back up from the descendant to the startObject.\n */\nexport const mapOperationSub = transformer.transformNodeSpecific.bind(transformer);\n\n/**\n * Async variant of {@link mapOperationSub}, accepting promise-returning callbacks and returning a Promise.\n * The traversal stays strictly sequential (depth-first);\n * see {@link TransformerSubTyped.transformNodeSpecificAsync}.\n */\nexport const mapOperationSubAsync = transformer.transformNodeSpecificAsync.bind(transformer);\n\n/**\n * Transform a single operation pre-order, similar to {@link mapOperationPreOrder},\n * but also allowing you to target subTypes - it is to {@link mapOperationSub} what\n * {@link mapOperationPreOrder} is to {@link mapOperation}.\n * e.g. replacing every aggregate expression, and iterating into the operator expression it becomes:\n * ```ts\n * mapOperationSubPreOrder(\n * algebraFactory.createAggregateExpression('count', inner, false),\n * {},\n * { [Algebra.Types.EXPRESSION]: { [Algebra.ExpressionTypes.AGGREGATE]: copy =>\n * ({ newValue: algebraFactory.createOperatorExpression('!', [ copy.expression ]) }),\n * }},\n * );\n * ```\n * Just like {@link mapOperationSub}, a callback registered for the subType of an operation takes\n * precedence over the one registered for its type.\n * The same caveats as on {@link mapOperationPreOrder} apply: the callback returns the value taking the\n * place of the operation together with the {@link TransformContext} of that value, and the descendants\n * it is handed are those of the input tree.\n * They are documented in detail on {@link TransformerSubTyped.transformNodeSpecificPreOrder}.\n * @param startObject the object from which we will start the transformation,\n * potentially visiting and transforming its descendants along the way.\n * @param nodeCallBacks a dictionary mapping the various operation types to a mapper.\n * The mapper allows you to manipulate the copy of the current operation, and expects you to return the\n * value that should take the current operations place, together with the context of that value.\n * That context steers how we iterate into the returned value.\n * @param nodeSpecificCallBacks Same as nodeCallBacks but using an additional level of indirection to\n * indicate the subType.\n * @return the result of transforming the startObject and the descendants of its rewrites.\n */\nexport const mapOperationSubPreOrder = transformer.transformNodeSpecificPreOrder.bind(transformer);\n\n/**\n * Async variant of {@link mapOperationSubPreOrder}, accepting promise-returning callbacks and returning a\n * Promise. The traversal stays strictly sequential (depth-first);\n * see {@link TransformerSubTyped.transformNodeSpecificPreOrderAsync}.\n */\nexport const mapOperationSubPreOrderAsync = transformer.transformNodeSpecificPreOrderAsync.bind(transformer);\n\n/**\n * Similar to {@link mapOperation}, but only visiting instead of copying and transforming explicitly.\n * e.g.:\n * ```ts\n * visitOperation({\n * type: Algebra.Types.DISTINCT,\n * input: {\n * type: Algebra.Types.PROJECT,\n * input: { type: Algebra.Types.DISTINCT },\n * },\n * }, {\n * [Algebra.Types.DISTINCT]: { visitor: () => console.log('1') },\n * [Algebra.Types.PROJECT]: {\n * preVisitor: () => ({ continue: false }),\n * visitor: () => console.log('2'),\n * },\n * });\n * ```\n * Will first call the preVisitor on the project and notice it should not iterate on its descendants.\n * It then visits the project, and the outermost distinct, printing '21'.\n * The pre-visitor visits starting from the root, going deeper, while the actual visitor goes in reverse.\n * @param startObject the object from which we will start visiting,\n * potentially visiting its descendants along the way.\n * @param nodeCallBacks a dictionary mapping the various operation types to objects optionally\n * containing preVisitor and visitor.\n * The preVisitor allows you to provide {@link VisitContext} for the current object,\n * altering how it will be visited.\n * The visitor allows you to visit the object from deepest to the outermost object.\n * This is useful if you for example want to manipulate the objects you visit during your visits,\n * similar to {@link mapOperation}.\n */\nexport const visitOperation = transformer.visitNode.bind(transformer);\n\n/**\n * Async variant of {@link visitOperation}, accepting promise-returning callbacks and returning a Promise.\n * The traversal stays strictly sequential (depth-first); see {@link TransformerTyped.visitNodeAsync}.\n */\nexport const visitOperationAsync = transformer.visitNodeAsync.bind(transformer);\n\n/**\n * Visits an object and it's descendants, similar to {@link visitOperation},\n * but also allowing you to target subTypes. e.g.:\n * e.g.:\n * ```ts\n * visitOperationSub({\n * type: Algebra.Types.DISTINCT,\n * input: {\n * type: Algebra.Types.DISTINCT,\n * subType: 'special',\n * },\n * }, {\n * [Algebra.Types.DISTINCT]: {\n * visitor: () => console.log('1'),\n * preVisitor: () => {\n * console.log('2');\n * return {};\n * },\n * },\n * }, {\n * [Algebra.Types.DISTINCT]: { special: {\n * visitor: () => console.log('3'),\n * }},\n * });\n * ```\n * Will call the preVisitor on the outer distinct, then the visitor of the special distinct,\n * followed by the visiting the outer distinct, printing '231'.\n * The pre-visitor visits starting from the root, going deeper, while the actual visitor goes in reverse.\n * @param startObject the object from which we will start visiting,\n * potentially visiting its descendants along the way.\n * @param nodeCallBacks a dictionary mapping the various operation types to objects optionally\n * containing preVisitor and visitor.\n * The preVisitor allows you to provide {@link VisitContext} for the current object,\n * altering how it will be visited.\n * The visitor allows you to visit the object from deepest to the outermost object.\n * This is useful if you for example want to manipulate the objects you visit during your visits,\n * similar to {@link mapOperation}.\n * @param nodeSpecificCallBacks Same as nodeCallBacks but using an additional level of indirection to\n * indicate the subType.\n */\nexport const visitOperationSub = transformer.visitNodeSpecific.bind(transformer);\n\n/**\n * Async variant of {@link visitOperationSub}, accepting promise-returning callbacks and returning a Promise.\n * The traversal stays strictly sequential (depth-first);\n * see {@link TransformerSubTyped.visitNodeSpecificAsync}.\n */\nexport const visitOperationSubAsync = transformer.visitNodeSpecificAsync.bind(transformer);\n\n/**\n * Absolute IRIs start with a scheme - [RFC 3986, section 3.1](https://www.rfc-editor.org/rfc/rfc3986#section-3.1)\n */\nconst absoluteIriRegex = /^[a-z][\\d+.a-z-]*:/iu;\n\n/**\n * [RFC 3986, appendix B](https://www.rfc-editor.org/rfc/rfc3986#appendix-B). Matches every string.\n */\nconst iriComponentsRegex = /^(?:([^:/?#]+):)?(?:\\/\\/([^/?#]*))?([^?#]*)(?:\\?([^#]*))?(?:#(.*))?$/su;\n\n/**\n * {@link iriComponentsRegex} without the scheme, so an invalid relative IRI like '1a:b' is kept whole as a path.\n */\nconst relativeIriComponentsRegex = /^(?:\\/\\/([^/?#]*))?([^?#]*)(?:\\?([^#]*))?(?:#(.*))?$/su;\n\n/**\n * [RFC 3986, section 5.2.4](https://www.rfc-editor.org/rfc/rfc3986#section-5.2.4)\n */\nfunction removeDotSegments(path: string): string {\n let input = path;\n let output = '';\n const removeLastOutputSegment = (): void => {\n const pos = output.lastIndexOf('/');\n output = output.slice(0, pos > 0 ? pos : 0);\n };\n while (input.length > 0) {\n if (input.startsWith('../')) {\n input = input.slice(3);\n } else if (input.startsWith('./') || input.startsWith('/./')) {\n input = input.slice(2);\n } else if (input === '/.') {\n input = '/';\n } else if (input.startsWith('/../')) {\n input = input.slice(3);\n removeLastOutputSegment();\n } else if (input === '/..') {\n input = '/';\n removeLastOutputSegment();\n } else if (input === '.' || input === '..') {\n input = '';\n } else {\n // Move the first path segment (including its leading '/', if any) to the output\n const segmentEnd = input.indexOf('/', 1);\n const segment = segmentEnd === -1 ? input : input.slice(0, segmentEnd);\n output += segment;\n input = input.slice(segment.length);\n }\n }\n return output;\n}\n\n/**\n * Resolves relative IRIs against the base IRI as described in the [Syntax for IRIs](https://www.w3.org/TR/sparql12-query/#QSynIRI),\n * using [RFC 3986, section 5.2](https://www.rfc-editor.org/rfc/rfc3986#section-5.2) without normalization.\n * Absolute IRIs are returned unmodified.\n */\nexport function resolveIRI(iri: string, base: string | undefined): string {\n if (absoluteIriRegex.test(iri)) {\n return iri;\n }\n if (!base) {\n throw new Error(`Cannot resolve relative IRI ${iri} because no base IRI was set.`);\n }\n const [ , relativeAuthority, relativePath, relativeQuery, relativeFragment ] =\n relativeIriComponentsRegex.exec(iri)!;\n const [ , baseScheme, baseAuthority, basePath, baseQuery ] = iriComponentsRegex.exec(base)!;\n\n // Transform references - https://www.rfc-editor.org/rfc/rfc3986#section-5.2.2\n let resolvedAuthority: string | undefined;\n let resolvedPath: string;\n let resolvedQuery: string | undefined;\n if (relativeAuthority === undefined) {\n if (relativePath === '') {\n resolvedPath = basePath;\n resolvedQuery = relativeQuery ?? baseQuery;\n } else {\n if (relativePath.startsWith('/')) {\n resolvedPath = removeDotSegments(relativePath);\n } else if (baseAuthority !== undefined && basePath === '') {\n // Merge paths - https://www.rfc-editor.org/rfc/rfc3986#section-5.2.3\n resolvedPath = removeDotSegments(`/${relativePath}`);\n } else {\n resolvedPath = removeDotSegments(basePath.slice(0, basePath.lastIndexOf('/') + 1) + relativePath);\n }\n resolvedQuery = relativeQuery;\n }\n resolvedAuthority = baseAuthority;\n } else {\n resolvedAuthority = relativeAuthority;\n resolvedPath = removeDotSegments(relativePath);\n resolvedQuery = relativeQuery;\n }\n\n // Component recomposition - https://www.rfc-editor.org/rfc/rfc3986#section-5.3\n // Like the RFC, a path starting with '//' is not guarded against: '..//g' against 'urn:x/y' gives 'urn://g'.\n let result = baseScheme === undefined ? '' : `${baseScheme}:`;\n if (resolvedAuthority !== undefined) {\n result += `//${resolvedAuthority}`;\n }\n result += resolvedPath;\n if (resolvedQuery !== undefined) {\n result += `?${resolvedQuery}`;\n }\n if (relativeFragment !== undefined) {\n result += `#${relativeFragment}`;\n }\n return result;\n}\n\n// TODO: find a cleaner way\n/**\n * Outputs a JSON object corresponding to the input algebra-like.\n */\nexport function objectify(algebra: any): any {\n if (algebra.termType) {\n if (algebra.termType === 'Quad') {\n return {\n type: 'pattern',\n termType: 'Quad',\n subject: objectify(algebra.subject),\n predicate: objectify(algebra.predicate),\n object: objectify(algebra.object),\n graph: objectify(algebra.graph),\n };\n }\n const result: any = { termType: algebra.termType, value: algebra.value };\n if (algebra.language) {\n result.language = algebra.language;\n }\n if (algebra.datatype) {\n result.datatype = objectify(algebra.datatype);\n }\n return result;\n }\n if (Array.isArray(algebra)) {\n return algebra.map(e => objectify(e));\n }\n if (algebra === Object(algebra)) {\n const result: any = {};\n for (const key of Object.keys(algebra)) {\n result[key] = objectify(algebra[key]);\n }\n return result;\n }\n return algebra;\n}\n\n/**\n * Detects all [in-scope variables](https://www.w3.org/TR/sparql12-query/#variableScope).\n * In practice this means iterating through the entire algebra tree, finding all variables,\n * and stopping at every operation that hides the variables of its input:\n * - PROJECT only exposes the variables it projects.\n * - GROUP only exposes its keys and the variables its aggregates are bound to.\n * - The right-hand side of a MINUS is not in scope, only the left-hand side is.\n * - The pattern of an `(NOT) EXISTS` is not in scope\n * (\"use of a variable in FILTER or in MINUS does not cause the variable to be in-scope\n * outside of those forms\").\n * - The templates of a CONSTRUCT or a DELETE/INSERT consume solution mappings,\n * they do not produce them, so their variables are not in scope either.\n * @param {Operation} op - Input algebra tree.\n * @param visitor the visitor to be used to traverse the various nodes.\n * Allows you to provide a visitor with different default preVisitor cotexts.\n * @returns {RDF.Variable[]} - List of unique in-scope variables.\n */\nexport function inScopeVariables(\n op: A.BaseOperation,\n visitor: typeof visitOperation = visitOperation,\n): RDF.Variable[] {\n const variables: Record<string, RDF.Variable> = {};\n\n function addVariable(v: RDF.Variable): void {\n variables[v.value] = v;\n }\n\n function recurseTerm(quad: RDF.BaseQuad): void {\n // Subject\n if (quad.subject.termType === 'Variable') {\n addVariable(quad.subject);\n } else if (quad.subject.termType === 'Quad') {\n recurseTerm(quad.subject);\n }\n // Predicate\n if (quad.predicate.termType === 'Variable') {\n addVariable(quad.predicate);\n } else if (quad.predicate.termType === 'Quad') {\n recurseTerm(quad.predicate);\n }\n // Object\n if (quad.object.termType === 'Variable') {\n addVariable(quad.object);\n } else if (quad.object.termType === 'Quad') {\n recurseTerm(quad.object);\n }\n\n // Graph\n if (quad.graph.termType === 'Variable') {\n addVariable(quad.graph);\n }\n if (quad.graph.termType === 'Quad') {\n recurseTerm(quad.graph);\n }\n }\n\n function visitingRecursion(curOp: A.BaseOperation): void {\n // https://www.w3.org/TR/sparql11-query/#variableScope\n visitor(curOp, {\n [Types.CONSTRUCT]: {\n // The variables of the template are consumed, they are not in scope.\n preVisitor: () => ({ ignoreKeys: new Set([ 'template' ]) }),\n },\n [Types.DELETE_INSERT]: {\n // The variables of the templates are consumed, they are not in scope.\n preVisitor: () => ({ ignoreKeys: new Set([ 'delete', 'insert' ]) }),\n },\n [Types.EXPRESSION]: {\n // Variables only used within an expression are not in scope,\n // this includes the pattern of an (NOT) EXISTS.\n preVisitor: (op: A.Expression) =>\n op.subType === ExpressionTypes.EXISTENCE ? { continue: false } : {},\n visitor: (op: A.Expression & { variable?: RDF.Variable }) => {\n if (op.subType === ExpressionTypes.AGGREGATE && op.variable) {\n addVariable(op.variable);\n }\n },\n },\n [Types.EXTEND]: { visitor: op =>\n addVariable(op.variable),\n },\n [Types.GRAPH]: { visitor: (op) => {\n if (op.name.termType === 'Variable') {\n addVariable(op.name);\n }\n } },\n [Types.GROUP]: {\n // A group only outputs its keys and the variables its aggregates are bound to,\n // the variables of its input are not visible above it.\n preVisitor: () => ({ ignoreKeys: new Set([ 'variables', 'input' ]) }),\n visitor: (op) => {\n for (const v of op.variables) {\n addVariable(v);\n }\n },\n },\n [Types.PATH]: { visitor: (op) => {\n // Subject\n if (op.subject.termType === 'Variable') {\n addVariable(op.subject);\n } else if (op.subject.termType === 'Quad') {\n recurseTerm(op.subject);\n }\n // Predicate\n if (op.object.termType === 'Variable') {\n addVariable(op.object);\n } else if (op.object.termType === 'Quad') {\n recurseTerm(op.object);\n }\n // Object\n if (op.graph.termType === 'Variable') {\n addVariable(op.graph);\n } else if (op.graph.termType === 'Quad') {\n recurseTerm(op.graph);\n }\n } },\n [Types.PATTERN]: { visitor: op => recurseTerm(op) },\n [Types.PROJECT]: {\n preVisitor: () => ({ continue: false }),\n visitor: (op) => {\n for (const v of op.variables) {\n addVariable(v);\n }\n },\n },\n [Types.SERVICE]: { visitor: (op) => {\n if (op.name.termType === 'Variable') {\n addVariable(op.name);\n }\n } },\n [Types.VALUES]: { visitor: (op) => {\n for (const v of op.variables) {\n addVariable(v);\n }\n } },\n [Types.MINUS]: {\n preVisitor: () => ({ continue: false }),\n visitor: (op) => {\n // Cannot fully visit, only the left hand side is scoped\n visitingRecursion(op.input[0]);\n },\n },\n });\n }\n visitingRecursion(op);\n\n return Object.values(variables);\n}\n", "import type * as RDF from '@rdfjs/types';\nimport {\n findPatternBoundedVars,\n lex,\n} from '@traqula/rules-sparql-1-1';\nimport type {\n ContextDefinition,\n DatasetClauses,\n Path,\n PatternValues,\n SparqlQuery,\n Term,\n TripleCollection,\n TripleNesting,\n TermIri,\n TermBlank,\n TermLiteral,\n TermVariable,\n} from '@traqula/rules-sparql-1-1';\nimport * as Algebra from '../algebra.js';\nimport * as util from '../util.js';\nimport type { AlgebraIndir } from './core.js';\n\nconst pnLocalEscGlobal = new RegExp(lex.patterns.pnLocalEscPattern.source, 'gu');\n\nexport const translateNamed: AlgebraIndir<'translateNamed', RDF.NamedNode, [TermIri]> = {\n name: 'translateNamed',\n fun: () => ({ astFactory: F, currentPrefixes, currentBase, dataFactory }, term) => {\n let fullIri: string = term.value;\n if (F.isTermNamedPrefixed(term)) {\n const expanded = currentPrefixes[term.prefix];\n if (!expanded) {\n throw new Error(`Unknown prefix: ${term.prefix}`);\n }\n // Remove the backslash of PN_LOCAL_ESC escapes, percent-encodings (PLX) are kept as is.\n // \"The RDF string of the IRI is formed by unescaping the reserved characters in the second argument, PN_LOCAL,\n // and concatenating this onto the namespace.\" - https://www.w3.org/TR/rdf12-turtle/#sec-parsing-terms\n // Percent-encodings: \"These sequences are not decoded during processing.\"\n // - https://www.w3.org/TR/sparql12-query/#sec-escapes\n fullIri = expanded + term.value.replaceAll(pnLocalEscGlobal, escaped => escaped.slice(1));\n }\n return dataFactory.namedNode(util.resolveIRI(fullIri, currentBase));\n },\n};\n\nexport type AstToRdfTerm<T extends Term> = T extends TermVariable ? RDF.Variable :\n T extends TermBlank ? RDF.BlankNode :\n T extends TermLiteral ? RDF.Literal :\n T extends TermIri ? RDF.NamedNode : never;\n\nexport const translateTerm: AlgebraIndir<'translateTerm', RDF.Term, [Term]> = {\n name: 'translateTerm',\n fun: ({ SUBRULE }) => ({ astFactory: F, dataFactory }, term) => {\n if (F.isTermNamed(term)) {\n return SUBRULE(translateNamed, term);\n }\n if (F.isTermBlank(term)) {\n return dataFactory.blankNode(term.label);\n }\n if (F.isTermVariable(term)) {\n return dataFactory.variable(term.value);\n }\n if (F.isTermLiteral(term)) {\n const langOrIri = typeof term.langOrIri === 'object' ?\n SUBRULE(translateNamed, term.langOrIri) :\n term.langOrIri;\n return dataFactory.literal(term.value, langOrIri);\n }\n throw new Error(`Unexpected term: ${JSON.stringify(term)}`);\n },\n};\n\nexport const registerContextDefinitions: AlgebraIndir<'registerContextDefinitions', void, [ContextDefinition[]]> = {\n name: 'registerContextDefinitions',\n fun: ({ SUBRULE }) => (c, definitions) => {\n const { astFactory: F, currentPrefixes } = c;\n for (const def of definitions) {\n if (F.isContextDefinitionPrefix(def)) {\n currentPrefixes[def.key] = SUBRULE(translateTerm, def.value).value;\n }\n if (F.isContextDefinitionBase(def)) {\n c.currentBase = SUBRULE(translateTerm, def.value).value;\n }\n }\n },\n};\n\nexport const translateInlineData: AlgebraIndir<'translateInlineData', Algebra.Values, [PatternValues]> = {\n name: 'translateInlineData',\n fun: ({ SUBRULE }) => ({ algebraFactory: AF }, values) => {\n const variables = values.variables.map(x => <AstToRdfTerm<typeof x>> SUBRULE(translateTerm, x));\n const bindings = values.values.map((binding) => {\n const map: Record<string, RDF.NamedNode | RDF.Literal> = {};\n for (const [ key, value ] of Object.entries(binding)) {\n if (value !== undefined) {\n map[key] = <RDF.NamedNode | RDF.Literal> SUBRULE(translateTerm, value);\n }\n }\n return map;\n });\n return AF.createValues(variables, bindings);\n },\n};\n\nexport const translateDatasetClause:\nAlgebraIndir<'translateDatasetClause', { default: RDF.NamedNode[]; named: RDF.NamedNode[] }, [DatasetClauses]> = {\n name: 'translateDatasetClause',\n fun: ({ SUBRULE }) => (_, dataset) => ({\n default: dataset.clauses.filter(x => x.clauseType === 'default')\n .map(x => SUBRULE(translateNamed, x.value)),\n named: dataset.clauses.filter(x => x.clauseType === 'named')\n .map(x => SUBRULE(translateNamed, x.value)),\n }),\n};\n\nexport const translateBlankNodesToVariables:\nAlgebraIndir<'translateBlankNodesToVariables', Algebra.Operation, [Algebra.Operation]> = {\n name: 'translateBlankNodesToVariables',\n fun: ({ SUBRULE }) => ({ algebraFactory: AF, variables }, res) => {\n const blankToVariableMapping: Record<string, RDF.Variable> = {};\n const variablesRaw: Set<string> = new Set(variables);\n\n function uniqueVar(label: string): RDF.Variable {\n let counter = 0;\n let labelLoop = label;\n while (variables.has(labelLoop)) {\n labelLoop = `${label}${counter++}`;\n }\n return AF.dataFactory.variable!(labelLoop);\n };\n\n function blankToVariable(term: RDF.Term): RDF.Term {\n if (term.termType === 'BlankNode') {\n let variable = blankToVariableMapping[term.value];\n if (!variable) {\n variable = uniqueVar(term.value);\n variablesRaw.add(variable.value);\n blankToVariableMapping[term.value] = variable;\n }\n return variable;\n }\n if (term.termType === 'Quad') {\n return AF.dataFactory.quad(\n blankToVariable(term.subject),\n blankToVariable(term.predicate),\n blankToVariable(term.object),\n blankToVariable(term.graph),\n );\n }\n return term;\n }\n\n return util.mapOperation<'unsafe', typeof res>(res, {\n [Algebra.Types.PATH]: {\n preVisitor: () => ({ continue: false }),\n transform: pathOp => AF.createPath(\n blankToVariable(pathOp.subject),\n pathOp.predicate,\n blankToVariable(pathOp.object),\n blankToVariable(pathOp.graph),\n ),\n },\n [Algebra.Types.PATTERN]: {\n preVisitor: () => ({ continue: false }),\n transform: patternOp => AF.createPattern(\n blankToVariable(patternOp.subject),\n blankToVariable(patternOp.predicate),\n blankToVariable(patternOp.object),\n blankToVariable(patternOp.graph),\n ),\n },\n [Algebra.Types.CONSTRUCT]: {\n preVisitor: () => ({ continue: false }),\n // Blank nodes in CONSTRUCT templates must be maintained\n transform: constructOp =>\n AF.createConstruct(SUBRULE(translateBlankNodesToVariables, constructOp.input), constructOp.template),\n },\n [Algebra.Types.DELETE_INSERT]: {\n preVisitor: () => ({ continue: false }),\n transform: delInsOp =>\n // Make sure blank nodes remain in the INSERT block, but do update the WHERE block\n AF.createDeleteInsert(\n delInsOp.delete,\n delInsOp.insert,\n delInsOp.where && SUBRULE(translateBlankNodesToVariables, delInsOp.where),\n )\n ,\n },\n });\n },\n};\n\n/**\n * Will be used to make sure new variables don't overlap\n */\nexport const findAllVariables: AlgebraIndir<'findAllVariables', void, [object]> = {\n name: 'findAllVariables',\n fun: () => ({ transformer, variables }, thingy) => {\n transformer.visitNodeSpecific(thingy, {}, { term: { variable: { visitor: (_var) => {\n variables.add(_var.value);\n } }}});\n },\n};\n\n/**\n * 18.2.1\n */\nexport const inScopeVariables:\nAlgebraIndir<'inScopeVariables', Set<string>, [SparqlQuery | TripleNesting | TripleCollection | Path | Term]> = {\n name: 'inScopeVariables',\n fun: () => (_, thingy) => {\n const vars = new Set<string>();\n findPatternBoundedVars(thingy, vars);\n return vars;\n },\n};\n\nexport const generateFreshVar: AlgebraIndir<'generateFreshVar', RDF.Variable, []> = {\n name: 'generateFreshVar',\n fun: () => (c) => {\n let newVar = `var${c.varCount++}`;\n while (c.variables.has(newVar)) {\n newVar = `var${c.varCount++}`;\n }\n c.variables.add(newVar);\n return c.dataFactory.variable(newVar);\n },\n};\n", "import type * as RDF from '@rdfjs/types';\nimport type { IndirDef } from '@traqula/core';\nimport type { PathPure } from '@traqula/rules-sparql-1-1';\nimport { AstFactory, AstTransformer } from '@traqula/rules-sparql-1-1';\nimport { DataFactory } from 'rdf-data-factory';\nimport * as Algebra from '../algebra.js';\nimport { AlgebraFactory } from '../algebraFactory.js';\n\nexport interface AlgebraContext {\n variables: Set<string>;\n varCount: number;\n useQuads: boolean;\n algebraFactory: AlgebraFactory;\n transformer: AstTransformer;\n astFactory: AstFactory;\n dataFactory: RDF.DataFactory<RDF.BaseQuad> & { variable: Function };\n currentBase: string | undefined;\n currentPrefixes: Record<string, string>;\n}\n\nexport interface ContextConfigs {\n dataFactory?: RDF.DataFactory<RDF.BaseQuad> & { variable: Function };\n quads?: boolean;\n prefixes?: Record<string, string>;\n baseIRI?: string;\n blankToVariable?: boolean;\n}\nexport function createAlgebraContext(config: ContextConfigs): AlgebraContext {\n const dataFactory = config.dataFactory ?? new DataFactory<RDF.BaseQuad>();\n return {\n variables: new Set<string>(),\n varCount: 0,\n useQuads: false,\n transformer: new AstTransformer(),\n astFactory: new AstFactory(),\n dataFactory,\n algebraFactory: new AlgebraFactory(dataFactory),\n currentBase: config.baseIRI,\n currentPrefixes: Object.assign(Object.create(null), config.prefixes),\n };\n}\n\nexport type AlgebraIndir<Name extends string, Ret, Arg extends any[]> = IndirDef<AlgebraContext, Name, Ret, Arg>;\n\nexport interface FlattenedTriple {\n subject: RDF.Term;\n predicate: RDF.Term | PathPure;\n object: RDF.Term;\n}\n\nexport const types = Algebra.Types;\nexport const typeVals = Object.values(types);\n\nexport function isTerm(term: any): term is RDF.Term {\n return Boolean(term?.termType);\n}\n\n// This is not completely correct but this way we also catch SPARQL.js triples\nexport function isTriple(triple: any): triple is RDF.Quad {\n return triple.subject && triple.predicate && triple.object;\n}\n\nexport function isVariable(term: RDF.Term): term is RDF.Variable {\n return term?.termType === 'Variable';\n}\n", "import type * as RDF from '@rdfjs/types';\nimport { DataFactory } from 'rdf-data-factory';\nimport { stringToTerm } from 'rdf-string';\nimport * as A from './algebra.js';\nimport type { PropertyPathSymbol, Update } from './algebra.js';\n\nfunction known<T extends A.Operation = A.Operation>(x: A.BaseOperation): T;\nfunction known<T extends A.Operation = A.Operation>(x: A.BaseOperation[]): T[];\nfunction known<T extends A.Operation = A.Operation>(\n x: A.BaseOperation | A.BaseOperation[],\n): typeof x extends any[] ? T[] : T {\n return <any> x;\n}\n\n/**\n * Factory for creating SPARQL Algebra operation objects.\n * Provides methods for every algebra operation type defined in\n * [SPARQL 1.1 Algebra](https://www.w3.org/TR/sparql11-query/#sparqlAlgebra).\n */\nexport class AlgebraFactory {\n public dataFactory: RDF.DataFactory<RDF.BaseQuad, RDF.BaseQuad>;\n public stringType: RDF.NamedNode;\n\n public constructor(dataFactory?: RDF.DataFactory<RDF.BaseQuad>) {\n this.dataFactory = dataFactory ?? new DataFactory();\n this.stringType = <RDF.NamedNode> this.createTerm('http://www.w3.org/2001/XMLSchema#string');\n }\n\n public createAlt(input: A.BaseOperation[], flatten = true): A.Alt {\n return this.flattenMulti({\n type: A.Types.ALT,\n input: <PropertyPathSymbol[]> input,\n }, flatten);\n }\n\n public createAsk(input: A.BaseOperation): A.Ask {\n return { type: A.Types.ASK, input: known(input) };\n }\n\n public createBoundAggregate(\n variable: RDF.Variable,\n aggregate: string,\n expression: A.BaseExpression,\n distinct: boolean,\n separator?: string,\n ): A.BoundAggregate {\n const result = <A.BoundAggregate> this.createAggregateExpression(\n aggregate,\n known<A.Expression>(expression),\n distinct,\n separator,\n );\n result.variable = variable;\n return result;\n }\n\n public createBgp(patterns: A.Pattern[]): A.Bgp {\n return { type: A.Types.BGP, patterns };\n }\n\n public createConstruct(input: A.BaseOperation, template: A.Pattern[]): A.Construct {\n return { type: A.Types.CONSTRUCT, input: known(input), template };\n }\n\n public createDescribe(input: A.BaseOperation, terms: (RDF.Variable | RDF.NamedNode)[]): A.Describe {\n return { type: A.Types.DESCRIBE, input: known(input), terms };\n }\n\n public createDistinct(input: A.BaseOperation): A.Distinct {\n return { type: A.Types.DISTINCT, input: known(input) };\n }\n\n public createExtend(\n input: A.BaseOperation,\n variable: RDF.Variable,\n expression: A.BaseExpression,\n ): A.Extend {\n return { type: A.Types.EXTEND, input: known(input), variable, expression: known(expression) };\n }\n\n public createFrom(input: A.BaseOperation, def: RDF.NamedNode[], named: RDF.NamedNode[]): A.From {\n return { type: A.Types.FROM, input: known(input), default: def, named };\n }\n\n public createFilter(input: A.BaseOperation, expression: A.BaseExpression): A.Filter {\n return { type: A.Types.FILTER, input: known(input), expression: known(expression) };\n }\n\n public createGraph(input: A.BaseOperation, name: RDF.Variable | RDF.NamedNode): A.Graph {\n return { type: A.Types.GRAPH, input: known(input), name };\n }\n\n public createGroup(\n input: A.BaseOperation,\n variables: RDF.Variable[],\n aggregates: A.BaseOperation[],\n ): A.Group {\n return { type: A.Types.GROUP, input: known(input), variables, aggregates: known(aggregates) };\n }\n\n public createInv(path: A.BaseOperation): A.Inv {\n return { type: A.Types.INV, path: <PropertyPathSymbol> path };\n }\n\n public createJoin(input: A.BaseOperation[], flatten = true): A.Join {\n return this.flattenMulti({ type: A.Types.JOIN, input: known(input) }, flatten);\n }\n\n public createLeftJoin(\n left: A.BaseOperation,\n right: A.BaseOperation,\n expression?: A.BaseExpression,\n ): A.LeftJoin {\n if (expression) {\n return {\n type: A.Types.LEFT_JOIN,\n input: [ known(left), known(right) ],\n expression: known<A.Expression>(expression),\n };\n }\n return { type: A.Types.LEFT_JOIN, input: [ known(left), known(right) ]};\n }\n\n public createLink(iri: RDF.NamedNode): A.Link {\n return { type: A.Types.LINK, iri };\n }\n\n public createMinus(left: A.BaseOperation, right: A.BaseOperation): A.Minus {\n return { type: A.Types.MINUS, input: [ known(left), known(right) ]};\n }\n\n public createNop(): A.Nop {\n return { type: A.Types.NOP };\n }\n\n public createNps(iris: RDF.NamedNode[]): A.Nps {\n return { type: A.Types.NPS, iris };\n }\n\n public createOneOrMorePath(path: A.BaseOperation): A.OneOrMorePath {\n return { type: A.Types.ONE_OR_MORE_PATH, path: <PropertyPathSymbol> path };\n }\n\n public createOrderBy(input: A.BaseOperation, expressions: A.BaseExpression[]): A.OrderBy {\n return { type: A.Types.ORDER_BY, input: known(input), expressions: known(expressions) };\n }\n\n public createPath(\n subject: RDF.Term,\n predicate: A.BaseOperation,\n object: RDF.Term,\n graph?: RDF.Term,\n ): A.Path {\n if (graph) {\n return { type: A.Types.PATH, subject, predicate: <PropertyPathSymbol> predicate, object, graph };\n }\n return {\n type: A.Types.PATH,\n subject,\n predicate: <PropertyPathSymbol> predicate,\n object,\n graph: this.dataFactory.defaultGraph(),\n };\n }\n\n public createPattern(subject: RDF.Term, predicate: RDF.Term, object: RDF.Term, graph?: RDF.Term): A.Pattern {\n const pattern = <A.Pattern> this.dataFactory.quad(subject, predicate, object, graph);\n pattern.type = A.Types.PATTERN;\n return pattern;\n }\n\n /**\n * Providing no variables is interpreted as a `SELECT *`.\n */\n public createProject(input: A.BaseOperation, variables: RDF.Variable[]): A.Project {\n return { type: A.Types.PROJECT, input: known(input), variables };\n }\n\n public createReduced(input: A.BaseOperation): A.Reduced {\n return { type: A.Types.REDUCED, input: known(input) };\n }\n\n public createSeq(input: A.BaseOperation[], flatten = true): A.Seq {\n return this.flattenMulti({\n type: A.Types.SEQ,\n input: <PropertyPathSymbol[]> input,\n }, flatten);\n }\n\n public createService(input: A.BaseOperation, name: RDF.NamedNode | RDF.Variable, silent?: boolean): A.Service {\n return { type: A.Types.SERVICE, input: known(input), name, silent: Boolean(silent) };\n }\n\n public createSlice(input: A.BaseOperation, start: number, length?: number): A.Slice {\n start = start || 0;\n if (length !== undefined) {\n return { type: A.Types.SLICE, input: known(input), start, length };\n }\n return { type: A.Types.SLICE, input: known(input), start };\n }\n\n public createUnion(input: A.BaseOperation[], flatten = true): A.Union {\n return this.flattenMulti({ type: A.Types.UNION, input: known(input) }, flatten);\n }\n\n public createValues(variables: RDF.Variable[], bindings: Record<string, RDF.Literal | RDF.NamedNode>[]): A.Values {\n return { type: A.Types.VALUES, variables, bindings };\n }\n\n public createZeroOrMorePath(path: A.BaseOperation): A.ZeroOrMorePath {\n return {\n type: A.Types.ZERO_OR_MORE_PATH,\n path: <PropertyPathSymbol> path,\n };\n }\n\n public createZeroOrOnePath(path: A.BaseOperation): A.ZeroOrOnePath {\n return {\n type: A.Types.ZERO_OR_ONE_PATH,\n path: <PropertyPathSymbol> path,\n };\n }\n\n public createAggregateExpression(\n aggregator: string,\n expression: A.BaseExpression,\n distinct: boolean,\n separator?: string,\n ): A.AggregateExpression {\n if (separator !== undefined) {\n return {\n type: A.Types.EXPRESSION,\n subType: A.ExpressionTypes.AGGREGATE,\n aggregator: <any> aggregator,\n expression: known(expression),\n separator,\n distinct,\n };\n }\n return {\n type: A.Types.EXPRESSION,\n subType: A.ExpressionTypes.AGGREGATE,\n aggregator: <any> aggregator,\n expression: known(expression),\n distinct,\n };\n }\n\n public createExistenceExpression(not: boolean, input: A.BaseOperation): A.ExistenceExpression {\n return { type: A.Types.EXPRESSION, subType: A.ExpressionTypes.EXISTENCE, not, input: known(input) };\n }\n\n public createNamedExpression(name: RDF.NamedNode, args: A.BaseExpression[]): A.NamedExpression {\n return { type: A.Types.EXPRESSION, subType: A.ExpressionTypes.NAMED, name, args: known(args) };\n }\n\n public createOperatorExpression(operator: string, args: A.BaseExpression[]): A.OperatorExpression {\n return { type: A.Types.EXPRESSION, subType: A.ExpressionTypes.OPERATOR, operator, args: known(args) };\n }\n\n public createTermExpression(term: RDF.Term): A.TermExpression {\n return { type: A.Types.EXPRESSION, subType: A.ExpressionTypes.TERM, term };\n }\n\n public createWildcardExpression(): A.WildcardExpression {\n return { type: A.Types.EXPRESSION, subType: A.ExpressionTypes.WILDCARD, wildcard: { type: 'wildcard' }};\n }\n\n public createTerm(str: string): RDF.Term {\n if (str.startsWith('$')) {\n str = str.replace('$', '?');\n }\n return stringToTerm(str, this.dataFactory);\n }\n\n // Update functions\n public createCompositeUpdate(updates: A.BaseOperation[]): A.CompositeUpdate {\n return { type: A.Types.COMPOSITE_UPDATE, updates: <Update[]> updates };\n }\n\n public createDeleteInsert(\n deleteQuads?: A.Pattern[],\n insertQuads?: A.Pattern[],\n where?: A.BaseOperation,\n ): A.DeleteInsert {\n const result: A.DeleteInsert = { type: A.Types.DELETE_INSERT };\n if (deleteQuads) {\n result.delete = deleteQuads;\n }\n if (insertQuads) {\n result.insert = insertQuads;\n }\n if (where) {\n result.where = known(where);\n }\n return result;\n }\n\n public createLoad(source: RDF.NamedNode, destination?: RDF.NamedNode, silent?: boolean): A.Load {\n const result: A.Load = { type: A.Types.LOAD, source };\n if (destination) {\n result.destination = destination;\n }\n return this.addSilent(result, Boolean(silent));\n }\n\n public createClear(source: 'DEFAULT' | 'NAMED' | 'ALL' | RDF.NamedNode, silent?: boolean): A.Clear {\n return this.addSilent({ type: A.Types.CLEAR, source }, Boolean(silent));\n }\n\n public createCreate(source: RDF.NamedNode, silent?: boolean): A.Create {\n return this.addSilent({ type: A.Types.CREATE, source }, Boolean(silent));\n }\n\n public createDrop(source: 'DEFAULT' | 'NAMED' | 'ALL' | RDF.NamedNode, silent?: boolean): A.Drop {\n return this.addSilent({ type: A.Types.DROP, source }, Boolean(silent));\n }\n\n public createAdd(source: 'DEFAULT' | RDF.NamedNode, destination: 'DEFAULT' | RDF.NamedNode, silent?: boolean): A.Add {\n return this.addSilent({\n type: A.Types.ADD,\n source,\n destination,\n }, Boolean(silent));\n }\n\n public createMove(\n source: 'DEFAULT' | RDF.NamedNode,\n destination: 'DEFAULT' | RDF.NamedNode,\n silent?: boolean,\n ): A.Move {\n return this.addSilent({\n type: A.Types.MOVE,\n source,\n destination,\n }, Boolean(silent));\n }\n\n public createCopy(\n source: 'DEFAULT' | RDF.NamedNode,\n destination: 'DEFAULT' | RDF.NamedNode,\n silent?: boolean,\n ): A.Copy {\n return this.addSilent({\n type: A.Types.COPY,\n source,\n destination,\n }, Boolean(silent));\n }\n\n private addSilent<T extends A.UpdateGraph>(input: T, silent: boolean): T {\n if (silent) {\n input.silent = silent;\n }\n return input;\n }\n\n private flattenMulti<T extends A.Multi>(input: T, flatten: boolean): T {\n if (!flatten) {\n return input;\n }\n const type = input.type;\n const subType = input.subType;\n const children = input.input;\n const newChildren: A.Operation[] = [];\n for (const child of children) {\n if (child.type === type && (!subType || subType === child.subType)) {\n newChildren.push(...(<A.Multi> child).input);\n } else {\n newChildren.push(child);\n }\n }\n input.input = newChildren;\n return input;\n }\n}\n", "import type * as RDF from '@rdfjs/types';\nimport type { Path, PathNegatedElt, PathPure, TermIri } from '@traqula/rules-sparql-1-1';\nimport { Types } from '../algebra.js';\nimport type { Algebra } from '../index.js';\nimport type { AlgebraIndir, FlattenedTriple } from './core.js';\nimport { isTerm } from './core.js';\nimport { generateFreshVar, translateNamed } from './general.js';\n\n/**\n * 18.2.2.3 Translate Property Path Expressions\n * 18.2.2.4 Translate Property Path Patterns\n */\nexport const translatePath:\nAlgebraIndir<'translatePath', (Algebra.Path | Algebra.Pattern)[], [FlattenedTriple & { predicate: PathPure }]> = {\n name: 'translatePath',\n fun: ({ SUBRULE }) => (_, triple) => {\n const sub = triple.subject;\n const pred = SUBRULE(translatePathPredicate, triple.predicate);\n const obj = triple.object;\n\n return SUBRULE(simplifyPath, sub, pred, obj);\n },\n};\n\n/**\n * 18.2.2.3 Translate Property Path Expressions\n */\nexport const translatePathPredicate:\nAlgebraIndir<'translatePathPredicate', Algebra.PropertyPathSymbol, [RDF.NamedNode | Path]> = {\n name: 'translatePathPredicate',\n fun: ({ SUBRULE }) => ({ astFactory: F, algebraFactory: AF }, predicate) => {\n if (F.isTerm(predicate)) {\n return SUBRULE(translatePathPredicate, SUBRULE(translateNamed, predicate));\n }\n // Iri -> link(iri)\n if (isTerm(predicate)) {\n return AF.createLink(predicate);\n }\n\n // ^path -> inv(path)\n if (predicate.subType === '^') {\n return AF.createInv(SUBRULE(translatePathPredicate, predicate.items[0]));\n }\n\n if (predicate.subType === '!') {\n // Negation is either over a single predicate or a list of disjuncted properties - that can only have modifier '^'\n const normals: TermIri[] = [];\n const inverted: TermIri[] = [];\n // Either the item of this one is an `|`, `^` or `iri`\n const contained = predicate.items[0];\n let items: (TermIri | PathNegatedElt)[];\n if (F.isPathPure(contained) && contained.subType === '|') {\n items = contained.items;\n } else {\n items = [ contained ];\n }\n\n for (const item of items) {\n if (F.isTerm(item)) {\n normals.push(item);\n } else if (item.subType === '^') {\n inverted.push(item.items[0]);\n } else {\n throw new Error(`Unexpected item: ${JSON.stringify(item)}`);\n }\n }\n\n // NPS elements do not have the LINK function\n const normalElement = AF.createNps(normals.map(x => SUBRULE(translateNamed, x)));\n const invertedElement = AF.createInv(AF.createNps(inverted.map(x => SUBRULE(translateNamed, x))));\n\n // !(:iri1|...|:irin) -> NPS({:iri1 ... :irin})\n if (inverted.length === 0) {\n return normalElement;\n }\n // !(^:iri1|...|^:irin) -> inv(NPS({:iri1 ... :irin}))\n if (normals.length === 0) {\n return invertedElement;\n }\n // !(:iri1|...|:irii|^:irii+1|...|^:irim -> alt(NPS({:iri1 ...:irii}), inv(NPS({:irii+1, ..., :irim})) )\n return AF.createAlt([ normalElement, invertedElement ]);\n }\n\n // Path1 / path -> seq(path1, path2)\n if (predicate.subType === '/') {\n return AF.createSeq(predicate.items.map(item => SUBRULE(translatePathPredicate, <PathPure> item)));\n }\n // Path1 | path2 -> alt(path1, path2)\n if (predicate.subType === '|') {\n return AF.createAlt(predicate.items.map(item => SUBRULE(translatePathPredicate, <PathPure> item)));\n }\n // Path* -> ZeroOrMorePath(path)\n if (predicate.subType === '*') {\n return AF.createZeroOrMorePath(SUBRULE(translatePathPredicate, <PathPure> predicate.items[0]));\n }\n // Path+ -> OneOrMorePath(path)\n if (predicate.subType === '+') {\n return AF.createOneOrMorePath(SUBRULE(translatePathPredicate, <PathPure> predicate.items[0]));\n }\n // Path? -> ZeroOrOnePath(path)\n if (predicate.subType === '?') {\n return AF.createZeroOrOnePath(SUBRULE(translatePathPredicate, <PathPure> predicate.items[0]));\n }\n\n throw new Error(`Unable to translate path expression ${JSON.stringify(predicate)}`);\n },\n};\n\n/**\n * 18.2.2.4 Translate Property Path Patterns\n */\nexport const simplifyPath:\nAlgebraIndir<'simplifyPath', (Algebra.Pattern | Algebra.Path)[], [RDF.Term, Algebra.PropertyPathSymbol, RDF.Term]> = {\n name: 'simplifyPath',\n fun: ({ SUBRULE }) => ({ algebraFactory: AF }, subject, predicate, object) => {\n // X link(iri) Y -> X iri Y\n if (predicate.type === Types.LINK) {\n return [ AF.createPattern(subject, predicate.iri, object) ];\n }\n\n // X inv(iri) Y -> Y iri X\n if (predicate.type === Types.INV) {\n return SUBRULE(simplifyPath, <RDF.Quad_Subject> object, predicate.path, subject);\n }\n\n // X seq(P, Q) Y -> X P ?V . ?V Q P\n if (predicate.type === Types.SEQ) {\n let iter = subject;\n const result: (Algebra.Pattern | Algebra.Path)[] = [];\n for (const pathOfSeq of predicate.input.slice(0, -1)) {\n const joinVar = SUBRULE(generateFreshVar);\n result.push(...SUBRULE(simplifyPath, iter, pathOfSeq, joinVar));\n iter = joinVar;\n }\n result.push(...SUBRULE(simplifyPath, iter, predicate.input.at(-1)!, object));\n return result;\n }\n\n // X P Y -> Path(X, P, Y)\n return [ AF.createPath(subject, predicate, object) ];\n },\n};\n", "import type * as RDF from '@rdfjs/types';\nimport type { BasicGraphPattern, PathPure, TripleCollection, TripleNesting } from '@traqula/rules-sparql-1-1';\nimport type { Algebra } from '../index.js';\nimport type { AlgebraIndir, FlattenedTriple } from './core.js';\nimport { isVariable, types, typeVals } from './core.js';\nimport { generateFreshVar, translateTerm } from './general.js';\n\nexport const translateTripleCollection:\nAlgebraIndir<'translateTripleCollection', void, [TripleCollection, FlattenedTriple[]]> = {\n name: 'translateTripleCollection',\n fun: ({ SUBRULE }) => (_, collection, result) => {\n SUBRULE(translateBasicGraphPattern, collection.triples, result);\n },\n};\n\n/**\n * When flattening, nested subject triples first, followed by nested object triples, lastly the current tripple.\n */\nexport const translateBasicGraphPattern:\nAlgebraIndir<'translateBasicGraphPattern', void, [BasicGraphPattern, FlattenedTriple[]]> = {\n name: 'translateBasicGraphPattern',\n fun: ({ SUBRULE }) => ({ astFactory: F }, triples, result) => {\n for (const triple of triples) {\n if (F.isTripleCollection(triple)) {\n SUBRULE(translateTripleCollection, triple, result);\n } else {\n SUBRULE(translateTripleNesting, triple, result);\n }\n }\n },\n};\n\n/**\n * Generates: everything for the subject collection + everything for the object collection + itself\n */\nexport const translateTripleNesting:\nAlgebraIndir<'translateTripleNesting', void, [TripleNesting, FlattenedTriple[]]> = {\n name: 'translateTripleNesting',\n fun: ({ SUBRULE }) => ({ astFactory: F }, triple, result) => {\n let subject: RDF.Term;\n let predicate: RDF.Term | PathPure;\n let object: RDF.Term;\n if (F.isTripleCollection(triple.subject)) {\n SUBRULE(translateTripleCollection, triple.subject, result);\n subject = SUBRULE(translateTerm, triple.subject.identifier);\n } else {\n subject = SUBRULE(translateTerm, triple.subject);\n }\n\n if (F.isPathPure(triple.predicate)) {\n predicate = triple.predicate;\n } else {\n predicate = SUBRULE(translateTerm, triple.predicate);\n }\n\n if (F.isTripleCollection(triple.object)) {\n SUBRULE(translateTripleCollection, triple.object, result);\n object = SUBRULE(translateTerm, triple.object.identifier);\n } else {\n object = SUBRULE(translateTerm, triple.object);\n }\n\n result.push({\n subject,\n predicate,\n object,\n });\n },\n};\n\n/**\n * Translate terms to be of some graph\n * @param c algebraContext\n * @param algOp algebra operation to translate\n * @param graph that should be assigned to the triples in algOp\n * @param replacement used for replacing shadowed variables.\n */\nexport const recurseGraph:\nAlgebraIndir<'recurseGraph', Algebra.Operation, [Algebra.Operation, RDF.Term, RDF.Variable | undefined]> = {\n name: 'recurseGraph',\n fun: ({ SUBRULE }) => (_, algOp, graph, replacement) => {\n if (algOp.type === types.GRAPH) {\n if (replacement) {\n // At this point we would lose track of the replacement which would result in incorrect results\n // This would indicate the library is not being used as intended though\n throw new Error('Recursing through nested GRAPH statements with a replacement is impossible.');\n }\n // In case there were nested GRAPH statements that were not recursed yet for some reason\n algOp = SUBRULE(recurseGraph, algOp.input, algOp.name, undefined);\n } else if (algOp.type === types.SERVICE) {\n // Service blocks are not affected by enclosing GRAPH statements, so nothing is modified in this block.\n // See https://github.com/joachimvh/SPARQLAlgebra.js/pull/104#issuecomment-1838016303\n } else if (algOp.type === types.BGP) {\n algOp.patterns = algOp.patterns.map((quad) => {\n if (replacement) {\n if (quad.subject.equals(graph)) {\n quad.subject = replacement;\n }\n if (quad.predicate.equals(graph)) {\n quad.predicate = replacement;\n }\n if (quad.object.equals(graph)) {\n quad.object = replacement;\n }\n }\n if (quad.graph.termType === 'DefaultGraph') {\n quad.graph = graph;\n }\n return quad;\n });\n } else if (algOp.type === types.PATH) {\n if (replacement) {\n if (algOp.subject.equals(graph)) {\n algOp.subject = replacement;\n }\n if (algOp.object.equals(graph)) {\n algOp.object = replacement;\n }\n }\n if (algOp.graph.termType === 'DefaultGraph') {\n algOp.graph = graph;\n }\n } else if (algOp.type === types.PROJECT && !replacement) {\n // Need to replace variables in subqueries should the graph also be a variable of the same name\n // unless the subquery projects that variable\n if (!algOp.variables.some(v => v.equals(graph))) {\n replacement = SUBRULE(generateFreshVar);\n }\n algOp.input = SUBRULE(recurseGraph, algOp.input, graph, replacement);\n } else if (algOp.type === types.EXTEND && !replacement) {\n // This can happen if the query extends an expression to the name of the graph\n // since the extend happens here there should be no further occurrences of this name\n // if there are it's the same situation as above\n if (algOp.variable.equals(graph)) {\n replacement = SUBRULE(generateFreshVar);\n }\n algOp.input = SUBRULE(recurseGraph, algOp.input, graph, replacement);\n } else if (algOp.type === types.MINUS && graph.termType === 'Variable') {\n algOp.graphScopeVar = graph;\n algOp.input = [\n SUBRULE(recurseGraph, algOp.input[0], graph, replacement),\n SUBRULE(recurseGraph, algOp.input[1], graph, replacement),\n ];\n } else {\n for (const [ key, value ] of Object.entries(algOp)) {\n const castedKey = <keyof typeof algOp> key;\n if (Array.isArray(value)) {\n algOp[castedKey] = <any> value.map((x: any) => SUBRULE(recurseGraph, x, graph, replacement));\n } else if (typeVals.includes(value.type)) {\n // Can't do instanceof on an interface\n algOp[castedKey] = <any> SUBRULE(recurseGraph, value, graph, replacement);\n } else if (replacement && isVariable(value) && value.equals(graph)) {\n algOp[castedKey] = <any> replacement;\n }\n }\n }\n\n return algOp;\n },\n};\n\nexport const translateQuad: AlgebraIndir<'translateQuad', Algebra.Pattern, [FlattenedTriple]> = {\n name: 'translateQuad',\n fun: () => ({ astFactory: F, algebraFactory: AF }, quad) => {\n if (F.isPathPure(quad.predicate)) {\n throw new Error('Trying to translate property path to quad.');\n }\n // Graphs are needed here\n return AF.createPattern(quad.subject, quad.predicate, quad.object, (<any>quad).graph);\n },\n};\n", "import type * as RDF from '@rdfjs/types';\nimport type {\n GraphQuads,\n GraphRef,\n GraphRefDefault,\n GraphRefSpecific,\n PatternBgp,\n Update,\n UpdateOperation,\n UpdateOperationDeleteData,\n UpdateOperationDeleteWhere,\n UpdateOperationInsertData,\n UpdateOperationLoad,\n UpdateOperationModify,\n} from '@traqula/rules-sparql-1-1';\nimport type { Algebra } from '../index.js';\nimport type { AlgebraIndir, FlattenedTriple } from './core.js';\nimport { registerContextDefinitions, translateDatasetClause, translateNamed, translateTerm } from './general.js';\nimport { translateGraphPattern } from './patterns.js';\nimport { recurseGraph, translateBasicGraphPattern, translateQuad } from './tripleAndQuad.js';\n\nexport const translateUpdate: AlgebraIndir<'translateUpdate', Algebra.Operation, [Update]> = {\n name: 'translateUpdate',\n fun: ({ SUBRULE }) => ({ algebraFactory: AF }, thingy) => {\n const updates: Algebra.Update[] = thingy.updates.flatMap((update) => {\n SUBRULE(registerContextDefinitions, update.context);\n return update.operation ? [ SUBRULE(translateSingleUpdate, update.operation) ] : [];\n });\n if (updates.length === 0) {\n return AF.createNop();\n }\n if (updates.length === 1) {\n return updates[0];\n }\n return AF.createCompositeUpdate(updates);\n },\n};\n\nexport const translateSingleUpdate: AlgebraIndir<'translateSingleUpdate', Algebra.Update, [UpdateOperation]> = {\n name: 'translateSingleUpdate',\n fun: ({ SUBRULE }) => ({ astFactory: F, algebraFactory: AF }, op) => {\n if (F.isUpdateOperationLoad(op)) {\n return SUBRULE(translateUpdateGraphLoad, op);\n }\n if (F.isUpdateOperationClear(op)) {\n return AF.createClear(SUBRULE(translateGraphRef, op.destination), op.silent);\n }\n if (F.isUpdateOperationCreate(op)) {\n return AF.createCreate(<RDF.NamedNode> SUBRULE(translateGraphRef, op.destination), op.silent);\n }\n if (F.isUpdateOperationDrop(op)) {\n return AF.createDrop(SUBRULE(translateGraphRef, op.destination), op.silent);\n }\n if (F.isUpdateOperationAdd(op)) {\n return AF.createAdd(\n SUBRULE(translateGraphRefDefSpec, op.source),\n SUBRULE(translateGraphRefDefSpec, op.destination),\n op.silent,\n );\n }\n if (F.isUpdateOperationCopy(op)) {\n return AF.createCopy(\n SUBRULE(translateGraphRefDefSpec, op.source),\n SUBRULE(translateGraphRefDefSpec, op.destination),\n op.silent,\n );\n }\n if (F.isUpdateOperationMove(op)) {\n return AF.createMove(\n SUBRULE(translateGraphRefDefSpec, op.source),\n SUBRULE(translateGraphRefDefSpec, op.destination),\n op.silent,\n );\n }\n if (F.isUpdateOperationInsertData(op) || F.isUpdateOperationDeleteData(op) || F.isUpdateOperationDeleteWhere(op) ||\n F.isUpdateOperationModify(op)) {\n return SUBRULE(translateInsertDelete, op);\n }\n\n throw new Error(`Unknown update type ${JSON.stringify(op)}`);\n },\n};\n\nexport const translateInsertDelete:\nAlgebraIndir<\n 'translateInsertDelete',\nAlgebra.Update,\n[UpdateOperationInsertData | UpdateOperationDeleteData | UpdateOperationDeleteWhere | UpdateOperationModify]\n> = {\n name: 'translateInsertDelete',\n fun: ({ SUBRULE }) => ({ useQuads, algebraFactory: AF, astFactory: F }, op) => {\n if (!useQuads) {\n throw new Error('INSERT/DELETE operations are only supported with quads option enabled');\n }\n\n const deleteTriples: Algebra.Pattern[] = [];\n const insertTriples: Algebra.Pattern[] = [];\n let where: Algebra.Operation | undefined;\n if (F.isUpdateOperationDeleteData(op) || F.isUpdateOperationDeleteWhere(op)) {\n deleteTriples.push(...op.data.flatMap(quad => SUBRULE(translateUpdateTriplesBlock, quad, undefined)));\n if (F.isUpdateOperationDeleteWhere(op)) {\n where = AF.createBgp(deleteTriples);\n }\n } else if (F.isUpdateOperationInsertData(op)) {\n insertTriples.push(...op.data.flatMap(quad => SUBRULE(translateUpdateTriplesBlock, quad, undefined)));\n } else {\n deleteTriples.push(...op.delete.flatMap(quad =>\n SUBRULE(translateUpdateTriplesBlock, quad, op.graph ? SUBRULE(translateNamed, op.graph) : op.graph)));\n insertTriples.push(...op.insert.flatMap(quad =>\n SUBRULE(translateUpdateTriplesBlock, quad, op.graph ? SUBRULE(translateNamed, op.graph) : op.graph)));\n if (op.where.patterns.length > 0) {\n where = SUBRULE(translateGraphPattern, op.where);\n const use: { default: RDF.NamedNode[]; named: RDF.NamedNode[] } = SUBRULE(translateDatasetClause, op.from);\n if (use.default.length > 0 || use.named.length > 0) {\n where = AF.createFrom(where, use.default, use.named);\n } else if (F.isUpdateOperationModify(op) && op.graph) {\n // This is equivalent\n where = SUBRULE(recurseGraph, where, SUBRULE(translateNamed, op.graph), undefined);\n }\n }\n }\n\n return AF.createDeleteInsert(\n deleteTriples.length > 0 ? deleteTriples : undefined,\n insertTriples.length > 0 ? insertTriples : undefined,\n where,\n );\n },\n};\n\n// UPDATE parsing will always return quads and have no GRAPH elements\nexport const translateUpdateTriplesBlock:\nAlgebraIndir<'translateUpdateTriplesBlock', Algebra.Pattern[], [PatternBgp | GraphQuads, RDF.NamedNode | undefined]> = {\n name: 'translateUpdateTriplesBlock',\n fun: ({ SUBRULE }) => (c, thingy, graph) => {\n const F = c.astFactory;\n let currentGraph: RDF.NamedNode | RDF.Variable | undefined = graph;\n let patternBgp: PatternBgp;\n if (F.isGraphQuads(thingy)) {\n currentGraph = <RDF.NamedNode | RDF.Variable> SUBRULE(translateTerm, thingy.graph);\n patternBgp = thingy.triples;\n } else {\n patternBgp = thingy;\n }\n let triples: FlattenedTriple[] = [];\n SUBRULE(translateBasicGraphPattern, patternBgp.triples, triples);\n if (currentGraph) {\n triples = triples.map(triple => Object.assign(triple, { graph: currentGraph }));\n }\n return triples.map(triple => SUBRULE(translateQuad, triple));\n },\n};\n\nexport const translateGraphRefSpecific: AlgebraIndir<'translateGraphRefSpecific', RDF.NamedNode, [GraphRefSpecific]> = {\n name: 'translateGraphRefSpecific',\n fun: ({ SUBRULE }) => (_, graph) => SUBRULE(translateNamed, graph.graph),\n};\n\nexport const translateGraphRefDefSpec:\nAlgebraIndir<'translateGraphRefDefSpec', RDF.NamedNode | 'DEFAULT', [GraphRefSpecific | GraphRefDefault]> = {\n name: 'translateGraphRefDefSpec',\n fun: ({ SUBRULE }) => ({ astFactory: F }, graph) =>\n F.isGraphRefDefault(graph) ? 'DEFAULT' : SUBRULE(translateGraphRefSpecific, graph),\n};\n\nexport const translateGraphRef:\nAlgebraIndir<'translateGraphRef', 'DEFAULT' | 'NAMED' | 'ALL' | RDF.NamedNode, [GraphRef]> = {\n name: 'translateGraphRef',\n fun: ({ SUBRULE }) => (c, graph) => {\n const F = c.astFactory;\n if (F.isGraphRefAll(graph)) {\n return 'ALL';\n }\n if (F.isGraphRefNamed(graph)) {\n return 'NAMED';\n }\n return SUBRULE(translateGraphRefDefSpec, graph);\n },\n};\n\nexport const translateUpdateGraphLoad: AlgebraIndir<'translateUpdateGraphLoad', Algebra.Load, [UpdateOperationLoad]> = {\n name: 'translateUpdateGraphLoad',\n fun: ({ SUBRULE }) => ({ algebraFactory: AF }, op) => AF.createLoad(\n SUBRULE(translateNamed, op.source),\n op.destination ? SUBRULE(translateNamed, op.destination.graph) : undefined,\n op.silent,\n ),\n};\n", "import type { PatternGroup, SparqlQuery } from '@traqula/rules-sparql-1-1';\nimport type { Algebra } from '../index.js';\nimport { translateAggregates } from './aggregate.js';\nimport type { AlgebraIndir } from './core.js';\nimport {\n findAllVariables,\n registerContextDefinitions,\n translateBlankNodesToVariables,\n} from './general.js';\nimport {\n translateGraphPattern,\n} from './patterns.js';\nimport {\n translateUpdate,\n} from './updates.js';\n\nexport const translateQuery:\nAlgebraIndir<'translateQuery', Algebra.Operation, [SparqlQuery, boolean | undefined, boolean | undefined]> = {\n name: 'translateQuery',\n fun: ({ SUBRULE }) => (c, sparql, quads, blankToVariable) => {\n const F = c.astFactory;\n c.variables = new Set();\n c.varCount = 0;\n c.useQuads = quads ?? false;\n\n let result: Algebra.Operation;\n\n // Find ALL variables here to fill `variables` array - needed to create fresh variables\n SUBRULE(findAllVariables, sparql);\n\n if (F.isQuery(sparql)) {\n SUBRULE(registerContextDefinitions, sparql.context);\n // Group and where are identical, having only 1 makes parsing easier, can be undefined in DESCRIBE\n const group: PatternGroup = sparql.where ?? F.patternGroup([], F.gen());\n result = SUBRULE(translateGraphPattern, group);\n // 18.2.4 Converting Groups, Aggregates, HAVING, final VALUES clause and SELECT Expressions\n result = SUBRULE(translateAggregates, sparql, result);\n } else {\n result = SUBRULE(translateUpdate, sparql);\n }\n if (blankToVariable) {\n result = SUBRULE(translateBlankNodesToVariables, result);\n }\n\n return result;\n },\n};\n", "import type * as RDF from '@rdfjs/types';\nimport type {\n Expression,\n PathPure,\n Pattern,\n PatternBgp,\n PatternFilter,\n PatternGroup,\n Wildcard,\n} from '@traqula/rules-sparql-1-1';\nimport type { Algebra } from '../index.js';\nimport type { AlgebraIndir, FlattenedTriple } from './core.js';\nimport { types } from './core.js';\nimport type { AstToRdfTerm } from './general.js';\nimport { translateInlineData, translateNamed, translateTerm } from './general.js';\nimport { translatePath } from './path.js';\nimport { translateQuery } from './toAlgebra.js';\nimport { recurseGraph, translateBasicGraphPattern, translateQuad } from './tripleAndQuad.js';\n\n/**\n * Handles part of: 18.2.2.2 Collect FILTER Elements\n */\nexport const translateExpression: AlgebraIndir<'translateExpression', Algebra.Expression, [Expression | Wildcard]> = {\n name: 'translateExpression',\n fun: ({ SUBRULE }) => ({ astFactory: F, algebraFactory: AF }, expr) => {\n if (F.isTerm(expr)) {\n return AF.createTermExpression(SUBRULE(translateTerm, expr));\n }\n\n if (F.isWildcard(expr)) {\n return AF.createWildcardExpression();\n }\n\n if (F.isExpressionAggregate(expr)) {\n return AF.createAggregateExpression(\n expr.aggregation,\n SUBRULE(translateExpression, expr.expression[0]),\n expr.distinct,\n F.isExpressionAggregateSeparator(expr) ? expr.separator : undefined,\n );\n }\n\n if (F.isExpressionFunctionCall(expr)) {\n // Outdated typings\n return AF.createNamedExpression(\n SUBRULE(translateNamed, expr.function),\n expr.args.map(subExpr => SUBRULE(translateExpression, subExpr)),\n );\n }\n\n if (F.isExpressionOperator(expr)) {\n return AF.createOperatorExpression(\n expr.operator,\n expr.args.map(subExpr => SUBRULE(translateExpression, subExpr)),\n );\n }\n\n if (F.isExpressionPatternOperation(expr)) {\n return AF.createExistenceExpression(\n expr.operator === 'notexists',\n SUBRULE(translateGraphPattern, expr.args),\n );\n }\n\n throw new Error(`Unknown expression: ${JSON.stringify(expr)}`);\n },\n};\n\nexport const translateGraphPattern: AlgebraIndir<'translateGraphPattern', Algebra.Operation, [Pattern]> = {\n name: 'translateGraphPattern',\n fun: ({ SUBRULE }) => ({ astFactory: F, algebraFactory: AF, useQuads }, pattern) => {\n // 18.2.2.1: Expand Syntax Forms -\n // partly done by sparql parser, partly in this.translateTerm, and partly in BGP\n // https://www.w3.org/TR/sparql11-query/#sparqlExpandForms\n // https://www.w3.org/TR/sparql11-query/#QSynIRI\n if (F.isPatternBgp(pattern)) {\n return SUBRULE(translateBgp, pattern);\n }\n\n // 18.2.2.6: Translate Graph Patterns - GroupOrUnionGraphPattern\n if (F.isPatternUnion(pattern)) {\n return AF.createUnion(\n pattern.patterns.map((group: PatternGroup) => SUBRULE(translateGraphPattern, group)),\n );\n }\n\n // 18.2.2.6: Translate Graph Patterns - GraphGraphPattern\n if (F.isPatternGraph(pattern)) {\n // Sparql.js combines the group graph pattern and the graph itself in the same object.\n // We split here so the group graph pattern can be interpreted correctly.\n const group = F.patternGroup(pattern.patterns, pattern.loc);\n let result = SUBRULE(translateGraphPattern, group);\n\n // Output depends on if we use quads or not\n if (useQuads) {\n result = SUBRULE(recurseGraph, result, SUBRULE(translateTerm, pattern.name), undefined);\n } else {\n result = AF.createGraph(result, <RDF.NamedNode | RDF.Variable> SUBRULE(translateTerm, pattern.name));\n }\n\n return result;\n }\n\n // 18.2.2.6: Translate Graph Patterns - InlineData\n if (F.isPatternValues(pattern)) {\n return SUBRULE(translateInlineData, pattern);\n }\n\n // 18.2.2.6: Translate Graph Patterns - SubSelect\n if (F.isQuerySelect(pattern)) {\n return SUBRULE(translateQuery, pattern, useQuads, false);\n }\n\n // 18.2.2.6: Translate Graph Patterns - GroupGraphPattern\n if (F.isPatternGroup(pattern)) {\n // 18.2.2.2 - Collect FILTER Elements\n const filters: PatternFilter[] = [];\n const nonfilters: Pattern[] = [];\n for (const subPattern of pattern.patterns) {\n if (F.isPatternFilter(subPattern)) {\n filters.push(subPattern);\n } else {\n nonfilters.push(subPattern);\n }\n }\n\n // 18.2.2.6 - GroupGraphPattern\n let result: Algebra.Operation = AF.createBgp([]);\n for (const pattern of nonfilters) {\n result = SUBRULE(accumulateGroupGraphPattern, result, pattern);\n }\n\n // 18.2.2.7 - Filters of Group - translateExpression handles notExists negation.\n const expressions: Algebra.Expression[] = filters.map(filter => SUBRULE(translateExpression, filter.expression));\n if (expressions.length > 0) {\n let conjunction = expressions[0];\n for (const expression of expressions.slice(1)) {\n conjunction = AF.createOperatorExpression('&&', [ conjunction, expression ]);\n }\n // One big filter applied on the group\n result = AF.createFilter(result, conjunction);\n }\n\n return result;\n }\n\n throw new Error(`Unexpected pattern: ${pattern.subType}`);\n },\n};\n\n/**\n * 18.2.2.1: Expand Syntax Forms: Flatten TripleCollection\n * 18.2.2.3: Translate Property Path Expressions\n * 18.2.2.4: Translate Property Path Patterns\n * 18.2.2.5: Translate Basic Graph Patterns\n */\nexport const translateBgp: AlgebraIndir<'translateBgp', Algebra.Operation, [PatternBgp]> = {\n name: 'translateBgp',\n fun: ({ SUBRULE }) => ({ astFactory: F, algebraFactory: AF }, bgp) => {\n let patterns: Algebra.Pattern[] = [];\n const joins: Algebra.Operation[] = [];\n const flattenedTriples: FlattenedTriple[] = [];\n SUBRULE(translateBasicGraphPattern, bgp.triples, flattenedTriples);\n for (const triple of flattenedTriples) {\n if (F.isPathPure(triple.predicate)) {\n const smartType = <FlattenedTriple & { predicate: PathPure }> triple;\n // TranslatePath returns a mix of Quads and Paths\n const path = SUBRULE(translatePath, smartType);\n for (const p of path) {\n if (p.type === types.PATH) {\n if (patterns.length > 0) {\n joins.push(AF.createBgp(patterns));\n }\n patterns = [];\n joins.push(p);\n } else {\n patterns.push(p);\n }\n }\n } else {\n patterns.push(SUBRULE(translateQuad, triple));\n }\n }\n if (patterns.length > 0) {\n joins.push(AF.createBgp(patterns));\n }\n if (joins.length === 1) {\n return joins[0];\n }\n return AF.createJoin(joins);\n },\n};\n\n/**\n * 18.2.2.6 Translate Graph Patterns - GroupGraphPattern\n */\nexport const accumulateGroupGraphPattern:\nAlgebraIndir<'accumulateGroupGraphPattern', Algebra.Operation, [Algebra.Operation, Pattern]> = {\n name: 'accumulateGroupGraphPattern',\n fun: ({ SUBRULE }) => ({ astFactory: F, algebraFactory: AF }, algebraOp, pattern) => {\n if (F.isPatternOptional(pattern)) {\n // Optional input needs to be interpreted as a group\n const groupAsAlgebra = SUBRULE(translateGraphPattern, F.patternGroup(pattern.patterns, pattern.loc));\n // Only hoist FILTER into LEFT_JOIN if it's a direct child of this OPTIONAL's group (per SPARQL 18.2.2.8):\n // a nested group's FILTER is scoped to that inner group and hoisting it would change what bindings it sees.\n if (groupAsAlgebra.type === types.FILTER && pattern.patterns.some(p => F.isPatternFilter(p))) {\n return AF.createLeftJoin(algebraOp, groupAsAlgebra.input, groupAsAlgebra.expression);\n }\n return AF.createLeftJoin(algebraOp, groupAsAlgebra);\n }\n\n if (F.isPatternMinus(pattern)) {\n // Minus input needs to be interpreted as a group\n const groupAsAlgebra = SUBRULE(translateGraphPattern, F.patternGroup(pattern.patterns, pattern.loc));\n return AF.createMinus(algebraOp, groupAsAlgebra);\n }\n\n if (F.isPatternBind(pattern)) {\n return AF.createExtend(\n algebraOp,\n <AstToRdfTerm<typeof pattern.variable>> SUBRULE(translateTerm, pattern.variable),\n SUBRULE(translateExpression, pattern.expression),\n );\n }\n\n if (F.isPatternService(pattern)) {\n // Transform to group so child-nodes get parsed correctly\n const group = F.patternGroup(pattern.patterns, pattern.loc);\n const A = AF.createService(\n SUBRULE(translateGraphPattern, group),\n <AstToRdfTerm<typeof pattern.name>> SUBRULE(translateTerm, pattern.name),\n pattern.silent,\n );\n return SUBRULE(simplifiedJoin, algebraOp, A);\n }\n\n const A = SUBRULE(translateGraphPattern, pattern);\n return SUBRULE(simplifiedJoin, algebraOp, A);\n },\n};\n\nexport const simplifiedJoin:\nAlgebraIndir<'simplifiedJoin', Algebra.Operation, [Algebra.Operation, Algebra.Operation]> = {\n name: 'simplifiedJoin',\n fun: () => ({ algebraFactory: AF }, G, A) => {\n // Note: this is more simplification than requested in 18.2.2.8, but no reason not to do it.\n if (G.type === types.BGP && A.type === types.BGP) {\n G = AF.createBgp([ ...G.patterns, ...A.patterns ]);\n } else if (G.type === types.BGP && G.patterns.length === 0) {\n // 18.2.2.8 (simplification)\n G = A;\n } else if (A.type === types.BGP && A.patterns.length === 0) {\n // Do nothing\n } else {\n G = AF.createJoin([ G, A ]);\n }\n return G;\n },\n};\n", "import {\n mapAggregate,\n translateAggregates,\n translateNamed,\n translateInlineData,\n translateDatasetClause,\n translateBlankNodesToVariables,\n findAllVariables,\n generateFreshVar,\n translatePath,\n translatePathPredicate,\n simplifyPath,\n translateExpression,\n translateGraphPattern,\n translateBgp,\n accumulateGroupGraphPattern,\n simplifiedJoin,\n translateTripleCollection,\n translateBasicGraphPattern,\n translateTripleNesting,\n recurseGraph,\n translateQuad,\n translateUpdate,\n translateSingleUpdate,\n translateInsertDelete,\n translateUpdateTriplesBlock,\n translateGraphRefSpecific,\n translateGraphRefDefSpec,\n translateGraphRef,\n translateUpdateGraphLoad,\n translateTerm,\n registerContextDefinitions,\n translateBoundAggregate,\n translateQuery,\n createAlgebraContext,\n inScopeVariables,\n} from '@traqula/algebra-transformations-1-1';\nimport type { Algebra, ContextConfigs } from '@traqula/algebra-transformations-1-1';\nimport { IndirBuilder } from '@traqula/core';\nimport type { SparqlQuery } from '@traqula/rules-sparql-1-1';\n\n/**\n * Pre-configured {@link IndirBuilder} for translating SPARQL 1.1 AST to SPARQL Algebra.\n * Combines all SPARQL 1.1 algebra transformation definitions.\n * Use {@link IndirBuilder.create IndirBuilder.create(toAlgebra11Builder)} to extend it.\n */\nexport const toAlgebra11Builder = IndirBuilder\n .create(<const> [\n // Aggregate\n translateAggregates,\n mapAggregate,\n translateBoundAggregate,\n ])\n .addMany(\n // General\n translateNamed,\n translateTerm,\n registerContextDefinitions,\n translateInlineData,\n translateDatasetClause,\n translateBlankNodesToVariables,\n findAllVariables,\n inScopeVariables,\n generateFreshVar,\n // Path\n translatePath,\n translatePathPredicate,\n simplifyPath,\n // Patterns\n translateExpression,\n translateGraphPattern,\n translateBgp,\n accumulateGroupGraphPattern,\n simplifiedJoin,\n // TripleAndQuad\n translateTripleCollection,\n translateBasicGraphPattern,\n translateTripleNesting,\n recurseGraph,\n translateQuad,\n // Updates\n translateUpdate,\n translateSingleUpdate,\n translateInsertDelete,\n translateUpdateTriplesBlock,\n translateGraphRefSpecific,\n translateGraphRefDefSpec,\n translateGraphRef,\n translateUpdateGraphLoad,\n // ToAlgebra\n translateQuery,\n );\n\n/**\n * Translates the given SPARQL query to SPARQL Algebra.\n * @param query - sparql 1.1 AST generated by Traqula\n * @param options - Optional options object. Current options:\n * @param options.dataFactory - The Datafactory used to generate terms. Default @rdfjs/data-model.\n * @param options.quads - Boolean indicating whether triples should be converted to Quads\n * (consumes GRAPH statements). Default false.\n * @param options.prefixes - Pre-defined prefixes for the given query. Default empty.\n * @param options.baseIRI - Base IRI that should be used for the query.\n * Default undefined (throws error if required).\n * @param options.blankToVariable - translate all blank nodes into variables\n * @returns Operation\n */\nexport function toAlgebra(query: SparqlQuery, options: ContextConfigs = {}): Algebra.Operation {\n const c = createAlgebraContext(options);\n const transformer = toAlgebra11Builder.build();\n return transformer.translateQuery(c, query, options.quads, options.blankToVariable);\n}\n", "import type * as RDF from '@rdfjs/types';\nimport {\n translateNamed,\n translateTerm,\n translateTripleCollection,\n translateTripleNesting,\n} from '@traqula/algebra-transformations-1-1';\nimport type { FlattenedTriple } from '@traqula/algebra-transformations-1-1';\nimport type * as T11 from '@traqula/rules-sparql-1-1';\nimport type {\n Expression,\n Ordering,\n Path,\n PatternBind,\n SparqlQuery,\n Term,\n TripleCollection,\n TripleNesting,\n Wildcard,\n} from '@traqula/rules-sparql-1-2';\nimport {\n findPatternBoundedVars,\n} from '@traqula/rules-sparql-1-2';\nimport { termToString } from 'rdf-string';\nimport type { AlgebraIndir } from './types.js';\n\nconst reificationIri = 'http://www.w3.org/1999/02/22-rdf-syntax-ns#reifies';\n\nexport type MapAggregateType = Wildcard | Expression | Ordering | PatternBind;\n\nexport const translateTerm12: AlgebraIndir<(typeof translateTerm)['name'], RDF.Term, [Term]> = {\n name: 'translateTerm',\n fun: $ => (C, term) => {\n if (C.astFactory.isTermTriple(term)) {\n return C.dataFactory.quad(\n $.SUBRULE(translateTerm12, term.subject),\n $.SUBRULE(translateTerm12, term.predicate),\n $.SUBRULE(translateTerm12, term.object),\n );\n }\n if (C.astFactory.isTermLiteral(term)) {\n if (!term.langOrIri) {\n return C.dataFactory.literal(term.value);\n }\n if (typeof term.langOrIri === 'object') {\n const iri = $.SUBRULE(translateNamed, term.langOrIri);\n return C.dataFactory.literal(term.value, iri);\n }\n const [ lang, langDir ] = term.langOrIri.split('--');\n if (langDir && (langDir === '' || langDir === 'ltr' || langDir === 'rtl')) {\n return C.dataFactory.literal(term.value, {\n language: lang,\n direction: langDir,\n });\n }\n return C.dataFactory.literal(term.value, term.langOrIri);\n }\n return translateTerm.fun($)(C, term);\n },\n};\n\nexport const translateTripleCollection12: AlgebraIndir<\n (typeof translateTripleCollection)['name'],\nvoid,\n[TripleCollection, FlattenedTriple[]]\n> = {\n name: 'translateTripleCollection',\n fun: s => (c, collection, result) => {\n if (c.astFactory.isTripleCollectionReifiedTriple(collection)) {\n const { SUBRULE } = s;\n const { dataFactory } = c;\n const identifier = SUBRULE(translateTerm12, collection.identifier);\n SUBRULE(translateTripleNesting12, collection.triples[0], result);\n // Given the rule for triple nesting, the triple itself is always generated last\n // (followed by annotations, but they are not allowed within reified triples\n const { subject, predicate, object } = result.pop()!;\n const asTerm = dataFactory.quad(subject, <Exclude<typeof predicate, T11.PathPure>> predicate, object);\n result.push({\n subject: identifier,\n predicate: dataFactory.namedNode(reificationIri),\n object: asTerm,\n });\n } else {\n translateTripleCollection.fun(s)(c, <T11.TripleCollection> collection, result);\n }\n },\n};\n\n/**\n * Generates: everything for the subject collection + everything for the object collection + itself +\n * the annotations triples\n */\nexport const translateTripleNesting12: AlgebraIndir<\n (typeof translateTripleNesting)['name'],\nvoid,\n[TripleNesting, FlattenedTriple[]]\n> = {\n name: 'translateTripleNesting',\n fun: s => (c, triple, result) => {\n translateTripleNesting.fun(s)(c, <T11.TripleNesting>triple, result);\n const SUBRULE = s.SUBRULE;\n const { subject, predicate, object } = result.at(-1)!;\n const { astFactory: F, dataFactory } = c;\n if (triple.annotations && triple.annotations.length > 0) {\n // Blocks know who identifies them. -> Can just add it to list of triples\n // -> a blocks identifier only need to be registered when the identifier is not explicitly registered before.\n // We register: <annotationNode, reifies, tripleNesting>\n // You cannot have an annotation on a triple that has paths\n const asTerm = dataFactory.quad(subject, <Exclude<typeof predicate, T11.PathPure>> predicate, object);\n const registered = new Set<string>();\n for (const annotation of triple.annotations) {\n let subject: RDF.Term;\n const tripleCollection = F.isTripleCollection(annotation);\n if (tripleCollection) {\n subject = SUBRULE(translateTerm12, annotation.identifier);\n } else {\n subject = SUBRULE(translateTerm12, annotation.val);\n }\n if (!registered.has(termToString(subject))) {\n result.push({\n subject,\n predicate: dataFactory.namedNode(reificationIri),\n object: asTerm,\n });\n }\n registered.add(termToString(subject));\n if (tripleCollection) {\n SUBRULE(translateTripleCollection12, annotation, result);\n }\n }\n }\n },\n};\n\n/**\n * 18.2.1\n */\nexport const inScopeVariables:\nAlgebraIndir<'inScopeVariables', Set<string>, [SparqlQuery | TripleNesting | TripleCollection | Path | Term]> = {\n name: 'inScopeVariables',\n fun: () => (_, thingy) => {\n const vars = new Set<string>();\n findPatternBoundedVars(thingy, vars);\n return vars;\n },\n};\n", "import type * as RDF from '@rdfjs/types';\nimport type * as Trans11 from '@traqula/algebra-transformations-1-1';\nimport {\n createAlgebraContext as createAlgebraContext11,\n createAstContext as createAstContext11,\n} from '@traqula/algebra-transformations-1-1';\nimport type { IndirDef, Patch } from '@traqula/core';\nimport { AstFactory } from '@traqula/rules-sparql-1-2';\nimport type * as T12 from '@traqula/rules-sparql-1-2';\n\nexport type AlgebraContext = Patch<Trans11.AlgebraContext, {\n astFactory: AstFactory;\n}>;\n\nexport type FlattenedTriple = Patch<Trans11.FlattenedTriple, { predicate: RDF.Term | T12.PathPure }>;\nexport type ContextConfigs = Trans11.ContextConfigs;\nexport function createAlgebraContext(config: ContextConfigs): AlgebraContext {\n const context11 = createAlgebraContext11(config);\n return {\n ...context11,\n astFactory: new AstFactory(),\n };\n}\n\nexport type AlgebraIndir<Name extends string, Ret, Arg extends any[]> = IndirDef<AlgebraContext, Name, Ret, Arg>;\n\nexport type AstContext = Patch<Trans11.AstContext, {\n astFactory: AstFactory;\n}>;\n\nexport function createAstContext(): AstContext {\n const context11 = createAstContext11();\n return {\n ...context11,\n astFactory: new AstFactory(),\n };\n}\n\nexport type AstIndir<Name extends string, Ret, Arg extends any[]> = IndirDef<AstContext, Name, Ret, Arg>;\n", "import type * as RDF from '@rdfjs/types';\nimport { toAlgebra11Builder } from '@traqula/algebra-sparql-1-1';\nimport type {\n accumulateGroupGraphPattern,\n Algebra,\n Algebra as A,\n ContextConfigs,\n findAllVariables,\n generateFreshVar,\n mapAggregate,\n recurseGraph,\n registerContextDefinitions,\n simplifiedJoin,\n simplifyPath,\n translateAggregates,\n translateBasicGraphPattern,\n translateBgp,\n translateBlankNodesToVariables,\n translateBoundAggregate,\n translateDatasetClause,\n translateExpression,\n translateGraphPattern,\n translateGraphRef,\n translateGraphRefDefSpec,\n translateGraphRefSpecific,\n translateInlineData,\n translateInsertDelete,\n translateNamed,\n translatePath,\n translatePathPredicate,\n translateQuad,\n translateQuery,\n translateSingleUpdate,\n translateTerm,\n translateTripleCollection,\n translateTripleNesting,\n translateUpdate,\n translateUpdateGraphLoad,\n translateUpdateTriplesBlock,\n} from '@traqula/algebra-transformations-1-1';\nimport type { AlgebraContext, FlattenedTriple, MapAggregateType } from '@traqula/algebra-transformations-1-2';\nimport {\n createAlgebraContext,\n inScopeVariables,\n translateTerm12,\n translateTripleCollection12,\n translateTripleNesting12,\n} from '@traqula/algebra-transformations-1-2';\nimport { IndirBuilder } from '@traqula/core';\n\nimport type * as T12 from '@traqula/rules-sparql-1-2';\n\n/**\n * Pre-configured {@link IndirBuilder} for translating SPARQL 1.2 AST to SPARQL Algebra.\n * Extends the SPARQL 1.1 algebra builder with SPARQL 1.2 specific transformations\n * (e.g. triple terms, reified triples).\n * Use {@link IndirBuilder.create IndirBuilder.create(toAlgebra12Builder)} to extend it.\n */\nexport const toAlgebra12Builder = IndirBuilder\n .create(toAlgebra11Builder)\n .widenContext<AlgebraContext>()\n .patchRule(translateTerm12)\n .patchRule(translateTripleCollection12)\n .patchRule(translateTripleNesting12)\n .patchRule(inScopeVariables)\n .typePatch<{\n // Aggregate\n [translateAggregates.name]: [A.Operation, [T12.Query, A.Operation]];\n [mapAggregate.name]: [MapAggregateType, [MapAggregateType, Record<string, T12.ExpressionAggregate>]];\n [translateBoundAggregate.name]: [A.BoundAggregate, [T12.ExpressionAggregate, RDF.Variable]];\n // General\n [translateNamed.name]: [RDF.NamedNode, [T12.TermIri]];\n [translateTerm.name]: [RDF.Term, [T12.Term]];\n [registerContextDefinitions.name]: [void, [T12.ContextDefinition[]]];\n [translateInlineData.name]: [A.Values, [T12.PatternValues]];\n [translateDatasetClause.name]: [{ default: RDF.NamedNode[]; named: RDF.NamedNode[] }, [T12.DatasetClauses]];\n [translateBlankNodesToVariables.name]: [A.Operation, [A.Operation]];\n [findAllVariables.name]: [void, [object]];\n [inScopeVariables.name]: [\n Set<string>,\n [T12.SparqlQuery | T12.TripleNesting | T12.TripleCollection | T12.Path | T12.Term],\n ];\n [generateFreshVar.name]: [RDF.Variable, []];\n // Path\n [translatePath.name]: [(A.Path | A.Pattern)[], [FlattenedTriple & { predicate: T12.PathPure }]];\n [translatePathPredicate.name]: [A.PropertyPathSymbol, [RDF.NamedNode | T12.Path]];\n [simplifyPath.name]: [(Algebra.Pattern | Algebra.Path)[], [RDF.Term, A.PropertyPathSymbol, RDF.Term]];\n // Patterns\n [translateExpression.name]: [A.Expression, [T12.Expression | T12.Wildcard]];\n [translateGraphPattern.name]: [A.Operation, [T12.Pattern]];\n [translateBgp.name]: [A.Operation, [T12.PatternBgp]];\n [accumulateGroupGraphPattern.name]: [A.Operation, [A.Operation, T12.Pattern]];\n [simplifiedJoin.name]: [A.Operation, [A.Operation, A.Operation]];\n // TripleAndQuad\n [translateTripleCollection.name]: [void, [T12.TripleCollection, FlattenedTriple[]]];\n [translateBasicGraphPattern.name]: [void, [T12.BasicGraphPattern, FlattenedTriple[]]];\n [translateTripleNesting.name]: [void, [T12.TripleNesting, FlattenedTriple[]]];\n [recurseGraph.name]: [A.Operation, [A.Operation, RDF.Term, RDF.Variable | undefined]];\n [translateQuad.name]: [A.Pattern, [FlattenedTriple]];\n // Updates\n [translateUpdate.name]: [A.Operation, [T12.Update]];\n [translateSingleUpdate.name]: [A.Update, [T12.UpdateOperation]];\n [translateInsertDelete.name]: [\n A.Operation,\n [T12.UpdateOperationInsertData | T12.UpdateOperationDeleteData\n | T12.UpdateOperationDeleteWhere | T12.UpdateOperationModify],\n ];\n [translateUpdateTriplesBlock.name]: [A.Pattern, [T12.PatternBgp | T12.GraphQuads, RDF.NamedNode | undefined]];\n [translateGraphRefSpecific.name]: [RDF.NamedNode, [T12.GraphRefSpecific]];\n [translateGraphRefDefSpec.name]: [RDF.NamedNode | 'DEFAULT', [T12.GraphRefSpecific | T12.GraphRefDefault]];\n [translateGraphRef.name]: ['DEFAULT' | 'NAMED' | 'ALL' | RDF.NamedNode, [T12.GraphRef]];\n [translateUpdateGraphLoad.name]: [A.Load, [T12.UpdateOperationLoad]];\n // ToAlgebra\n [translateQuery.name]: [A.Operation, [T12.SparqlQuery, boolean | undefined, boolean | undefined]];\n }>();\n\n/**\n * Translates the given SPARQL query to SPARQL Algebra.\n * @param query - sparql 1.2 AST generated by Traqula\n * @param options - Optional options object. Current options:\n * @param options.dataFactory - The Datafactory used to generate terms. Default @rdfjs/data-model.\n * @param options.quads - Boolean indicating whether triples should be converted to Quads\n * (consumes GRAPH statements). Default false.\n * @param options.prefixes - Pre-defined prefixes for the given query. Default empty.\n * @param options.baseIRI - Base IRI that should be used for the query.\n * Default undefined (throws error if required).\n * @param options.blankToVariable - translate all blank nodes into variables\n * @returns Operation\n */\nexport function toAlgebra(query: T12.SparqlQuery, options: ContextConfigs = {}): A.Operation {\n const c = createAlgebraContext(options);\n const transformer = toAlgebra12Builder.build();\n return transformer.translateQuery(c, query, options.quads, options.blankToVariable);\n}\n", "/**\n * From query text to SPARQL algebra, with traqula (the comunica parser and\n * algebra transformer for SPARQL 1.2).\n */\n\nimport { Parser } from '@traqula/parser-sparql-1-2';\nimport { toAlgebra } from '@traqula/algebra-sparql-1-2';\n\nexport type Algebra = any;\n\nexport interface TranslateOptions {\n /** Base IRI for relative IRIs; a placeholder is used when the query has none */\n baseIRI?: string;\n}\n\n/** The base used when the query has no BASE: relative IRIs then print as `<http://base/...>` */\nexport const DEFAULT_BASE_IRI = 'http://base/';\n\nexport class AlgebraError extends Error {\n constructor(message: string) {\n super(message);\n this.name = 'AlgebraError';\n }\n}\n\nlet parser: Parser | undefined;\n\n/** Translate a query to its algebra, or throw an AlgebraError with the parser's message */\nexport function translate(query: string, options: TranslateOptions = {}): Algebra {\n if (!query || !query.trim()) throw new AlgebraError('The query is empty.');\n if (!parser) parser = new Parser();\n let ast: unknown;\n const baseIRI = options.baseIRI || DEFAULT_BASE_IRI;\n try {\n ast = parser.parse(query, { baseIRI });\n } catch (error) {\n throw new AlgebraError(cleanParseMessage(error));\n }\n try {\n // Triple patterns with an explicit `graph` operator, as in the specification\n return toAlgebra(ast as any, { quads: false, baseIRI });\n } catch (error) {\n // Updates are only translated with quads\n try {\n return toAlgebra(ast as any, { quads: true, baseIRI });\n } catch {\n throw new AlgebraError(error instanceof Error ? error.message : String(error));\n }\n }\n}\n\n/** The parser's messages list every token it expected; keep the readable head */\nexport function cleanParseMessage(error: unknown): string {\n const message = error instanceof Error ? error.message : String(error);\n const lines = message.split('\\n').map((line) => line.trimEnd());\n const kept: string[] = [];\n for (const line of lines) {\n if (/^\\s*<\\[/.test(line) || /^\\s*\\[/.test(line)) break; // the token sequences\n kept.push(line);\n if (kept.length >= 4) break;\n }\n return (\n kept\n .join('\\n')\n .replace(/::\\s*$/, '.')\n .trim() || message\n );\n}\n", "/**\n * Printing RDF/JS terms, expressions and property paths in SPARQL syntax,\n * with IRIs shortened by the prefixes of the query.\n */\n\nexport interface Prefixes {\n [prefix: string]: string;\n}\n\nconst XSD = 'http://www.w3.org/2001/XMLSchema#';\nconst BARE_DATATYPES = new Set([`${XSD}integer`, `${XSD}decimal`, `${XSD}double`, `${XSD}boolean`]);\n\n/** Shorten an IRI with the longest matching prefix, else write it in angle brackets */\nexport function printIri(iri: string, prefixes: Prefixes = {}): string {\n let best: [string, string] | undefined;\n for (const [prefix, namespace] of Object.entries(prefixes)) {\n if (!namespace || !iri.startsWith(namespace)) continue;\n if (!best || namespace.length > best[1].length) best = [prefix, namespace];\n }\n if (best) {\n const local = iri.slice(best[1].length);\n if (/^[A-Za-z0-9_\\-.:%]*$/.test(local) && !local.endsWith('.')) return `${best[0]}:${local}`;\n }\n return `<${iri}>`;\n}\n\n/** An RDF/JS term as SPARQL text */\nexport function printTerm(term: any, prefixes: Prefixes = {}): string {\n if (term === undefined || term === null) return '';\n if (typeof term === 'string') return term;\n switch (term.termType) {\n case 'Variable':\n return `?${term.value}`;\n case 'NamedNode':\n return printIri(term.value, prefixes);\n case 'BlankNode':\n return `_:${term.value}`;\n case 'DefaultGraph':\n return '';\n case 'Literal': {\n const value = JSON.stringify(String(term.value));\n const language = term.language || term['xml:lang'];\n if (language) return `${value}@${language}`;\n const datatype = term.datatype?.value;\n if (!datatype || datatype === `${XSD}string`) return value;\n if (\n BARE_DATATYPES.has(datatype) &&\n /^[+-]?(\\d+(\\.\\d*)?|\\.\\d+)([eE][+-]?\\d+)?$|^(true|false)$/.test(term.value)\n ) {\n return String(term.value);\n }\n return `${value}^^${printIri(datatype, prefixes)}`;\n }\n case 'Quad':\n return printQuad(term, prefixes);\n default:\n if (typeof term.value === 'string') return term.value;\n return JSON.stringify(term);\n }\n}\n\n/** A triple or quad pattern as `?s <p> ?o` (a non-default graph is appended as `@ <g>`) */\nexport function printQuad(quad: any, prefixes: Prefixes = {}): string {\n const parts = [\n printTermOrPath(quad.subject, prefixes),\n printTermOrPath(quad.predicate, prefixes),\n printTermOrPath(quad.object, prefixes),\n ];\n if (quad.graph && quad.graph.termType !== 'DefaultGraph')\n parts.push(`@ ${printTerm(quad.graph, prefixes)}`);\n return parts.join(' ');\n}\n\nfunction printTermOrPath(value: any, prefixes: Prefixes): string {\n if (\n value &&\n typeof value === 'object' &&\n !('termType' in value) &&\n typeof value.type === 'string'\n ) {\n return printPath(value, prefixes);\n }\n return printTerm(value, prefixes);\n}\n\n/** A property path in SPARQL syntax */\nexport function printPath(\n path: any,\n prefixes: Prefixes = {},\n parent: 'alt' | 'seq' | 'unary' | undefined = undefined\n): string {\n if (!path || typeof path !== 'object') return String(path);\n if ('termType' in path) return printTerm(path, prefixes);\n const inner = (child: any, as: 'alt' | 'seq' | 'unary') => printPath(child, prefixes, as);\n let text: string;\n switch (path.type) {\n case 'link':\n return printTerm(path.iri, prefixes);\n case 'inv':\n return `^${inner(path.path, 'unary')}`;\n case 'seq':\n text = (path.input || []).map((p: any) => inner(p, 'seq')).join('/');\n break;\n case 'alt':\n text = (path.input || []).map((p: any) => inner(p, 'alt')).join('|');\n break;\n case 'ZeroOrMorePath':\n return `${inner(path.path, 'unary')}*`;\n case 'OneOrMorePath':\n return `${inner(path.path, 'unary')}+`;\n case 'ZeroOrOnePath':\n return `${inner(path.path, 'unary')}?`;\n case 'nps':\n return `!(${(path.iris || []).map((iri: any) => printTerm(iri, prefixes)).join('|')})`;\n default:\n return path.type;\n }\n // A sequence binds tighter than an alternative; a modifier or inverse binds tighter than both\n const needsBrackets = parent === 'unary' || (parent === 'seq' && path.type === 'alt');\n return needsBrackets ? `(${text})` : text;\n}\n\n/** An expression in SPARQL-like prefix notation, e.g. `(> ?o 3)` or `(count ?o)` */\nexport function printExpression(expression: any, prefixes: Prefixes = {}): string {\n if (expression === undefined || expression === null) return '';\n if (typeof expression !== 'object') return String(expression);\n if ('termType' in expression) return printTerm(expression, prefixes);\n switch (expression.subType ?? expression.expressionType) {\n case 'term':\n return printTerm(expression.term, prefixes);\n case 'operator': {\n const args = (expression.args || []).map((arg: any) => printExpression(arg, prefixes));\n return `(${expression.operator} ${args.join(' ')})`.replace(' )', ')');\n }\n case 'named': {\n const args = (expression.args || []).map((arg: any) => printExpression(arg, prefixes));\n return `(${printTerm(expression.name, prefixes)} ${args.join(' ')})`.replace(' )', ')');\n }\n case 'aggregate': {\n const inner = expression.expression ? printExpression(expression.expression, prefixes) : '*';\n const distinct = expression.distinct ? 'distinct ' : '';\n const separator =\n expression.aggregator === 'group_concat' && expression.separator !== undefined\n ? ` ${JSON.stringify(expression.separator)}`\n : '';\n return `(${expression.aggregator} ${distinct}${inner}${separator})`;\n }\n case 'existence':\n return `(${expression.not ? 'notexists' : 'exists'} ...)`;\n case 'wildcard':\n return '*';\n default:\n if (expression.operator) return `(${expression.operator})`;\n return JSON.stringify(expression);\n }\n}\n", "/**\n * Two views of an algebra expression: a tree for the screen, and the\n * s-expression text (the notation of ARQ and the SPARQL specification\n * examples) for copying into issues and documentation.\n */\n\nimport { printExpression, printPath, printQuad, printTerm, type Prefixes } from './terms';\n\n/** One node of the algebra tree shown on screen */\nexport interface AlgebraNode {\n /** The operator, e.g. \"project\" */\n operator: string;\n /** Its arguments on the same line, e.g. \"?s ?n\" */\n args?: string;\n /** Lines below the operator, e.g. the triples of a bgp */\n details?: string[];\n children: AlgebraNode[];\n}\n\nfunction list(items: any[] | undefined, print: (item: any) => string): string {\n return `(${(items || []).map(print).join(' ')})`;\n}\n\nfunction variables(items: any[] | undefined, prefixes: Prefixes): string {\n return (items || []).map((item) => printTerm(item, prefixes)).join(' ');\n}\n\n/** Build the screen tree of an algebra expression */\nexport function toTree(algebra: any, prefixes: Prefixes = {}): AlgebraNode {\n const node = (\n operator: string,\n args?: string,\n children: any[] = [],\n details?: string[]\n ): AlgebraNode => ({\n operator,\n args: args || undefined,\n details: details && details.length ? details : undefined,\n children: children.filter(Boolean).map((child) => toTree(child, prefixes)),\n });\n if (!algebra || typeof algebra !== 'object') return node(String(algebra));\n const inputs: any[] = Array.isArray(algebra.input)\n ? algebra.input\n : algebra.input\n ? [algebra.input]\n : [];\n switch (algebra.type) {\n case 'bgp':\n return node(\n 'bgp',\n undefined,\n [],\n (algebra.patterns || []).map((p: any) => printQuad(p, prefixes))\n );\n case 'path':\n return node(\n 'path',\n undefined,\n [],\n [printQuad({ ...algebra, predicate: algebra.predicate }, prefixes)]\n );\n case 'join':\n case 'union':\n case 'minus':\n case 'distinct':\n case 'reduced':\n case 'ask':\n return node(algebra.type, undefined, inputs);\n case 'leftjoin':\n return node(\n 'leftjoin',\n algebra.expression ? printExpression(algebra.expression, prefixes) : undefined,\n inputs\n );\n case 'filter':\n return node('filter', printExpression(algebra.expression, prefixes), inputs);\n case 'extend':\n return node(\n 'extend',\n `${printTerm(algebra.variable, prefixes)} := ${printExpression(algebra.expression, prefixes)}`,\n inputs\n );\n case 'project':\n return node('project', variables(algebra.variables, prefixes), inputs);\n case 'orderby':\n return node(\n 'orderby',\n (algebra.expressions || []).map((e: any) => printExpression(e, prefixes)).join(' '),\n inputs\n );\n case 'slice': {\n const parts: string[] = [];\n if (algebra.start) parts.push(`offset ${algebra.start}`);\n if (algebra.length !== undefined) parts.push(`limit ${algebra.length}`);\n return node('slice', parts.join(' '), inputs);\n }\n case 'group': {\n const aggregates = (algebra.aggregates || []).map(\n (a: any) => `${printTerm(a.variable, prefixes)} := ${printExpression(a, prefixes)}`\n );\n return node('group', variables(algebra.variables, prefixes), inputs, aggregates);\n }\n case 'graph':\n return node('graph', printTerm(algebra.name, prefixes), inputs);\n case 'service':\n return node(\n 'service',\n `${algebra.silent ? 'silent ' : ''}${printTerm(algebra.name, prefixes)}`,\n inputs\n );\n case 'values': {\n const vars = (algebra.variables || []).map((v: any) => printTerm(v, prefixes));\n const rows = (algebra.bindings || []).map(\n (row: any) =>\n `[${vars\n .map((v: string) => {\n const term = row[v.slice(1)];\n return term === undefined ? 'UNDEF' : printTerm(term, prefixes);\n })\n .join(' ')}]`\n );\n return node('values', vars.join(' '), [], rows);\n }\n case 'from': {\n const details: string[] = [];\n for (const g of algebra.default || []) details.push(`from ${printTerm(g, prefixes)}`);\n for (const g of algebra.named || []) details.push(`from named ${printTerm(g, prefixes)}`);\n return node('dataset', undefined, inputs, details);\n }\n case 'construct':\n return node(\n 'construct',\n undefined,\n inputs,\n (algebra.template || []).map((q: any) => printQuad(q, prefixes))\n );\n case 'describe':\n return node('describe', variables(algebra.terms, prefixes), inputs);\n case 'deleteinsert': {\n const details: string[] = [];\n for (const q of algebra.delete || []) details.push(`delete ${printQuad(q, prefixes)}`);\n for (const q of algebra.insert || []) details.push(`insert ${printQuad(q, prefixes)}`);\n return node('modify', undefined, algebra.where ? [algebra.where] : [], details);\n }\n case 'compositeupdate':\n return node('update', undefined, algebra.updates || []);\n case 'load':\n return node(\n 'load',\n `${algebra.silent ? 'silent ' : ''}${printTerm(algebra.source, prefixes)}` +\n (algebra.destination ? ` into ${printTerm(algebra.destination, prefixes)}` : '')\n );\n case 'clear':\n case 'drop':\n case 'create':\n return node(\n algebra.type,\n `${algebra.silent ? 'silent ' : ''}${typeof algebra.source === 'string' ? algebra.source : printTerm(algebra.source, prefixes)}`\n );\n case 'add':\n case 'move':\n case 'copy':\n return node(\n algebra.type,\n `${algebra.silent ? 'silent ' : ''}${printGraphRef(algebra.source, prefixes)} to ${printGraphRef(algebra.destination, prefixes)}`\n );\n case 'nop':\n return node('nop');\n default: {\n const details: string[] = [];\n for (const [key, value] of Object.entries(algebra)) {\n if (key === 'type' || key === 'input' || key === 'loc' || key === 'RTT') continue;\n details.push(`${key}: ${describeValue(value, prefixes)}`);\n }\n return node(String(algebra.type || 'unknown'), undefined, inputs, details);\n }\n }\n}\n\nfunction printGraphRef(value: any, prefixes: Prefixes): string {\n if (typeof value === 'string') return value;\n return printTerm(value, prefixes);\n}\n\nfunction describeValue(value: any, prefixes: Prefixes): string {\n if (Array.isArray(value)) return value.map((v) => describeValue(v, prefixes)).join(', ');\n if (value && typeof value === 'object') {\n if ('termType' in value) return printTerm(value, prefixes);\n if (value.subType || value.expressionType) return printExpression(value, prefixes);\n if (typeof value.type === 'string' && /path|link|inv|seq|alt|nps/i.test(value.type))\n return printPath(value, prefixes);\n return JSON.stringify(value);\n }\n return String(value);\n}\n\n/** The s-expression of an algebra expression, in the style of ARQ's `qparse --print=op` */\nexport function toSExpression(algebra: any, prefixes: Prefixes = {}): string {\n const lines: string[] = [];\n write(algebra, prefixes, 0, lines);\n return lines.join('\\n');\n}\n\nfunction write(algebra: any, prefixes: Prefixes, depth: number, lines: string[]): void {\n const pad = ' '.repeat(depth);\n const push = (text: string) => lines.push(pad + text);\n if (!algebra || typeof algebra !== 'object') {\n push(String(algebra));\n return;\n }\n const inputs: any[] = Array.isArray(algebra.input)\n ? algebra.input\n : algebra.input\n ? [algebra.input]\n : [];\n const open = (head: string, children: any[] = inputs) => {\n if (children.length === 0) {\n push(`(${head})`);\n return;\n }\n push(`(${head}`);\n for (const child of children) write(child, prefixes, depth + 1, lines);\n lines[lines.length - 1] += ')';\n };\n const expr = (e: any) => printExpression(e, prefixes);\n switch (algebra.type) {\n case 'bgp':\n if (!algebra.patterns?.length) {\n push('(bgp)');\n return;\n }\n push('(bgp');\n for (const pattern of algebra.patterns)\n lines.push(`${pad} (triple ${printQuad(pattern, prefixes)})`);\n lines[lines.length - 1] += ')';\n return;\n case 'path':\n push(`(path ${printQuad(algebra, prefixes)})`);\n return;\n case 'join':\n case 'union':\n case 'minus':\n case 'distinct':\n case 'reduced':\n case 'ask':\n open(algebra.type);\n return;\n case 'leftjoin':\n open(algebra.expression ? `leftjoin ${expr(algebra.expression)}` : 'leftjoin');\n return;\n case 'filter':\n open(`filter ${expr(algebra.expression)}`);\n return;\n case 'extend':\n open(`extend ((${printTerm(algebra.variable, prefixes)} ${expr(algebra.expression)}))`);\n return;\n case 'project':\n open(`project ${list(algebra.variables, (v) => printTerm(v, prefixes))}`);\n return;\n case 'orderby':\n open(`order ${list(algebra.expressions, expr)}`);\n return;\n case 'slice':\n open(`slice ${algebra.start ?? 0} ${algebra.length === undefined ? '_' : algebra.length}`);\n return;\n case 'group':\n open(\n `group ${list(algebra.variables, (v) => printTerm(v, prefixes))} ${list(\n algebra.aggregates,\n (a) => `(${printTerm(a.variable, prefixes)} ${expr(a)})`\n )}`\n );\n return;\n case 'graph':\n open(`graph ${printTerm(algebra.name, prefixes)}`);\n return;\n case 'service':\n open(`service ${algebra.silent ? 'silent ' : ''}${printTerm(algebra.name, prefixes)}`);\n return;\n case 'values': {\n const vars = (algebra.variables || []).map((v: any) => printTerm(v, prefixes));\n push(`(table (vars ${vars.join(' ')})`);\n for (const row of algebra.bindings || []) {\n const cells = vars\n .map((v: string) => {\n const term = row[v.slice(1)];\n return term === undefined ? undefined : `[${v} ${printTerm(term, prefixes)}]`;\n })\n .filter(Boolean);\n lines.push(`${pad} (row ${cells.join(' ')})`.replace('(row )', '(row)'));\n }\n lines[lines.length - 1] += ')';\n return;\n }\n case 'from': {\n const graphs = [\n ...(algebra.default || []).map((g: any) => printTerm(g, prefixes)),\n ...(algebra.named || []).map((g: any) => `(named ${printTerm(g, prefixes)})`),\n ];\n open(`dataset (${graphs.join(' ')})`);\n return;\n }\n case 'construct':\n push('(construct');\n for (const pattern of algebra.template || [])\n lines.push(`${pad} (triple ${printQuad(pattern, prefixes)})`);\n for (const child of inputs) write(child, prefixes, depth + 1, lines);\n lines[lines.length - 1] += ')';\n return;\n case 'describe':\n open(`describe ${list(algebra.terms, (t) => printTerm(t, prefixes))}`);\n return;\n case 'deleteinsert':\n push('(modify');\n for (const q of algebra.delete || [])\n lines.push(`${pad} (delete (triple ${printQuad(q, prefixes)}))`);\n for (const q of algebra.insert || [])\n lines.push(`${pad} (insert (triple ${printQuad(q, prefixes)}))`);\n if (algebra.where) write(algebra.where, prefixes, depth + 1, lines);\n lines[lines.length - 1] += ')';\n return;\n case 'compositeupdate':\n open('update', algebra.updates || []);\n return;\n default: {\n const tree = toTree(algebra, prefixes);\n open([tree.operator, tree.args, ...(tree.details || [])].filter(Boolean).join(' '));\n }\n }\n}\n", "/**\n * Inline Lucide icons (https://lucide.dev, ISC licence)\n *\n * Only the few icons the plugin needs are inlined, so there is no icon font\n * or runtime dependency. They are stroke icons drawn in `currentColor`.\n */\n\nconst ICON_PATHS = {\n 'list-tree':\n '<path d=\"M21 12h-8\"/><path d=\"M21 6H8\"/><path d=\"M21 18h-8\"/>' +\n '<path d=\"M3 6v4c0 1.1.9 2 2 2h3\"/><path d=\"M3 10v6c0 1.1.9 2 2 2h3\"/>',\n 'chevron-down': '<path d=\"m6 9 6 6 6-6\"/>',\n 'chevron-right': '<path d=\"m9 18 6-6-6-6\"/>',\n copy:\n '<rect width=\"14\" height=\"14\" x=\"8\" y=\"8\" rx=\"2\" ry=\"2\"/>' +\n '<path d=\"M4 16c-1.1 0-2-.9-2-2V4c0-1.1.9-2 2-2h10c1.1 0 2 .9 2 2\"/>',\n 'rotate-ccw': '<path d=\"M3 12a9 9 0 1 0 9-9 9.75 9.75 0 0 0-6.74 2.74L3 8\"/><path d=\"M3 3v5h5\"/>',\n 'unfold-vertical':\n '<path d=\"M12 22v-6\"/><path d=\"M12 8V2\"/><path d=\"M4 12H2\"/><path d=\"M10 12H8\"/>' +\n '<path d=\"M16 12h-2\"/><path d=\"M22 12h-2\"/><path d=\"m15 19-3 3-3-3\"/><path d=\"m15 5-3-3-3 3\"/>',\n 'fold-vertical':\n '<path d=\"M12 22v-6\"/><path d=\"M12 8V2\"/><path d=\"M4 12H2\"/><path d=\"M10 12H8\"/>' +\n '<path d=\"M16 12h-2\"/><path d=\"M22 12h-2\"/><path d=\"m15 19-3-3-3 3\"/><path d=\"m15 5-3 3-3-3\"/>',\n} as const;\n\nexport type IconName = keyof typeof ICON_PATHS;\n\n/** SVG markup of a Lucide icon (decorative: hidden from assistive technology) */\nexport function iconSvg(name: IconName, size = 16, strokeWidth = 1.75): string {\n return (\n `<svg xmlns=\"http://www.w3.org/2000/svg\" class=\"explain-icon explain-icon-${name}\" ` +\n `width=\"${size}\" height=\"${size}\" viewBox=\"0 0 24 24\" fill=\"none\" stroke=\"currentColor\" ` +\n `stroke-width=\"${strokeWidth}\" stroke-linecap=\"round\" stroke-linejoin=\"round\" ` +\n `aria-hidden=\"true\" focusable=\"false\">${ICON_PATHS[name]}</svg>`\n );\n}\n\n/** A Lucide icon as a DOM element */\nexport function icon(name: IconName, size?: number, strokeWidth?: number): SVGElement {\n const template = document.createElement('template');\n template.innerHTML = iconSvg(name, size, strokeWidth);\n return template.content.firstElementChild as SVGElement;\n}\n", "/**\n * DOM rendering of the Explain view: sections, the execution plan (as a tree,\n * as text or as a sandboxed page) and the algebra tree.\n */\n\nimport type { Plan, PlanNode } from './types';\nimport type { AlgebraNode } from './algebra/print';\nimport { icon, type IconName } from './icons';\n\n/** A `<button>` with an icon and a label */\nexport function button(\n label: string,\n iconName: IconName | undefined,\n onClick: () => void,\n title?: string\n): HTMLButtonElement {\n const el = document.createElement('button');\n el.type = 'button';\n el.className = 'explain-button';\n if (iconName) el.appendChild(icon(iconName, 14));\n const text = document.createElement('span');\n text.textContent = label;\n el.appendChild(text);\n if (title) el.title = title;\n el.addEventListener('click', onClick);\n return el;\n}\n\n/** Copy text to the clipboard; falls back to a hidden textarea where the API is missing */\nexport async function copyText(text: string): Promise<boolean> {\n try {\n if (navigator.clipboard?.writeText) {\n await navigator.clipboard.writeText(text);\n return true;\n }\n } catch {\n // fall through\n }\n try {\n const area = document.createElement('textarea');\n area.value = text;\n area.setAttribute('readonly', '');\n area.style.position = 'fixed';\n area.style.opacity = '0';\n document.body.appendChild(area);\n area.select();\n const ok = document.execCommand('copy');\n area.remove();\n return ok;\n } catch {\n return false;\n }\n}\n\n/** A \"Copy\" button that shows \"Copied\" for a moment */\nexport function copyButton(getText: () => string, label = 'Copy'): HTMLButtonElement {\n const el = button(label, 'copy', async () => {\n const ok = await copyText(getText());\n const span = el.querySelector('span');\n if (span) {\n span.textContent = ok ? 'Copied' : 'Copy failed';\n setTimeout(() => (span.textContent = label), 1500);\n }\n });\n return el;\n}\n\nexport interface Section {\n root: HTMLElement;\n body: HTMLElement;\n actions: HTMLElement;\n setStatus(text: string, kind?: 'muted' | 'error'): void;\n}\n\n/** A titled, collapsible block with an action bar */\nexport function section(title: string, collapsed = false): Section {\n const root = document.createElement('section');\n root.className = 'explain-section';\n const header = document.createElement('div');\n header.className = 'explain-section-header';\n const toggle = document.createElement('button');\n toggle.type = 'button';\n toggle.className = 'explain-section-toggle';\n toggle.setAttribute('aria-expanded', String(!collapsed));\n toggle.appendChild(icon('chevron-down', 16));\n const heading = document.createElement('span');\n heading.className = 'explain-section-title';\n heading.textContent = title;\n toggle.appendChild(heading);\n const status = document.createElement('span');\n status.className = 'explain-section-status';\n const actions = document.createElement('div');\n actions.className = 'explain-section-actions';\n header.append(toggle, status, actions);\n const body = document.createElement('div');\n body.className = 'explain-section-body';\n root.append(header, body);\n root.classList.toggle('explain-section--collapsed', collapsed);\n toggle.addEventListener('click', () => {\n const isCollapsed = root.classList.toggle('explain-section--collapsed');\n toggle.setAttribute('aria-expanded', String(!isCollapsed));\n });\n return {\n root,\n body,\n actions,\n setStatus(text, kind = 'muted') {\n status.textContent = text;\n status.className = `explain-section-status explain-section-status--${kind}`;\n },\n };\n}\n\nexport function message(text: string, kind: 'muted' | 'error' | 'info' = 'muted'): HTMLElement {\n const el = document.createElement('div');\n el.className = `explain-message explain-message--${kind}`;\n el.textContent = text;\n return el;\n}\n\nfunction formatMs(ms: number): string {\n if (ms >= 10000) return `${(ms / 1000).toFixed(1)} s`;\n if (ms >= 100) return `${Math.round(ms)} ms`;\n if (ms >= 10) return `${ms.toFixed(1)} ms`;\n return `${ms.toFixed(2)} ms`;\n}\n\nfunction formatRows(rows: number): string {\n return rows.toLocaleString('en-US');\n}\n\n/** The largest own time in a plan tree, used to scale the time bars */\nfunction maxOwnTime(node: PlanNode): number {\n let max = node.timeMs ?? 0;\n for (const child of node.children) max = Math.max(max, maxOwnTime(child));\n return max;\n}\n\nfunction countNodes(node: PlanNode | AlgebraNode): number {\n return 1 + node.children.reduce((sum, child) => sum + countNodes(child as any), 0);\n}\n\nexport interface TreeHandle {\n root: HTMLElement;\n expandAll(): void;\n collapseAll(): void;\n}\n\n/** Render an execution plan tree: one row per operation with rows, time and a time bar */\nexport function renderPlanTree(root: PlanNode, summary?: string[]): TreeHandle {\n const container = document.createElement('div');\n container.className = 'explain-plan';\n if (summary && summary.length) {\n const summaryEl = document.createElement('div');\n summaryEl.className = 'explain-summary';\n for (const line of summary) {\n const item = document.createElement('span');\n item.textContent = line;\n summaryEl.appendChild(item);\n }\n container.appendChild(summaryEl);\n }\n const max = maxOwnTime(root);\n const hasTimes = max > 0;\n const tree = document.createElement('div');\n tree.className = 'explain-tree';\n tree.setAttribute('role', 'tree');\n const rows: HTMLElement[] = [];\n const slowest = hasTimes ? findSlowest(root, max) : undefined;\n\n const build = (node: PlanNode, depth: number, parent: HTMLElement) => {\n const item = document.createElement('div');\n item.className = 'explain-node';\n item.setAttribute('role', 'treeitem');\n if (node.cached) item.classList.add('explain-node--cached');\n if (node === slowest) item.classList.add('explain-node--slowest');\n if (node.status && /not started|lazily|skipped/i.test(node.status))\n item.classList.add('explain-node--inactive');\n\n const row = document.createElement('div');\n row.className = 'explain-row';\n row.style.setProperty('--explain-depth', String(depth));\n\n const toggle = document.createElement('button');\n toggle.type = 'button';\n toggle.className = 'explain-toggle';\n if (node.children.length) {\n toggle.appendChild(icon('chevron-down', 14));\n toggle.setAttribute('aria-label', 'Collapse');\n toggle.addEventListener('click', () => {\n const collapsed = item.classList.toggle('explain-node--collapsed');\n toggle.setAttribute('aria-label', collapsed ? 'Expand' : 'Collapse');\n item.setAttribute('aria-expanded', String(!collapsed));\n });\n item.setAttribute('aria-expanded', 'true');\n } else {\n toggle.classList.add('explain-toggle--leaf');\n toggle.tabIndex = -1;\n }\n row.appendChild(toggle);\n\n const main = document.createElement('div');\n main.className = 'explain-row-main';\n const label = document.createElement('div');\n label.className = 'explain-label';\n label.textContent = node.label;\n if (node.cached) {\n const badge = document.createElement('span');\n badge.className = 'explain-badge';\n badge.textContent = 'cached';\n label.appendChild(badge);\n }\n if (node.status && !/^(completed|fully materialized)$/i.test(node.status)) {\n const badge = document.createElement('span');\n badge.className = 'explain-badge explain-badge--status';\n badge.textContent = node.status;\n label.appendChild(badge);\n }\n main.appendChild(label);\n const metaLines: string[] = [];\n if (node.columns && node.columns.length) metaLines.push(node.columns.join(' '));\n if (node.details && node.details.length) metaLines.push(...node.details);\n if (metaLines.length) {\n const meta = document.createElement('div');\n meta.className = 'explain-meta';\n for (const line of metaLines) {\n const span = document.createElement('span');\n span.textContent = line;\n meta.appendChild(span);\n }\n main.appendChild(meta);\n }\n row.appendChild(main);\n\n const stats = document.createElement('div');\n stats.className = 'explain-stats';\n const rowsEl = document.createElement('span');\n rowsEl.className = 'explain-rows';\n rowsEl.textContent = node.rows !== undefined ? `${formatRows(node.rows)} rows` : '';\n const timeEl = document.createElement('span');\n timeEl.className = 'explain-time';\n if (node.timeMs !== undefined) {\n timeEl.textContent = formatMs(node.timeMs);\n if (node.totalMs !== undefined && node.totalMs !== node.timeMs) {\n timeEl.title = `This operation: ${formatMs(node.timeMs)}. With its children: ${formatMs(node.totalMs)}.`;\n }\n }\n const bar = document.createElement('span');\n bar.className = 'explain-bar';\n if (hasTimes && node.timeMs !== undefined) {\n const fill = document.createElement('span');\n fill.className = 'explain-bar-fill';\n fill.style.width = `${Math.max(1, Math.round((node.timeMs / max) * 100))}%`;\n bar.appendChild(fill);\n }\n stats.append(rowsEl, timeEl, bar);\n row.appendChild(stats);\n item.appendChild(row);\n rows.push(item);\n\n if (node.children.length) {\n const children = document.createElement('div');\n children.className = 'explain-children';\n children.setAttribute('role', 'group');\n for (const child of node.children) build(child, depth + 1, children);\n item.appendChild(children);\n }\n parent.appendChild(item);\n };\n build(root, 0, tree);\n container.appendChild(tree);\n if (!hasTimes) container.classList.add('explain-plan--no-times');\n return {\n root: container,\n expandAll: () => rows.forEach((row) => row.classList.remove('explain-node--collapsed')),\n collapseAll: () =>\n rows.forEach((row) => {\n if (row.querySelector(':scope > .explain-children'))\n row.classList.add('explain-node--collapsed');\n }),\n };\n}\n\nfunction findSlowest(node: PlanNode, max: number): PlanNode | undefined {\n if (node.timeMs === max && !node.cached) return node;\n for (const child of node.children) {\n const found = findSlowest(child, max);\n if (found) return found;\n }\n return node.timeMs === max ? node : undefined;\n}\n\n/** Render a text plan in a scrollable monospace block */\nexport function renderText(text: string): HTMLElement {\n const pre = document.createElement('pre');\n pre.className = 'explain-text';\n pre.textContent = text;\n return pre;\n}\n\n/** Render an HTML plan page in a sandboxed frame: no scripts, no navigation, same look as the engine's page */\nexport function renderHtml(html: string): HTMLElement {\n const frame = document.createElement('iframe');\n frame.className = 'explain-frame';\n frame.setAttribute('sandbox', '');\n frame.setAttribute('referrerpolicy', 'no-referrer');\n frame.title = 'Execution plan';\n frame.srcdoc = html;\n return frame;\n}\n\n/** Render the algebra tree */\nexport function renderAlgebraTree(root: AlgebraNode): TreeHandle {\n const tree = document.createElement('div');\n tree.className = 'explain-tree explain-algebra';\n tree.setAttribute('role', 'tree');\n const items: HTMLElement[] = [];\n const build = (node: AlgebraNode, depth: number, parent: HTMLElement) => {\n const item = document.createElement('div');\n item.className = 'explain-node';\n item.setAttribute('role', 'treeitem');\n const row = document.createElement('div');\n row.className = 'explain-row';\n row.style.setProperty('--explain-depth', String(depth));\n const toggle = document.createElement('button');\n toggle.type = 'button';\n toggle.className = 'explain-toggle';\n if (node.children.length) {\n toggle.appendChild(icon('chevron-down', 14));\n toggle.setAttribute('aria-label', 'Collapse');\n toggle.addEventListener('click', () => {\n const collapsed = item.classList.toggle('explain-node--collapsed');\n toggle.setAttribute('aria-label', collapsed ? 'Expand' : 'Collapse');\n item.setAttribute('aria-expanded', String(!collapsed));\n });\n item.setAttribute('aria-expanded', 'true');\n } else {\n toggle.classList.add('explain-toggle--leaf');\n toggle.tabIndex = -1;\n }\n row.appendChild(toggle);\n const main = document.createElement('div');\n main.className = 'explain-row-main';\n const label = document.createElement('div');\n label.className = 'explain-label';\n const op = document.createElement('span');\n op.className = 'explain-operator';\n op.textContent = node.operator;\n label.appendChild(op);\n if (node.args) {\n const args = document.createElement('span');\n args.className = 'explain-args';\n args.textContent = node.args;\n label.appendChild(args);\n }\n main.appendChild(label);\n if (node.details && node.details.length) {\n const details = document.createElement('div');\n details.className = 'explain-meta explain-meta--code';\n for (const line of node.details) {\n const span = document.createElement('span');\n span.textContent = line;\n details.appendChild(span);\n }\n main.appendChild(details);\n }\n row.appendChild(main);\n item.appendChild(row);\n items.push(item);\n if (node.children.length) {\n const children = document.createElement('div');\n children.className = 'explain-children';\n children.setAttribute('role', 'group');\n for (const child of node.children) build(child, depth + 1, children);\n item.appendChild(children);\n }\n parent.appendChild(item);\n };\n build(root, 0, tree);\n return {\n root: tree,\n expandAll: () => items.forEach((item) => item.classList.remove('explain-node--collapsed')),\n collapseAll: () =>\n items.forEach((item) => {\n if (item.querySelector(':scope > .explain-children'))\n item.classList.add('explain-node--collapsed');\n }),\n };\n}\n\n/** Render a plan of any kind */\nexport function renderPlan(plan: Plan): { root: HTMLElement; tree?: TreeHandle; text?: string } {\n switch (plan.kind) {\n case 'tree': {\n const tree = renderPlanTree(plan.root, plan.summary);\n return { root: tree.root, tree, text: planTreeToText(plan.root, plan.summary) };\n }\n case 'text':\n return { root: renderText(plan.text), text: plan.text };\n case 'html':\n return { root: renderHtml(plan.html), text: plan.html };\n }\n}\n\n/** A plan tree as indented text, for the clipboard and the download */\nexport function planTreeToText(root: PlanNode, summary?: string[]): string {\n const lines: string[] = [];\n if (summary && summary.length) lines.push(...summary, '');\n const walk = (node: PlanNode, depth: number) => {\n const stats: string[] = [];\n if (node.rows !== undefined) stats.push(`${formatRows(node.rows)} rows`);\n if (node.timeMs !== undefined) stats.push(formatMs(node.timeMs));\n if (node.cached) stats.push('cached');\n if (node.status && !/^(completed|fully materialized)$/i.test(node.status))\n stats.push(node.status);\n lines.push(\n `${' '.repeat(depth)}${node.label}${stats.length ? ` [${stats.join(', ')}]` : ''}`\n );\n for (const detail of node.details || []) lines.push(`${' '.repeat(depth + 1)}${detail}`);\n for (const child of node.children) walk(child, depth + 1);\n };\n walk(root, 0);\n return lines.join('\\n');\n}\n\nexport { countNodes };\n", "/**\n * YASGUI Explain plugin\n *\n * A YASR result view with two parts:\n * - the execution plan of the query, asked from the endpoint's engine with one\n * background request after the query ran (QLever, GraphDB, Stardog,\n * Blazegraph, Neptune, TripleTrail), and\n * - the SPARQL algebra of the query, computed in the browser for any endpoint.\n */\n\nimport type {\n Engine,\n EngineChoice,\n ExplainPluginOptions,\n Plan,\n PlanRequest,\n PlanResponse,\n Yasr,\n} from './types';\nimport { ENGINES, ENGINE_IDS, isEngineChoice, resolveEngine, type ResolvedEngine } from './engines';\nimport { getEngineChoice, setEngineChoice } from './settings';\nimport { getHostToolbar, hasHostExecuteQuery, hasHostRequestOptions, readQueryLink } from './host';\nimport { translate, AlgebraError, type Algebra } from './algebra/translate';\nimport { toSExpression, toTree, type AlgebraNode } from './algebra/print';\nimport type { Prefixes } from './algebra/terms';\nimport { icon } from './icons';\nimport {\n button,\n copyButton,\n countNodes,\n message,\n planTreeToText,\n renderAlgebraTree,\n renderPlan,\n section,\n type TreeHandle,\n} from './render';\n\nconst DEFAULT_PREFIXES: Prefixes = {\n rdf: 'http://www.w3.org/1999/02/22-rdf-syntax-ns#',\n rdfs: 'http://www.w3.org/2000/01/rdf-schema#',\n xsd: 'http://www.w3.org/2001/XMLSchema#',\n owl: 'http://www.w3.org/2002/07/owl#',\n};\n\ninterface PlanState {\n engine: Engine;\n key: string;\n status: 'loading' | 'done' | 'error';\n plan?: Plan;\n error?: string;\n}\n\nexport class ExplainPlugin {\n priority = 1;\n label = 'Explain';\n helpReference = 'https://github.com/Matdata-eu/yasgui-explain-plugin#readme';\n\n private yasr: Yasr;\n private options: ExplainPluginOptions;\n private container: HTMLElement | null = null;\n private hostToolbarNodes: Element[] = [];\n private abortController: AbortController | null = null;\n /** Plans already fetched, by engine, endpoint and query */\n private planCache = new Map<string, Plan>();\n private planState: PlanState | null = null;\n private planSection: ReturnType<typeof section> | null = null;\n private algebra: Algebra | undefined;\n private algebraError: string | undefined;\n private algebraText: string | undefined;\n private query: string | undefined;\n private endpoint: string | undefined;\n\n constructor(yasr: Yasr, options: ExplainPluginOptions = {}) {\n this.yasr = yasr;\n this.options = options;\n }\n\n /** Change options after construction; the next draw uses them */\n setOptions(options: Partial<ExplainPluginOptions>): void {\n this.options = { ...this.options, ...options };\n }\n\n static get label(): string {\n return 'Explain';\n }\n\n static get priority(): number {\n return 1;\n }\n\n getIcon(): Element | undefined {\n const el = icon('list-tree', 18);\n el.setAttribute('aria-label', 'Explain view');\n return el;\n }\n\n /** The view is useful for any response, including failed ones: the algebra never needs results */\n canHandleResults(): boolean {\n return !!this.yasr.results;\n }\n\n private getPluginName(): string {\n const plugins = this.yasr.plugins || {};\n for (const [name, plugin] of Object.entries(plugins)) if (plugin === this) return name;\n return 'Explain';\n }\n\n private getOptions(): ExplainPluginOptions {\n const dynamic = this.yasr.config?.plugins?.[this.getPluginName()]?.dynamicConfig;\n return {\n ...this.options,\n ...(dynamic && typeof dynamic === 'object' ? (dynamic as ExplainPluginOptions) : {}),\n };\n }\n\n /** The prefixes of the query (and of the host), with the usual RDF ones as a fallback */\n private getPrefixes(): Prefixes {\n let known: Prefixes = {};\n try {\n if (typeof this.yasr.getPrefixes === 'function') known = this.yasr.getPrefixes() || {};\n else {\n const prefixes = this.yasr.config?.prefixes;\n if (typeof prefixes === 'function') known = prefixes() || {};\n else if (prefixes && typeof prefixes === 'object') known = prefixes;\n }\n } catch {\n // no prefixes then\n }\n return { ...DEFAULT_PREFIXES, ...known };\n }\n\n private readQueryAndEndpoint(options: ExplainPluginOptions): void {\n const link = readQueryLink(this.yasr);\n this.query = (options.getQuery ? options.getQuery() : undefined) ?? link.query;\n this.endpoint = (options.getEndpoint ? options.getEndpoint() : undefined) ?? link.endpoint;\n }\n\n private serverHeader(): string | null {\n try {\n const headers = this.yasr.results?.res?.headers ?? this.yasr.results?.getHeaders?.();\n if (headers && typeof headers.get === 'function') return headers.get('server');\n if (headers && typeof headers === 'object') return headers.server ?? headers.Server ?? null;\n } catch {\n // headers not exposed\n }\n return null;\n }\n\n private resolveEngine(options: ExplainPluginOptions): ResolvedEngine {\n const stored = getEngineChoice(this.endpoint);\n return resolveEngine(stored, this.endpoint, this.serverHeader(), options.engine);\n }\n\n draw(): void {\n this.cleanup();\n const options = this.getOptions();\n this.readQueryAndEndpoint(options);\n\n const wrapper = document.createElement('div');\n wrapper.className = 'yasgui-explain-plugin';\n this.container = wrapper;\n\n const resolved = this.resolveEngine(options);\n this.drawToolbar(wrapper, options, resolved);\n\n // Execution plan\n this.planSection = section('Execution plan');\n wrapper.appendChild(this.planSection.root);\n this.drawPlanSection(options, resolved);\n\n // Algebra\n wrapper.appendChild(this.drawAlgebraSection(options));\n\n this.yasr.resultsEl.appendChild(wrapper);\n }\n\n private drawToolbar(\n wrapper: HTMLElement,\n options: ExplainPluginOptions,\n resolved: ResolvedEngine\n ): void {\n const slot = getHostToolbar(this.yasr);\n const host = !!slot;\n const nodes: Element[] = [];\n\n const engineLabel = document.createElement('label');\n engineLabel.className = host ? 'yasr_toolbarSelect' : 'explain-field';\n const engineText = document.createElement('span');\n engineText.textContent = 'Engine';\n const select = document.createElement('select');\n select.className = host ? '' : 'explain-select';\n select.setAttribute('aria-label', 'Engine of the endpoint');\n const addOption = (value: EngineChoice, text: string) => {\n const option = document.createElement('option');\n option.value = value;\n option.textContent = text;\n select.appendChild(option);\n };\n const detected =\n resolved.source === 'detected' && resolved.engine ? ` (${resolved.engine.label})` : '';\n addOption('auto', `Detect${detected}`);\n for (const id of options.engines || ENGINE_IDS)\n if (ENGINES[id]) addOption(id, ENGINES[id].label);\n addOption('none', 'No plan');\n const stored =\n options.engine && options.engine !== 'auto' ? options.engine : getEngineChoice(this.endpoint);\n select.value = isEngineChoice(stored) ? stored : 'auto';\n select.disabled = !!options.engine && options.engine !== 'auto';\n select.addEventListener('change', () => {\n const choice = select.value;\n if (!isEngineChoice(choice)) return;\n setEngineChoice(this.endpoint, choice);\n this.draw();\n });\n engineLabel.append(engineText, select);\n nodes.push(engineLabel);\n\n const refresh = button(\n 'Refresh plan',\n 'rotate-ccw',\n () => {\n if (this.planState) this.planCache.delete(this.planState.key);\n this.draw();\n },\n 'Ask the engine for the plan again'\n );\n if (host) refresh.className = 'yasr_toolbarButton';\n refresh.disabled = !resolved.engine;\n nodes.push(refresh);\n\n if (slot) {\n for (const node of nodes) slot.appendChild(node);\n this.hostToolbarNodes = nodes;\n } else {\n const toolbar = document.createElement('div');\n toolbar.className = 'explain-toolbar';\n for (const node of nodes) toolbar.appendChild(node);\n wrapper.appendChild(toolbar);\n }\n }\n\n private drawPlanSection(options: ExplainPluginOptions, resolved: ResolvedEngine): void {\n const planSection = this.planSection;\n if (!planSection) return;\n planSection.body.replaceChildren();\n planSection.actions.replaceChildren();\n this.planState = null;\n\n if (!resolved.engine) {\n planSection.setStatus('');\n planSection.body.appendChild(\n message(\n resolved.source === 'none'\n ? 'No engine recognised for this endpoint. Pick it in the Engine list when it is QLever, GraphDB, Stardog, Blazegraph, Neptune or TripleTrail; other engines publish no plan over the SPARQL protocol.'\n : 'No plan is asked for this endpoint. Pick an engine in the Engine list to fetch one.'\n )\n );\n return;\n }\n if (!this.query || !this.endpoint) {\n planSection.setStatus('');\n planSection.body.appendChild(\n message('The plugin cannot read the query and the endpoint of this tab.')\n );\n return;\n }\n const engine = resolved.engine;\n const key = `${engine.id}\\n${this.endpoint}\\n${this.query}`;\n planSection.setStatus(engine.label);\n const cached = this.planCache.get(key);\n if (cached) {\n this.showPlan({ engine, key, status: 'done', plan: cached });\n return;\n }\n if (options.autoFetch === false) {\n this.planState = { engine, key, status: 'error' };\n planSection.body.appendChild(\n message(`Press \"Refresh plan\" to ask ${engine.label} for the plan.`)\n );\n return;\n }\n void this.fetchPlan(engine, key);\n }\n\n private async fetchPlan(engine: Engine, key: string): Promise<void> {\n const planSection = this.planSection;\n if (!planSection || !this.query || !this.endpoint) return;\n this.abortController?.abort();\n const controller = new AbortController();\n this.abortController = controller;\n this.planState = { engine, key, status: 'loading' };\n planSection.body.replaceChildren(message(`Asking ${engine.label} for the plan\u2026`, 'info'));\n let request: PlanRequest;\n try {\n request = engine.buildRequest(this.query, this.endpoint);\n } catch (error) {\n this.showPlan({\n engine,\n key,\n status: 'error',\n error: error instanceof Error ? error.message : String(error),\n });\n return;\n }\n try {\n const response = await this.runRequest(engine, request, controller.signal);\n if (controller.signal.aborted) return;\n const { body, contentType, status } = await readResponse(response);\n if (status !== undefined && status >= 400) {\n const where = request.endpoint ? ` from ${request.endpoint}` : '';\n const hint =\n status === 404 && request.endpoint\n ? ' The server does not expose this explain URL; a proxy in front of the endpoint may only forward queries.'\n : '';\n throw new Error(\n `HTTP ${status}${where}${body ? `: ${body.slice(0, 500)}` : ''}.${hint}`.replace(\n '..',\n '.'\n )\n );\n }\n const plan = engine.parse(body, contentType);\n this.planCache.set(key, plan);\n if (controller.signal.aborted) return;\n this.showPlan({ engine, key, status: 'done', plan });\n } catch (error) {\n if (controller.signal.aborted) return;\n const text = error instanceof Error ? error.message : String(error);\n this.showPlan({ engine, key, status: 'error', error: text });\n } finally {\n if (this.abortController === controller) this.abortController = null;\n }\n }\n\n /** Send the plan request through the host (with the tab's settings) or, failing that, directly */\n private async runRequest(\n engine: Engine,\n request: PlanRequest,\n signal: AbortSignal\n ): Promise<PlanResponse> {\n const custom = this.getOptions().requestPlan;\n if (custom) return custom(request, signal);\n // The host runs the request with the tab's authentication and settings. Hosts without\n // `queryRequest` drop `extraArgs` and `endpoint`: fine when the engine only prefers them.\n if (\n hasHostExecuteQuery(this.yasr) &&\n (!engine.needsRequestOptions || hasHostRequestOptions(this.yasr))\n ) {\n return this.yasr.executeQuery!(request.query, {\n acceptHeader: request.accept,\n signal,\n extraArgs: request.extraArgs,\n endpoint: request.endpoint,\n });\n }\n // Plain fetch: no authentication or custom headers of the tab\n const url = request.endpoint || this.endpoint!;\n const params = new URLSearchParams();\n params.set('query', request.query);\n for (const [name, value] of Object.entries(request.extraArgs || {})) params.set(name, value);\n const response = await fetch(url, {\n method: 'POST',\n headers: { Accept: request.accept, 'Content-Type': 'application/x-www-form-urlencoded' },\n body: params.toString(),\n signal,\n mode: 'cors',\n });\n const content = await response.text();\n return { status: response.status, headers: response.headers, content };\n }\n\n private showPlan(state: PlanState): void {\n const planSection = this.planSection;\n if (!planSection) return;\n this.planState = state;\n planSection.body.replaceChildren();\n planSection.actions.replaceChildren();\n if (state.status === 'error' || !state.plan) {\n planSection.setStatus(`${state.engine.label}: failed`, 'error');\n planSection.body.appendChild(message(state.error || 'No plan.', 'error'));\n planSection.body.appendChild(message(state.engine.description));\n return;\n }\n const rendered = renderPlan(state.plan);\n const count = state.plan.kind === 'tree' ? countNodes(state.plan.root) : undefined;\n planSection.setStatus(\n count !== undefined ? `${state.engine.label} \u00B7 ${count} operations` : state.engine.label\n );\n if (rendered.tree) this.addTreeActions(planSection.actions, rendered.tree);\n if (rendered.text !== undefined && state.plan.kind !== 'html') {\n planSection.actions.appendChild(copyButton(() => rendered.text || ''));\n }\n planSection.body.appendChild(rendered.root);\n }\n\n private addTreeActions(actions: HTMLElement, tree: TreeHandle): void {\n actions.appendChild(button('Expand all', 'unfold-vertical', () => tree.expandAll()));\n actions.appendChild(button('Collapse all', 'fold-vertical', () => tree.collapseAll()));\n }\n\n private drawAlgebraSection(options: ExplainPluginOptions): HTMLElement {\n const algebraSection = section('Algebra');\n this.algebra = undefined;\n this.algebraError = undefined;\n this.algebraText = undefined;\n if (!this.query) {\n algebraSection.body.appendChild(message('The plugin cannot read the query of this tab.'));\n return algebraSection.root;\n }\n const prefixes = this.getPrefixes();\n let tree: AlgebraNode;\n try {\n this.algebra = translate(this.query, { baseIRI: options.baseIRI });\n tree = toTree(this.algebra, prefixes);\n this.algebraText = toSExpression(this.algebra, prefixes);\n } catch (error) {\n this.algebraError = error instanceof AlgebraError ? error.message : String(error);\n algebraSection.setStatus('syntax error', 'error');\n algebraSection.body.appendChild(message(this.algebraError, 'error'));\n return algebraSection.root;\n }\n algebraSection.setStatus(`${countNodes(tree)} operations`);\n const handle = renderAlgebraTree(tree);\n this.addTreeActions(algebraSection.actions, handle);\n algebraSection.actions.appendChild(copyButton(() => this.algebraText || '', 'Copy'));\n algebraSection.body.appendChild(handle.root);\n return algebraSection.root;\n }\n\n /** YASR's download button saves the plan and the algebra as text */\n download(filename?: string) {\n const parts: string[] = [];\n if (this.planState?.plan) {\n parts.push(`# Execution plan (${this.planState.engine.label})`, '');\n const plan = this.planState.plan;\n parts.push(\n plan.kind === 'tree'\n ? planTreeToText(plan.root, plan.summary)\n : plan.kind === 'text'\n ? plan.text\n : plan.html\n );\n parts.push('');\n }\n if (this.algebraText) parts.push('# Algebra', '', this.algebraText, '');\n if (parts.length === 0) return undefined;\n const base = (filename || 'query').replace(/\\.[a-z0-9]+$/i, '');\n return {\n getData: () => parts.join('\\n'),\n contentType: 'text/plain',\n filename: `${base}-explain.txt`,\n title: 'Download the plan and the algebra',\n };\n }\n\n private cleanup(): void {\n this.abortController?.abort();\n this.abortController = null;\n for (const node of this.hostToolbarNodes) node.remove();\n this.hostToolbarNodes = [];\n this.container?.remove();\n this.container = null;\n this.planSection = null;\n }\n\n destroy(): void {\n this.cleanup();\n this.planCache.clear();\n }\n}\n\nasync function readResponse(\n response: PlanResponse\n): Promise<{ body: string; contentType: string | undefined; status: number | undefined }> {\n let body: string | undefined =\n typeof response?.content === 'string' ? response.content : undefined;\n if (body === undefined && typeof response?.data === 'string') body = response.data;\n if (body === undefined && typeof response?.text === 'function') body = await response.text();\n if (body === undefined && response && typeof response === 'object' && !('status' in response))\n body = JSON.stringify(response);\n let contentType: string | undefined;\n const headers: any = response?.headers;\n if (headers && typeof headers.get === 'function')\n contentType = headers.get('content-type') || undefined;\n else if (headers && typeof headers === 'object')\n contentType = headers['content-type'] || headers['Content-Type'];\n return { body: body ?? '', contentType, status: response?.status };\n}\n\nexport default ExplainPlugin;\n"],
|
|
5
|
+
"mappings": ";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA,0CAAAA,UAAAC,SAAA;AAAA;AAMA,IAAAA,QAAO,UAAU,SAASC,OAAMC,IAAG,GAAG;AACpC,UAAIA,OAAM,EAAG,QAAO;AAEpB,UAAIA,MAAK,KAAK,OAAOA,MAAK,YAAY,OAAO,KAAK,UAAU;AAC1D,YAAIA,GAAE,gBAAgB,EAAE,YAAa,QAAO;AAE5C,YAAI,QAAQ,GAAGC;AACf,YAAI,MAAM,QAAQD,EAAC,GAAG;AACpB,mBAASA,GAAE;AACX,cAAI,UAAU,EAAE,OAAQ,QAAO;AAC/B,eAAK,IAAI,QAAQ,QAA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C,kBAAc,QAAQ,IAAI,cAAc,KAAK;AAAA,WACtC,WAAW,OAAO,YAAY;AACrC,kBAAc,QAAQ,cAAc,KAAK,QAAQ,cAAc;AACjE,SAAO,EAAE,MAAM,sBAAQ,IAAI,aAAa,QAAQ,qCAAU,OAAO;AACnE;AAEA,IAAO,wBAAQ;;;AvX7df,IAAI,OAAO,WAAW,eAAe,OAAO,UAAU,OAAO,OAAO,MAAM;AACxE,SAAO,OAAO,KAAK,eAAe,WAAW,qBAAa;AAC5D;AAEA,IAAO,gBAAQ;",
|
|
6
|
+
"names": ["exports", "module", "equal", "a", "keys", "exports", "exports", "exports", "exports", "object", "graph", "exports", "exports", "DataFactory", "object", "graph", "exports", "exports", "exports", "termToString", "stringToTerm", "exports", "query", "query", "query", "query", "query", "explainUrl", "isNumber", "seconds", "root", "query", "path", "query", "first", "last", "copy", "obj", "Symbol", "objectProto", "nativeObjectToString", "symToStringTag", "string", "INFINITY", "funcProto", "funcToString", "hasOwnProperty", "object", "WeakMap", "count", "MAX_SAFE_INTEGER", "Buffer", "argsTag", "funcTag", "freeExports", "freeModule", "moduleExports", "types", "HASH_UNDEFINED", "Map", "map", "path", "values", "offset", "rsAstralRange", "rsComboMarksRange", "reComboHalfMarksRange", "rsComboSymbolsRange", "rsComboRange", "rsVarRange", "rsZWJ", "object", "freeExports", "freeModule", "moduleExports", "Buffer", "objectProto", "propertyIsEnumerable", "nativeGetSymbols", "Promise", "Set", "mapTag", "objectTag", "setTag", "weakMapTag", "dataViewTag", "hasOwnProperty", "Uint8Array", "symbolProto", "boolTag", "dateTag", "numberTag", "regexpTag", "stringTag", "symbolTag", "arrayBufferTag", "float32Tag", "float64Tag", "int8Tag", "int16Tag", "int32Tag", "uint8Tag", "uint8ClampedTag", "uint16Tag", "uint32Tag", "argsTag", "arrayTag", "errorTag", "funcTag", "genTag", "key", "CLONE_SYMBOLS_FLAG", "HASH_UNDEFINED", "values", "othValue", "map", "COMPARE_PARTIAL_FLAG", "COMPARE_UNORDERED_FLAG", "symbolValueOf", "path", "collection", "LARGE_ARRAY_SIZE", "includes", "nativeMax", "FUNC_ERROR_TEXT", "INFINITY", "from", "to", "str", "message", "LexerDefinitionErrorType", "offset", "msg", "currConfig", "tokenLabel", "hasTokenLabel", "hasTokenLabel", "tokenLabel", "getExtraProductionArgument", "path", "PROD_TYPE", "tokenMatcher", "path", "keys", "prefixKeys", "collectorVisitor", "message", "resolveGrammar", "validateGrammar", "rules", "CstVisitorDefinitionError", "allTokenTypes", "separator", "ParserDefinitionErrorType", "resolveGrammar", "validateGrammar", "str", "createToken", "rules", "rules", "self", "rules", "rules", "rules", "self", "parser", "defaults", "_a", "_b", "_c", "copy", "pending", "context", "_d", "copy", "copy", "add", "baseDecl", "bind", "clear", "copy", "create", "deleteClause", "drop", "filter", "insertClause", "iri", "load", "move", "prefixDecl", "usingClause", "drop", "filter", "values", "BuiltInCalls", "string", "createToken", "createToken", "decimalPattern", "createToken", "createToken", "decimalPattern", "createToken", "values", "drop", "filter", "nodeType", "distinct", "separator", "nodeType", "graphRef", "graph", "nodeType", "nodeType", "variables", "values", "expression", "silent", "nodeType", "where", "values", "nodeType", "having", "limit", "offset", "nodeType", "nodeType", "silent", "where", "from", "graph", "graphNode", "object", "graph", "CommonIRIs", "expression", "variables", "query", "groupBy", "var_", "update", "blankNode", "str", "lang", "iri", "F", "baseDecl", "prefixDecl", "F", "iri", "iri", "usingClause", "F", "named", "nil", "distinct", "F", "F", "iri", "head", "hat", "exclamation", "F", "blankNode", "where", "F", "filter", "bind", "optional", "graph", "service", "silent", "values", "variables", "var_", "nil", "iri", "minus", "group", "head", "expression", "nil", "distinct", "F", "head", "expression", "integer", "iri", "functionCall", "having", "order", "F", "limit", "offset", "values", "F", "from", "where", "select", "distinct", "reduced", "last", "star", "variables", "construct", "describe", "ask", "update", "F", "head", "load", "clear", "drop", "add", "move", "copy", "create", "silent", "iri", "createToken", "graph", "del", "deleteClause", "insert", "insertClause", "where", "named", "graphAll", "quads", "last", "values", "update", "F", "rules", "rules", "rules", "validators_exports", "findPatternBoundedVars", "queryProjectionIsGood", "AstFactory", "object", "reifier", "version", "F", "AstFactory", "findPatternBoundedVars", "values", "annotation", "queryProjectionIsGood", "query", "variables", "groupBy", "grammar_exports", "buildInHasLang", "buildInHasLangDir", "buildInLangDir", "builtInCall", "dataBlockValue", "graphNode", "graphNodePath", "iriFull", "object", "objectPath", "primaryExpression", "prologue", "rdfLiteral", "selectQuery", "string", "triplesSameSubject", "triplesSameSubjectPath", "unaryExpression", "varOrTerm", "lexer_exports", "iriRef", "stringLiteral1", "stringLiteral2", "stringLiteralLong1", "stringLiteralLong2", "createToken", "iriRef", "stringLiteral1", "stringLiteral2", "stringLiteralLong1", "stringLiteralLong2", "AstFactory", "F", "selectQuery", "from", "where", "queryProjectionIsGood", "stringLiteral1", "stringLiteral2", "prologue", "dataBlockValue", "reifier", "triplesSameSubjectImpl", "triplesSameSubject", "triplesSameSubjectPath", "objectImpl", "graphNodePath", "graphNode", "object", "objectPath", "annotation", "head", "varOrTerm", "rdfLiteral", "primaryExpression", "buildInLangDir", "buildInHasLang", "buildInHasLangDir", "builtInCall", "langTag", "string", "stringLiteralLong1", "stringLiteralLong2", "iriFull", "iriRef", "unaryExpression", "validators_exports", "grammar_exports", "Parser", "lexer_exports", "query", "Types", "ExpressionTypes", "transformer", "path", "iri", "F", "values", "variables", "map", "transformer", "import_rdf_data_factory", "flatten", "aggregate", "expression", "distinct", "separator", "named", "variables", "path", "iri", "object", "graph", "silent", "str", "where", "F", "object", "collection", "F", "object", "graph", "update", "F", "where", "graph", "quads", "F", "F", "pattern", "filter", "expression", "path", "A", "F", "query", "variables", "having", "order", "var_", "expression", "filter", "bind", "aggregate", "equal", "import_rdf_string", "iri", "lang", "collection", "object", "F", "annotation", "subject", "inScopeVariables", "findPatternBoundedVars", "createAlgebraContext", "AstFactory", "inScopeVariables", "query", "createAlgebraContext", "transformer", "message", "query", "Parser", "iri", "datatype", "path", "as", "expression", "distinct", "separator", "a", "head", "root", "formatMs", "ms", "max", "sum", "known", "select", "where", "count"]
|
|
7
|
+
}
|