@cloudcare/codemirror-dql 0.0.55 → 0.0.56

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.
@@ -1,49 +1,3105 @@
1
1
  "use strict";
2
+ var __assign = (this && this.__assign) || function () {
3
+ __assign = Object.assign || function(t) {
4
+ for (var s, i = 1, n = arguments.length; i < n; i++) {
5
+ s = arguments[i];
6
+ for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
7
+ t[p] = s[p];
8
+ }
9
+ return t;
10
+ };
11
+ return __assign.apply(this, arguments);
12
+ };
13
+ var __rest = (this && this.__rest) || function (s, e) {
14
+ var t = {};
15
+ for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
16
+ t[p] = s[p];
17
+ if (s != null && typeof Object.getOwnPropertySymbols === "function")
18
+ for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
19
+ if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))
20
+ t[p[i]] = s[p[i]];
21
+ }
22
+ return t;
23
+ };
24
+ var __read = (this && this.__read) || function (o, n) {
25
+ var m = typeof Symbol === "function" && o[Symbol.iterator];
26
+ if (!m) return o;
27
+ var i = m.call(o), r, ar = [], e;
28
+ try {
29
+ while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);
30
+ }
31
+ catch (error) { e = { error: error }; }
32
+ finally {
33
+ try {
34
+ if (r && !r.done && (m = i["return"])) m.call(i);
35
+ }
36
+ finally { if (e) throw e.error; }
37
+ }
38
+ return ar;
39
+ };
40
+ var __spreadArray = (this && this.__spreadArray) || function (to, from, pack) {
41
+ if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {
42
+ if (ar || !(i in from)) {
43
+ if (!ar) ar = Array.prototype.slice.call(from, 0, i);
44
+ ar[i] = from[i];
45
+ }
46
+ }
47
+ return to.concat(ar || Array.prototype.slice.call(from));
48
+ };
49
+ var __values = (this && this.__values) || function(o) {
50
+ var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0;
51
+ if (m) return m.call(o);
52
+ if (o && typeof o.length === "number") return {
53
+ next: function () {
54
+ if (o && i >= o.length) o = void 0;
55
+ return { value: o && o[i++], done: !o };
56
+ }
57
+ };
58
+ throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined.");
59
+ };
2
60
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.Parser = void 0;
61
+ exports.Parser = exports.dqlSyntaxContexts = void 0;
62
+ var common_1 = require("@lezer/common");
4
63
  var language_1 = require("@codemirror/language");
