forked from elastic/esql-js
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcst_to_ast_converter.ts
More file actions
3869 lines (3095 loc) · 114 KB
/
cst_to_ast_converter.ts
File metadata and controls
3869 lines (3095 loc) · 114 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License
* 2.0; you may not use this file except in compliance with the Elastic License
* 2.0.
*/
import type * as antlr from 'antlr4';
import * as cst from '../antlr/esql_parser';
import type * as ast from '../../types';
import { isCommand, isStringLiteral } from '../../ast/is';
import { LeafPrinter } from '../../pretty_print';
import { getPosition } from './tokens';
import { nonNullable, unescapeColumn } from './helpers';
import { firstItem, lastItem, resolveItem, singleItems } from '../../ast/visitor/utils';
import { type AstNodeParserFields, Builder } from '../../ast/builder';
import { type ArithmeticUnaryContext } from '../antlr/esql_parser';
import { PromQLParser } from '../../embedded_languages/promql/parser/parser';
import type { AstNodeTemplate } from '../../ast/builder';
import type { Parser } from './parser';
import type { PromQLAstQueryExpression } from '../../embedded_languages/promql/types';
const textExistsAndIsValid = (text: string | undefined): text is string =>
!!(text && !/<missing /.test(text));
type ESQLAstMatchBooleanExpression = ast.ESQLColumn | ast.ESQLBinaryExpression | ast.ESQLInlineCast;
/**
* Transforms an ANTLR ES|QL Concrete Syntax Tree (CST) into a
* Kibana Abstract Syntax Tree (AST).
*
* Most of the methods in this class are 1-to-1 mapping from CST-to-AST,
* they are designed to convert specific CST nodes into their
* corresponding AST nodes.
*/
export class CstToAstConverter {
constructor(protected readonly parser: Parser) {}
// -------------------------------------------------------------------- utils
private getParserFields(ctx: antlr.ParserRuleContext): AstNodeParserFields {
return {
text: ctx.getText(),
location: getPosition(ctx.start, ctx.stop),
incomplete: Boolean(ctx.exception),
};
}
private createParserFieldsFromToken(
token: antlr.Token,
text: string = token.text
): AstNodeParserFields {
const fields: AstNodeParserFields = {
text,
location: getPosition(token, token),
incomplete: false,
};
return fields;
}
private createParserFieldsFromTerminalNode(node: antlr.TerminalNode): AstNodeParserFields {
const text = node.getText();
const symbol = node.symbol;
const fields: AstNodeParserFields = {
text,
location: getPosition(symbol, symbol),
incomplete: false,
};
return fields;
}
private toIdentifierFromTerminalNode(node: antlr.TerminalNode): ast.ESQLIdentifier {
return this.toIdentifierFromToken(node.symbol);
}
private toIdentifierFromToken(token: antlr.Token): ast.ESQLIdentifier {
const name = token.text;
return Builder.identifier({ name }, this.createParserFieldsFromToken(token));
}
private fromParserRuleToUnknown(ctx: antlr.ParserRuleContext): ast.ESQLUnknownItem {
const location = getPosition(ctx.start, ctx.stop);
const max = Math.min(location.max, this.parser.src.length - 1);
return {
type: 'unknown',
name: 'unknown',
text: this.parser.src.slice(location.min, max + 1),
location: { min: location.min, max },
incomplete: Boolean(ctx.exception),
};
}
/**
* Extends `fn.location` to cover all its arguments.
*
* @deprecated This should never have been necessary. Function location should be
* accurately set during parsing or initial AST construction.
*/
private extendLocationToArgs(fn: ast.ESQLFunction) {
const location = fn.location;
if (fn.args) {
// get min location navigating in depth keeping the left/first arg
location.min = this.walkFunctionStructure(fn.args, location, 'min', () => 0);
// get max location navigating in depth keeping the right/last arg
location.max = this.walkFunctionStructure(
fn.args,
location,
'max',
(args) => args.length - 1
);
// in case of empty array as last arg, bump the max location by 3 chars (empty brackets)
if (
Array.isArray(fn.args[fn.args.length - 1]) &&
!(fn.args[fn.args.length - 1] as ast.ESQLAstItem[]).length
) {
location.max += 3;
}
}
return location;
}
/**
* @deprecated Do not use. This method will be removed once
* `extendLocationToArgs` is removed.
*/
private walkFunctionStructure(
args: ast.ESQLAstItem[],
initialLocation: ast.ESQLLocation,
prop: 'min' | 'max',
getNextItemIndex: (arg: ast.ESQLAstItem[]) => number
) {
let nextArg: ast.ESQLAstItem | undefined = args[getNextItemIndex(args)];
const location = { ...initialLocation };
while (Array.isArray(nextArg) || nextArg) {
if (Array.isArray(nextArg)) {
nextArg = nextArg[getNextItemIndex(nextArg)];
} else {
location[prop] = Math[prop](location[prop], nextArg.location[prop]);
if (nextArg.type === 'function') {
nextArg = nextArg.args[getNextItemIndex(nextArg.args)];
} else {
nextArg = undefined;
}
}
}
return location[prop];
}
// -------------------------------------------------------------------- query
fromStatements(ctx: cst.StatementsContext): ast.ESQLAstQueryExpression | undefined {
const setCommandCtxs = ctx.setCommand_list();
const singleStatement = ctx.singleStatement();
let header: ast.ESQLAstSetHeaderCommand[] | undefined;
// Process SET instructions and create header if they exist
if (setCommandCtxs && setCommandCtxs.length > 0) {
header = this.fromSetCommands(setCommandCtxs);
}
// Get the main query from singleStatement
const query = this.fromSingleStatement(singleStatement);
if (!query) {
const emptyQuery = Builder.expression.query([], this.getParserFields(ctx), header);
emptyQuery.incomplete = true;
return emptyQuery;
}
query.header = header;
return query;
}
fromSingleStatement(ctx: cst.SingleStatementContext): ast.ESQLAstQueryExpression | undefined {
if (!ctx) return undefined;
return this.fromAnyQuery(ctx.query());
}
private fromAnyQuery(ctx: cst.QueryContext): ast.ESQLAstQueryExpression | undefined {
if (ctx instanceof cst.CompositeQueryContext) {
return this.fromCompositeQuery(ctx);
} else {
if (ctx instanceof cst.QueryContext) {
return this.fromQuery(ctx);
} else {
return undefined;
}
}
}
private fromCompositeQuery(
ctx: cst.CompositeQueryContext
): ast.ESQLAstQueryExpression | undefined {
const query = this.fromAnyQuery(ctx.query());
if (!query) {
return;
}
const processingCommandCtx = ctx.processingCommand();
const processingCommand = this.fromProcessingCommand(processingCommandCtx);
if (processingCommand) {
query.commands.push(processingCommand);
}
return query;
}
private fromSingleCommandQuery(ctx: cst.SingleCommandQueryContext): ast.ESQLCommand | undefined {
return this.fromSourceCommand(ctx.sourceCommand());
}
private fromQuery(ctx: cst.QueryContext): ast.ESQLAstQueryExpression | undefined {
const children = ctx.children;
if (!children) {
return;
}
const length = children.length;
if (!length) {
return;
}
const commands: ast.ESQLAstQueryExpression['commands'] = [];
for (let i = 0; i < length; i++) {
const childCtx = children[i];
const child = this.fromAny(childCtx);
if (isCommand(child)) {
commands.push(child);
}
}
return Builder.expression.query(commands, this.getParserFields(ctx));
}
private fromAny(ctx: antlr.ParseTree): ast.ESQLProperNode | undefined {
if (ctx instanceof cst.SingleCommandQueryContext) {
return this.fromSingleCommandQuery(ctx);
} else if (ctx instanceof cst.SourceCommandContext) {
return this.fromSourceCommand(ctx);
} else if (ctx instanceof cst.ProcessingCommandContext) {
return this.fromProcessingCommand(ctx);
}
return undefined;
}
private fromSubqueryExpression(
ctx: cst.SubqueryExpressionContext
): ast.ESQLAstQueryExpression | undefined {
const queryCtx = ctx.query();
if (queryCtx instanceof cst.QueryContext) {
return this.fromQuery(queryCtx);
} else {
return undefined;
}
}
// ------------------------------------------------------------- query header
private fromSetCommands(setCommandCtxs: cst.SetCommandContext[]): ast.ESQLAstSetHeaderCommand[] {
const setCommands: ast.ESQLAstSetHeaderCommand[] = setCommandCtxs
.map((setCommandCtx) => this.fromSetCommand(setCommandCtx))
.filter(nonNullable);
return setCommands;
}
// ---------------------------------------------------------------------- SET
private fromSetCommand(ctx: cst.SetCommandContext): ast.ESQLAstSetHeaderCommand {
const setFieldCtx = ctx.setField();
const binaryExpression = this.fromSetFieldContext(setFieldCtx);
const args = binaryExpression ? [binaryExpression] : [];
const command = Builder.header.command.set(args, {}, this.getParserFields(ctx));
return command;
}
private fromSetFieldContext(ctx: cst.SetFieldContext): ast.ESQLBinaryExpression<'='> | null {
const leftCtx = ctx.identifier();
const constantCtx = ctx.constant();
const mapExpressionCtx = ctx.mapExpression();
const assignToken = ctx.ASSIGN();
if (!leftCtx) {
return null;
}
const left = this.toIdentifierFromContext(leftCtx);
// Handle constant value
if (constantCtx) {
const right = this.fromConstantToArray(constantCtx) as ast.ESQLLiteral;
const expression = this.toBinaryExpression('=', ctx, [left, right]);
if (left.incomplete || right.incomplete) {
expression.incomplete = true;
}
return expression;
}
// Handle map expression
if (mapExpressionCtx) {
const right = this.fromMapExpression(mapExpressionCtx);
const expression = this.toBinaryExpression('=', ctx, [left, right]);
if (left.incomplete || right?.incomplete) {
expression.incomplete = true;
}
return expression;
}
// Handle missing value (incomplete assignment)
if (assignToken) {
const expression = this.toBinaryExpression('=', ctx, [left, []]);
expression.incomplete = true;
expression.location = {
min: left.location.min,
max: assignToken.symbol.stop,
};
return expression;
}
return null;
}
private toIdentifierFromContext(ctx: cst.IdentifierContext): ast.ESQLIdentifier {
const identifierToken = ctx.UNQUOTED_IDENTIFIER() || ctx.QUOTED_IDENTIFIER();
if (identifierToken) {
return this.toIdentifierFromTerminalNode(identifierToken);
}
// Fallback: create identifier from the full context text
return Builder.identifier({ name: ctx.getText() }, this.getParserFields(ctx));
}
// ----------------------------------------------------------------- commands
public fromSourceCommand(ctx: cst.SourceCommandContext): ast.ESQLCommand | undefined {
const fromCommandCtx = ctx.fromCommand();
if (fromCommandCtx) {
return this.fromFromCommand(fromCommandCtx);
}
const rowCommandCtx = ctx.rowCommand();
if (rowCommandCtx) {
return this.fromRowCommand(rowCommandCtx);
}
const tsCommandCtx = ctx.timeSeriesCommand();
if (tsCommandCtx) {
return this.fromTimeseriesCommand(tsCommandCtx);
}
const explainCommandCtx = ctx.explainCommand();
if (explainCommandCtx) {
return this.fromExplainCommand(explainCommandCtx);
}
const showCommandCtx = ctx.showCommand();
if (showCommandCtx) {
return this.fromShowCommand(showCommandCtx);
}
const promqlCommandCtx = ctx.promqlCommand();
if (promqlCommandCtx) {
return this.fromPromqlCommand(promqlCommandCtx);
}
// throw new Error(`Unknown source command: ${this.getSrc(ctx)}`);
}
public fromProcessingCommand(ctx: cst.ProcessingCommandContext): ast.ESQLCommand | undefined {
const limitCommandCtx = ctx.limitCommand();
if (limitCommandCtx) {
return this.fromLimitCommand(limitCommandCtx);
}
const evalCommandCtx = ctx.evalCommand();
if (evalCommandCtx) {
return this.fromEvalCommand(evalCommandCtx);
}
const whereCommandCtx = ctx.whereCommand();
if (whereCommandCtx) {
return this.fromWhereCommand(whereCommandCtx);
}
const keepCommandCtx = ctx.keepCommand();
if (keepCommandCtx) {
return this.fromKeepCommand(keepCommandCtx);
}
const statsCommandCtx = ctx.statsCommand();
if (statsCommandCtx) {
return this.fromStatsCommand(statsCommandCtx);
}
const sortCommandCtx = ctx.sortCommand();
if (sortCommandCtx) {
return this.fromSortCommand(sortCommandCtx);
}
const dropCommandCtx = ctx.dropCommand();
if (dropCommandCtx) {
return this.fromDropCommand(dropCommandCtx);
}
const renameCommandCtx = ctx.renameCommand();
if (renameCommandCtx) {
return this.fromRenameCommand(renameCommandCtx);
}
const dissectCommandCtx = ctx.dissectCommand();
if (dissectCommandCtx) {
return this.fromDissectCommand(dissectCommandCtx);
}
const grokCommandCtx = ctx.grokCommand();
if (grokCommandCtx) {
return this.fromGrokCommand(grokCommandCtx);
}
const enrichCommandCtx = ctx.enrichCommand();
if (enrichCommandCtx) {
return this.fromEnrichCommand(enrichCommandCtx);
}
const mvExpandCommandCtx = ctx.mvExpandCommand();
if (mvExpandCommandCtx) {
return this.fromMvExpandCommand(mvExpandCommandCtx);
}
const joinCommandCtx = ctx.joinCommand();
if (joinCommandCtx) {
return this.fromJoinCommand(joinCommandCtx);
}
const changePointCommandCtx = ctx.changePointCommand();
if (changePointCommandCtx) {
return this.fromChangePointCommand(changePointCommandCtx);
}
const completionCommandCtx = ctx.completionCommand();
if (completionCommandCtx) {
return this.fromCompletionCommand(completionCommandCtx);
}
const registeredDomainCommandCtx = ctx.registeredDomainCommand();
if (registeredDomainCommandCtx) {
return this.fromRegisteredDomainCommand(registeredDomainCommandCtx);
}
const sampleCommandCtx = ctx.sampleCommand();
if (sampleCommandCtx) {
return this.fromSampleCommand(sampleCommandCtx);
}
const inlinestatsCommandCtx = ctx.inlineStatsCommand();
if (inlinestatsCommandCtx) {
return this.fromInlinestatsCommand(inlinestatsCommandCtx);
}
const rerankCommandCtx = ctx.rerankCommand();
if (rerankCommandCtx) {
return this.fromRerankCommand(rerankCommandCtx);
}
const fuseCommandCtx = ctx.fuseCommand();
if (fuseCommandCtx) {
return this.fromFuseCommand(fuseCommandCtx);
}
const forkCommandCtx = ctx.forkCommand();
if (forkCommandCtx) {
return this.fromForkCommand(forkCommandCtx);
}
const mmrCommand = ctx.mmrCommand();
if (mmrCommand) {
return this.fromMmrCommand(mmrCommand);
}
const uriPartsCommandCtx = ctx.uriPartsCommand();
if (uriPartsCommandCtx) {
return this.fromUriPartsCommand(uriPartsCommandCtx);
}
const tsInfoCommandCtx = ctx.tsInfoCommand();
if (tsInfoCommandCtx) {
return this.fromTsInfoCommand(tsInfoCommandCtx);
}
const metricsInfoCommandCtx = ctx.metricsInfoCommand();
if (metricsInfoCommandCtx) {
return this.fromMetricsInfoCommand(metricsInfoCommandCtx);
}
const userAgentCommandCtx = ctx.userAgentCommand();
if (userAgentCommandCtx) {
return this.fromUserAgentCommand(userAgentCommandCtx);
}
// agent-marker: append new command dispatcher branches here
// throw new Error(`Unknown processing command: ${this.getSrc(ctx)}`;
}
private createCommand<
Name extends string,
Cmd extends ast.ESQLCommand<Name> = ast.ESQLCommand<Name>,
>(name: Name, ctx: antlr.ParserRuleContext, partial?: Partial<Cmd>): Cmd {
const parserFields = this.getParserFields(ctx);
const command = Builder.command({ name, args: [] }, parserFields) as Cmd;
if (partial) {
Object.assign(command, partial);
}
return command;
}
private toOption(
name: string,
ctx: antlr.ParserRuleContext,
args: ast.ESQLAstItem[] = [],
incomplete?: boolean
): ast.ESQLCommandOption {
return {
type: 'option',
name,
text: ctx.getText(),
location: getPosition(ctx.start, ctx.stop),
args,
incomplete:
incomplete ??
(Boolean(ctx.exception) || [...singleItems(args)].some((arg) => arg.incomplete)),
};
}
// ------------------------------------------------------------------ EXPLAIN
private fromExplainCommand(ctx: cst.ExplainCommandContext): ast.ESQLCommand<'explain'> {
const command = this.createCommand('explain', ctx);
const arg = this.fromSubqueryExpression(ctx.subqueryExpression());
if (arg) {
command.args.push(arg);
}
return command;
}
// --------------------------------------------------------------------- FROM
private fromFromCommand(ctx: cst.FromCommandContext): ast.ESQLCommand<'from'> | undefined {
// When parsing queries with nested empty subqueries like "FROM a, (FROM b, ())",
// ANTLR incorrectly identifies the empty parentheses "()" as a fromCommand context.
// This phantom context contains only closing parentheses (e.g., ")" or "))")
// without any actual FROM keyword, which would lead to malformed AST nodes.
if (!ctx.FROM()) {
return undefined;
}
const command = this.fromFromCompatibleCommand('from', ctx);
const hasValidText = textExistsAndIsValid(ctx.getText());
if (!hasValidText) {
command.incomplete = true;
}
return command;
}
private fromFromCompatibleCommand<Name extends string>(
commandName: Name,
ctx: antlr.ParserRuleContext & Pick<cst.FromCommandContext, 'indexPatternAndMetadataFields'>
): ast.ESQLCommand<Name> {
const command = this.createCommand(commandName, ctx);
const indexPatternAndMetadataCtx = ctx.indexPatternAndMetadataFields();
const metadataCtx = indexPatternAndMetadataCtx.metadata();
const indexPatternOrSubqueryCtxs = indexPatternAndMetadataCtx.indexPatternOrSubquery_list();
const sources = indexPatternOrSubqueryCtxs
.map((indexPatternOrSubqueryCtx) => {
const indexPatternCtx = indexPatternOrSubqueryCtx.indexPattern();
if (indexPatternCtx) {
return this.toSource(indexPatternCtx);
}
const subqueryCtx = indexPatternOrSubqueryCtx.subquery();
if (subqueryCtx) {
return this.fromSubquery(subqueryCtx);
}
return null;
})
.filter((source): source is ast.ESQLSource => source !== null);
command.args.push(...sources);
if (metadataCtx && metadataCtx.METADATA()) {
const name = metadataCtx.METADATA().getText().toLowerCase();
const option = this.toOption(name, metadataCtx);
const optionArgs = this.toColumnsFromCommand(metadataCtx);
option.args.push(...optionArgs);
command.args.push(option);
}
return command;
}
private fromSubquery(ctx: cst.SubqueryContext): ast.ESQLParens {
const sourceCommandCtx = ctx.subquerySourceCommand();
const processingCommandCtxs = ctx.processingCommand_list();
const commands: ast.ESQLCommand[] = [];
if (sourceCommandCtx) {
const fromCommandCtx = sourceCommandCtx.fromCommand();
const rowCommandCtx = sourceCommandCtx.rowCommand();
const timeSeriesCommandCtx = sourceCommandCtx.timeSeriesCommand();
if (fromCommandCtx) {
const fromCommand = this.fromFromCommand(fromCommandCtx);
if (fromCommand) {
commands.push(fromCommand);
}
} else if (rowCommandCtx) {
commands.push(this.fromRowCommand(rowCommandCtx));
} else if (timeSeriesCommandCtx) {
commands.push(this.fromTimeseriesCommand(timeSeriesCommandCtx));
}
}
for (const procCmdCtx of processingCommandCtxs) {
const procCommand = this.fromProcessingCommand(procCmdCtx);
if (procCommand) {
commands.push(procCommand);
}
}
const openParen = ctx.LP();
const closeParen = ctx.RP();
// ANTLR inserts tokens with text like "<missing ')'>" when they're missing
const closeParenText = closeParen?.getText() ?? '';
const hasCloseParen = closeParen && !/<missing /.test(closeParenText);
const incomplete = Boolean(ctx.exception) || !hasCloseParen;
const query = Builder.expression.query(commands, {
...this.getParserFields(ctx),
incomplete,
});
return Builder.expression.parens(query, {
incomplete: incomplete || query.incomplete,
location: getPosition(
openParen?.symbol ?? ctx.start,
hasCloseParen ? closeParen.symbol : ctx.stop
),
});
}
// ---------------------------------------------------------------------- ROW
private fromRowCommand(ctx: cst.RowCommandContext): ast.ESQLCommand<'row'> {
const command = this.createCommand('row', ctx);
const fields = this.fromFields(ctx.fields());
command.args.push(...fields);
return command;
}
// ----------------------------------------------------------------------- TS
private fromTimeseriesCommand(ctx: cst.TimeSeriesCommandContext): ast.ESQLCommand<'ts'> {
return this.fromFromCompatibleCommand('ts', ctx);
}
// --------------------------------------------------------------------- SHOW
private fromShowCommand(ctx: cst.ShowCommandContext): ast.ESQLCommand<'show'> {
const command = this.createCommand('show', ctx);
if (ctx instanceof cst.ShowInfoContext) {
const infoCtx = ctx as cst.ShowInfoContext;
const arg = this.toIdentifierFromTerminalNode(infoCtx.INFO());
arg.name = arg.name.toUpperCase();
command.args.push(arg);
}
return command;
}
// -------------------------------------------------------------------- LIMIT
private fromLimitCommand(ctx: cst.LimitCommandContext): ast.ESQLCommand<'limit'> {
const command = this.createCommand('limit', ctx);
if (ctx.constant()) {
const limitValue = this.fromConstantToArray(ctx.constant());
if (limitValue != null) {
command.args.push(limitValue);
}
}
const limitByGroupKeyCtx = ctx.limitByGroupKey();
if (limitByGroupKeyCtx) {
const booleanExpressions = limitByGroupKeyCtx
.booleanExpression_list()
.filter((e) => !e.exception);
const args = booleanExpressions.map((e) =>
this.fromBooleanExpressionToExpressionOrUnknown(e)
);
const byOption = this.toByOption(limitByGroupKeyCtx, args);
if (byOption) {
command.args.push(byOption);
command.incomplete ||= byOption.incomplete;
}
}
return command;
}
// --------------------------------------------------------------------- EVAL
private fromEvalCommand(ctx: cst.EvalCommandContext): ast.ESQLCommand<'eval'> {
const command = this.createCommand('eval', ctx);
const fields = this.fromFields(ctx.fields());
command.args.push(...fields);
return command;
}
// -------------------------------------------------------------------- WHERE
private fromWhereCommand(ctx: cst.WhereCommandContext): ast.ESQLCommand<'where'> {
const command = this.createCommand('where', ctx);
const expression = this.fromBooleanExpressionToExpressionOrUnknown(ctx.booleanExpression());
command.args.push(expression);
return command;
}
// --------------------------------------------------------------------- KEEP
private fromKeepCommand(ctx: cst.KeepCommandContext): ast.ESQLCommand<'keep'> {
const args = this.fromQualifiedNamePatterns(ctx.qualifiedNamePatterns());
const command = this.createCommand('keep', ctx, { args });
return command;
}
private fromQualifiedNamePatterns(
ctx: cst.QualifiedNamePatternsContext
): ast.ESQLAstExpression[] {
const itemCtxs = ctx.qualifiedNamePattern_list();
const result: ast.ESQLAstExpression[] = [];
for (const itemCtx of itemCtxs) {
const node = this.fromQualifiedNamePattern(itemCtx);
result.push(node);
}
return result;
}
// -------------------------------------------------------------------- STATS
private fromStatsCommand(ctx: cst.StatsCommandContext): ast.ESQLCommand<'stats'> {
return this.fromStatsLikeCommand('stats', ctx);
}
private fromStatsLikeCommand<Name extends string>(
name: Name,
ctx: antlr.ParserRuleContext &
Pick<cst.StatsCommandContext, '_stats' | '_grouping' | 'aggFields' | 'fields' | 'BY'>
): ast.ESQLCommand<Name> {
const command = this.createCommand(name, ctx);
if (ctx._stats) {
command.args.push(...this.fromAggFields(ctx.aggFields()));
}
if (ctx._grouping && ctx.fields()) {
const option = this.toByOption(ctx, this.fromFields(ctx.fields()));
if (option) {
command.args.push(option);
}
}
return command;
}
private fromAggField(ctx: cst.AggFieldContext) {
const fieldCtx = ctx.field();
const field = this.fromField(fieldCtx);
if (!field) {
return;
}
const booleanExpression = ctx.booleanExpression();
if (!booleanExpression) {
return field;
}
const condition = this.fromBooleanExpressionToExpressionOrUnknown(booleanExpression);
const aggField = Builder.expression.where(
[field, condition],
{},
{
location: {
min: firstItem([resolveItem(field)])?.location?.min ?? 0,
max: firstItem([resolveItem(condition)])?.location?.max ?? 0,
},
}
);
return aggField;
}
private toByOption(
ctx: antlr.ParserRuleContext & Pick<cst.StatsCommandContext, 'BY'>,
args: ast.ESQLAstItem[]
): ast.ESQLCommandOption | undefined {
const byCtx = ctx.BY();
if (!byCtx) {
return;
}
const option = this.toOption(byCtx.getText().toLowerCase(), ctx, args, !args.length);
option.location.min = byCtx.symbol.start;
const lastArg = lastItem(option.args);
option.location.max = lastArg?.location.max ?? byCtx.symbol.stop;
return option;
}
// --------------------------------------------------------------------- SORT
private fromSortCommand(ctx: cst.SortCommandContext): ast.ESQLCommand<'sort'> {
const command = this.createCommand('sort', ctx);
command.args.push(...this.fromOrderExpressions(ctx.orderExpression_list()));
return command;
}
private fromOrderExpressions(
ctx: cst.OrderExpressionContext[]
): Array<ast.ESQLOrderExpression | ast.ESQLAstItem> {
const expressions: Array<ast.ESQLOrderExpression | ast.ESQLAstItem> = [];
for (const orderCtx of ctx) {
expressions.push(this.fromOrderExpression(orderCtx));
}
return expressions;
}
private fromOrderExpression(
ctx: cst.OrderExpressionContext
): ast.ESQLOrderExpression | ast.ESQLAstItem {
const arg = this.fromBooleanExpressionToExpressionOrUnknown(ctx.booleanExpression());
let order: ast.ESQLOrderExpression['order'] = '';
let nulls: ast.ESQLOrderExpression['nulls'] = '';
const ordering = ctx._ordering?.text?.toUpperCase();
if (ordering) order = ordering as ast.ESQLOrderExpression['order'];
const nullOrdering = ctx._nullOrdering?.text?.toUpperCase();
switch (nullOrdering) {
case 'LAST':
nulls = 'NULLS LAST';
break;
case 'FIRST':
nulls = 'NULLS FIRST';
break;
}
if (!order && !nulls) {
return arg;
}
return Builder.expression.order(
arg as ast.ESQLColumn,
{ order, nulls },
this.getParserFields(ctx)
);
}
// --------------------------------------------------------------------- DROP
private fromDropCommand(ctx: cst.DropCommandContext): ast.ESQLCommand<'drop'> {
const args = this.fromQualifiedNamePatterns(ctx.qualifiedNamePatterns());
const command = this.createCommand('drop', ctx, { args });
return command;
}
// ------------------------------------------------------------------- RENAME
private fromRenameCommand(ctx: cst.RenameCommandContext): ast.ESQLCommand<'rename'> {
const command = this.createCommand('rename', ctx);
const renameArgs = this.fromRenameClauses(ctx.renameClause_list());
command.args.push(...renameArgs);
return command;
}
private fromRenameClauses(clausesCtx: cst.RenameClauseContext[]): ast.ESQLAstItem[] {
return clausesCtx
.map((clause) => {
const asToken = clause.getToken(cst.default.AS, 0);
const assignToken = clause.getToken(cst.default.ASSIGN, 0);
const renameToken = asToken || assignToken;
if (renameToken && textExistsAndIsValid(renameToken.getText())) {
const renameFunction = this.toFunction(
renameToken.getText().toLowerCase(),
clause,
undefined,
'binary-expression'
);
const renameArgsInOrder = asToken
? [clause._oldName, clause._newName]
: [clause._newName, clause._oldName];
for (const arg of renameArgsInOrder) {
if (textExistsAndIsValid(arg.getText())) {
renameFunction.args.push(this.toColumn(arg));
}
}
const firstArg = firstItem(renameFunction.args);
const lastArg = lastItem(renameFunction.args);
const location = renameFunction.location;
if (firstArg) location.min = firstArg.location.min;
if (lastArg) location.max = lastArg.location.max;
return renameFunction;