/
PlSqlAntlrListenerConverter.cs
626 lines (531 loc) · 22.6 KB
/
PlSqlAntlrListenerConverter.cs
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
using System;
using System.Collections.Generic;
using System.Threading;
using Antlr4.Runtime;
using Antlr4.Runtime.Misc;
using PT.PM.AntlrUtils;
using PT.PM.Common;
using PT.PM.Common.Exceptions;
using PT.PM.Common.Files;
using PT.PM.Common.Nodes;
using PT.PM.Common.Nodes.Collections;
using PT.PM.Common.Nodes.Expressions;
using PT.PM.Common.Nodes.Statements;
using PT.PM.Common.Nodes.Statements.TryCatchFinally;
using PT.PM.Common.Nodes.Tokens;
using PT.PM.Common.Nodes.Tokens.Literals;
using PT.PM.Common.Nodes.TypeMembers;
using static PT.PM.PlSqlParseTreeUst.PlSqlParser;
namespace PT.PM.PlSqlParseTreeUst
{
public class PlSqlAntlrListenerConverter : AntlrListenerConverter
{
private static readonly int[] binaryOperatorPlSqlTypes = {ASTERISK, SOLIDUS, PLUS_SIGN, MINUS_SIGN, BAR};
public PlSqlAntlrListenerConverter(TextFile sourceFile, AntlrParserConverter antlrParser)
: base(sourceFile, antlrParser)
{
}
public override void ExitEveryRule([NotNull] ParserRuleContext context)
{
Ust result = null;
bool defaultConversion = false;
try
{
switch (context.RuleIndex)
{
case RULE_create_procedure_body:
result = ConvertCreateProcedureBody(context);
break;
case RULE_parameter:
result = ConvertParameter(context);
break;
case RULE_body:
result = ConvertBody(context);
break;
case RULE_variable_declaration:
result = ConvertVariableDeclaration(context);
break;
case RULE_exception_handler:
result = ConvertExceptionHandler(context);
break;
case RULE_seq_of_statements:
result = ConvertSeqOfStatements(context);
break;
case RULE_seq_of_declare_specs:
result = ConvertSeqOfDeclareSpecs(context);
break;
case RULE_grant_statement:
result = ConvertGrantStatement(context);
break;
case RULE_statement:
result = ConvertStatement(context);
break;
case RULE_assignment_statement:
result = ConvertAssignmentStatement(context);
break;
case RULE_continue_statement:
result = ConvertContinueStatement(context);
break;
case RULE_exit_statement:
result = ConvertExitStatement(context);
break;
case RULE_return_statement:
result = ConvertReturnStatement(context);
break;
case RULE_open_statement:
case RULE_open_for_statement:
case RULE_fetch_statement:
case RULE_close_statement:
result = ConvertCursorStatement(context);
break;
case RULE_cursor_name:
case RULE_variable_name:
result = ConvertCursorOrVariableName(context);
break;
case RULE_function_call:
case RULE_procedure_call:
result = ConvertFunctionOrProcedureCall(context);
break;
case RULE_routine_name:
result = ConvertRoutineName(context);
break;
case RULE_general_element_part:
result = ConvertGeneralElementPart(context);
break;
case RULE_function_argument:
result = ConvertFunctionArgument(context);
break;
case RULE_execute_immediate:
result = ConvertExecuteImmediate(context);
break;
case RULE_relational_expression:
result = ConvertRelationalExpression(context);
break;
case RULE_relational_operator:
result = ConvertRelationalOperator(context);
break;
case RULE_logical_expression:
result = ConvertLogicalExpression(context);
break;
case RULE_unary_logical_expression:
result = ConvertUnaryLogicalExpression(context);
break;
case RULE_concatenation:
result = ConvertConcatenationExpression(context);
break;
case RULE_query_block:
result = ConvertQueryBlock(context);
break;
default:
defaultConversion = true;
result = ConvertChildren();
break;
}
}
catch (Exception ex) when (!(ex is ThreadAbortException))
{
if (!defaultConversion)
{
result = ConvertChildren();
}
Logger.LogError(new ConversionException(root.SourceFile, ex));
Console.WriteLine(ex);
}
finally
{
RemoveAndAdd(result);
}
}
private Ust ConvertQueryBlock(ParserRuleContext context)
{
var children = GetChildren();
var query = new InvocationExpression(context.GetTextSpan())
{
Target = children[0].AsIdToken()
};
var queryElements = new List<Expression>();
for (var i = 1; i < children.Count; i++)
{
var child = children[i];
if (child is Collection collection)
{
queryElements.AddRange(ExtractCollection(collection));
}
else if (child is WrapperExpression wrapperExpression &&
wrapperExpression.Node is Collection collection2)
{
queryElements.AddRange(ExtractCollection(collection2));
}
else
{
queryElements.Add(child.AsExpression());
}
}
query.Arguments = new ArgsUst(queryElements);
return query;
}
private IEnumerable<Expression> ExtractCollection(Collection collection)
{
var result = new List<Expression>();
foreach (var node in collection.Collection)
{
switch (node)
{
case Keyword keyword:
result.Add(keyword.AsIdToken());
break;
case Collection nestedCollection:
result.AddRange(ExtractCollection(nestedCollection));
break;
case WrapperExpression wrapper:
if (wrapper.Node is Collection collection2)
{
result.AddRange(ExtractCollection(collection2));
break;
}
result.Add(wrapper);
break;
default:
result.Add(node.AsExpression());
break;
}
}
return result;
}
private MethodDeclaration ConvertCreateProcedureBody(ParserRuleContext context)
{
List<Ust> children = GetChildren();
int nameIndex = TryGetChildOfType(out IdToken name);
var parameters = new List<ParameterDeclaration>();
var statements = new List<Statement>();
for (int i = nameIndex + 1; i < children.Count; i++)
{
Ust child = children[i];
if (child is ParameterDeclaration param)
{
parameters.Add(param);
}
else if (child is BlockStatement block)
{
statements.AddRange(block.Statements);
}
else if (child is Statement statement)
{
statements.Add(statement);
}
}
return new MethodDeclaration(name, parameters, new BlockStatement(statements), context.GetTextSpan());
}
private ParameterDeclaration ConvertParameter(ParserRuleContext context)
{
return new ParameterDeclaration(null, null, GetChild(0).AsIdToken(), context.GetTextSpan());
}
private Statement ConvertBody(ParserRuleContext context)
{
const int exceptionKeywordIndex = 2;
List<Ust> children = GetChildren();
BlockStatement block = (BlockStatement) children[1];
if (CheckChild<Keyword>(EXCEPTION, exceptionKeywordIndex))
{
var tryCatchStatement = new TryCatchStatement(block, context.GetTextSpan());
int endInd = GetChildFromEnd(0) is Keyword ? children.Count - 1 : children.Count - 2;
var catchClauses = new List<CatchClause>(endInd - exceptionKeywordIndex - 1);
for (int i = exceptionKeywordIndex + 1; i < endInd; i++)
{
catchClauses.Add((CatchClause) children[i]);
}
tryCatchStatement.CatchClauses = catchClauses;
return tryCatchStatement;
}
return block;
}
private VariableDeclarationExpression ConvertVariableDeclaration(ParserRuleContext context)
{
List<Ust> children = GetChildren();
var left = children[0].AsIdToken();
int rightInd = children[children.Count - 1] is Punctuator ? children.Count - 2 : children.Count - 1;
var right = children[rightInd];
if (right is Collection collection)
{
right = collection.Collection.FindLast(x => !(x is Punctuator));
}
return new VariableDeclarationExpression(
null,
new List<AssignmentExpression>
{new AssignmentExpression(left, right.AsExpression(), context.GetTextSpan())});
}
private CatchClause ConvertExceptionHandler(ParserRuleContext context)
{
var body = (BlockStatement) GetChildFromEnd(0);
if (body.Statements.Count == 1 &&
body.Statements[0] is ExpressionStatement expressionStatement &&
expressionStatement.Expression is NullLiteral)
{
body = new BlockStatement(new Statement[0], body.Statements[0].TextSpan);
}
return new CatchClause(null, null, body, context.GetTextSpan());
}
private BlockStatement ConvertSeqOfStatements(ParserRuleContext context)
{
List<Ust> children = GetChildren();
var statements = new List<Statement>(children.Count);
for (int i = 0; i < children.Count; i++)
{
if (children[i] is Statement statement)
{
statements.Add(statement);
}
}
return new BlockStatement(statements, context.GetTextSpan());
}
private BlockStatement ConvertSeqOfDeclareSpecs(ParserRuleContext context)
{
List<Ust> children = GetChildren();
var statements = new List<Statement>(children.Count);
foreach (Ust child in children)
{
statements.Add(child.AsStatement());
}
return new BlockStatement(statements, context.GetTextSpan());
}
private ExpressionStatement ConvertGrantStatement(ParserRuleContext context)
{
List<Ust> children = GetChildren();
IdToken name;
int argInd;
if (CheckChild<Keyword>(ALL, 1))
{
name = new IdToken("grant_all", children[0].TextSpan.Union(children[1].TextSpan));
argInd = 2;
}
else
{
name = children[0].AsIdToken();
argInd = 1;
}
var args = new List<Expression>(children.Count - argInd);
for (int i = argInd; i < children.Count; i++)
{
args.Add(children[i].AsExpression());
}
return new ExpressionStatement(new InvocationExpression(name, new ArgsUst(args), context.GetTextSpan()));
}
private Statement ConvertStatement(ParserRuleContext context)
{
return GetChild(0).AsStatement();
}
private AssignmentExpression ConvertAssignmentStatement(ParserRuleContext context)
{
List<Ust> children = GetChildren();
var left = children[0].AsExpression();
var right = children[2].AsExpression();
return new AssignmentExpression(left, right, context.GetTextSpan());
}
private ContinueStatement ConvertContinueStatement(ParserRuleContext context)
{
return new ContinueStatement(context.GetTextSpan());
}
private BreakStatement ConvertExitStatement(ParserRuleContext context)
{
return new BreakStatement(context.GetTextSpan());
}
private ReturnStatement ConvertReturnStatement(ParserRuleContext context)
{
return new ReturnStatement(GetChild(0).AsExpression(), context.GetTextSpan());
}
private ExpressionStatement ConvertCursorStatement(ParserRuleContext context)
{
List<Ust> children = GetChildren();
var invocation = new InvocationExpression(context.GetTextSpan())
{
Target = children[0].AsIdToken(),
Arguments = new ArgsUst(children[1].AsExpression())
};
for (int i = 2; i < children.Count; i++)
{
Ust child = children[i];
if (!(child is ITerminal) || child is Token)
{
invocation.Arguments.Collection.Add(child.AsExpression());
}
}
return new ExpressionStatement(invocation);
}
private ArgumentExpression ConvertCursorOrVariableName(ParserRuleContext context)
{
var argModifier = new InOutModifierLiteral(InOutModifier.InOut, TextSpan.Zero);
TextSpan contextTextSpan = context.GetTextSpan();
var arg = new IdToken(GetChildFromEnd(0).Substring, contextTextSpan);
return new ArgumentExpression(argModifier, arg, contextTextSpan);
}
private InvocationExpression ConvertExecuteImmediate(ParserRuleContext context)
{
List<Ust> children = GetChildren();
var invocation = new InvocationExpression(context.GetTextSpan())
{
Target = children[0].AsIdToken(),
Arguments = new ArgsUst(children[2].AsExpression())
};
return invocation;
}
private InvocationExpression ConvertFunctionOrProcedureCall(ParserRuleContext context)
{
List<Ust> children = GetChildren();
int targetIndex = CheckChild<Keyword>(CALL, 0) ? 1 : 0;
ArgsUst args = children[children.Count - 1] is ArgsUst argsUst ? argsUst : new ArgsUst();
return new InvocationExpression(children[targetIndex].AsExpression(), args, context.GetTextSpan());
}
private Expression ConvertRoutineName(ParserRuleContext context)
{
List<Ust> children = GetChildren();
Expression result = children[0].AsIdToken();
int index = 1;
while (CheckChild<IOperatorOrPunctuator>(PERIOD, index))
{
Expression name = children[index + 1].AsIdToken();
result = new MemberReferenceExpression(result, name, result.TextSpan.Union(name.TextSpan));
index += 2;
}
return result;
}
private Expression ConvertGeneralElementPart(ParserRuleContext context)
{
List<Ust> children = GetChildren();
int index = CheckChild<Keyword>(INTRODUCER, 0) ? 2 : 0;
Expression result = children[index].AsExpression();
index++;
while (CheckChild<IOperatorOrPunctuator>(PERIOD, index))
{
Expression name = children[index + 1].AsIdToken();
result = new MemberReferenceExpression(result, name, result.TextSpan.Union(name.TextSpan));
index += 2;
}
if (!(children[children.Count - 1] is ArgsUst args))
{
return result;
}
return new InvocationExpression(result, args, context.GetTextSpan());
}
private ArgsUst ConvertFunctionArgument(ParserRuleContext context)
{
List<Ust> children = GetChildren();
var args = new List<Expression>(children.Count);
foreach (Ust child in children)
{
if (!(child is Punctuator))
{
args.Add(child.AsExpression());
}
}
return new ArgsUst(args, context.GetTextSpan());
}
private Expression ConvertRelationalExpression(ParserRuleContext context)
{
List<Ust> children = GetChildren();
if (children.Count == 1)
{
return children[0].AsExpression();
}
var right = children[children.Count - 1].AsExpression();
var op = (BinaryOperatorLiteral) children[children.Count - 2];
var left = GetLeftChildFromLeftRecursiveRule(context).AsExpression();
return new BinaryOperatorExpression(left, op, right, context.GetTextSpan());
}
private BinaryOperatorLiteral ConvertRelationalOperator(ParserRuleContext context)
{
var opText = GetChild(0).ToString(false);
if (!BinaryOperatorLiteral.TextBinaryOperator.TryGetValue(opText, out var op))
{
op = BinaryOperator.NotEqual;
}
return new BinaryOperatorLiteral(op, context.GetTextSpan());
}
private Ust ConvertLogicalExpression(ParserRuleContext context)
{
List<Ust> children = GetChildren();
if (children.Count == 1)
{
return children[0].AsExpression();
}
var right = children[children.Count - 1].AsExpression();
Ust opUst = children[children.Count - 2];
BinaryOperatorLiteral op;
if (opUst is BinaryOperatorLiteral binaryOperatorLiteral)
{
op = binaryOperatorLiteral;
}
else
{
op = new BinaryOperatorLiteral(BinaryOperatorLiteral.TextBinaryOperator[opUst.ToString(false).ToLowerInvariant()],
opUst.TextSpan);
}
var left = GetLeftChildFromLeftRecursiveRule(context).AsExpression();
return new BinaryOperatorExpression(left, op, right, context.GetTextSpan());
}
private Expression ConvertUnaryLogicalExpression(ParserRuleContext context)
{
var children = GetChildren();
int index = 0;
if (CheckChild<Keyword>(NOT, 0))
{
index++;
}
Expression result = children[index].AsExpression();
if (index == 1)
{
var opLiteral = new UnaryOperatorLiteral(UnaryOperator.Not, children[0].TextSpan);
result = new UnaryOperatorExpression(opLiteral, result, children[0].TextSpan.Union(children[1].TextSpan));
}
index++;
while (CheckChild<Keyword>(IS, index))
{
int isIndex = index;
index++;
bool not = false;
if (CheckChild<Keyword>(NOT, index))
{
not = true;
index++;
}
var rightExpr = children[index].AsExpression();
index++;
if (not)
{
var opLiteral = new UnaryOperatorLiteral(UnaryOperator.Not, children[index - 1].TextSpan);
rightExpr = new UnaryOperatorExpression(opLiteral, rightExpr, opLiteral.TextSpan.Union(rightExpr.TextSpan));
}
var bopLiteral = new BinaryOperatorLiteral(BinaryOperator.Is, children[isIndex].TextSpan);
result = new BinaryOperatorExpression(result, bopLiteral, rightExpr, result.TextSpan.Union(rightExpr.TextSpan));
}
return result;
}
private Expression ConvertConcatenationExpression(ParserRuleContext context)
{
List<Ust> children = GetChildren();
var operatorIndex = IsParseTreeExists ? 1 : 0;
if (!CheckChild<IOperatorOrPunctuator>(binaryOperatorPlSqlTypes, operatorIndex))
{
return ConvertChildren().AsExpression();
}
var right = children[children.Count - 1].AsExpression();
Ust opUst = children[operatorIndex];
BinaryOperatorLiteral op;
if (CheckChild<IOperatorOrPunctuator>(BAR, operatorIndex))
{
op = new BinaryOperatorLiteral(BinaryOperator.Plus,
opUst.TextSpan.Union(children[operatorIndex + 1].TextSpan));
}
else if (opUst is BinaryOperatorLiteral binaryOperatorLiteral)
{
op = binaryOperatorLiteral;
}
else
{
op = new BinaryOperatorLiteral(BinaryOperatorLiteral.TextBinaryOperator[opUst.ToString(false).ToLowerInvariant()],
opUst.TextSpan);
}
var left = GetLeftChildFromLeftRecursiveRule(context).AsExpression();
return new BinaryOperatorExpression(left, op, right, context.GetTextSpan());
}
}
}