64
+ var maxRepairDepth = 8;
65
+ var maxMismatchRepairDepth = 3;
66
+ var analysisBudgetMs = 100;
67
+ var maxDiagnostics = 100;
68
+ var numericClauses = new Map([
69
+ ['LimitClause', 'LIMIT'],
70
+ ['OffsetClause', 'OFFSET'],
71
+ ['SLimitClause', 'SLIMIT'],
72
+ ['SOffsetClause', 'SOFFSET'],
73
+ ]);
74
+ var queryClauseLabels = new Map([
75
+ ['TargetClause', 'projection'],
76
+ ['FilterClause', 'WHERE'],
77
+ ['TimeClause', 'time range'],
78
+ ['ByClause', 'BY'],
79
+ ['HavingClause', 'HAVING'],
80
+ ['OrderClause', 'ORDER BY'],
81
+ ['LimitClause', 'LIMIT'],
82
+ ['OffsetClause', 'OFFSET'],
83
+ ['SOrderClause', 'SORDER BY'],
84
+ ['SLimitClause', 'SLIMIT'],
85
+ ['SOffsetClause', 'SOFFSET'],
86
+ ]);
87
+ var expressionParents = new Set(['BinaryExpr', 'Expr', 'HavingExpr', 'ProjectionExpr']);
88
+ var commaContextBoundaries = new Set(['CaseExpr', 'Query']);
89
+ exports.dqlSyntaxContexts = {
90
+ DQL: 'DQL query',
91
+ DQLConditions: 'DQL condition',
92
+ QueryExpr: 'DQL query',
93
+ ShowExpr: 'SHOW expression',
94
+ QueryFragment: 'query fragment',
95
+ QueryFragmentClause: 'query fragment clause',
96
+ Query: 'query structure',
97
+ QueryClause: 'query clause',
98
+ Namespace: 'namespace',
99
+ IndexExpr: 'namespace index list',
100
+ IndexItem: 'namespace index',
101
+ DataSourceListFragment: 'data source list fragment',
102
+ DataSourceItemFragment: 'data source fragment',
103
+ DataSourceList: 'data source list',
104
+ DataSourceItem: 'data source',
105
+ QuerySource: 'nested query',
106
+ OuterFunctionCall: 'outer function call',
107
+ RawOuterFunctionCallBody: 'outer function arguments',
108
+ RequiredNumberOuterFunctionCallBody: 'outer function arguments',
109
+ OptionalNumberOuterFunctionCallBody: 'outer function arguments',
110
+ FillOuterFunctionCallBody: 'outer function arguments',
111
+ VariadicOuterFunctionCallBody: 'outer function arguments',
112
+ EvalExpr: 'eval expression',
113
+ FunctionCall: 'function call',
114
+ EvalIdentifier: 'eval function name',
115
+ RollupIdentifier: 'rollup function name',
116
+ RollupFunctionCall: 'rollup function call',
117
+ RollupFunctionCallBody: 'rollup function arguments',
118
+ RollupArg: 'rollup function argument',
119
+ FunctionIdentifier: 'function name',
120
+ OuterFunctionCallBody: 'outer function arguments',
121
+ OuterArgItem: 'outer function argument',
122
+ Queted: 'quoted query delimiter',
123
+ EvalCallBody: 'eval function arguments',
124
+ FunctionCallBody: 'function arguments',
125
+ ArgItem: 'function argument',
126
+ InValue: 'argument value list',
127
+ SingleExpr: 'expression value',
128
+ Expr: 'expression',
129
+ HavingClause: 'HAVING clause',
130
+ SingleHavingExpr: 'HAVING expression value',
131
+ HavingExpr: 'HAVING expression',
132
+ TargetClause: 'projection clause',
133
+ Projection: 'projection list',
134
+ ProjectFunc: 'projection function list',
135
+ ProjectFuncItem: 'projection function',
136
+ ProjectionFragment: 'projection fragment',
137
+ ProjectionItemFragment: 'projection fragment item',
138
+ ProjectionItem: 'projection item',
139
+ ProjectionFieldFragment: 'projection field fragment',
140
+ ProjectionField: 'projection field',
141
+ SingleFieldExpr: 'projection expression value',
142
+ ProjectionExpr: 'projection expression',
143
+ AsExpr: 'alias',
144
+ FilterClause: 'filter clause',
145
+ InFieldValue: 'filter value list',
146
+ FieldName: 'field name',
147
+ JsonField: 'JSON field path',
148
+ CaseExpr: 'CASE expression',
149
+ CaseOperand: 'CASE operand',
150
+ CaseWhenClause: 'CASE WHEN clause',
151
+ CaseElseClause: 'CASE ELSE clause',
152
+ CaseCondition: 'CASE condition',
153
+ CaseFilterExpr: 'CASE filter expression',
154
+ CasePredicate: 'CASE predicate',
155
+ CaseValue: 'CASE value',
156
+ CaseFunctionCall: 'CASE function call',
157
+ CaseFunctionIdentifier: 'CASE function name',
158
+ CaseFunctionCallBody: 'CASE function arguments',
159
+ FilterFragmentExpr: 'filter fragment',
160
+ ComparisonExpr: 'comparison expression',
161
+ LogicalFragmentExpr: 'logical filter expression',
162
+ LogicOp: 'logical operator',
163
+ NotInSeq: 'NOT IN operator',
164
+ Operator: 'comparison operator',
165
+ FilterSubExpr: 'filter subquery',
166
+ FilterExpr: 'filter expression',
167
+ BinaryExpr: 'binary expression',
168
+ TimeClause: 'time range clause',
169
+ TimeRange: 'time range',
170
+ TimeExpr: 'time range value',
171
+ ByClause: 'BY clause',
172
+ OrderClause: 'ORDER BY clause',
173
+ SOrderClause: 'SORDER BY clause',
174
+ LimitClause: 'LIMIT clause',
175
+ OffsetClause: 'OFFSET clause',
176
+ SLimitClause: 'SLIMIT clause',
177
+ SOffsetClause: 'SOFFSET clause',
178
+ ByExpr: 'grouping expression',
179
+ ByListExpr: 'grouping field list',
180
+ ByItem: 'grouping field',
181
+ FieldCall: 'grouping field function',
182
+ SingleByExpr: 'grouping expression value',
183
+ ByMathExpr: 'grouping expression',
184
+ NestedByMathExpr: 'nested grouping expression',
185
+ };
186
+ var functionCallBodyParents = new Set([
187
+ 'FunctionCallBody',
188
+ 'EvalCallBody',
189
+ 'OuterFunctionCallBody',
190
+ 'RawOuterFunctionCallBody',
191
+ 'RequiredNumberOuterFunctionCallBody',
192
+ 'OptionalNumberOuterFunctionCallBody',
193
+ 'FillOuterFunctionCallBody',
194
+ 'VariadicOuterFunctionCallBody',
195
+ 'RollupFunctionCallBody',
196
+ 'CaseFunctionCallBody',
197
+ ]);
5
198
  var Parser = /** @class */ (function () {
6
- function Parser(state) {
7
- this.tree = (0, language_1.syntaxTree)(state);
199
+ function Parser(state, deadline) {
200
+ if (deadline === void 0) { deadline = Date.now() + analysisBudgetMs; }
8
201
  this.state = state;
202
+ this.deadline = deadline;
203
+ var completeTree = this.getCompleteTree(state);
204
+ this.tree = completeTree !== null && completeTree !== void 0 ? completeTree : common_1.Tree.empty;
205
+ this.treeComplete = Boolean(completeTree && completeTree.topNode.to >= state.doc.length);
9
206
  this.diagnostics = [];
207
+ this.repairDepth = 0;
208
+ this.mismatchRepairDepth = 0;
209
+ this.terminalRepairUsed = false;
210
+ this.delimiterIssue = undefined;
211
+ this.quotedQueryDelimiterInfo = undefined;
212
+ this.caseResultDiagnostics = undefined;
213
+ this.caseResultRecoveryErrors = new Set();
10
214
  }
11
215
  Parser.prototype.getDiagnostics = function () {
12
- return this.diagnostics.sort(function (a, b) {
216
+ var seen = new Set();
217
+ var diagnostics = __spreadArray([], __read(this.diagnostics), false).sort(function (a, b) {
13
218
  return a.from - b.from;
219
+ })
220
+ .filter(function (diagnostic) {
221
+ var key = "".concat(diagnostic.from, ":").concat(diagnostic.to, ":").concat(diagnostic.message);
222
+ if (seen.has(key))
223
+ return false;
224
+ seen.add(key);
225
+ return true;
14
226
  });
227
+ if (diagnostics.length <= maxDiagnostics)
228
+ return diagnostics;
229
+ var headCount = Math.floor((maxDiagnostics - 1) / 2);
230
+ var tailCount = maxDiagnostics - headCount - 1;
231
+ return __spreadArray(__spreadArray(__spreadArray([], __read(diagnostics.slice(0, headCount)), false), __read(diagnostics.slice(-tailCount)), false), [
232
+ {
233
+ severity: 'warning',
234
+ source: 'DQL syntax',
235
+ message: "too many syntax errors; showing the first ".concat(headCount, " and last ").concat(tailCount),
236
+ from: this.state.doc.length,
237
+ to: this.state.doc.length,
238
+ },
239
+ ], false);
15
240
  };
16
241
  Parser.prototype.analyze = function () {
17
- // when you are at the root of the tree, the first node is not `Expr` but a node with no name.
18
- // So to be able to iterate other the node relative to the promql node, we have to get the first child at the beginning
19
- this.checkAST(this.tree.topNode.firstChild);
20
- this.diagnoseAllErrorNodes();
242
+ var isPrimaryAnalysis = this.repairDepth === 0 && this.mismatchRepairDepth === 0;
243
+ try {
244
+ if (this.maskLineComments(this.state.doc.toString()).trim().length === 0) {
245
+ return;
246
+ }
247
+ if (!this.treeComplete || Date.now() >= this.deadline) {
248
+ if (isPrimaryAnalysis) {
249
+ this.pushIncompleteAnalysisWarning();
250
+ }
251
+ return;
252
+ }
253
+ var delimiterIssue = this.getDelimiterIssue();
254
+ if (Date.now() >= this.deadline) {
255
+ if (isPrimaryAnalysis && this.diagnostics.length === 0)
256
+ this.pushIncompleteAnalysisWarning();
257
+ return;
258
+ }
259
+ if (isPrimaryAnalysis && !delimiterIssue)
260
+ this.checkAST(this.tree.topNode.firstChild);
261
+ if (Date.now() >= this.deadline) {
262
+ if (isPrimaryAnalysis && this.diagnostics.length === 0)
263
+ this.pushIncompleteAnalysisWarning();
264
+ return;
265
+ }
266
+ this.diagnoseAllErrorNodes();
267
+ if (isPrimaryAnalysis && Date.now() >= this.deadline && this.diagnostics.length === 0)
268
+ this.pushIncompleteAnalysisWarning();
269
+ }
270
+ catch (error) {
271
+ if (!(error instanceof RangeError))
272
+ throw error;
273
+ this.diagnostics.length = 0;
274
+ if (isPrimaryAnalysis) {
275
+ this.diagnostics.push({
276
+ severity: 'warning',
277
+ source: 'DQL syntax',
278
+ message: 'syntax analysis stopped because the query is too deeply nested',
279
+ from: 0,
280
+ to: Math.min(1, this.state.doc.length),
281
+ });
282
+ }
283
+ }
284
+ };
285
+ Parser.prototype.pushIncompleteAnalysisWarning = function () {
286
+ var message = 'syntax analysis incomplete; query is too large or deeply nested';
287
+ if (this.diagnostics.some(function (diagnostic) { return diagnostic.message === message; }))
288
+ return;
289
+ this.diagnostics.push({
290
+ severity: 'warning',
291
+ source: 'DQL syntax',
292
+ message: message,
293
+ from: 0,
294
+ to: Math.min(1, this.state.doc.length),
295
+ });
296
+ };
297
+ Parser.prototype.getCompleteTree = function (state) {
298
+ try {
299
+ if ((0, language_1.syntaxTreeAvailable)(state, state.doc.length)) {
300
+ var ready = (0, language_1.ensureSyntaxTree)(state, state.doc.length, 0);
301
+ if (ready && ready.topNode.to >= state.doc.length)
302
+ return ready;
303
+ }
304
+ var remaining = this.deadline - Date.now();
305
+ if (remaining <= 0)
306
+ return null;
307
+ var tree = (0, language_1.ensureSyntaxTree)(state, state.doc.length, Math.max(1, Math.ceil(remaining)));
308
+ return tree && tree.topNode.to >= state.doc.length ? tree : null;
309
+ }
310
+ catch (error) {
311
+ if (error instanceof RangeError)
312
+ return null;
313
+ throw error;
314
+ }
21
315
  };
22
316
  Parser.prototype.diagnoseAllErrorNodes = function () {
317
+ var e_1, _a, e_2, _b, e_3, _c, e_4, _d, e_5, _e, e_6, _f, e_7, _g, e_8, _h;
318
+ var _this = this;
319
+ var _j, _k, _l;
23
320
  var cursor = this.tree.cursor();
321
+ var groups = new Set();
322
+ var diagnostics = [];
323
+ var quotedQueryInfo = this.findQuotedQueryDelimiterInfo();
324
+ var _loop_1 = function (fallbackDiagnostic) {
325
+ if (!diagnostics.some(function (existing) { return _this.isSameDiagnostic(existing, fallbackDiagnostic); }))
326
+ diagnostics.push(fallbackDiagnostic);
327
+ };
328
+ try {
329
+ for (var _m = __values(quotedQueryInfo.fallbackDiagnostics), _o = _m.next(); !_o.done; _o = _m.next()) {
330
+ var fallbackDiagnostic = _o.value;
331
+ _loop_1(fallbackDiagnostic);
332
+ }
333
+ }
334
+ catch (e_1_1) { e_1 = { error: e_1_1 }; }
335
+ finally {
336
+ try {
337
+ if (_o && !_o.done && (_a = _m.return)) _a.call(_m);
338
+ }
339
+ finally { if (e_1) throw e_1.error; }
340
+ }
341
+ if (Date.now() >= this.deadline) {
342
+ this.appendDiagnostics(diagnostics);
343
+ return;
344
+ }
345
+ if (quotedQueryInfo.fallbackRanges.length > 0) {
346
+ this.appendDiagnostics(diagnostics);
347
+ return;
348
+ }
349
+ var delimiterIssue = this.getDelimiterIssue();
350
+ if ((delimiterIssue === null || delimiterIssue === void 0 ? void 0 : delimiterIssue.kind) === 'mismatched') {
351
+ var delimiterDiagnostic_1 = this.makeDelimiterDiagnostic(delimiterIssue);
352
+ if (!diagnostics.some(function (existing) { return _this.isSameDiagnostic(existing, delimiterDiagnostic_1); }))
353
+ diagnostics.push(delimiterDiagnostic_1);
354
+ if (this.mismatchRepairDepth < maxMismatchRepairDepth) {
355
+ var repairedDiagnostics = delimiterIssue.recovery === 'delete'
356
+ ? this.diagnoseAfterDeletion(delimiterIssue.actualFrom, delimiterIssue.actualFrom + 1)
357
+ : this.diagnoseAfterReplacement(delimiterIssue.actualFrom, delimiterIssue.actualFrom + 1, delimiterIssue.close);
358
+ var _loop_2 = function (repairedDiagnostic) {
359
+ if (!diagnostics.some(function (existing) { return _this.isSameDiagnostic(existing, repairedDiagnostic); })) {
360
+ diagnostics.push(repairedDiagnostic);
361
+ }
362
+ };
363
+ try {
364
+ for (var repairedDiagnostics_1 = __values(repairedDiagnostics), repairedDiagnostics_1_1 = repairedDiagnostics_1.next(); !repairedDiagnostics_1_1.done; repairedDiagnostics_1_1 = repairedDiagnostics_1.next()) {
365
+ var repairedDiagnostic = repairedDiagnostics_1_1.value;
366
+ _loop_2(repairedDiagnostic);
367
+ }
368
+ }
369
+ catch (e_2_1) { e_2 = { error: e_2_1 }; }
370
+ finally {
371
+ try {
372
+ if (repairedDiagnostics_1_1 && !repairedDiagnostics_1_1.done && (_b = repairedDiagnostics_1.return)) _b.call(repairedDiagnostics_1);
373
+ }
374
+ finally { if (e_2) throw e_2.error; }
375
+ }
376
+ }
377
+ else {
378
+ var repairedDiagnostics = this.diagnoseAfterBulkDelimiterRecovery(delimiterIssue);
379
+ var _loop_3 = function (repairedDiagnostic) {
380
+ if (!diagnostics.some(function (existing) { return _this.isSameDiagnostic(existing, repairedDiagnostic); })) {
381
+ diagnostics.push(repairedDiagnostic);
382
+ }
383
+ };
384
+ try {
385
+ for (var repairedDiagnostics_2 = __values(repairedDiagnostics), repairedDiagnostics_2_1 = repairedDiagnostics_2.next(); !repairedDiagnostics_2_1.done; repairedDiagnostics_2_1 = repairedDiagnostics_2.next()) {
386
+ var repairedDiagnostic = repairedDiagnostics_2_1.value;
387
+ _loop_3(repairedDiagnostic);
388
+ }
389
+ }
390
+ catch (e_3_1) { e_3 = { error: e_3_1 }; }
391
+ finally {
392
+ try {
393
+ if (repairedDiagnostics_2_1 && !repairedDiagnostics_2_1.done && (_c = repairedDiagnostics_2.return)) _c.call(repairedDiagnostics_2);
394
+ }
395
+ finally { if (e_3) throw e_3.error; }
396
+ }
397
+ }
398
+ this.appendDiagnostics(diagnostics);
399
+ return;
400
+ }
401
+ if ((delimiterIssue === null || delimiterIssue === void 0 ? void 0 : delimiterIssue.kind) === 'unexpectedClosing') {
402
+ var delimiterDiagnostic_2 = this.makeDelimiterDiagnostic(delimiterIssue);
403
+ if (!diagnostics.some(function (existing) { return _this.isSameDiagnostic(existing, delimiterDiagnostic_2); }))
404
+ diagnostics.push(delimiterDiagnostic_2);
405
+ var repairedDiagnostics = this.mismatchRepairDepth < maxMismatchRepairDepth
406
+ ? this.diagnoseAfterDeletion(delimiterIssue.actualFrom, delimiterIssue.actualFrom + 1)
407
+ : this.diagnoseAfterBulkUnexpectedClosingRecovery(delimiterIssue);
408
+ var _loop_4 = function (repairedDiagnostic) {
409
+ if (!diagnostics.some(function (existing) { return _this.isSameDiagnostic(existing, repairedDiagnostic); }))
410
+ diagnostics.push(repairedDiagnostic);
411
+ };
412
+ try {
413
+ for (var repairedDiagnostics_3 = __values(repairedDiagnostics), repairedDiagnostics_3_1 = repairedDiagnostics_3.next(); !repairedDiagnostics_3_1.done; repairedDiagnostics_3_1 = repairedDiagnostics_3.next()) {
414
+ var repairedDiagnostic = repairedDiagnostics_3_1.value;
415
+ _loop_4(repairedDiagnostic);
416
+ }
417
+ }
418
+ catch (e_4_1) { e_4 = { error: e_4_1 }; }
419
+ finally {
420
+ try {
421
+ if (repairedDiagnostics_3_1 && !repairedDiagnostics_3_1.done && (_d = repairedDiagnostics_3.return)) _d.call(repairedDiagnostics_3);
422
+ }
423
+ finally { if (e_4) throw e_4.error; }
424
+ }
425
+ this.appendDiagnostics(diagnostics);
426
+ return;
427
+ }
428
+ if (delimiterIssue &&
429
+ (delimiterIssue.kind === 'quotedQuery' ||
430
+ (delimiterIssue.kind === 'quote' && (!delimiterIssue.newline || Boolean((_j = delimiterIssue.repairLineBreaks) === null || _j === void 0 ? void 0 : _j.length))))) {
431
+ diagnostics.push(this.makeDelimiterDiagnostic(delimiterIssue));
432
+ if (delimiterIssue.kind === 'quote' && delimiterIssue.newline && ((_k = delimiterIssue.repairLineBreaks) === null || _k === void 0 ? void 0 : _k.length)) {
433
+ var repairs = this.findStringNewlineRepairs(delimiterIssue);
434
+ var _loop_5 = function (repair) {
435
+ var repairDiagnostic = this_1.makeDiagnosticAt(repair.from, repair.from + 1, 'unescaped newline in string literal', "delimiter:".concat(repair.from));
436
+ if (!diagnostics.some(function (existing) { return _this.isSameDiagnostic(existing, repairDiagnostic); }))
437
+ diagnostics.push(repairDiagnostic);
438
+ };
439
+ var this_1 = this;
440
+ try {
441
+ for (var _p = __values(repairs.slice(0, maxRepairDepth + 1)), _q = _p.next(); !_q.done; _q = _p.next()) {
442
+ var repair = _q.value;
443
+ _loop_5(repair);
444
+ }
445
+ }
446
+ catch (e_5_1) { e_5 = { error: e_5_1 }; }
447
+ finally {
448
+ try {
449
+ if (_q && !_q.done && (_e = _p.return)) _e.call(_p);
450
+ }
451
+ finally { if (e_5) throw e_5.error; }
452
+ }
453
+ var lineBreaks = __spreadArray([], __read(new Set(repairs.flatMap(function (repair) { return repair.lineBreaks; }))), false).sort(function (left, right) { return left - right; });
454
+ var repairedDiagnostics = this.diagnoseAfterInsertions(lineBreaks, '\\');
455
+ var _loop_6 = function (repairedDiagnostic) {
456
+ if (!diagnostics.some(function (existing) { return _this.isSameDiagnostic(existing, repairedDiagnostic); }))
457
+ diagnostics.push(repairedDiagnostic);
458
+ };
459
+ try {
460
+ for (var repairedDiagnostics_4 = __values(repairedDiagnostics), repairedDiagnostics_4_1 = repairedDiagnostics_4.next(); !repairedDiagnostics_4_1.done; repairedDiagnostics_4_1 = repairedDiagnostics_4.next()) {
461
+ var repairedDiagnostic = repairedDiagnostics_4_1.value;
462
+ _loop_6(repairedDiagnostic);
463
+ }
464
+ }
465
+ catch (e_6_1) { e_6 = { error: e_6_1 }; }
466
+ finally {
467
+ try {
468
+ if (repairedDiagnostics_4_1 && !repairedDiagnostics_4_1.done && (_f = repairedDiagnostics_4.return)) _f.call(repairedDiagnostics_4);
469
+ }
470
+ finally { if (e_6) throw e_6.error; }
471
+ }
472
+ this.appendDiagnostics(diagnostics);
473
+ return;
474
+ }
475
+ if (this.repairDepth < maxRepairDepth &&
476
+ (delimiterIssue.repairAt !== undefined || (delimiterIssue.kind === 'quote' && ((_l = delimiterIssue.repairLineBreaks) === null || _l === void 0 ? void 0 : _l.length)))) {
477
+ var repairedDiagnostics = this.diagnoseAfterInsertion(delimiterIssue.repairAt, delimiterIssue.quote);
478
+ var _loop_7 = function (repairedDiagnostic) {
479
+ if (!diagnostics.some(function (existing) { return _this.isSameDiagnostic(existing, repairedDiagnostic); })) {
480
+ diagnostics.push(repairedDiagnostic);
481
+ }
482
+ };
483
+ try {
484
+ for (var repairedDiagnostics_5 = __values(repairedDiagnostics), repairedDiagnostics_5_1 = repairedDiagnostics_5.next(); !repairedDiagnostics_5_1.done; repairedDiagnostics_5_1 = repairedDiagnostics_5.next()) {
485
+ var repairedDiagnostic = repairedDiagnostics_5_1.value;
486
+ _loop_7(repairedDiagnostic);
487
+ }
488
+ }
489
+ catch (e_7_1) { e_7 = { error: e_7_1 }; }
490
+ finally {
491
+ try {
492
+ if (repairedDiagnostics_5_1 && !repairedDiagnostics_5_1.done && (_g = repairedDiagnostics_5.return)) _g.call(repairedDiagnostics_5);
493
+ }
494
+ finally { if (e_7) throw e_7.error; }
495
+ }
496
+ }
497
+ this.appendDiagnostics(diagnostics);
498
+ return;
499
+ }
500
+ if (delimiterIssue && delimiterIssue.kind !== 'unclosed') {
501
+ var delimiterDiagnostic_3 = this.makeDelimiterDiagnostic(delimiterIssue);
502
+ if (!diagnostics.some(function (existing) { return _this.isSameDiagnostic(existing, delimiterDiagnostic_3); }))
503
+ diagnostics.push(delimiterDiagnostic_3);
504
+ if (delimiterDiagnostic_3.group)
505
+ groups.add(delimiterDiagnostic_3.group);
506
+ }
507
+ try {
508
+ for (var _r = __values(this.findCaseResultDiagnostics()), _s = _r.next(); !_s.done; _s = _r.next()) {
509
+ var caseDiagnostic = _s.value;
510
+ if (!caseDiagnostic.group || !groups.has(caseDiagnostic.group)) {
511
+ diagnostics.push(caseDiagnostic);
512
+ if (caseDiagnostic.group)
513
+ groups.add(caseDiagnostic.group);
514
+ }
515
+ }
516
+ }
517
+ catch (e_8_1) { e_8 = { error: e_8_1 }; }
518
+ finally {
519
+ try {
520
+ if (_s && !_s.done && (_h = _r.return)) _h.call(_r);
521
+ }
522
+ finally { if (e_8) throw e_8.error; }
523
+ }
524
+ var _loop_8 = function () {
525
+ var e_9, _t, e_10, _u;
526
+ if (Date.now() >= this_2.deadline)
527
+ return "break";
528
+ if (!cursor.type.isError) {
529
+ return "continue";
530
+ }
531
+ if (quotedQueryInfo.fallbackRanges.some(function (range) {
532
+ return cursor.from === cursor.to ? cursor.from >= range.from && cursor.from <= range.to : cursor.from < range.to && cursor.to > range.from;
533
+ })) {
534
+ return "continue";
535
+ }
536
+ var diagnostic = this_2.describeError(cursor.node);
537
+ if (!diagnostic || (diagnostic.group && groups.has(diagnostic.group))) {
538
+ return "continue";
539
+ }
540
+ if (diagnostics.some(function (existing) { return existing.from === diagnostic.from && existing.to === diagnostic.to; })) {
541
+ return "continue";
542
+ }
543
+ if (diagnostic.group) {
544
+ groups.add(diagnostic.group);
545
+ }
546
+ diagnostics.push(diagnostic);
547
+ if (diagnostic.repair) {
548
+ if (this_2.repairDepth < maxRepairDepth) {
549
+ var repairedDiagnostics = this_2.diagnoseAfterInsertion(diagnostic.repair.insertAt, diagnostic.repair.text);
550
+ var _loop_9 = function (repairedDiagnostic) {
551
+ if (!diagnostics.some(function (existing) { return _this.isSameDiagnostic(existing, repairedDiagnostic); })) {
552
+ diagnostics.push(repairedDiagnostic);
553
+ }
554
+ };
555
+ try {
556
+ for (var repairedDiagnostics_6 = (e_9 = void 0, __values(repairedDiagnostics)), repairedDiagnostics_6_1 = repairedDiagnostics_6.next(); !repairedDiagnostics_6_1.done; repairedDiagnostics_6_1 = repairedDiagnostics_6.next()) {
557
+ var repairedDiagnostic = repairedDiagnostics_6_1.value;
558
+ _loop_9(repairedDiagnostic);
559
+ }
560
+ }
561
+ catch (e_9_1) { e_9 = { error: e_9_1 }; }
562
+ finally {
563
+ try {
564
+ if (repairedDiagnostics_6_1 && !repairedDiagnostics_6_1.done && (_t = repairedDiagnostics_6.return)) _t.call(repairedDiagnostics_6);
565
+ }
566
+ finally { if (e_9) throw e_9.error; }
567
+ }
568
+ }
569
+ else if (!this_2.terminalRepairUsed) {
570
+ var repairedDiagnostics = this_2.diagnoseAfterTerminalInsertion(diagnostic);
571
+ var _loop_10 = function (repairedDiagnostic) {
572
+ if (!diagnostics.some(function (existing) { return _this.isSameDiagnostic(existing, repairedDiagnostic); })) {
573
+ diagnostics.push(repairedDiagnostic);
574
+ }
575
+ };
576
+ try {
577
+ for (var repairedDiagnostics_7 = (e_10 = void 0, __values(repairedDiagnostics)), repairedDiagnostics_7_1 = repairedDiagnostics_7.next(); !repairedDiagnostics_7_1.done; repairedDiagnostics_7_1 = repairedDiagnostics_7.next()) {
578
+ var repairedDiagnostic = repairedDiagnostics_7_1.value;
579
+ _loop_10(repairedDiagnostic);
580
+ }
581
+ }
582
+ catch (e_10_1) { e_10 = { error: e_10_1 }; }
583
+ finally {
584
+ try {
585
+ if (repairedDiagnostics_7_1 && !repairedDiagnostics_7_1.done && (_u = repairedDiagnostics_7.return)) _u.call(repairedDiagnostics_7);
586
+ }
587
+ finally { if (e_10) throw e_10.error; }
588
+ }
589
+ }
590
+ return "break";
591
+ }
592
+ };
593
+ var this_2 = this;
24
594
  while (cursor.next()) {
25
- // usually there is an error node at the end of the expression when user is typing
26
- // so it's not really a useful information to say the expression is wrong.
27
- // Hopefully if there is an error node at the end of the tree, checkAST should yell more precisely
28
- if (cursor.type.id === 0 && cursor.to !== this.tree.topNode.to) {
29
- var node = cursor.node.parent;
30
- this.diagnostics.push({
31
- severity: 'error',
32
- message: 'unexpected expression',
33
- from: node ? node.from : cursor.from,
34
- to: node ? node.to : cursor.to,
35
- });
595
+ var state_1 = _loop_8();
596
+ if (state_1 === "break")
597
+ break;
598
+ }
599
+ this.appendDiagnostics(diagnostics);
600
+ };
601
+ Parser.prototype.describeError = function (node) {
602
+ var _a;
603
+ var delimiterIssue = this.getDelimiterIssue();
604
+ if (delimiterIssue && delimiterIssue.kind !== 'unclosed' && this.isRelatedDelimiterError(node, delimiterIssue)) {
605
+ return null;
606
+ }
607
+ var parent = node.parent;
608
+ if (!parent) {
609
+ return this.makeDiagnostic(node, 'incomplete DQL query');
610
+ }
611
+ var parentName = parent.name;
612
+ var previous = this.siblingSkippingLineComments(node, 'previous');
613
+ var next = this.siblingSkippingLineComments(node, 'next');
614
+ var previousText = previous ? this.nodeText(previous) : '';
615
+ var errorText = this.nodeText(node);
616
+ var group = "".concat(parentName, ":").concat(parent.from, ":").concat(parent.to, ":").concat(node.from, ":").concat(node.to);
617
+ var unknownFunctionDiagnostic = this.describeUnknownFunction(node);
618
+ if (unknownFunctionDiagnostic)
619
+ return unknownFunctionDiagnostic;
620
+ var commaRunDiagnostic = this.describeConsecutiveCommaError(node, parent);
621
+ if (commaRunDiagnostic)
622
+ return commaRunDiagnostic;
623
+ if (parentName === 'Namespace') {
624
+ if (errorText === ':') {
625
+ return this.makeDiagnosticRepairing(node, 'expected "::" after namespace', node.to, ':', "Namespace:".concat(parent.from, ":").concat(parent.to));
626
+ }
627
+ return this.makeDiagnostic(node, 'expected "::" after namespace', "Namespace:".concat(parent.from, ":").concat(parent.to));
628
+ }
629
+ if (parentName === 'Query' && node.from === node.to && (previous === null || previous === void 0 ? void 0 : previous.name) === 'Namespace' && !this.containsError(previous)) {
630
+ var hasSingleColon = this.state.sliceDoc(node.from, node.from + 1) === ':';
631
+ return this.makeDiagnosticRepairingAt(node.from, node.from + (hasSingleColon ? 1 : 0), 'expected "::" after namespace', node.from + (hasSingleColon ? 1 : 0), hasSingleColon ? ':' : '::', "Namespace:".concat(previous.from, ":").concat(previous.to));
632
+ }
633
+ if (parentName === 'Query' && node.from === node.to && (previous === null || previous === void 0 ? void 0 : previous.name) === 'DColon') {
634
+ return this.makeDiagnostic(node, 'data source expected after "::"', group);
635
+ }
636
+ if (parentName === 'DataSourceItem') {
637
+ return this.makeDiagnostic(node, 'data source expected after "::"', group);
638
+ }
639
+ if (parentName === 'DataSourceList') {
640
+ if (node.from === node.to && (previous === null || previous === void 0 ? void 0 : previous.name) === 'DataSourceItem' && (next === null || next === void 0 ? void 0 : next.name) === 'DataSourceItem') {
641
+ if (this.isAdjacentToComma(node, parent)) {
642
+ return this.makeDiagnostic(node, 'data source expected after ","', group);
643
+ }
644
+ if (this.looksLikeProjectionAfterMissingColon(next)) {
645
+ return this.makeDiagnosticRepairing(node, 'expected ":" after data source', node.from, ':', group);
646
+ }
647
+ return this.makeDiagnostic(node, 'expected "," between data sources', group);
648
+ }
649
+ if (this.isAdjacentToComma(node, parent)) {
650
+ return this.makeDiagnostic(node, 'data source expected after ","', group);
651
+ }
652
+ return this.makeUnexpectedTokenDiagnostic(node, exports.dqlSyntaxContexts.DataSourceList, group);
653
+ }
654
+ if (parentName === 'TargetClause') {
655
+ if (node.from === node.to && (previous === null || previous === void 0 ? void 0 : previous.name) === 'Comma') {
656
+ return this.makeDiagnostic(node, 'projection expected after ":"', group);
657
+ }
658
+ return this.makeUnexpectedTokenDiagnostic(node, exports.dqlSyntaxContexts.TargetClause, group);
659
+ }
660
+ if (parentName === 'Projection') {
661
+ if (this.isCommaSequence(errorText) || this.isCommaOnlyList(parent)) {
662
+ return this.makeDiagnostic(node, 'projection item expected between commas', this.commaSequenceGroup(parent));
663
+ }
664
+ if (errorText === ',' && !previous) {
665
+ return this.makeDiagnostic(node, 'projection item expected before ","', group);
666
+ }
667
+ if (this.isAdjacentToComma(node, parent)) {
668
+ return this.makeDiagnostic(node, 'projection item expected after ","', group);
669
+ }
670
+ if (node.from === node.to && (previous === null || previous === void 0 ? void 0 : previous.name) === 'ProjectionItem' && (next === null || next === void 0 ? void 0 : next.name) === 'ProjectionItem') {
671
+ return this.makeDiagnostic(node, 'expected "," between projection items', group);
672
+ }
673
+ return this.makeUnexpectedTokenDiagnostic(node, 'projection', group);
674
+ }
675
+ if (parentName === 'ProjectionField' && (previous === null || previous === void 0 ? void 0 : previous.name) === 'As') {
676
+ return this.makeDiagnostic(node, 'alias expected after "AS"', group);
677
+ }
678
+ if (parentName === 'ProjectionField' && node.from === node.to && previous && (next === null || next === void 0 ? void 0 : next.name) === 'AsExpr') {
679
+ if (this.maskLineComments(this.state.sliceDoc(next.to)).trimStart().startsWith('(')) {
680
+ return null;
681
+ }
682
+ return this.makeDiagnostic(node, 'expected "AS" before projection alias', group);
683
+ }
684
+ if (parentName === 'OuterFunctionCall') {
685
+ return this.makeUnexpectedTokenDiagnostic(node, exports.dqlSyntaxContexts.OuterFunctionCall, group);
686
+ }
687
+ if (functionCallBodyParents.has(parentName)) {
688
+ if (parentName === 'OuterFunctionCallBody' && this.hasErroredSibling(parent)) {
689
+ return null;
690
+ }
691
+ if (this.isCommaSequence(errorText) || this.isCommaOnlyList(parent)) {
692
+ return this.makeDiagnostic(node, 'function argument expected between commas', this.commaSequenceGroup(parent));
693
+ }
694
+ if (errorText === ',' && !previous) {
695
+ return this.makeDiagnostic(node, 'function argument expected before ","', group);
696
+ }
697
+ if (this.isAdjacentToComma(node, parent)) {
698
+ return this.makeDiagnostic(node, 'function argument expected after ","', group);
699
+ }
700
+ if (node.from === this.tree.topNode.to) {
701
+ var issue = this.getDelimiterIssue();
702
+ if ((issue === null || issue === void 0 ? void 0 : issue.kind) === 'unclosed') {
703
+ return this.makeDelimiterDiagnostic(issue);
704
+ }
705
+ }
706
+ return this.makeUnexpectedTokenDiagnostic(node, 'function call', group);
707
+ }
708
+ if (parentName === 'ArgItem' && node.from === node.to) {
709
+ if ((previous === null || previous === void 0 ? void 0 : previous.name) === 'EqlSingle') {
710
+ return this.makeDiagnostic(node, 'function argument value expected after "="', group);
711
+ }
712
+ return this.makeDiagnostic(node, 'expected "," between function arguments', group);
713
+ }
714
+ if (parentName === 'InValue' || parentName === 'InFieldValue') {
715
+ var context_1 = parentName === 'InValue' ? 'argument value' : 'filter value';
716
+ if (this.isCommaSequence(errorText) || this.isCommaOnlyList(parent)) {
717
+ return this.makeDiagnostic(node, "".concat(context_1, " expected between commas"), this.commaSequenceGroup(parent));
718
+ }
719
+ if (errorText === ',' && !previous) {
720
+ return this.makeDiagnostic(node, "".concat(context_1, " expected before \",\""), group);
721
+ }
722
+ if (this.isAdjacentToComma(node, parent)) {
723
+ return this.makeDiagnostic(node, "".concat(context_1, " expected after \",\""), group);
724
+ }
725
+ return this.makeUnexpectedTokenDiagnostic(node, exports.dqlSyntaxContexts[parentName], group);
726
+ }
727
+ if (parentName === 'IndexExpr' || parentName === 'IndexItem') {
728
+ if (this.isCommaSequence(errorText)) {
729
+ return this.makeDiagnostic(node, 'namespace index expected between commas', group);
730
+ }
731
+ if (errorText === ',' && !previous) {
732
+ return this.makeDiagnostic(node, 'namespace index expected before ","', group);
733
+ }
734
+ if (this.isAdjacentToComma(node, parent)) {
735
+ return this.makeDiagnostic(node, 'namespace index expected after ","', group);
736
+ }
737
+ return this.makeUnexpectedTokenDiagnostic(node, 'namespace index list', group);
738
+ }
739
+ if (parentName === 'ByListExpr') {
740
+ if (this.isCommaSequence(errorText)) {
741
+ return this.makeDiagnostic(node, 'grouping field expected between commas', group);
742
+ }
743
+ if (errorText === ',' && !previous) {
744
+ return this.makeDiagnostic(node, 'grouping field expected before ","', group);
745
+ }
746
+ if (this.isAdjacentToComma(node, parent)) {
747
+ return this.makeDiagnostic(node, 'grouping field expected after ","', group);
748
+ }
749
+ return this.makeUnexpectedTokenDiagnostic(node, 'grouping field list', group);
750
+ }
751
+ if (parentName === 'ByExpr' && errorText === ',') {
752
+ return this.makeDiagnostic(node, 'grouping field expected before ","', group);
753
+ }
754
+ if (expressionParents.has(parentName)) {
755
+ if (previous && this.isOperator(previous)) {
756
+ return this.makeDiagnostic(node, "right-hand expression expected after \"".concat(previousText, "\""), group);
757
+ }
758
+ return this.makeUnexpectedTokenDiagnostic(node, 'expression', group);
759
+ }
760
+ var caseWhenClause = this.findAncestor(parent, 'CaseWhenClause');
761
+ if (caseWhenClause) {
762
+ var missingCondition = /^\s*when\s+(then)\b/i.exec(this.maskLineComments(this.nodeText(caseWhenClause)));
763
+ if (missingCondition) {
764
+ var thenOffset = missingCondition.index + missingCondition[0].toLowerCase().lastIndexOf('then');
765
+ return this.makeDiagnosticAt(caseWhenClause.from + thenOffset, caseWhenClause.from + thenOffset + 4, 'CASE condition expected after "WHEN"', this.caseGroup(caseWhenClause));
766
+ }
767
+ }
768
+ if (parentName === 'CaseCondition') {
769
+ return this.makeDiagnostic(node, 'expected "THEN" after CASE condition', this.caseGroup(parent));
770
+ }
771
+ if (parentName === 'CaseWhenClause') {
772
+ if ((previous === null || previous === void 0 ? void 0 : previous.name) === 'Then') {
773
+ return this.makeDiagnostic(node, 'CASE result expected after "THEN"', this.caseGroup(parent));
774
+ }
775
+ if ((previous === null || previous === void 0 ? void 0 : previous.name) === 'CaseCondition' && this.containsError(previous)) {
776
+ return null;
777
+ }
778
+ return this.makeDiagnostic(node, 'expected "THEN" after CASE condition', this.caseGroup(parent));
779
+ }
780
+ if (parentName === 'CaseElseClause') {
781
+ return this.makeDiagnostic(node, 'CASE result expected after "ELSE"', this.caseGroup(parent));
782
+ }
783
+ if (parentName === 'CaseExpr') {
784
+ if (this.caseResultRecoveryErrors.has(this.nodeRangeKey(node)))
785
+ return null;
786
+ if (errorText)
787
+ return this.makeUnexpectedTokenDiagnostic(node, exports.dqlSyntaxContexts.CaseExpr, group);
788
+ if (previous && this.containsError(previous)) {
789
+ return null;
790
+ }
791
+ if ((previous === null || previous === void 0 ? void 0 : previous.name) === 'CaseOperand') {
792
+ return this.makeDiagnostic(node, 'CASE expression requires at least one "WHEN" clause', this.caseGroup(parent));
793
+ }
794
+ return this.makeDiagnostic(node, 'expected "END" to close CASE expression', this.caseGroup(parent));
795
+ }
796
+ var numericKeyword = numericClauses.get(parentName);
797
+ if (numericKeyword) {
798
+ return this.makeDiagnostic(node, "number expected after \"".concat(numericKeyword, "\""), group);
799
+ }
800
+ if (parentName === 'ByClause') {
801
+ return this.makeDiagnostic(node, 'grouping field expected after "BY"', group);
802
+ }
803
+ if (parentName === 'HavingClause') {
804
+ return this.makeDiagnostic(node, 'expression expected after "HAVING"', group);
805
+ }
806
+ if (parentName === 'OrderClause' || parentName === 'SOrderClause') {
807
+ var keyword = parentName === 'OrderClause' ? 'ORDER' : 'SORDER';
808
+ if (!parent.getChild('By')) {
809
+ return this.makeDiagnostic(node, "expected \"BY\" after \"".concat(keyword, "\""), group);
810
+ }
811
+ return this.makeDiagnostic(node, "sort field expected after \"".concat(keyword, " BY\""), group);
812
+ }
813
+ if (parentName === 'RollupIdentifier') {
814
+ var timeClause_1 = this.findAncestor(parent, 'TimeClause');
815
+ var child = (_a = timeClause_1 === null || timeClause_1 === void 0 ? void 0 : timeClause_1.firstChild) !== null && _a !== void 0 ? _a : null;
816
+ while (child) {
817
+ if (child.type.isError)
818
+ return null;
819
+ child = child.nextSibling;
820
+ }
821
+ }
822
+ if (parentName === 'TimeClause') {
823
+ if (!this.nodeText(parent).trimEnd().endsWith(']')) {
824
+ return this.makeDiagnostic(node, 'expected "]" to close time range', group);
825
+ }
826
+ return this.makeUnexpectedTokenDiagnostic(node, exports.dqlSyntaxContexts.TimeClause, group);
827
+ }
828
+ var timeClause = this.findAncestor(parent, 'TimeClause');
829
+ if (timeClause && /^\[\s*]$/.test(this.maskLineComments(this.nodeText(timeClause)))) {
830
+ return this.makeDiagnostic(node, 'time range value expected between "[" and "]"', "TimeClause:".concat(timeClause.from, ":").concat(timeClause.to));
831
+ }
832
+ if (parentName === 'FilterClause') {
833
+ if (this.isCommaSequence(errorText) || this.isCommaOnlyList(parent)) {
834
+ return this.makeDiagnostic(node, 'filter expression expected between commas', this.commaSequenceGroup(parent));
835
+ }
836
+ if (errorText === ',' && !previous) {
837
+ return this.makeDiagnostic(node, 'filter expression expected before ","', group);
838
+ }
839
+ if (this.isAdjacentToComma(node, parent)) {
840
+ return this.makeDiagnostic(node, 'filter expression expected after ","', group);
841
+ }
842
+ if (node.from === node.to && (previous === null || previous === void 0 ? void 0 : previous.name) === 'FilterExpr' && (next === null || next === void 0 ? void 0 : next.name) === 'FilterExpr') {
843
+ return this.makeDiagnostic(node, 'comparison operator expected between filter expressions', group);
844
+ }
845
+ if (!this.nodeText(parent).trimEnd().endsWith('}')) {
846
+ return this.makeDiagnostic(node, 'expected "}" to close filter clause', group);
847
+ }
848
+ return this.makeUnexpectedTokenDiagnostic(node, exports.dqlSyntaxContexts.FilterClause, group);
849
+ }
850
+ if (node.from === this.tree.topNode.to) {
851
+ var issue = this.getDelimiterIssue();
852
+ if ((issue === null || issue === void 0 ? void 0 : issue.kind) === 'unclosed') {
853
+ return this.makeDelimiterDiagnostic(issue);
36
854
  }
37
855
  }
856
+ var context = this.findSyntaxContext(parent);
857
+ return this.makeUnexpectedTokenDiagnostic(node, context, group);
38
858
  };
39
- Parser.prototype.checkAST = function (node) { };
40
- Parser.prototype.addDiagnostic = function (node, msg) {
41
- this.diagnostics.push({
859
+ Parser.prototype.makeUnexpectedTokenDiagnostic = function (node, context, group) {
860
+ var text = this.nodeText(node);
861
+ var rawToken = text.length > 20 ? "".concat(text.slice(0, 20), "...") : text;
862
+ var token = rawToken.replace(/"/g, '\\"');
863
+ return this.makeDiagnostic(node, token ? "unexpected token \"".concat(token, "\" in ").concat(context) : "incomplete ".concat(context), group);
864
+ };
865
+ Parser.prototype.findSyntaxContext = function (node) {
866
+ var current = node;
867
+ while (current) {
868
+ var context = exports.dqlSyntaxContexts[current.name];
869
+ if (context) {
870
+ return context;
871
+ }
872
+ current = current.parent;
873
+ }
874
+ return exports.dqlSyntaxContexts.DQL;
875
+ };
876
+ Parser.prototype.makeDiagnostic = function (node, message, group) {
877
+ return this.makeDiagnosticAt(node.from, node.to, message, group);
878
+ };
879
+ Parser.prototype.makeDiagnosticRepairing = function (node, message, insertAt, text, group) {
880
+ return this.makeDiagnosticRepairingAt(node.from, node.to, message, insertAt, text, group);
881
+ };
882
+ Parser.prototype.makeDiagnosticRepairingAt = function (from, to, message, insertAt, text, group) {
883
+ return __assign(__assign({}, this.makeDiagnosticAt(from, to, message, group)), { repair: { insertAt: insertAt, text: text } });
884
+ };
885
+ Parser.prototype.diagnoseAfterInsertion = function (insertAt, text) {
886
+ var _this = this;
887
+ var repairedState = this.state.update({ changes: { from: insertAt, insert: text }, filter: false }).state;
888
+ if (repairedState.doc.length !== this.state.doc.length + text.length) {
889
+ return [];
890
+ }
891
+ var repairedParser = new Parser(repairedState, this.deadline);
892
+ repairedParser.repairDepth = this.repairDepth + 1;
893
+ repairedParser.mismatchRepairDepth = this.mismatchRepairDepth;
894
+ repairedParser.terminalRepairUsed = this.terminalRepairUsed;
895
+ repairedParser.analyze();
896
+ return repairedParser.getDiagnostics().map(function (diagnostic) { return (__assign(__assign({}, diagnostic), { from: _this.mapRepairedPosition(diagnostic.from, insertAt, text.length), to: _this.mapRepairedPosition(diagnostic.to, insertAt, text.length) })); });
897
+ };
898
+ Parser.prototype.diagnoseAfterInsertions = function (insertAts, text) {
899
+ var _this = this;
900
+ var positions = __spreadArray([], __read(new Set(insertAts)), false).sort(function (left, right) { return left - right; });
901
+ if (positions.length === 0)
902
+ return [];
903
+ var repairedState = this.state.update({
904
+ changes: positions.map(function (from) { return ({ from: from, insert: text }); }),
905
+ filter: false,
906
+ }).state;
907
+ if (repairedState.doc.length !== this.state.doc.length + positions.length * text.length) {
908
+ return [];
909
+ }
910
+ var repairedParser = new Parser(repairedState, this.deadline);
911
+ repairedParser.repairDepth = this.repairDepth + 1;
912
+ repairedParser.mismatchRepairDepth = this.mismatchRepairDepth;
913
+ repairedParser.terminalRepairUsed = this.terminalRepairUsed;
914
+ repairedParser.analyze();
915
+ return repairedParser.getDiagnostics().map(function (diagnostic) { return (__assign(__assign({}, diagnostic), { from: _this.mapRepairedPositionAfterInsertions(diagnostic.from, positions, text.length), to: _this.mapRepairedPositionAfterInsertions(diagnostic.to, positions, text.length) })); });
916
+ };
917
+ Parser.prototype.diagnoseAfterReplacement = function (from, to, text) {
918
+ var repairedState = this.state.update({ changes: { from: from, to: to, insert: text }, filter: false }).state;
919
+ if (repairedState.doc.length !== this.state.doc.length - (to - from) + text.length) {
920
+ return [];
921
+ }
922
+ var repairedParser = new Parser(repairedState, this.deadline);
923
+ repairedParser.repairDepth = this.repairDepth + 1;
924
+ repairedParser.mismatchRepairDepth = this.mismatchRepairDepth + 1;
925
+ repairedParser.terminalRepairUsed = this.terminalRepairUsed;
926
+ repairedParser.analyze();
927
+ return repairedParser.getDiagnostics();
928
+ };
929
+ Parser.prototype.diagnoseAfterDeletion = function (from, to) {
930
+ var repairedState = this.state.update({ changes: { from: from, to: to, insert: '' }, filter: false }).state;
931
+ var deletedLength = to - from;
932
+ if (repairedState.doc.length !== this.state.doc.length - deletedLength) {
933
+ return [];
934
+ }
935
+ var repairedParser = new Parser(repairedState, this.deadline);
936
+ repairedParser.repairDepth = this.repairDepth + 1;
937
+ repairedParser.mismatchRepairDepth = this.mismatchRepairDepth + 1;
938
+ repairedParser.terminalRepairUsed = this.terminalRepairUsed;
939
+ repairedParser.analyze();
940
+ return repairedParser.getDiagnostics().map(function (diagnostic) { return (__assign(__assign({}, diagnostic), { from: diagnostic.from < from ? diagnostic.from : diagnostic.from + deletedLength, to: diagnostic.to <= from && diagnostic.from < from ? diagnostic.to : diagnostic.to + deletedLength })); });
941
+ };
942
+ Parser.prototype.diagnoseAfterBulkDelimiterRecovery = function (issue) {
943
+ var _a;
944
+ var firstTransaction = this.state.update({
945
+ changes: {
946
+ from: issue.actualFrom,
947
+ to: issue.actualFrom + 1,
948
+ insert: issue.recovery === 'delete' ? '' : issue.close,
949
+ },
950
+ filter: false,
951
+ });
952
+ var bulkChanges = this.findBulkDelimiterRecoveryChanges(firstTransaction.state);
953
+ if (bulkChanges === null)
954
+ return [];
955
+ var bulkTransaction = bulkChanges.length > 0 ? firstTransaction.state.update({ changes: bulkChanges, filter: false }) : null;
956
+ var repairedState = (_a = bulkTransaction === null || bulkTransaction === void 0 ? void 0 : bulkTransaction.state) !== null && _a !== void 0 ? _a : firstTransaction.state;
957
+ var repairedParser = new Parser(repairedState, this.deadline);
958
+ repairedParser.repairDepth = this.repairDepth + 1;
959
+ repairedParser.mismatchRepairDepth = this.mismatchRepairDepth + 1;
960
+ repairedParser.terminalRepairUsed = this.terminalRepairUsed;
961
+ repairedParser.analyze();
962
+ var diagnostics = repairedParser.getDiagnostics();
963
+ if (bulkTransaction) {
964
+ diagnostics = this.mapDiagnosticsThroughChanges(diagnostics, bulkTransaction.changes);
965
+ }
966
+ return this.mapDiagnosticsThroughChanges(diagnostics, firstTransaction.changes);
967
+ };
968
+ Parser.prototype.diagnoseAfterBulkUnexpectedClosingRecovery = function (issue) {
969
+ var _a;
970
+ var firstTransaction = this.state.update({
971
+ changes: { from: issue.actualFrom, to: issue.actualFrom + 1, insert: '' },
972
+ filter: false,
973
+ });
974
+ var bulkChanges = this.findBulkDelimiterRecoveryChanges(firstTransaction.state);
975
+ if (bulkChanges === null)
976
+ return [];
977
+ var bulkTransaction = bulkChanges.length > 0 ? firstTransaction.state.update({ changes: bulkChanges, filter: false }) : null;
978
+ var repairedState = (_a = bulkTransaction === null || bulkTransaction === void 0 ? void 0 : bulkTransaction.state) !== null && _a !== void 0 ? _a : firstTransaction.state;
979
+ var repairedParser = new Parser(repairedState, this.deadline);
980
+ repairedParser.repairDepth = this.repairDepth + 1;
981
+ repairedParser.mismatchRepairDepth = this.mismatchRepairDepth + 1;
982
+ repairedParser.terminalRepairUsed = this.terminalRepairUsed;
983
+ repairedParser.analyze();
984
+ var diagnostics = repairedParser.getDiagnostics();
985
+ if (bulkTransaction)
986
+ diagnostics = this.mapDiagnosticsThroughChanges(diagnostics, bulkTransaction.changes);
987
+ return this.mapDiagnosticsThroughChanges(diagnostics, firstTransaction.changes);
988
+ };
989
+ Parser.prototype.diagnoseAfterTerminalInsertion = function (diagnostic) {
990
+ var e_11, _a;
991
+ var _b;
992
+ if (!diagnostic.repair)
993
+ return [];
994
+ var firstTransaction = this.state.update({
995
+ changes: { from: diagnostic.repair.insertAt, insert: diagnostic.repair.text },
996
+ filter: false,
997
+ });
998
+ var matchingRepairs = this.findMatchingRepairs(firstTransaction.state, diagnostic.message);
999
+ if (diagnostic.message === 'expected "::" after namespace') {
1000
+ try {
1001
+ for (var _c = __values(this.findLikelyNamespaceSeparatorInsertions(firstTransaction.state.doc.toString())), _d = _c.next(); !_d.done; _d = _c.next()) {
1002
+ var from = _d.value;
1003
+ matchingRepairs.push({ from: from, insert: ':' });
1004
+ }
1005
+ }
1006
+ catch (e_11_1) { e_11 = { error: e_11_1 }; }
1007
+ finally {
1008
+ try {
1009
+ if (_d && !_d.done && (_a = _c.return)) _a.call(_c);
1010
+ }
1011
+ finally { if (e_11) throw e_11.error; }
1012
+ }
1013
+ }
1014
+ var uniqueRepairs = matchingRepairs
1015
+ .sort(function (left, right) { return left.from - right.from; })
1016
+ .filter(function (repair, index, repairs) { return index === 0 || repair.from !== repairs[index - 1].from || repair.insert !== repairs[index - 1].insert; });
1017
+ var bulkTransaction = uniqueRepairs.length > 0
1018
+ ? firstTransaction.state.update({
1019
+ changes: uniqueRepairs,
1020
+ filter: false,
1021
+ })
1022
+ : null;
1023
+ var repairedState = (_b = bulkTransaction === null || bulkTransaction === void 0 ? void 0 : bulkTransaction.state) !== null && _b !== void 0 ? _b : firstTransaction.state;
1024
+ var repairedParser = new Parser(repairedState, this.deadline);
1025
+ repairedParser.repairDepth = this.repairDepth + 1;
1026
+ repairedParser.mismatchRepairDepth = this.mismatchRepairDepth;
1027
+ repairedParser.terminalRepairUsed = true;
1028
+ repairedParser.analyze();
1029
+ var diagnostics = repairedParser.getDiagnostics();
1030
+ if (bulkTransaction) {
1031
+ diagnostics = this.mapDiagnosticsThroughChanges(diagnostics, bulkTransaction.changes);
1032
+ }
1033
+ return this.mapDiagnosticsThroughChanges(diagnostics, firstTransaction.changes);
1034
+ };
1035
+ Parser.prototype.findStringNewlineRepairs = function (issue) {
1036
+ var _a;
1037
+ var text = this.state.doc.toString();
1038
+ var repairs = new Map();
1039
+ if ((_a = issue.repairLineBreaks) === null || _a === void 0 ? void 0 : _a.length)
1040
+ repairs.set(issue.from, issue.repairLineBreaks);
1041
+ var cursor = this.tree.cursor();
1042
+ while (cursor.next()) {
1043
+ if (cursor.name !== 'StringLiteral' || cursor.from >= cursor.to || text[cursor.to] !== '\n')
1044
+ continue;
1045
+ if (this.findAncestor(cursor.node.parent, 'IndexItem'))
1046
+ continue;
1047
+ var quote = text[cursor.from];
1048
+ if (quote !== '"' && quote !== "'")
1049
+ continue;
1050
+ var recovery = this.findStringNewlineRecovery(text, cursor.from + 1, quote);
1051
+ if (recovery === null || recovery === void 0 ? void 0 : recovery.lineBreaks.length)
1052
+ repairs.set(cursor.from, recovery.lineBreaks);
1053
+ }
1054
+ var transparent = this.findLexicalQuotedQueryWrapperDelimiters(this.tree, text);
1055
+ for (var index = 0; index < text.length; index += 1) {
1056
+ if (transparent.has(index))
1057
+ continue;
1058
+ var char = text[index];
1059
+ if (char === '#') {
1060
+ while (index + 1 < text.length && text[index + 1] !== '\n')
1061
+ index += 1;
1062
+ continue;
1063
+ }
1064
+ if (char.charCodeAt(0) === 96) {
1065
+ var closing = text.indexOf(char, index + 1);
1066
+ if (closing < 0)
1067
+ break;
1068
+ index = closing;
1069
+ continue;
1070
+ }
1071
+ if (char !== '"' && char !== "'")
1072
+ continue;
1073
+ var recovery = this.findStringNewlineRecovery(text, index + 1, char);
1074
+ if (!recovery)
1075
+ break;
1076
+ if (recovery.lineBreaks.length)
1077
+ repairs.set(index, recovery.lineBreaks);
1078
+ index = recovery.end - 1;
1079
+ }
1080
+ return __spreadArray([], __read(repairs.entries()), false).map(function (_a) {
1081
+ var _b = __read(_a, 2), from = _b[0], lineBreaks = _b[1];
1082
+ return ({ from: from, lineBreaks: lineBreaks });
1083
+ }).sort(function (left, right) { return left.from - right.from; });
1084
+ };
1085
+ Parser.prototype.findLexicalQuotedQueryWrapperDelimiters = function (tree, text) {
1086
+ var transparent = new Set();
1087
+ var cursor = tree.cursor();
1088
+ while (cursor.next()) {
1089
+ if (cursor.name !== 'OuterArgItem' || !cursor.node.getChild('Query'))
1090
+ continue;
1091
+ var opening = cursor.node.getChildren('Queted')[0];
1092
+ if (!opening)
1093
+ continue;
1094
+ var quote = text[opening.from];
1095
+ var closing = this.findLexicalQuotedQueryClosing(text, opening.from, quote);
1096
+ if (closing !== null) {
1097
+ transparent.add(opening.from);
1098
+ transparent.add(closing);
1099
+ }
1100
+ }
1101
+ return transparent;
1102
+ };
1103
+ Parser.prototype.findLexicalQuotedQueryClosing = function (text, opening, wrapperQuote) {
1104
+ var pairs = { '(': ')', '[': ']', '{': '}' };
1105
+ var closers = new Set(Object.values(pairs));
1106
+ var stack = [];
1107
+ var quote = '';
1108
+ var escaped = false;
1109
+ var inComment = false;
1110
+ for (var index = opening + 1; index < text.length; index += 1) {
1111
+ if (Date.now() >= this.deadline)
1112
+ return null;
1113
+ var char = text[index];
1114
+ if (inComment) {
1115
+ if (char === '\n')
1116
+ inComment = false;
1117
+ continue;
1118
+ }
1119
+ if (quote) {
1120
+ if (escaped) {
1121
+ escaped = false;
1122
+ }
1123
+ else if (char === '\\' && quote.charCodeAt(0) !== 96) {
1124
+ escaped = true;
1125
+ }
1126
+ else if (char === quote) {
1127
+ quote = '';
1128
+ }
1129
+ continue;
1130
+ }
1131
+ var following = char === wrapperQuote ? this.nextNonTriviaCharacter(text, index + 1) : '';
1132
+ if (following === ')' || following === ',')
1133
+ return index;
1134
+ if (char === '"' || char === "'" || char.charCodeAt(0) === 96) {
1135
+ quote = char;
1136
+ }
1137
+ else if (char === '#') {
1138
+ inComment = true;
1139
+ }
1140
+ else if (pairs[char]) {
1141
+ stack.push(pairs[char]);
1142
+ }
1143
+ else if (closers.has(char)) {
1144
+ if (stack[stack.length - 1] === char)
1145
+ stack.pop();
1146
+ else if (stack.length > 0)
1147
+ stack.pop();
1148
+ }
1149
+ }
1150
+ return null;
1151
+ };
1152
+ Parser.prototype.nextNonTriviaCharacter = function (text, start) {
1153
+ var inComment = false;
1154
+ for (var index = start; index < text.length; index += 1) {
1155
+ if (Date.now() >= this.deadline)
1156
+ return '';
1157
+ var char = text[index];
1158
+ if (inComment) {
1159
+ if (char === '\n')
1160
+ inComment = false;
1161
+ }
1162
+ else if (char === '#') {
1163
+ inComment = true;
1164
+ }
1165
+ else if (!/\s/.test(char)) {
1166
+ return char;
1167
+ }
1168
+ }
1169
+ return '';
1170
+ };
1171
+ Parser.prototype.findMatchingRepairs = function (state, message) {
1172
+ var candidate = new Parser(state, this.deadline);
1173
+ if (!candidate.treeComplete)
1174
+ return [];
1175
+ var repairs = [];
1176
+ var cursor = candidate.tree.cursor();
1177
+ while (cursor.next()) {
1178
+ if (!cursor.type.isError)
1179
+ continue;
1180
+ var described = candidate.describeError(cursor.node);
1181
+ if ((described === null || described === void 0 ? void 0 : described.message) === message && described.repair) {
1182
+ repairs.push({ from: described.repair.insertAt, insert: described.repair.text });
1183
+ }
1184
+ }
1185
+ return repairs;
1186
+ };
1187
+ Parser.prototype.mapDiagnosticsThroughChanges = function (diagnostics, changes) {
1188
+ var inverse = changes.invertedDesc;
1189
+ return diagnostics.map(function (diagnostic) { return (__assign(__assign({}, diagnostic), { from: inverse.mapPos(diagnostic.from, 1), to: inverse.mapPos(diagnostic.to, diagnostic.from === diagnostic.to ? 1 : -1) })); });
1190
+ };
1191
+ Parser.prototype.findLikelyNamespaceSeparatorInsertions = function (text) {
1192
+ var masked = this.maskStringsAndLineComments(text);
1193
+ var pattern = /(?:^|\()\s*[A-Za-z_-][A-Za-z0-9_-]*(?:\([^()\n]*\))?\s*:(?!:)/g;
1194
+ var insertions = [];
1195
+ var match = pattern.exec(masked);
1196
+ while (match) {
1197
+ insertions.push(match.index + match[0].lastIndexOf(':') + 1);
1198
+ match = pattern.exec(masked);
1199
+ }
1200
+ return __spreadArray([], __read(new Set(insertions)), false);
1201
+ };
1202
+ Parser.prototype.findBulkDelimiterRecoveryChanges = function (state) {
1203
+ var e_12, _a;
1204
+ var _b, _c, _d;
1205
+ if (Date.now() >= this.deadline)
1206
+ return null;
1207
+ var text = state.doc.toString();
1208
+ var candidate = new Parser(state, this.deadline);
1209
+ if (!candidate.treeComplete)
1210
+ return null;
1211
+ var transparent = candidate.findQuotedQueryDelimiterInfo().transparent;
1212
+ var pairs = { '(': ')', '[': ']', '{': '}' };
1213
+ var closers = new Set(Object.values(pairs));
1214
+ var tokens = [];
1215
+ var quote = '';
1216
+ var escaped = false;
1217
+ var inComment = false;
1218
+ for (var index = 0; index < text.length; index += 1) {
1219
+ if (Date.now() >= this.deadline)
1220
+ return null;
1221
+ var char = text[index];
1222
+ if (transparent.has(index))
1223
+ continue;
1224
+ if (inComment) {
1225
+ if (char === '\n')
1226
+ inComment = false;
1227
+ continue;
1228
+ }
1229
+ if (quote) {
1230
+ if (escaped) {
1231
+ escaped = false;
1232
+ }
1233
+ else if (char === '\\' && quote.charCodeAt(0) !== 96) {
1234
+ escaped = true;
1235
+ }
1236
+ else if (char === quote) {
1237
+ quote = '';
1238
+ }
1239
+ else if (char === '\n' && quote.charCodeAt(0) !== 96) {
1240
+ quote = '';
1241
+ }
1242
+ continue;
1243
+ }
1244
+ if (char === '"' || char === "'" || char.charCodeAt(0) === 96) {
1245
+ quote = char;
1246
+ }
1247
+ else if (char === '#') {
1248
+ inComment = true;
1249
+ }
1250
+ else if (pairs[char] || closers.has(char)) {
1251
+ tokens.push({ char: char, from: index });
1252
+ }
1253
+ }
1254
+ var stack = [];
1255
+ var stackCloserCounts = new Map();
1256
+ var futureCloserCounts = new Map();
1257
+ var changes = [];
1258
+ try {
1259
+ for (var tokens_1 = __values(tokens), tokens_1_1 = tokens_1.next(); !tokens_1_1.done; tokens_1_1 = tokens_1.next()) {
1260
+ var token = tokens_1_1.value;
1261
+ if (Date.now() >= this.deadline)
1262
+ return null;
1263
+ if (pairs[token.char]) {
1264
+ var closer = pairs[token.char];
1265
+ stack.push(closer);
1266
+ stackCloserCounts.set(closer, ((_b = stackCloserCounts.get(closer)) !== null && _b !== void 0 ? _b : 0) + 1);
1267
+ futureCloserCounts.clear();
1268
+ continue;
1269
+ }
1270
+ var expected = stack[stack.length - 1];
1271
+ if (!expected) {
1272
+ changes.push({ from: token.from, to: token.from + 1, insert: '' });
1273
+ continue;
1274
+ }
1275
+ if (token.char === expected) {
1276
+ stack.pop();
1277
+ stackCloserCounts.set(expected, ((_c = stackCloserCounts.get(expected)) !== null && _c !== void 0 ? _c : 1) - 1);
1278
+ futureCloserCounts.clear();
1279
+ continue;
1280
+ }
1281
+ var sameCloserDepth = (_d = stackCloserCounts.get(expected)) !== null && _d !== void 0 ? _d : 0;
1282
+ var futureCloserCount = futureCloserCounts.get(expected);
1283
+ if (futureCloserCount === undefined) {
1284
+ var countedClosers = this.countFutureClosersAtCurrentDepth(text, token.from + 1, expected, transparent);
1285
+ if (countedClosers === null)
1286
+ return null;
1287
+ futureCloserCount = countedClosers;
1288
+ futureCloserCounts.set(expected, countedClosers);
1289
+ }
1290
+ if (futureCloserCount >= sameCloserDepth) {
1291
+ changes.push({ from: token.from, to: token.from + 1, insert: '' });
1292
+ }
1293
+ else {
1294
+ changes.push({ from: token.from, to: token.from + 1, insert: expected });
1295
+ stack.pop();
1296
+ stackCloserCounts.set(expected, sameCloserDepth - 1);
1297
+ }
1298
+ }
1299
+ }
1300
+ catch (e_12_1) { e_12 = { error: e_12_1 }; }
1301
+ finally {
1302
+ try {
1303
+ if (tokens_1_1 && !tokens_1_1.done && (_a = tokens_1.return)) _a.call(tokens_1);
1304
+ }
1305
+ finally { if (e_12) throw e_12.error; }
1306
+ }
1307
+ return changes;
1308
+ };
1309
+ Parser.prototype.isSameDiagnostic = function (left, right) {
1310
+ return left.from === right.from && left.to === right.to && left.message === right.message;
1311
+ };
1312
+ Parser.prototype.appendDiagnostics = function (diagnostics) {
1313
+ var e_13, _a;
1314
+ try {
1315
+ for (var diagnostics_1 = __values(diagnostics), diagnostics_1_1 = diagnostics_1.next(); !diagnostics_1_1.done; diagnostics_1_1 = diagnostics_1.next()) {
1316
+ var diagnostic = diagnostics_1_1.value;
1317
+ var _group = diagnostic.group, _repair = diagnostic.repair, codeMirrorDiagnostic = __rest(diagnostic, ["group", "repair"]);
1318
+ this.diagnostics.push(codeMirrorDiagnostic);
1319
+ }
1320
+ }
1321
+ catch (e_13_1) { e_13 = { error: e_13_1 }; }
1322
+ finally {
1323
+ try {
1324
+ if (diagnostics_1_1 && !diagnostics_1_1.done && (_a = diagnostics_1.return)) _a.call(diagnostics_1);
1325
+ }
1326
+ finally { if (e_13) throw e_13.error; }
1327
+ }
1328
+ };
1329
+ Parser.prototype.mapRepairedPosition = function (position, insertAt, insertedLength) {
1330
+ return position <= insertAt ? position : Math.max(insertAt, position - insertedLength);
1331
+ };
1332
+ Parser.prototype.mapRepairedPositionAfterInsertions = function (position, insertAts, insertedLength) {
1333
+ var e_14, _a;
1334
+ var mapped = position;
1335
+ var priorInsertedLength = 0;
1336
+ try {
1337
+ for (var insertAts_1 = __values(insertAts), insertAts_1_1 = insertAts_1.next(); !insertAts_1_1.done; insertAts_1_1 = insertAts_1.next()) {
1338
+ var insertAt = insertAts_1_1.value;
1339
+ if (position > insertAt + priorInsertedLength) {
1340
+ mapped -= insertedLength;
1341
+ }
1342
+ priorInsertedLength += insertedLength;
1343
+ }
1344
+ }
1345
+ catch (e_14_1) { e_14 = { error: e_14_1 }; }
1346
+ finally {
1347
+ try {
1348
+ if (insertAts_1_1 && !insertAts_1_1.done && (_a = insertAts_1.return)) _a.call(insertAts_1);
1349
+ }
1350
+ finally { if (e_14) throw e_14.error; }
1351
+ }
1352
+ return mapped;
1353
+ };
1354
+ Parser.prototype.makeDiagnosticAt = function (from, to, message, group) {
1355
+ return {
42
1356
  severity: 'error',
43
- message: msg,
44
- from: node.from,
45
- to: node.to,
1357
+ source: 'DQL syntax',
1358
+ message: message,
1359
+ from: from,
1360
+ to: to,
1361
+ group: group,
1362
+ };
1363
+ };
1364
+ Parser.prototype.nodeText = function (node) {
1365
+ return this.state.sliceDoc(node.from, node.to);
1366
+ };
1367
+ Parser.prototype.isAdjacentToComma = function (node, parent) {
1368
+ var before = this.maskLineComments(this.state.sliceDoc(parent.from, node.from)).trimEnd();
1369
+ var after = this.maskLineComments(this.state.sliceDoc(node.to, parent.to)).trimStart();
1370
+ return before.endsWith(',') || after.startsWith(',') || this.nodeText(node) === ',';
1371
+ };
1372
+ Parser.prototype.isCommaSequence = function (text) {
1373
+ return /^,{2,}$/.test(this.maskLineComments(text).replace(/\s/g, ''));
1374
+ };
1375
+ Parser.prototype.isCommaOnlyList = function (node) {
1376
+ return /^(?:\(,{2,}\)|\[,{2,}\]|\{,{2,}\})$/.test(this.maskLineComments(this.nodeText(node)).replace(/\s/g, ''));
1377
+ };
1378
+ Parser.prototype.commaSequenceGroup = function (node) {
1379
+ return "".concat(node.name, ":").concat(node.from, ":").concat(node.to, ":comma-sequence");
1380
+ };
1381
+ Parser.prototype.describeConsecutiveCommaError = function (node, parent) {
1382
+ var contexts = {
1383
+ Projection: 'projection item',
1384
+ FunctionCallBody: 'function argument',
1385
+ EvalCallBody: 'function argument',
1386
+ OuterFunctionCallBody: 'function argument',
1387
+ RawOuterFunctionCallBody: 'function argument',
1388
+ RequiredNumberOuterFunctionCallBody: 'function argument',
1389
+ OptionalNumberOuterFunctionCallBody: 'function argument',
1390
+ FillOuterFunctionCallBody: 'function argument',
1391
+ VariadicOuterFunctionCallBody: 'function argument',
1392
+ RollupFunctionCallBody: 'function argument',
1393
+ CaseFunctionCallBody: 'function argument',
1394
+ InValue: 'argument value',
1395
+ InFieldValue: 'filter value',
1396
+ IndexExpr: 'namespace index',
1397
+ ByListExpr: 'grouping field',
1398
+ FilterClause: 'filter expression',
1399
+ };
1400
+ var context = parent;
1401
+ while (context && !contexts[context.name]) {
1402
+ if (commaContextBoundaries.has(context.name))
1403
+ return null;
1404
+ context = context.parent;
1405
+ }
1406
+ if (!context)
1407
+ return null;
1408
+ var masked = this.maskStringsAndLineComments(this.nodeText(context));
1409
+ var commaRun = /(?:,\s*){2,}/g;
1410
+ var match = commaRun.exec(masked);
1411
+ while (match) {
1412
+ var lastCommaOffset = match.index + match[0].lastIndexOf(',');
1413
+ var runFrom = context.from + match.index;
1414
+ var runTo = context.from + lastCommaOffset + 1;
1415
+ var recoveredCase = context.name === 'Projection' ? this.findCaseExprEndingAt(context, runFrom) : null;
1416
+ if (recoveredCase && this.containsError(recoveredCase) && node.from <= runTo && node.to >= runFrom) {
1417
+ return this.makeDiagnosticAt(runFrom, runFrom, 'CASE result expected after "THEN"', 'CaseResult:' + recoveredCase.from + ':' + recoveredCase.to);
1418
+ }
1419
+ var overlapsRun = node.from === node.to
1420
+ ? (node.from > runFrom || !this.hasMissingValueBeforeComma(node)) && node.from <= runTo
1421
+ : node.from < runTo && node.to > runFrom;
1422
+ if (overlapsRun) {
1423
+ var before = masked
1424
+ .slice(0, match.index)
1425
+ .replace(/\s/g, '')
1426
+ .replace(/^[([{]/, '');
1427
+ var message = before ? "".concat(contexts[context.name], " expected after \",\"") : "".concat(contexts[context.name], " expected between commas");
1428
+ return this.makeDiagnosticAt(node.from, node.to, message, "".concat(context.name, ":").concat(context.from, ":").concat(runFrom, ":").concat(runTo, ":comma-sequence"));
1429
+ }
1430
+ match = commaRun.exec(masked);
1431
+ }
1432
+ return null;
1433
+ };
1434
+ Parser.prototype.hasMissingValueBeforeComma = function (node) {
1435
+ var previous = this.siblingSkippingLineComments(node, 'previous');
1436
+ return Boolean(previous && (this.isOperator(previous) || previous.name === 'Then' || previous.name === 'Else'));
1437
+ };
1438
+ Parser.prototype.findCaseExprEndingAt = function (node, position) {
1439
+ var child = node.firstChild;
1440
+ while (child) {
1441
+ if (child.name === 'CaseExpr' && child.to === position)
1442
+ return child;
1443
+ var nested = this.findCaseExprEndingAt(child, position);
1444
+ if (nested)
1445
+ return nested;
1446
+ child = child.nextSibling;
1447
+ }
1448
+ return null;
1449
+ };
1450
+ Parser.prototype.siblingSkippingLineComments = function (node, direction) {
1451
+ var sibling = direction === 'previous' ? node.prevSibling : node.nextSibling;
1452
+ while ((sibling === null || sibling === void 0 ? void 0 : sibling.name) === 'LineComment') {
1453
+ sibling = direction === 'previous' ? sibling.prevSibling : sibling.nextSibling;
1454
+ }
1455
+ return sibling;
1456
+ };
1457
+ Parser.prototype.hasErroredSibling = function (node) {
1458
+ var sibling = node.prevSibling;
1459
+ while (sibling) {
1460
+ if (sibling.type.isError || this.containsError(sibling)) {
1461
+ return true;
1462
+ }
1463
+ sibling = sibling.prevSibling;
1464
+ }
1465
+ sibling = node.nextSibling;
1466
+ while (sibling) {
1467
+ if (sibling.type.isError || this.containsError(sibling)) {
1468
+ return true;
1469
+ }
1470
+ sibling = sibling.nextSibling;
1471
+ }
1472
+ return false;
1473
+ };
1474
+ Parser.prototype.maskLineComments = function (text) {
1475
+ var masked = '';
1476
+ var quote = '';
1477
+ var escaped = false;
1478
+ var inComment = false;
1479
+ for (var index = 0; index < text.length; index += 1) {
1480
+ var char = text[index];
1481
+ if (inComment) {
1482
+ if (char === '\n') {
1483
+ inComment = false;
1484
+ masked += char;
1485
+ }
1486
+ else {
1487
+ masked += ' ';
1488
+ }
1489
+ continue;
1490
+ }
1491
+ if (quote) {
1492
+ masked += char;
1493
+ if (escaped) {
1494
+ escaped = false;
1495
+ }
1496
+ else if (char === '\\' && quote !== '`') {
1497
+ escaped = true;
1498
+ }
1499
+ else if (char === quote) {
1500
+ quote = '';
1501
+ }
1502
+ else if (char === '\n' && quote !== '`') {
1503
+ quote = '';
1504
+ }
1505
+ continue;
1506
+ }
1507
+ if (char === '"' || char === "'" || char === '`') {
1508
+ quote = char;
1509
+ masked += char;
1510
+ }
1511
+ else if (char === '#') {
1512
+ inComment = true;
1513
+ masked += ' ';
1514
+ }
1515
+ else {
1516
+ masked += char;
1517
+ }
1518
+ }
1519
+ return masked;
1520
+ };
1521
+ Parser.prototype.maskStringsAndLineComments = function (text) {
1522
+ var masked = '';
1523
+ var quote = '';
1524
+ var escaped = false;
1525
+ var inComment = false;
1526
+ for (var index = 0; index < text.length; index += 1) {
1527
+ var char = text[index];
1528
+ if (inComment) {
1529
+ if (char === '\n') {
1530
+ inComment = false;
1531
+ masked += char;
1532
+ }
1533
+ else {
1534
+ masked += ' ';
1535
+ }
1536
+ continue;
1537
+ }
1538
+ if (quote) {
1539
+ masked += char === '\n' ? char : ' ';
1540
+ if (escaped) {
1541
+ escaped = false;
1542
+ }
1543
+ else if (char === '\\' && quote !== '`') {
1544
+ escaped = true;
1545
+ }
1546
+ else if (char === quote) {
1547
+ quote = '';
1548
+ }
1549
+ else if (char === '\n' && quote !== '`') {
1550
+ quote = '';
1551
+ }
1552
+ continue;
1553
+ }
1554
+ if (char === '"' || char === "'" || char === '`') {
1555
+ quote = char;
1556
+ masked += 'x';
1557
+ }
1558
+ else if (char === '#') {
1559
+ inComment = true;
1560
+ masked += ' ';
1561
+ }
1562
+ else {
1563
+ masked += char;
1564
+ }
1565
+ }
1566
+ return masked;
1567
+ };
1568
+ Parser.prototype.containsError = function (node) {
1569
+ var child = node.firstChild;
1570
+ while (child) {
1571
+ if (child.type.isError || this.containsError(child)) {
1572
+ return true;
1573
+ }
1574
+ child = child.nextSibling;
1575
+ }
1576
+ return false;
1577
+ };
1578
+ Parser.prototype.looksLikeProjectionAfterMissingColon = function (node) {
1579
+ var querySource = node.getChild('QuerySource');
1580
+ return Boolean(querySource && this.containsError(querySource) && !this.containsNode(querySource, 'DColon'));
1581
+ };
1582
+ Parser.prototype.containsNode = function (node, name) {
1583
+ var child = node.firstChild;
1584
+ while (child) {
1585
+ if (child.name === name || this.containsNode(child, name)) {
1586
+ return true;
1587
+ }
1588
+ child = child.nextSibling;
1589
+ }
1590
+ return false;
1591
+ };
1592
+ Parser.prototype.findAncestor = function (node, name) {
1593
+ var current = node;
1594
+ while (current) {
1595
+ if (current.name === name) {
1596
+ return current;
1597
+ }
1598
+ current = current.parent;
1599
+ }
1600
+ return null;
1601
+ };
1602
+ Parser.prototype.caseGroup = function (node) {
1603
+ var current = node;
1604
+ while (current && current.name !== 'CaseWhenClause' && current.name !== 'CaseElseClause' && current.name !== 'CaseExpr') {
1605
+ current = current.parent;
1606
+ }
1607
+ return current ? "".concat(current.name, ":").concat(current.from, ":").concat(current.to) : "Case:".concat(node.from, ":").concat(node.to);
1608
+ };
1609
+ Parser.prototype.findCaseResultDiagnostics = function () {
1610
+ if (this.caseResultDiagnostics)
1611
+ return this.caseResultDiagnostics;
1612
+ var diagnostics = [];
1613
+ var seen = new Set();
1614
+ var cursor = this.tree.cursor();
1615
+ while (cursor.next()) {
1616
+ if (cursor.name !== 'CaseExpr')
1617
+ continue;
1618
+ var clause = cursor.node.firstChild;
1619
+ while (clause) {
1620
+ var isWhenClause = clause.name === 'CaseWhenClause';
1621
+ var isElseClause = clause.name === 'CaseElseClause';
1622
+ var recovery = this.siblingSkippingLineComments(clause, 'next');
1623
+ if ((isWhenClause || isElseClause) && (recovery === null || recovery === void 0 ? void 0 : recovery.type.isError)) {
1624
+ var clauseText = this.maskStringsAndLineComments(this.nodeText(clause));
1625
+ var match = isWhenClause ? /\bthen\s+(else|end)\b/i.exec(clauseText) : /\belse\s+(end)\b/i.exec(clauseText);
1626
+ if (match) {
1627
+ var marker = match[1];
1628
+ if (marker.toLowerCase() === 'end' && recovery.from !== recovery.to) {
1629
+ clause = clause.nextSibling;
1630
+ continue;
1631
+ }
1632
+ var markerOffset = match.index + match[0].toLowerCase().lastIndexOf(marker.toLowerCase());
1633
+ var from = clause.from + markerOffset;
1634
+ var message = isWhenClause ? 'CASE result expected after "THEN"' : 'CASE result expected after "ELSE"';
1635
+ var key = "".concat(from, ":").concat(message);
1636
+ if (!seen.has(key)) {
1637
+ diagnostics.push(this.makeDiagnosticAt(from, from + marker.length, message, "CaseResult:".concat(from)));
1638
+ seen.add(key);
1639
+ }
1640
+ this.caseResultRecoveryErrors.add(this.nodeRangeKey(recovery));
1641
+ }
1642
+ }
1643
+ clause = clause.nextSibling;
1644
+ }
1645
+ }
1646
+ this.caseResultDiagnostics = diagnostics;
1647
+ return diagnostics;
1648
+ };
1649
+ Parser.prototype.nodeRangeKey = function (node) {
1650
+ return "".concat(node.from, ":").concat(node.to);
1651
+ };
1652
+ Parser.prototype.isOperator = function (node) {
1653
+ return [
1654
+ 'Pow',
1655
+ 'Mul',
1656
+ 'Div',
1657
+ 'Mod',
1658
+ 'Add',
1659
+ 'Sub',
1660
+ 'Eql',
1661
+ 'EqlSingle',
1662
+ 'Neq',
1663
+ 'Lte',
1664
+ 'Lss',
1665
+ 'Gte',
1666
+ 'Gtr',
1667
+ 'EqlRegex',
1668
+ 'NeqRegex',
1669
+ 'In',
1670
+ 'NotInSeq',
1671
+ 'And',
1672
+ 'Or',
1673
+ 'DAnd',
1674
+ 'DOr',
1675
+ ].includes(node.name);
1676
+ };
1677
+ Parser.prototype.getDelimiterIssue = function () {
1678
+ if (this.delimiterIssue === undefined) {
1679
+ this.delimiterIssue = this.findDelimiterIssue(this.tree.topNode.to);
1680
+ }
1681
+ return this.delimiterIssue;
1682
+ };
1683
+ Parser.prototype.makeDelimiterDiagnostic = function (issue) {
1684
+ if (issue.kind === 'quote' || issue.kind === 'quotedQuery') {
1685
+ var context = issue.kind === 'quote' ? 'string literal' : 'quoted query';
1686
+ var message = issue.kind === 'quote' && issue.newline
1687
+ ? 'unescaped newline in string literal'
1688
+ : "unterminated ".concat(context, "; expected closing ").concat(this.quoteName(issue.quote));
1689
+ return this.makeDiagnosticAt(issue.from, issue.from + 1, message, "delimiter:".concat(issue.from));
1690
+ }
1691
+ if (issue.kind === 'mismatched') {
1692
+ var message = issue.context
1693
+ ? "expected ".concat(this.quoteName(issue.close), " instead of ").concat(this.quoteName(issue.actual), " to close ").concat(issue.context)
1694
+ : issue.recovery === 'delete'
1695
+ ? "unexpected closing delimiter \"".concat(issue.actual, "\" before \"").concat(issue.close, "\"")
1696
+ : "expected \"".concat(issue.close, "\" instead of \"").concat(issue.actual, "\" to close \"").concat(issue.open, "\"");
1697
+ return this.makeDiagnosticAt(issue.actualFrom, issue.actualFrom + 1, message, "delimiter:".concat(issue.from));
1698
+ }
1699
+ if (issue.kind === 'unexpectedClosing') {
1700
+ return this.makeDiagnosticAt(issue.actualFrom, issue.actualFrom + 1, "unexpected closing delimiter \"".concat(issue.actual, "\""), "delimiter:".concat(issue.actualFrom));
1701
+ }
1702
+ return this.makeDiagnosticAt(issue.at, issue.at, "expected \"".concat(issue.close, "\" to close \"").concat(issue.open, "\""), "delimiter:".concat(issue.from));
1703
+ };
1704
+ Parser.prototype.isRelatedDelimiterError = function (node, issue) {
1705
+ if (issue.kind === 'quote' || issue.kind === 'quotedQuery') {
1706
+ if (node.from !== node.to) {
1707
+ return node.from < issue.end && node.to > issue.from;
1708
+ }
1709
+ var includesEnd = issue.kind === 'quotedQuery' || !issue.newline;
1710
+ return node.from >= issue.from && (node.from < issue.end || (includesEnd && node.from === issue.end));
1711
+ }
1712
+ return node.from === issue.actualFrom || (node.from <= issue.actualFrom && node.to > issue.actualFrom) || node.from === this.tree.topNode.to;
1713
+ };
1714
+ Parser.prototype.quoteName = function (quote) {
1715
+ return quote === '"' ? 'double quote' : quote === "'" ? 'single quote' : 'backtick';
1716
+ };
1717
+ Parser.prototype.findQuotedQueryDelimiterInfo = function () {
1718
+ var e_15, _a, e_16, _b, e_17, _c;
1719
+ var _d;
1720
+ if (this.quotedQueryDelimiterInfo)
1721
+ return this.quotedQueryDelimiterInfo;
1722
+ var transparent = new Set();
1723
+ var issues = new Map();
1724
+ var fallbackRanges = [];
1725
+ var fallbackDiagnostics = [];
1726
+ var addFallbackRange = function (range) {
1727
+ if (range && !fallbackRanges.some(function (existing) { return existing.from === range.from && existing.to === range.to; })) {
1728
+ fallbackRanges.push(range);
1729
+ }
1730
+ };
1731
+ var pending = null;
1732
+ var cursor = this.tree.cursor();
1733
+ while (cursor.next()) {
1734
+ if (Date.now() >= this.deadline)
1735
+ break;
1736
+ if (cursor.name === 'StringLiteral') {
1737
+ addFallbackRange(this.findFallbackQuotedQueryRange(cursor.node));
1738
+ }
1739
+ if (cursor.name === 'Queted' && ((_d = cursor.node.parent) === null || _d === void 0 ? void 0 : _d.name) !== 'OuterArgItem') {
1740
+ addFallbackRange(this.findFallbackQuotedQueryRangeFromOpening(cursor.from));
1741
+ }
1742
+ if (cursor.name !== 'OuterArgItem') {
1743
+ continue;
1744
+ }
1745
+ var quoted = [];
1746
+ var child = cursor.node.firstChild;
1747
+ while (child) {
1748
+ if (child.name === 'Queted')
1749
+ quoted.push(child);
1750
+ child = child.nextSibling;
1751
+ }
1752
+ try {
1753
+ for (var quoted_1 = (e_15 = void 0, __values(quoted)), quoted_1_1 = quoted_1.next(); !quoted_1_1.done; quoted_1_1 = quoted_1.next()) {
1754
+ var quote = quoted_1_1.value;
1755
+ transparent.add(quote.from);
1756
+ }
1757
+ }
1758
+ catch (e_15_1) { e_15 = { error: e_15_1 }; }
1759
+ finally {
1760
+ try {
1761
+ if (quoted_1_1 && !quoted_1_1.done && (_a = quoted_1.return)) _a.call(quoted_1);
1762
+ }
1763
+ finally { if (e_15) throw e_15.error; }
1764
+ }
1765
+ if (quoted.length >= 2) {
1766
+ var first = quoted[0];
1767
+ var last = quoted[quoted.length - 1];
1768
+ var expected = this.nodeText(first);
1769
+ var actual = this.nodeText(last);
1770
+ if (expected !== actual) {
1771
+ issues.set(last.from, {
1772
+ kind: 'mismatched',
1773
+ open: expected,
1774
+ close: expected,
1775
+ from: first.from,
1776
+ actual: actual,
1777
+ actualFrom: last.from,
1778
+ context: 'quoted query',
1779
+ });
1780
+ }
1781
+ else {
1782
+ var range = { from: first.from, to: last.to };
1783
+ var payload = this.state.sliceDoc(first.to, last.from);
1784
+ if (this.repairScopedDelimiterMismatches(payload) !== null && this.isFallbackQuotedQueryRange(range.from, range.to)) {
1785
+ addFallbackRange(range);
1786
+ }
1787
+ }
1788
+ }
1789
+ else if (quoted.length === 1) {
1790
+ var quote = quoted[0];
1791
+ var wrapperQuote = this.nodeText(quote);
1792
+ var lexicalClosing = this.findLexicalQuotedQueryClosing(this.state.doc.toString(), quote.from, wrapperQuote);
1793
+ var fallbackRange = lexicalClosing === null ? null : { from: quote.from, to: lexicalClosing + 1 };
1794
+ if (fallbackRange && this.isFallbackQuotedQueryRange(fallbackRange.from, fallbackRange.to)) {
1795
+ addFallbackRange(fallbackRange);
1796
+ }
1797
+ else {
1798
+ var issue = {
1799
+ kind: 'quotedQuery',
1800
+ quote: wrapperQuote,
1801
+ from: quote.from,
1802
+ end: cursor.to,
1803
+ repairAt: cursor.to,
1804
+ };
1805
+ if (!pending || issue.from < pending.from)
1806
+ pending = issue;
1807
+ }
1808
+ }
1809
+ }
1810
+ fallbackRanges.sort(function (left, right) { return left.from - right.from || right.to - left.to; });
1811
+ var disjointFallbackRanges = [];
1812
+ try {
1813
+ for (var fallbackRanges_1 = __values(fallbackRanges), fallbackRanges_1_1 = fallbackRanges_1.next(); !fallbackRanges_1_1.done; fallbackRanges_1_1 = fallbackRanges_1.next()) {
1814
+ var range = fallbackRanges_1_1.value;
1815
+ var previous = disjointFallbackRanges[disjointFallbackRanges.length - 1];
1816
+ if (!previous || range.from >= previous.to)
1817
+ disjointFallbackRanges.push(range);
1818
+ }
1819
+ }
1820
+ catch (e_16_1) { e_16 = { error: e_16_1 }; }
1821
+ finally {
1822
+ try {
1823
+ if (fallbackRanges_1_1 && !fallbackRanges_1_1.done && (_b = fallbackRanges_1.return)) _b.call(fallbackRanges_1);
1824
+ }
1825
+ finally { if (e_16) throw e_16.error; }
1826
+ }
1827
+ fallbackRanges.splice.apply(fallbackRanges, __spreadArray([0, fallbackRanges.length], __read(disjointFallbackRanges), false));
1828
+ try {
1829
+ for (var fallbackRanges_2 = __values(fallbackRanges), fallbackRanges_2_1 = fallbackRanges_2.next(); !fallbackRanges_2_1.done; fallbackRanges_2_1 = fallbackRanges_2.next()) {
1830
+ var range = fallbackRanges_2_1.value;
1831
+ transparent.add(range.from);
1832
+ transparent.add(range.to - 1);
1833
+ }
1834
+ }
1835
+ catch (e_17_1) { e_17 = { error: e_17_1 }; }
1836
+ finally {
1837
+ try {
1838
+ if (fallbackRanges_2_1 && !fallbackRanges_2_1.done && (_c = fallbackRanges_2.return)) _c.call(fallbackRanges_2);
1839
+ }
1840
+ finally { if (e_17) throw e_17.error; }
1841
+ }
1842
+ fallbackDiagnostics.push.apply(fallbackDiagnostics, __spreadArray([], __read(this.diagnoseFallbackQuotedQueries(fallbackRanges)), false));
1843
+ this.quotedQueryDelimiterInfo = { transparent: transparent, issues: issues, pending: pending, fallbackRanges: fallbackRanges, fallbackDiagnostics: fallbackDiagnostics };
1844
+ return this.quotedQueryDelimiterInfo;
1845
+ };
1846
+ Parser.prototype.findFallbackQuotedQueryRange = function (node) {
1847
+ var e_18, _a;
1848
+ var _b;
1849
+ var indexItem = node.parent;
1850
+ var indexExpr = indexItem === null || indexItem === void 0 ? void 0 : indexItem.parent;
1851
+ var namespace = indexExpr === null || indexExpr === void 0 ? void 0 : indexExpr.parent;
1852
+ if ((indexItem === null || indexItem === void 0 ? void 0 : indexItem.name) !== 'IndexItem' || (indexExpr === null || indexExpr === void 0 ? void 0 : indexExpr.name) !== 'IndexExpr' || (namespace === null || namespace === void 0 ? void 0 : namespace.name) !== 'Namespace') {
1853
+ return null;
1854
+ }
1855
+ if (indexItem.prevSibling)
1856
+ return null;
1857
+ var namespaceParent = namespace.parent;
1858
+ if ((namespaceParent === null || namespaceParent === void 0 ? void 0 : namespaceParent.name) !== 'QueryExpr' && (namespaceParent === null || namespaceParent === void 0 ? void 0 : namespaceParent.name) !== 'Query')
1859
+ return null;
1860
+ if (namespaceParent.name === 'Query' && ((_b = this.siblingSkippingLineComments(namespace, 'next')) === null || _b === void 0 ? void 0 : _b.name) === 'DColon')
1861
+ return null;
1862
+ var raw = this.nodeText(node);
1863
+ var quote = raw[0];
1864
+ if (!['"', "'", '`'].includes(quote))
1865
+ return null;
1866
+ var text = this.state.doc.toString();
1867
+ var lexicalClosing = this.findLexicalQuotedQueryClosing(text, node.from, quote);
1868
+ var candidates = [lexicalClosing === null ? null : lexicalClosing + 1, raw.length >= 2 && raw[raw.length - 1] === quote ? node.to : null];
1869
+ try {
1870
+ for (var _c = __values(__spreadArray([], __read(new Set(candidates)), false)), _d = _c.next(); !_d.done; _d = _c.next()) {
1871
+ var to = _d.value;
1872
+ if (to === null || to <= node.from + 1 || this.state.sliceDoc(to - 1, to) !== quote)
1873
+ continue;
1874
+ if (this.isFallbackQuotedQueryRange(node.from, to))
1875
+ return { from: node.from, to: to };
1876
+ }
1877
+ }
1878
+ catch (e_18_1) { e_18 = { error: e_18_1 }; }
1879
+ finally {
1880
+ try {
1881
+ if (_d && !_d.done && (_a = _c.return)) _a.call(_c);
1882
+ }
1883
+ finally { if (e_18) throw e_18.error; }
1884
+ }
1885
+ return null;
1886
+ };
1887
+ Parser.prototype.findFallbackQuotedQueryRangeFromOpening = function (from) {
1888
+ var quote = this.state.sliceDoc(from, from + 1);
1889
+ if (!['"', "'", '`'].includes(quote))
1890
+ return null;
1891
+ var closing = this.findLexicalQuotedQueryClosing(this.state.doc.toString(), from, quote);
1892
+ if (closing === null || closing <= from)
1893
+ return null;
1894
+ var to = closing + 1;
1895
+ return this.isFallbackQuotedQueryRange(from, to) ? { from: from, to: to } : null;
1896
+ };
1897
+ Parser.prototype.isFallbackQuotedQueryRange = function (from, to) {
1898
+ var originalPayload = this.state.sliceDoc(from + 1, to - 1);
1899
+ if (!this.formsOuterQuotedQuery(from, to, 'M::cpu:(usage)'))
1900
+ return false;
1901
+ if (this.isQueryPayload(originalPayload))
1902
+ return true;
1903
+ var bulkRepairedPayload = this.repairScopedDelimiterMismatches(originalPayload);
1904
+ if (bulkRepairedPayload && this.isQueryPayload(bulkRepairedPayload))
1905
+ return true;
1906
+ var queue = [{ payload: originalPayload, depth: 0 }];
1907
+ var seen = new Set();
1908
+ while (queue.length > 0 && Date.now() < this.deadline) {
1909
+ var candidate = queue.shift();
1910
+ if (seen.has(candidate.payload))
1911
+ continue;
1912
+ seen.add(candidate.payload);
1913
+ var issue = this.findFirstDelimiterMismatch(candidate.payload);
1914
+ if (!issue) {
1915
+ if (candidate.depth > 0 && this.isQueryPayload(candidate.payload))
1916
+ return true;
1917
+ continue;
1918
+ }
1919
+ if (candidate.depth >= maxMismatchRepairDepth + 1)
1920
+ continue;
1921
+ queue.push({
1922
+ payload: candidate.payload.slice(0, issue.from) + candidate.payload.slice(issue.from + 1),
1923
+ depth: candidate.depth + 1,
1924
+ });
1925
+ if (issue.expected) {
1926
+ queue.push({
1927
+ payload: candidate.payload.slice(0, issue.from) + issue.expected + candidate.payload.slice(issue.from + 1),
1928
+ depth: candidate.depth + 1,
1929
+ });
1930
+ }
1931
+ }
1932
+ return false;
1933
+ };
1934
+ Parser.prototype.isQueryPayload = function (payload) {
1935
+ var _a;
1936
+ var payloadState = this.state.update({ changes: { from: 0, to: this.state.doc.length, insert: payload }, filter: false }).state;
1937
+ var payloadTree = this.getCompleteTree(payloadState);
1938
+ if (!payloadTree)
1939
+ return false;
1940
+ var cursor = payloadTree.cursor();
1941
+ while (cursor.next()) {
1942
+ if (cursor.name !== 'Query' || ((_a = cursor.node.parent) === null || _a === void 0 ? void 0 : _a.name) !== 'QueryExpr')
1943
+ continue;
1944
+ return !this.containsError(cursor.node) || Boolean(cursor.node.getChild('QueryClause'));
1945
+ }
1946
+ return false;
1947
+ };
1948
+ Parser.prototype.diagnoseFallbackQuotedQueries = function (ranges) {
1949
+ var e_19, _a, e_20, _b, e_21, _c, e_22, _d;
1950
+ var _this = this;
1951
+ if (ranges.length === 0)
1952
+ return [];
1953
+ var diagnostics = [];
1954
+ var canonicalPayload = 'M::cpu:(usage)';
1955
+ try {
1956
+ for (var ranges_1 = __values(ranges), ranges_1_1 = ranges_1.next(); !ranges_1_1.done; ranges_1_1 = ranges_1.next()) {
1957
+ var range = ranges_1_1.value;
1958
+ if (Date.now() >= this.deadline)
1959
+ return diagnostics;
1960
+ var payload = this.state.sliceDoc(range.from + 1, range.to - 1);
1961
+ var payloadState = this.state.update({ changes: { from: 0, to: this.state.doc.length, insert: payload }, filter: false }).state;
1962
+ var payloadParser = new Parser(payloadState, this.deadline);
1963
+ payloadParser.repairDepth = this.repairDepth;
1964
+ payloadParser.mismatchRepairDepth = this.mismatchRepairDepth;
1965
+ payloadParser.terminalRepairUsed = this.terminalRepairUsed;
1966
+ payloadParser.analyze();
1967
+ var _loop_11 = function (diagnostic) {
1968
+ var mapped = __assign(__assign({}, diagnostic), { from: diagnostic.from + range.from + 1, to: diagnostic.to + range.from + 1 });
1969
+ if (!diagnostics.some(function (existing) { return _this.isSameDiagnostic(existing, mapped); }))
1970
+ diagnostics.push(mapped);
1971
+ };
1972
+ try {
1973
+ for (var _e = (e_20 = void 0, __values(payloadParser.getDiagnostics())), _f = _e.next(); !_f.done; _f = _e.next()) {
1974
+ var diagnostic = _f.value;
1975
+ _loop_11(diagnostic);
1976
+ }
1977
+ }
1978
+ catch (e_20_1) { e_20 = { error: e_20_1 }; }
1979
+ finally {
1980
+ try {
1981
+ if (_f && !_f.done && (_b = _e.return)) _b.call(_e);
1982
+ }
1983
+ finally { if (e_20) throw e_20.error; }
1984
+ }
1985
+ }
1986
+ }
1987
+ catch (e_19_1) { e_19 = { error: e_19_1 }; }
1988
+ finally {
1989
+ try {
1990
+ if (ranges_1_1 && !ranges_1_1.done && (_a = ranges_1.return)) _a.call(ranges_1);
1991
+ }
1992
+ finally { if (e_19) throw e_19.error; }
1993
+ }
1994
+ if (Date.now() >= this.deadline)
1995
+ return diagnostics;
1996
+ var changes = ranges.map(function (range) { return ({ from: range.from + 1, to: range.to - 1, insert: canonicalPayload }); });
1997
+ var probeTransaction = this.state.update({ changes: changes, filter: false });
1998
+ var insertedRanges = [];
1999
+ var offset = 0;
2000
+ try {
2001
+ for (var ranges_2 = __values(ranges), ranges_2_1 = ranges_2.next(); !ranges_2_1.done; ranges_2_1 = ranges_2.next()) {
2002
+ var range = ranges_2_1.value;
2003
+ var from = range.from + 1 + offset;
2004
+ insertedRanges.push({ from: from, to: from + canonicalPayload.length });
2005
+ offset += canonicalPayload.length - (range.to - range.from - 2);
2006
+ }
2007
+ }
2008
+ catch (e_21_1) { e_21 = { error: e_21_1 }; }
2009
+ finally {
2010
+ try {
2011
+ if (ranges_2_1 && !ranges_2_1.done && (_c = ranges_2.return)) _c.call(ranges_2);
2012
+ }
2013
+ finally { if (e_21) throw e_21.error; }
2014
+ }
2015
+ var probeParser = new Parser(probeTransaction.state, this.deadline);
2016
+ probeParser.repairDepth = this.repairDepth;
2017
+ probeParser.mismatchRepairDepth = this.mismatchRepairDepth;
2018
+ probeParser.terminalRepairUsed = this.terminalRepairUsed;
2019
+ probeParser.analyze();
2020
+ var outerDiagnostics = probeParser.getDiagnostics().filter(function (diagnostic) {
2021
+ return !insertedRanges.some(function (range) {
2022
+ return diagnostic.from === diagnostic.to
2023
+ ? diagnostic.from >= range.from && diagnostic.from <= range.to
2024
+ : diagnostic.from < range.to && diagnostic.to > range.from;
2025
+ });
46
2026
  });
2027
+ var _loop_12 = function (diagnostic) {
2028
+ if (!diagnostics.some(function (existing) { return _this.isSameDiagnostic(existing, diagnostic); }))
2029
+ diagnostics.push(diagnostic);
2030
+ };
2031
+ try {
2032
+ for (var _g = __values(this.mapDiagnosticsThroughChanges(outerDiagnostics, probeTransaction.changes)), _h = _g.next(); !_h.done; _h = _g.next()) {
2033
+ var diagnostic = _h.value;
2034
+ _loop_12(diagnostic);
2035
+ }
2036
+ }
2037
+ catch (e_22_1) { e_22 = { error: e_22_1 }; }
2038
+ finally {
2039
+ try {
2040
+ if (_h && !_h.done && (_d = _g.return)) _d.call(_g);
2041
+ }
2042
+ finally { if (e_22) throw e_22.error; }
2043
+ }
2044
+ return diagnostics;
2045
+ };
2046
+ Parser.prototype.repairScopedDelimiterMismatches = function (text) {
2047
+ var e_23, _a;
2048
+ var _b, _c, _d;
2049
+ var pairs = { '(': ')', '[': ']', '{': '}' };
2050
+ var closers = new Set(Object.values(pairs));
2051
+ var stack = [];
2052
+ var stackCloserCounts = new Map();
2053
+ var futureCloserCounts = new Map();
2054
+ var changes = [];
2055
+ var transparent = new Set();
2056
+ var quote = '';
2057
+ var escaped = false;
2058
+ var inComment = false;
2059
+ for (var index = 0; index < text.length; index += 1) {
2060
+ if (Date.now() >= this.deadline)
2061
+ return null;
2062
+ var char = text[index];
2063
+ if (inComment) {
2064
+ if (char === '\n')
2065
+ inComment = false;
2066
+ continue;
2067
+ }
2068
+ if (quote) {
2069
+ if (escaped) {
2070
+ escaped = false;
2071
+ }
2072
+ else if (char === '\\' && quote.charCodeAt(0) !== 96) {
2073
+ escaped = true;
2074
+ }
2075
+ else if (char === quote) {
2076
+ quote = '';
2077
+ }
2078
+ continue;
2079
+ }
2080
+ if (char === '"' || char === "'" || char.charCodeAt(0) === 96) {
2081
+ quote = char;
2082
+ }
2083
+ else if (char === '#') {
2084
+ inComment = true;
2085
+ }
2086
+ else if (pairs[char]) {
2087
+ var closer = pairs[char];
2088
+ stack.push(closer);
2089
+ stackCloserCounts.set(closer, ((_b = stackCloserCounts.get(closer)) !== null && _b !== void 0 ? _b : 0) + 1);
2090
+ futureCloserCounts.clear();
2091
+ }
2092
+ else if (closers.has(char)) {
2093
+ var expected = stack[stack.length - 1];
2094
+ if (char === expected) {
2095
+ stack.pop();
2096
+ stackCloserCounts.set(expected, ((_c = stackCloserCounts.get(expected)) !== null && _c !== void 0 ? _c : 1) - 1);
2097
+ futureCloserCounts.clear();
2098
+ continue;
2099
+ }
2100
+ if (!expected) {
2101
+ changes.push({ from: index, to: index + 1, insert: '' });
2102
+ continue;
2103
+ }
2104
+ var sameCloserDepth = (_d = stackCloserCounts.get(expected)) !== null && _d !== void 0 ? _d : 0;
2105
+ var futureCloserCount = futureCloserCounts.get(expected);
2106
+ if (futureCloserCount === undefined) {
2107
+ var countedClosers = this.countFutureClosersAtCurrentDepth(text, index + 1, expected, transparent);
2108
+ if (countedClosers === null)
2109
+ return null;
2110
+ futureCloserCount = countedClosers;
2111
+ futureCloserCounts.set(expected, countedClosers);
2112
+ }
2113
+ if (futureCloserCount >= sameCloserDepth) {
2114
+ changes.push({ from: index, to: index + 1, insert: '' });
2115
+ }
2116
+ else {
2117
+ changes.push({ from: index, to: index + 1, insert: expected });
2118
+ stack.pop();
2119
+ stackCloserCounts.set(expected, sameCloserDepth - 1);
2120
+ }
2121
+ }
2122
+ }
2123
+ if (quote)
2124
+ return null;
2125
+ var missingClosers = __spreadArray([], __read(stack), false).reverse().join('');
2126
+ if (changes.length === 0 && !missingClosers)
2127
+ return null;
2128
+ var repaired = '';
2129
+ var copiedTo = 0;
2130
+ try {
2131
+ for (var changes_1 = __values(changes), changes_1_1 = changes_1.next(); !changes_1_1.done; changes_1_1 = changes_1.next()) {
2132
+ var change = changes_1_1.value;
2133
+ repaired += text.slice(copiedTo, change.from) + change.insert;
2134
+ copiedTo = change.to;
2135
+ }
2136
+ }
2137
+ catch (e_23_1) { e_23 = { error: e_23_1 }; }
2138
+ finally {
2139
+ try {
2140
+ if (changes_1_1 && !changes_1_1.done && (_a = changes_1.return)) _a.call(changes_1);
2141
+ }
2142
+ finally { if (e_23) throw e_23.error; }
2143
+ }
2144
+ return repaired + text.slice(copiedTo) + missingClosers;
2145
+ };
2146
+ Parser.prototype.findFirstDelimiterMismatch = function (text) {
2147
+ var pairs = { '(': ')', '[': ']', '{': '}' };
2148
+ var closers = new Set(Object.values(pairs));
2149
+ var stack = [];
2150
+ var quote = '';
2151
+ var escaped = false;
2152
+ var inComment = false;
2153
+ for (var index = 0; index < text.length; index += 1) {
2154
+ var char = text[index];
2155
+ if (inComment) {
2156
+ if (char === '\n')
2157
+ inComment = false;
2158
+ continue;
2159
+ }
2160
+ if (quote) {
2161
+ if (escaped) {
2162
+ escaped = false;
2163
+ }
2164
+ else if (char === '\\' && quote.charCodeAt(0) !== 96) {
2165
+ escaped = true;
2166
+ }
2167
+ else if (char === quote) {
2168
+ quote = '';
2169
+ }
2170
+ continue;
2171
+ }
2172
+ if (char === '"' || char === "'" || char.charCodeAt(0) === 96) {
2173
+ quote = char;
2174
+ }
2175
+ else if (char === '#') {
2176
+ inComment = true;
2177
+ }
2178
+ else if (pairs[char]) {
2179
+ stack.push(pairs[char]);
2180
+ }
2181
+ else if (closers.has(char)) {
2182
+ var expected = stack[stack.length - 1];
2183
+ if (char !== expected)
2184
+ return { from: index, expected: expected };
2185
+ stack.pop();
2186
+ }
2187
+ }
2188
+ return null;
2189
+ };
2190
+ Parser.prototype.formsOuterQuotedQuery = function (from, to, payload) {
2191
+ var repairedState = this.state.update({ changes: { from: from + 1, to: to - 1, insert: payload }, filter: false }).state;
2192
+ var repairedTree = this.getCompleteTree(repairedState);
2193
+ if (!repairedTree)
2194
+ return false;
2195
+ var wrapperQuote = this.state.sliceDoc(from, from + 1);
2196
+ var expectedClosing = from + payload.length + 1;
2197
+ var cursor = repairedTree.cursor();
2198
+ while (cursor.next()) {
2199
+ if (cursor.name !== 'OuterArgItem' || cursor.from !== from)
2200
+ continue;
2201
+ var query = cursor.node.getChild('Query');
2202
+ var quotes = cursor.node.getChildren('Queted');
2203
+ var openingQuote = quotes.find(function (quote) { return quote.from === from; });
2204
+ var closingQuote = quotes.find(function (quote) { return quote.from === expectedClosing; });
2205
+ if (query &&
2206
+ openingQuote &&
2207
+ closingQuote &&
2208
+ repairedState.sliceDoc(openingQuote.from, openingQuote.to) === wrapperQuote &&
2209
+ repairedState.sliceDoc(closingQuote.from, closingQuote.to) === wrapperQuote) {
2210
+ return true;
2211
+ }
2212
+ }
2213
+ return false;
2214
+ };
2215
+ Parser.prototype.findDelimiterIssue = function (end, scoreRecovery) {
2216
+ var _a, _b, _c, _d, _e;
2217
+ if (scoreRecovery === void 0) { scoreRecovery = true; }
2218
+ var text = this.state.sliceDoc(0, end);
2219
+ var stack = [];
2220
+ var pairs = { '(': ')', '[': ']', '{': '}' };
2221
+ var closingDelimiters = new Set(Object.values(pairs));
2222
+ var quote = '';
2223
+ var quoteFrom = -1;
2224
+ var quoteRepairCandidates = [];
2225
+ var escaped = false;
2226
+ var quotedQueryDelimiters = this.findQuotedQueryDelimiterInfo();
2227
+ var quotedQueryOuterDepth = -1;
2228
+ var _loop_13 = function (index) {
2229
+ if ((index & 255) === 0 && Date.now() >= this_3.deadline)
2230
+ return { value: null };
2231
+ var char = text[index];
2232
+ var fallbackRange = quotedQueryDelimiters.fallbackRanges.find(function (range) { return index >= range.from && index < range.to; });
2233
+ if (fallbackRange) {
2234
+ index = fallbackRange.to - 1;
2235
+ return out_index_1 = index, "continue";
2236
+ }
2237
+ var quotedQueryIssue = quotedQueryDelimiters.issues.get(index);
2238
+ if (quotedQueryIssue)
2239
+ return { value: quotedQueryIssue };
2240
+ if (quotedQueryDelimiters.transparent.has(index)) {
2241
+ if (((_a = quotedQueryDelimiters.pending) === null || _a === void 0 ? void 0 : _a.kind) === 'quotedQuery' && quotedQueryDelimiters.pending.from === index) {
2242
+ quotedQueryOuterDepth = stack.length;
2243
+ }
2244
+ return out_index_1 = index, "continue";
2245
+ }
2246
+ if (quote) {
2247
+ if (escaped) {
2248
+ escaped = false;
2249
+ }
2250
+ else if (char === '\\' && quote !== '`') {
2251
+ escaped = true;
2252
+ }
2253
+ else if (char === quote) {
2254
+ quote = '';
2255
+ quoteFrom = -1;
2256
+ quoteRepairCandidates = [];
2257
+ }
2258
+ else if (char === '\n' && quote !== '`') {
2259
+ var quotedQueryRepairAt = this_3.findVerifiedQuotedQueryRepairAt(text, quoteFrom, quote, (_b = stack[stack.length - 1]) === null || _b === void 0 ? void 0 : _b.close, end);
2260
+ if (quotedQueryRepairAt !== null) {
2261
+ return { value: {
2262
+ kind: 'quotedQuery',
2263
+ quote: quote,
2264
+ from: quoteFrom,
2265
+ end: end,
2266
+ repairAt: quotedQueryRepairAt,
2267
+ } };
2268
+ }
2269
+ var recovery = this_3.findStringNewlineRecovery(text, quoteFrom + 1, quote);
2270
+ return { value: {
2271
+ kind: 'quote',
2272
+ quote: quote,
2273
+ from: quoteFrom,
2274
+ end: (_c = recovery === null || recovery === void 0 ? void 0 : recovery.end) !== null && _c !== void 0 ? _c : index + 1,
2275
+ newline: true,
2276
+ repairLineBreaks: recovery === null || recovery === void 0 ? void 0 : recovery.lineBreaks,
2277
+ } };
2278
+ }
2279
+ else if (stack.length > 0 && char === stack[stack.length - 1].close) {
2280
+ quoteRepairCandidates.push(index);
2281
+ }
2282
+ return out_index_1 = index, "continue";
2283
+ }
2284
+ if (char === '"' || char === "'" || char === '`') {
2285
+ quote = char;
2286
+ quoteFrom = index;
2287
+ quoteRepairCandidates = [];
2288
+ return out_index_1 = index, "continue";
2289
+ }
2290
+ if (char === '#') {
2291
+ while (index + 1 < text.length && text[index + 1] !== '\n') {
2292
+ index += 1;
2293
+ }
2294
+ return out_index_1 = index, "continue";
2295
+ }
2296
+ if (pairs[char]) {
2297
+ stack.push({ open: char, close: pairs[char], from: index });
2298
+ return out_index_1 = index, "continue";
2299
+ }
2300
+ var last = stack[stack.length - 1];
2301
+ if (last && char === last.close) {
2302
+ if (((_d = quotedQueryDelimiters.pending) === null || _d === void 0 ? void 0 : _d.kind) === 'quotedQuery' &&
2303
+ quotedQueryOuterDepth > 0 &&
2304
+ stack.length === quotedQueryOuterDepth &&
2305
+ quotedQueryDelimiters.pending.repairAt === quotedQueryDelimiters.pending.end) {
2306
+ quotedQueryDelimiters.pending.repairAt = index;
2307
+ quotedQueryOuterDepth = -1;
2308
+ }
2309
+ stack.pop();
2310
+ }
2311
+ else if (last && closingDelimiters.has(char)) {
2312
+ var sameCloserDepth = stack.filter(function (entry) { return entry.close === last.close; }).length;
2313
+ var futureCloserCount = scoreRecovery
2314
+ ? this_3.countFutureClosersAtCurrentDepth(text, index + 1, last.close, quotedQueryDelimiters.transparent)
2315
+ : 0;
2316
+ return { value: {
2317
+ kind: 'mismatched',
2318
+ open: last.open,
2319
+ close: last.close,
2320
+ from: last.from,
2321
+ actual: char,
2322
+ actualFrom: index,
2323
+ recovery: scoreRecovery
2324
+ ? futureCloserCount !== null && futureCloserCount >= sameCloserDepth
2325
+ ? 'delete'
2326
+ : Date.now() >= this_3.deadline
2327
+ ? 'replace'
2328
+ : this_3.chooseMismatchRecovery(index, index + 1, last.close)
2329
+ : 'replace',
2330
+ } };
2331
+ }
2332
+ else if (!last && closingDelimiters.has(char) && !this_3.hasPrecedingErrorEndingAt(index)) {
2333
+ return { value: { kind: 'unexpectedClosing', actual: char, actualFrom: index } };
2334
+ }
2335
+ out_index_1 = index;
2336
+ };
2337
+ var this_3 = this, out_index_1;
2338
+ for (var index = 0; index < text.length; index += 1) {
2339
+ var state_2 = _loop_13(index);
2340
+ index = out_index_1;
2341
+ if (typeof state_2 === "object")
2342
+ return state_2.value;
2343
+ }
2344
+ if (quote) {
2345
+ return {
2346
+ kind: 'quote',
2347
+ quote: quote,
2348
+ from: quoteFrom,
2349
+ end: end,
2350
+ repairAt: this.chooseQuoteRepairAt(text, quoteFrom, quote, (_e = stack[stack.length - 1]) === null || _e === void 0 ? void 0 : _e.close, quoteRepairCandidates, end),
2351
+ };
2352
+ }
2353
+ if (quotedQueryDelimiters.pending)
2354
+ return quotedQueryDelimiters.pending;
2355
+ var unclosed = stack[stack.length - 1];
2356
+ return unclosed ? __assign(__assign({ kind: 'unclosed' }, unclosed), { at: end }) : null;
2357
+ };
2358
+ Parser.prototype.hasPrecedingErrorEndingAt = function (position) {
2359
+ var cursor = this.tree.cursor();
2360
+ while (cursor.next()) {
2361
+ if (cursor.type.isError && cursor.from < position && cursor.to === position)
2362
+ return true;
2363
+ }
2364
+ return false;
2365
+ };
2366
+ Parser.prototype.countFutureClosersAtCurrentDepth = function (text, start, closer, transparent) {
2367
+ var pairs = { '(': ')', '[': ']', '{': '}' };
2368
+ var closingDelimiters = new Set(Object.values(pairs));
2369
+ var nestedClosers = [];
2370
+ var quote = '';
2371
+ var escaped = false;
2372
+ var inComment = false;
2373
+ var count = 0;
2374
+ for (var index = start; index < text.length; index += 1) {
2375
+ if (Date.now() >= this.deadline)
2376
+ return null;
2377
+ var char = text[index];
2378
+ if (transparent.has(index))
2379
+ continue;
2380
+ if (inComment) {
2381
+ if (char === '\n')
2382
+ inComment = false;
2383
+ continue;
2384
+ }
2385
+ if (quote) {
2386
+ if (escaped) {
2387
+ escaped = false;
2388
+ }
2389
+ else if (char === '\\' && quote.charCodeAt(0) !== 96) {
2390
+ escaped = true;
2391
+ }
2392
+ else if (char === quote) {
2393
+ quote = '';
2394
+ }
2395
+ else if (char === '\n' && quote.charCodeAt(0) !== 96) {
2396
+ quote = '';
2397
+ }
2398
+ continue;
2399
+ }
2400
+ if (char === '"' || char === "'" || char.charCodeAt(0) === 96) {
2401
+ quote = char;
2402
+ }
2403
+ else if (char === '#') {
2404
+ inComment = true;
2405
+ }
2406
+ else if (pairs[char]) {
2407
+ nestedClosers.push(pairs[char]);
2408
+ }
2409
+ else if (closingDelimiters.has(char)) {
2410
+ if (nestedClosers.length > 0) {
2411
+ nestedClosers.pop();
2412
+ }
2413
+ else if (char === closer) {
2414
+ count += 1;
2415
+ }
2416
+ }
2417
+ }
2418
+ return count;
2419
+ };
2420
+ Parser.prototype.chooseQuoteRepairAt = function (text, quoteFrom, quote, expectedCloser, closerCandidates, end) {
2421
+ var _a;
2422
+ var quotedQueryRepairAt = this.findVerifiedQuotedQueryRepairAt(text, quoteFrom, quote, expectedCloser, end);
2423
+ if (quotedQueryRepairAt !== null)
2424
+ return quotedQueryRepairAt;
2425
+ var ordinaryPositions = closerCandidates.length > 0 ? __spreadArray([], __read(new Set(closerCandidates)), false).sort(function (left, right) { return left - right; }) : [end];
2426
+ var repairs = [];
2427
+ var _loop_14 = function (index) {
2428
+ var repair = this_4.scoreQuoteRepairCandidate(ordinaryPositions[index], quote, quoteFrom);
2429
+ repairs.push(repair);
2430
+ var localEnd = ((_a = ordinaryPositions[index + 1]) !== null && _a !== void 0 ? _a : ordinaryPositions[index]) + quote.length;
2431
+ if (repair.complete && !repair.errorPositions.some(function (_a) {
2432
+ var from = _a.from, to = _a.to;
2433
+ return from <= localEnd && to >= quoteFrom;
2434
+ })) {
2435
+ return { value: repair.insertAt };
2436
+ }
2437
+ };
2438
+ var this_4 = this;
2439
+ for (var index = 0; index < ordinaryPositions.length && Date.now() < this.deadline; index += 1) {
2440
+ var state_3 = _loop_14(index);
2441
+ if (typeof state_3 === "object")
2442
+ return state_3.value;
2443
+ }
2444
+ if (repairs.length < ordinaryPositions.length)
2445
+ return undefined;
2446
+ if (!repairs.some(function (_a) {
2447
+ var complete = _a.complete;
2448
+ return complete;
2449
+ }))
2450
+ return end;
2451
+ return this.pickQuoteRepair(repairs, end);
2452
+ };
2453
+ Parser.prototype.findVerifiedQuotedQueryRepairAt = function (text, quoteFrom, quote, expectedCloser, end) {
2454
+ var _this = this;
2455
+ var candidate = expectedCloser ? this.findQuotedQueryRepairCandidate(text, quoteFrom + 1, quote, expectedCloser) : null;
2456
+ var positions = __spreadArray([], __read(new Set([candidate, end].filter(function (position) { return position !== null; }))), false);
2457
+ var repairs = positions.map(function (insertAt) { return _this.scoreQuoteRepairCandidate(insertAt, quote, quoteFrom); }).filter(function (repair) { return repair.quotedQuery; });
2458
+ return repairs.length > 0 ? this.pickQuoteRepair(repairs, end) : null;
2459
+ };
2460
+ Parser.prototype.scoreQuoteRepairCandidate = function (insertAt, quote, quoteFrom) {
2461
+ if (Date.now() >= this.deadline) {
2462
+ return { insertAt: insertAt, errors: Number.POSITIVE_INFINITY, errorPositions: [], quotedQuery: false, complete: false };
2463
+ }
2464
+ var state = this.state.update({ changes: { from: insertAt, insert: quote }, filter: false }).state;
2465
+ var tree = this.getCompleteTree(state);
2466
+ if (!tree) {
2467
+ return { insertAt: insertAt, errors: Number.POSITIVE_INFINITY, errorPositions: [], quotedQuery: false, complete: false };
2468
+ }
2469
+ var cursor = tree.cursor();
2470
+ var errors = 0;
2471
+ var errorPositions = [];
2472
+ var quotedQuery = false;
2473
+ while (cursor.next()) {
2474
+ if (cursor.type.isError) {
2475
+ errors += 1;
2476
+ errorPositions.push({ from: cursor.from, to: cursor.to });
2477
+ }
2478
+ if (cursor.name !== 'OuterArgItem')
2479
+ continue;
2480
+ var quoted = [];
2481
+ var child = cursor.node.firstChild;
2482
+ while (child) {
2483
+ if (child.name === 'Queted')
2484
+ quoted.push(child);
2485
+ child = child.nextSibling;
2486
+ }
2487
+ if (quoted.length >= 2 && quoted[0].from === quoteFrom && quoted.some(function (node) { return node.from === insertAt; })) {
2488
+ quotedQuery = true;
2489
+ }
2490
+ }
2491
+ return { insertAt: insertAt, errors: errors, errorPositions: errorPositions, quotedQuery: quotedQuery, complete: true };
2492
+ };
2493
+ Parser.prototype.pickQuoteRepair = function (candidates, end) {
2494
+ return candidates.sort(function (left, right) {
2495
+ if (left.errors !== right.errors)
2496
+ return left.errors - right.errors;
2497
+ var leftAtEnd = left.insertAt === end;
2498
+ var rightAtEnd = right.insertAt === end;
2499
+ if (leftAtEnd !== rightAtEnd)
2500
+ return leftAtEnd ? 1 : -1;
2501
+ return right.insertAt - left.insertAt;
2502
+ })[0].insertAt;
2503
+ };
2504
+ Parser.prototype.findQuotedQueryRepairCandidate = function (text, start, outerQuote, expectedCloser) {
2505
+ var pairs = { '(': ')', '[': ']', '{': '}' };
2506
+ var closingDelimiters = new Set(Object.values(pairs));
2507
+ var stack = [];
2508
+ var quote = '';
2509
+ var escaped = false;
2510
+ var outerEscaped = false;
2511
+ var inComment = false;
2512
+ for (var index = start; index < text.length; index += 1) {
2513
+ var char = text[index];
2514
+ if (inComment) {
2515
+ if (char === '\n')
2516
+ inComment = false;
2517
+ continue;
2518
+ }
2519
+ if (quote) {
2520
+ if (escaped) {
2521
+ escaped = false;
2522
+ }
2523
+ else if (char === '\\' && quote.charCodeAt(0) !== 96) {
2524
+ escaped = true;
2525
+ }
2526
+ else if (char === quote) {
2527
+ quote = '';
2528
+ }
2529
+ continue;
2530
+ }
2531
+ if (outerEscaped) {
2532
+ outerEscaped = false;
2533
+ continue;
2534
+ }
2535
+ if (char === '\\' && outerQuote.charCodeAt(0) !== 96) {
2536
+ outerEscaped = true;
2537
+ continue;
2538
+ }
2539
+ if (char === '"' || char === "'" || char.charCodeAt(0) === 96) {
2540
+ quote = char;
2541
+ continue;
2542
+ }
2543
+ if (char === '#') {
2544
+ inComment = true;
2545
+ continue;
2546
+ }
2547
+ if (pairs[char]) {
2548
+ stack.push(pairs[char]);
2549
+ continue;
2550
+ }
2551
+ if (!closingDelimiters.has(char))
2552
+ continue;
2553
+ if (stack[stack.length - 1] === char) {
2554
+ stack.pop();
2555
+ }
2556
+ else if (stack.length === 0 && char === expectedCloser) {
2557
+ return index;
2558
+ }
2559
+ }
2560
+ return null;
2561
+ };
2562
+ Parser.prototype.chooseMismatchRecovery = function (from, to, expectedCloser) {
2563
+ var replacement = this.state.update({ changes: { from: from, to: to, insert: expectedCloser }, filter: false }).state;
2564
+ var deletion = this.state.update({ changes: { from: from, to: to, insert: '' }, filter: false }).state;
2565
+ var replacementBalanceCost = this.delimiterBalanceCost(replacement.doc.toString());
2566
+ var deletionBalanceCost = this.delimiterBalanceCost(deletion.doc.toString());
2567
+ return deletionBalanceCost < replacementBalanceCost ? 'delete' : 'replace';
2568
+ };
2569
+ Parser.prototype.delimiterBalanceCost = function (text) {
2570
+ var pairs = { '(': ')', '[': ']', '{': '}' };
2571
+ var closingDelimiters = new Set(Object.values(pairs));
2572
+ var stack = [];
2573
+ var quote = '';
2574
+ var escaped = false;
2575
+ var inComment = false;
2576
+ var errors = 0;
2577
+ for (var index = 0; index < text.length; index += 1) {
2578
+ if (Date.now() >= this.deadline)
2579
+ return Number.POSITIVE_INFINITY;
2580
+ var char = text[index];
2581
+ if (inComment) {
2582
+ if (char === '\n')
2583
+ inComment = false;
2584
+ continue;
2585
+ }
2586
+ if (quote) {
2587
+ if (escaped) {
2588
+ escaped = false;
2589
+ }
2590
+ else if (char === '\\' && quote.charCodeAt(0) !== 96) {
2591
+ escaped = true;
2592
+ }
2593
+ else if (char === quote) {
2594
+ quote = '';
2595
+ }
2596
+ else if (char === '\n' && quote.charCodeAt(0) !== 96) {
2597
+ quote = '';
2598
+ }
2599
+ continue;
2600
+ }
2601
+ if (char === '"' || char === "'" || char.charCodeAt(0) === 96) {
2602
+ quote = char;
2603
+ }
2604
+ else if (char === '#') {
2605
+ inComment = true;
2606
+ }
2607
+ else if (pairs[char]) {
2608
+ stack.push(pairs[char]);
2609
+ }
2610
+ else if (closingDelimiters.has(char)) {
2611
+ if (stack[stack.length - 1] === char) {
2612
+ stack.pop();
2613
+ }
2614
+ else {
2615
+ errors += 1;
2616
+ if (stack.length > 0)
2617
+ stack.pop();
2618
+ }
2619
+ }
2620
+ }
2621
+ return errors + stack.length + (quote ? 1 : 0);
2622
+ };
2623
+ Parser.prototype.findStringNewlineRecovery = function (text, start, quote) {
2624
+ var escaped = false;
2625
+ var lineBreaks = [];
2626
+ for (var index = start; index < text.length; index += 1) {
2627
+ var char = text[index];
2628
+ if (escaped) {
2629
+ escaped = false;
2630
+ }
2631
+ else if (char === '\\') {
2632
+ escaped = true;
2633
+ }
2634
+ else if (char === quote) {
2635
+ return { end: index + 1, lineBreaks: lineBreaks };
2636
+ }
2637
+ else if (char === '\n') {
2638
+ lineBreaks.push(index);
2639
+ }
2640
+ }
2641
+ return null;
2642
+ };
2643
+ Parser.prototype.checkAST = function (node) {
2644
+ if (!node || Date.now() >= this.deadline)
2645
+ return;
2646
+ if (!node.type.isError && !this.containsError(node)) {
2647
+ switch (node.name) {
2648
+ case 'Query':
2649
+ this.checkDuplicateQueryClauses(node);
2650
+ break;
2651
+ case 'ShowExpr':
2652
+ this.checkDuplicateShowClauses(node);
2653
+ this.checkShowFunctionRequirements(node);
2654
+ break;
2655
+ case 'TimeRange':
2656
+ this.checkTimeRangeShape(node);
2657
+ break;
2658
+ case 'RollupIdentifier':
2659
+ this.checkBareRollup(node);
2660
+ break;
2661
+ case 'RollupFunctionCall':
2662
+ this.checkRollupFunctionCall(node);
2663
+ break;
2664
+ case 'FunctionCall':
2665
+ this.checkFunctionCall(node);
2666
+ break;
2667
+ case 'OuterFunctionCall':
2668
+ this.checkOuterFunctionCall(node);
2669
+ break;
2670
+ case 'TargetClause':
2671
+ this.checkProjectionAlias(node);
2672
+ break;
2673
+ case 'LimitClause':
2674
+ case 'OffsetClause':
2675
+ case 'SLimitClause':
2676
+ case 'SOffsetClause':
2677
+ this.checkIntegerClause(node);
2678
+ break;
2679
+ case 'FilterSubExpr':
2680
+ this.checkFilterSubqueryOperator(node);
2681
+ break;
2682
+ case 'FieldName':
2683
+ this.checkFieldName(node);
2684
+ break;
2685
+ case 'CaseFunctionIdentifier':
2686
+ this.checkCaseFunction(node);
2687
+ break;
2688
+ case 'CaseExpr':
2689
+ this.checkCaseResults(node);
2690
+ break;
2691
+ }
2692
+ }
2693
+ var child = node.firstChild;
2694
+ while (child) {
2695
+ this.checkAST(child);
2696
+ child = child.nextSibling;
2697
+ }
2698
+ };
2699
+ Parser.prototype.checkDuplicateQueryClauses = function (query) {
2700
+ var seen = new Set();
2701
+ var child = query.firstChild;
2702
+ while (child) {
2703
+ if (child.name === 'QueryClause') {
2704
+ var clause = child.firstChild;
2705
+ if (clause) {
2706
+ var label = queryClauseLabels.get(clause.name);
2707
+ if (label) {
2708
+ if (seen.has(clause.name)) {
2709
+ this.pushSemanticDiagnostic(clause, "duplicate \"".concat(label, "\" clause"), "duplicate:".concat(query.from, ":").concat(clause.name));
2710
+ }
2711
+ else {
2712
+ seen.add(clause.name);
2713
+ }
2714
+ }
2715
+ }
2716
+ }
2717
+ child = child.nextSibling;
2718
+ }
2719
+ };
2720
+ Parser.prototype.checkDuplicateShowClauses = function (show) {
2721
+ var seen = new Set();
2722
+ var child = show.firstChild;
2723
+ while (child) {
2724
+ var label = queryClauseLabels.get(child.name);
2725
+ if (label) {
2726
+ if (seen.has(child.name)) {
2727
+ this.pushSemanticDiagnostic(child, "duplicate \"".concat(label, "\" clause"), "duplicate:".concat(show.from, ":").concat(child.name));
2728
+ }
2729
+ else {
2730
+ seen.add(child.name);
2731
+ }
2732
+ }
2733
+ child = child.nextSibling;
2734
+ }
2735
+ };
2736
+ Parser.prototype.checkIntegerClause = function (clause) {
2737
+ var number = clause.getChild('Number');
2738
+ if (!number)
2739
+ return;
2740
+ var value = this.numericValue(number);
2741
+ if (value !== null && Number.isInteger(value) && value >= 0)
2742
+ return;
2743
+ var keyword = numericClauses.get(clause.name);
2744
+ if (keyword)
2745
+ this.pushSemanticDiagnostic(number, "integer expected after \"".concat(keyword, "\""), "integer:".concat(clause.from));
2746
+ };
2747
+ Parser.prototype.checkTimeRangeShape = function (range) {
2748
+ var _a;
2749
+ var raw = this.maskLineComments(this.nodeText(range));
2750
+ var segments = this.splitTopLevelSegments(raw, ':');
2751
+ var expressions = [];
2752
+ var child = range.firstChild;
2753
+ while (child) {
2754
+ if (child.name === 'TimeExpr')
2755
+ expressions.push(child);
2756
+ child = child.nextSibling;
2757
+ }
2758
+ if (segments.length > 4) {
2759
+ this.pushSemanticDiagnostic(range, 'time range accepts at most four colon-separated values', "time-shape:".concat(range.from));
2760
+ return;
2761
+ }
2762
+ if (segments.every(function (segment) { return raw.slice(segment.from, segment.to).trim().length === 0; })) {
2763
+ this.pushSemanticDiagnostic(range, 'time range must contain at least one value', "time-shape:".concat(range.from));
2764
+ return;
2765
+ }
2766
+ var _loop_15 = function (index) {
2767
+ var segment = segments[index];
2768
+ var absoluteFrom = range.from + segment.from;
2769
+ var absoluteTo = range.from + segment.to;
2770
+ var segmentExpressions = expressions.filter(function (expression) { return expression.from >= absoluteFrom && expression.to <= absoluteTo; });
2771
+ var expressionCount = segmentExpressions.length;
2772
+ var hasText = raw.slice(segment.from, segment.to).trim().length > 0;
2773
+ if ((hasText && expressionCount !== 1) || (!hasText && expressionCount !== 0)) {
2774
+ this_5.pushSemanticDiagnosticAt(absoluteFrom, absoluteTo, 'invalid value in time range', "time-shape:".concat(range.from));
2775
+ return { value: void 0 };
2776
+ }
2777
+ if (segments.length > 1 && expressionCount === 1) {
2778
+ var kind = (_a = segmentExpressions[0].firstChild) === null || _a === void 0 ? void 0 : _a.name;
2779
+ if (index < 2 && kind !== 'Number' && kind !== 'Duration' && kind !== 'PresetExpr') {
2780
+ this_5.pushSemanticDiagnostic(segmentExpressions[0], 'time range boundary must be a timestamp, duration, or preset', "time-shape:".concat(range.from));
2781
+ return { value: void 0 };
2782
+ }
2783
+ if (index === 2 && kind !== 'Number' && kind !== 'Duration') {
2784
+ this_5.pushSemanticDiagnostic(segmentExpressions[0], 'time range interval must be a number or duration', "time-shape:".concat(range.from));
2785
+ return { value: void 0 };
2786
+ }
2787
+ if (index === 3 && kind !== 'RollupIdentifier' && kind !== 'RollupFunctionCall') {
2788
+ this_5.pushSemanticDiagnostic(segmentExpressions[0], 'time range rollup must be a supported rollup function', "time-shape:".concat(range.from));
2789
+ return { value: void 0 };
2790
+ }
2791
+ }
2792
+ };
2793
+ var this_5 = this;
2794
+ for (var index = 0; index < segments.length; index += 1) {
2795
+ var state_4 = _loop_15(index);
2796
+ if (typeof state_4 === "object")
2797
+ return state_4.value;
2798
+ }
2799
+ };
2800
+ Parser.prototype.checkBareRollup = function (identifier) {
2801
+ var _a;
2802
+ if (((_a = identifier.parent) === null || _a === void 0 ? void 0 : _a.name) === 'RollupFunctionCall')
2803
+ return;
2804
+ var name = this.nodeText(identifier).toLowerCase();
2805
+ if (name === 'ewma' || name === 'moving_average' || name === 'percentile') {
2806
+ this.pushSemanticDiagnostic(identifier, "rollup function \"".concat(name, "\" requires arguments"), "rollup:".concat(identifier.from));
2807
+ }
2808
+ else if (name === 'corr') {
2809
+ this.pushSemanticDiagnostic(identifier, 'rollup function "corr" requires multiple input fields and is only valid in the select clause', "rollup:".concat(identifier.from));
2810
+ }
2811
+ };
2812
+ Parser.prototype.checkRollupFunctionCall = function (call) {
2813
+ var identifier = call.getChild('RollupIdentifier');
2814
+ var body = call.getChild('RollupFunctionCallBody');
2815
+ if (!identifier || !body)
2816
+ return;
2817
+ var name = this.nodeText(identifier).toLowerCase();
2818
+ var args = this.directChildren(body, 'RollupArg');
2819
+ if (name === 'corr') {
2820
+ this.pushSemanticDiagnostic(identifier, 'rollup function "corr" requires multiple input fields and is only valid in the select clause', "rollup:".concat(identifier.from));
2821
+ return;
2822
+ }
2823
+ if (name !== 'ewma' && name !== 'moving_average' && name !== 'percentile') {
2824
+ this.pushSemanticDiagnostic(body, "rollup function \"".concat(name, "\" does not accept arguments in the time range"), "rollup:".concat(call.from));
2825
+ return;
2826
+ }
2827
+ var firstValue = args.length === 1 ? this.numericValue(args[0]) : null;
2828
+ if (name === 'ewma' && (firstValue === null || firstValue <= 0 || firstValue > 1)) {
2829
+ this.pushSemanticDiagnostic(body, 'rollup function "ewma" expects one numeric alpha argument in range (0, 1]', "rollup:".concat(call.from));
2830
+ }
2831
+ if (name === 'moving_average' && (firstValue === null || !Number.isInteger(firstValue) || firstValue < 1)) {
2832
+ this.pushSemanticDiagnostic(body, 'rollup function "moving_average" expects one positive integer argument', "rollup:".concat(call.from));
2833
+ }
2834
+ if (name === 'percentile') {
2835
+ if (firstValue === null || firstValue < 0 || firstValue > 100) {
2836
+ this.pushSemanticDiagnostic(body, 'rollup function "percentile" expects one numeric argument between 0 and 100', "rollup:".concat(call.from));
2837
+ }
2838
+ }
2839
+ };
2840
+ Parser.prototype.checkFunctionCall = function (call) {
2841
+ var identifier = call.getChild('FunctionIdentifier');
2842
+ var body = call.getChild('FunctionCallBody');
2843
+ if (!identifier || !body)
2844
+ return;
2845
+ var name = this.nodeText(identifier).toLowerCase();
2846
+ var args = this.directChildren(body, 'ArgItem');
2847
+ if (name === 'ewma') {
2848
+ var alpha = args.length === 2 ? this.numericValue(args[1]) : null;
2849
+ if (alpha === null || alpha <= 0 || alpha > 1) {
2850
+ this.pushSemanticDiagnostic(body, 'function "ewma" expects a field and an alpha argument in range (0, 1]', "function:".concat(call.from));
2851
+ }
2852
+ }
2853
+ else if (name === 'moving_average') {
2854
+ var window_1 = args.length === 2 ? this.numericValue(args[1]) : null;
2855
+ if (window_1 === null || !Number.isInteger(window_1) || window_1 < 1) {
2856
+ this.pushSemanticDiagnostic(body, 'function "moving_average" expects a field and a positive integer window', "function:".concat(call.from));
2857
+ }
2858
+ }
2859
+ else if (name === 'percentile') {
2860
+ var percentile = args.length === 2 ? this.numericValue(args[1]) : null;
2861
+ if (percentile === null || percentile < 0 || percentile > 100) {
2862
+ this.pushSemanticDiagnostic(body, 'function "percentile" expects a field and a numeric percentile between 0 and 100', "function:".concat(call.from));
2863
+ }
2864
+ }
2865
+ else if (name === 'corr' && args.length !== 2) {
2866
+ this.pushSemanticDiagnostic(body, 'function "corr" expects exactly two input fields', "function:".concat(call.from));
2867
+ }
2868
+ else if ((name === 'slope' || name === 'zscore' || name === 'mad_score' || name === 'change_score') && args.length !== 1) {
2869
+ this.pushSemanticDiagnostic(body, "function \"".concat(name, "\" expects exactly one input field"), "function:".concat(call.from));
2870
+ }
2871
+ else if (/^p(?:50|75|90|95|99)$/.test(name) && args.length !== 1) {
2872
+ this.pushSemanticDiagnostic(body, "function \"".concat(name, "\" expects exactly one input field"), "function:".concat(call.from));
2873
+ }
2874
+ };
2875
+ Parser.prototype.checkOuterFunctionCall = function (call) {
2876
+ var identifier = call.firstChild;
2877
+ if (!identifier || identifier.name === 'FunctionIdentifier')
2878
+ return;
2879
+ var name = this.nodeText(identifier).toLowerCase();
2880
+ var body = identifier.nextSibling;
2881
+ if (!body)
2882
+ return;
2883
+ var numbers = this.directChildren(body, 'Number');
2884
+ var argument = numbers.length > 0 ? this.numericValue(numbers[numbers.length - 1]) : null;
2885
+ if (name === 'moving_average' || name === 'top' || name === 'bottom') {
2886
+ if (argument === null || !Number.isInteger(argument) || argument < 1) {
2887
+ this.pushSemanticDiagnostic(identifier, "outer function \"".concat(name, "\" expects a positive integer argument"), "outer-function:".concat(call.from));
2888
+ }
2889
+ }
2890
+ else if (name === 'round' && argument !== null && (!Number.isInteger(argument) || argument < 0)) {
2891
+ this.pushSemanticDiagnostic(identifier, 'outer function "round" expects a non-negative integer digits argument', "outer-function:".concat(call.from));
2892
+ }
2893
+ else if (name === 'dbscan' && argument !== null && (argument <= 0 || argument > 3)) {
2894
+ this.pushSemanticDiagnostic(identifier, 'outer function "dbscan" expects eps in range (0, 3]', "outer-function:".concat(call.from));
2895
+ }
2896
+ else if (name === 'forecast' && argument !== null && (!Number.isInteger(argument) || argument < 1)) {
2897
+ this.pushSemanticDiagnostic(identifier, 'outer function "forecast" expects a positive integer steps argument', "outer-function:".concat(call.from));
2898
+ }
2899
+ else if (name === 'fill') {
2900
+ var mode = this.directChildren(body, 'Identifier')[0];
2901
+ if (mode && !/^(linear|previous)$/i.test(this.nodeText(mode))) {
2902
+ this.pushSemanticDiagnostic(mode, 'outer function "fill" mode must be "LINEAR" or "PREVIOUS"', "outer-function:".concat(call.from));
2903
+ }
2904
+ }
2905
+ };
2906
+ Parser.prototype.checkProjectionAlias = function (target) {
2907
+ var _a;
2908
+ var outerAlias = target.getChild('As');
2909
+ var projection = target.getChild('Projection');
2910
+ if (!outerAlias || !projection)
2911
+ return;
2912
+ var items = this.directChildren(projection, 'ProjectionItem');
2913
+ if (items.length !== 1) {
2914
+ this.pushSemanticDiagnostic(outerAlias, 'an alias after ")" requires exactly one projection item', "projection-alias:".concat(target.from));
2915
+ return;
2916
+ }
2917
+ if ((_a = items[0].getChild('ProjectionField')) === null || _a === void 0 ? void 0 : _a.getChild('As')) {
2918
+ this.pushSemanticDiagnostic(outerAlias, 'projection expression cannot have both inner and outer aliases', "projection-alias:".concat(target.from));
2919
+ }
2920
+ };
2921
+ Parser.prototype.checkFilterSubqueryOperator = function (subquery) {
2922
+ var binary = this.findAncestor(subquery.parent, 'BinaryExpr');
2923
+ if (!binary) {
2924
+ this.pushSemanticDiagnostic(subquery, 'filter subquery requires "IN" or "NOT IN"', "filter-subquery:".concat(subquery.from));
2925
+ return;
2926
+ }
2927
+ var operators = new Set([
2928
+ 'Pow',
2929
+ 'Mul',
2930
+ 'Div',
2931
+ 'Mod',
2932
+ 'Add',
2933
+ 'Sub',
2934
+ 'Eql',
2935
+ 'EqlSingle',
2936
+ 'Neq',
2937
+ 'Lte',
2938
+ 'Lss',
2939
+ 'Gte',
2940
+ 'Gtr',
2941
+ 'EqlRegex',
2942
+ 'NeqRegex',
2943
+ 'In',
2944
+ 'NotInSeq',
2945
+ 'And',
2946
+ 'Or',
2947
+ 'DAnd',
2948
+ 'DOr',
2949
+ ]);
2950
+ var operator = null;
2951
+ var child = binary.firstChild;
2952
+ while (child) {
2953
+ if (operators.has(child.name)) {
2954
+ operator = child;
2955
+ break;
2956
+ }
2957
+ child = child.nextSibling;
2958
+ }
2959
+ if (!operator || (operator.name !== 'In' && operator.name !== 'NotInSeq') || subquery.from < operator.to) {
2960
+ this.pushSemanticDiagnostic(operator !== null && operator !== void 0 ? operator : subquery, 'filter subquery requires "IN" or "NOT IN"', "filter-subquery:".concat(subquery.from));
2961
+ }
2962
+ };
2963
+ Parser.prototype.checkFieldName = function (field) {
2964
+ if (field.getChild('JsonField'))
2965
+ return;
2966
+ var text = this.nodeText(field);
2967
+ if (!text || text.startsWith('`') || text.startsWith('"') || text.startsWith("'"))
2968
+ return;
2969
+ if (text.includes('-')) {
2970
+ this.pushSemanticDiagnostic(field, 'field names containing "-" must be enclosed in backticks', "field-name:".concat(field.from));
2971
+ }
2972
+ };
2973
+ Parser.prototype.checkCaseFunction = function (identifier) {
2974
+ if (this.nodeText(identifier).toLowerCase() === 'substr') {
2975
+ this.pushSemanticDiagnostic(identifier, 'function "substr" is not supported inside CASE', "case-function:".concat(identifier.from));
2976
+ }
2977
+ };
2978
+ Parser.prototype.checkCaseResults = function (caseExpr) {
2979
+ var clause = caseExpr.firstChild;
2980
+ while (clause) {
2981
+ if (clause.name === 'CaseWhenClause' || clause.name === 'CaseElseClause') {
2982
+ var values = this.directChildren(clause, 'CaseValue');
2983
+ var result = values[values.length - 1];
2984
+ if (result && this.nodeText(result).trim().toLowerCase() === 'end') {
2985
+ var message = clause.name === 'CaseWhenClause' ? 'CASE result expected after "THEN"' : 'CASE result expected after "ELSE"';
2986
+ this.pushSemanticDiagnostic(result, message, "case-result:".concat(result.from));
2987
+ }
2988
+ }
2989
+ clause = clause.nextSibling;
2990
+ }
2991
+ };
2992
+ Parser.prototype.checkShowFunctionRequirements = function (show) {
2993
+ var identifier = show.getChild('ShowIdentifier');
2994
+ var body = show.getChild('FunctionCallBody');
2995
+ if (!identifier || !body)
2996
+ return;
2997
+ var name = this.nodeText(identifier).toLowerCase();
2998
+ var bodyText = this.maskStringsAndLineComments(this.nodeText(body));
2999
+ var hasKeyin = /\bkeyin\s*=/.test(bodyText.toLowerCase());
3000
+ var hasFrom = /\bfrom\s*=/.test(bodyText.toLowerCase());
3001
+ var filter = show.getChild('FilterClause');
3002
+ var hasSourceFilter = Boolean(filter && /@__source__/.test(this.maskStringsAndLineComments(this.nodeText(filter))));
3003
+ if ((name === 'show_tag_value' || name === 'show_tag_value_cardinality' || name === 'show_series_count_by_tag_value') && !hasKeyin) {
3004
+ this.pushSemanticDiagnostic(identifier, "\"".concat(name, "\" requires the named argument \"keyin\""), "show:".concat(show.from, ":keyin"));
3005
+ }
3006
+ if (name.startsWith('show_series_count_by_') && !hasFrom && !hasSourceFilter) {
3007
+ this.pushSemanticDiagnostic(identifier, "\"".concat(name, "\" requires \"from\" or an @__source__ filter"), "show:".concat(show.from, ":from"));
3008
+ }
3009
+ };
3010
+ Parser.prototype.pushSemanticDiagnostic = function (node, message, group) {
3011
+ this.pushSemanticDiagnosticAt(node.from, node.to, message, group);
3012
+ };
3013
+ Parser.prototype.pushSemanticDiagnosticAt = function (from, to, message, group) {
3014
+ var _this = this;
3015
+ var diagnostic = this.makeDiagnosticAt(from, Math.max(from + 1, to), message, group);
3016
+ if (!this.diagnostics.some(function (existing) { return _this.isSameDiagnostic(existing, diagnostic); }))
3017
+ this.appendDiagnostics([diagnostic]);
3018
+ };
3019
+ Parser.prototype.directChildren = function (node, name) {
3020
+ var children = [];
3021
+ var child = node.firstChild;
3022
+ while (child) {
3023
+ if (child.name === name)
3024
+ children.push(child);
3025
+ child = child.nextSibling;
3026
+ }
3027
+ return children;
3028
+ };
3029
+ Parser.prototype.numericValue = function (node) {
3030
+ if (!node)
3031
+ return null;
3032
+ var number = node.name === 'Number' ? node : node.getChild('Number');
3033
+ if (!number)
3034
+ return null;
3035
+ var sign = node.name !== 'Number' && node.getChild('Sub') ? -1 : 1;
3036
+ var value = sign * Number(this.nodeText(number).replace(/_/g, ''));
3037
+ return Number.isFinite(value) ? value : null;
3038
+ };
3039
+ Parser.prototype.splitTopLevelSegments = function (text, separator) {
3040
+ var segments = [];
3041
+ var from = 0;
3042
+ var quote = '';
3043
+ var escaped = false;
3044
+ var depth = 0;
3045
+ for (var index = 0; index < text.length; index += 1) {
3046
+ var char = text[index];
3047
+ if (quote) {
3048
+ if (escaped)
3049
+ escaped = false;
3050
+ else if (char === '\\' && quote !== '`')
3051
+ escaped = true;
3052
+ else if (char === quote)
3053
+ quote = '';
3054
+ continue;
3055
+ }
3056
+ if (char === '"' || char === "'" || char === '`') {
3057
+ quote = char;
3058
+ }
3059
+ else if (char === '(') {
3060
+ depth += 1;
3061
+ }
3062
+ else if (char === ')') {
3063
+ depth = Math.max(0, depth - 1);
3064
+ }
3065
+ else if (char === separator && depth === 0) {
3066
+ segments.push({ from: from, to: index });
3067
+ from = index + 1;
3068
+ }
3069
+ }
3070
+ segments.push({ from: from, to: text.length });
3071
+ return segments;
3072
+ };
3073
+ Parser.prototype.describeUnknownFunction = function (node) {
3074
+ var contextNames = new Set(['ProjectionField', 'FilterClause', 'HavingClause', 'ByExpr']);
3075
+ var context = node.parent;
3076
+ while (context && !contextNames.has(context.name))
3077
+ context = context.parent;
3078
+ if (!context)
3079
+ return null;
3080
+ var text = this.maskStringsAndLineComments(this.nodeText(context));
3081
+ var functionPattern = /\b([A-Za-z_][A-Za-z0-9_-]*)\s*\(/g;
3082
+ var match = functionPattern.exec(text);
3083
+ while (match) {
3084
+ var name_1 = match[1];
3085
+ var nameFrom = context.from + match.index;
3086
+ if (!this.containsFunctionCallStartingAt(context, nameFrom)) {
3087
+ return this.makeDiagnosticAt(nameFrom, nameFrom + name_1.length, "unknown function \"".concat(name_1, "\""), "unknown-function:".concat(context.from, ":").concat(nameFrom));
3088
+ }
3089
+ match = functionPattern.exec(text);
3090
+ }
3091
+ return null;
3092
+ };
3093
+ Parser.prototype.containsFunctionCallStartingAt = function (node, from) {
3094
+ if ((node.name === 'FunctionCall' || node.name === 'CaseFunctionCall' || node.name === 'FieldCall') && node.from === from)
3095
+ return true;
3096
+ var child = node.firstChild;
3097
+ while (child) {
3098
+ if (child.from <= from && child.to >= from && this.containsFunctionCallStartingAt(child, from))
3099
+ return true;
3100
+ child = child.nextSibling;
3101
+ }
3102
+ return false;
47
3103
  };
48
3104
  return Parser;
49
3105
  }());