@ant-yasa/uast-parser-java-js 0.1.19-beta.4 → 0.1.19-beta.41

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.
Files changed (35) hide show
  1. package/dist/package.json +73 -0
  2. package/dist/src/frontend/java/ASTBuilder.d.ts +171 -0
  3. package/dist/src/frontend/java/ASTBuilder.js +2369 -0
  4. package/dist/src/frontend/java/ASTBuilder.js.map +1 -0
  5. package/dist/src/frontend/java/ErrorListener.d.ts +9 -0
  6. package/dist/src/frontend/java/ErrorListener.js +24 -0
  7. package/dist/src/frontend/java/ErrorListener.js.map +1 -0
  8. package/dist/src/frontend/java/antlr/JavaLexer.d.ts +154 -0
  9. package/dist/src/frontend/java/antlr/JavaLexer.js +812 -0
  10. package/dist/src/frontend/java/antlr/JavaLexer.js.map +1 -0
  11. package/dist/src/frontend/java/antlr/JavaListener.d.ts +1393 -0
  12. package/dist/src/frontend/java/antlr/JavaListener.js +4 -0
  13. package/dist/src/frontend/java/antlr/JavaListener.js.map +1 -0
  14. package/dist/src/frontend/java/antlr/JavaParser.d.ts +2065 -0
  15. package/dist/src/frontend/java/antlr/JavaParser.js +15279 -0
  16. package/dist/src/frontend/java/antlr/JavaParser.js.map +1 -0
  17. package/dist/src/frontend/java/antlr/JavaVisitor.d.ts +892 -0
  18. package/dist/src/frontend/java/antlr/JavaVisitor.js +4 -0
  19. package/dist/src/frontend/java/antlr/JavaVisitor.js.map +1 -0
  20. package/dist/src/frontend/java/parser.d.ts +20 -0
  21. package/dist/src/frontend/java/parser.js +93 -0
  22. package/dist/src/frontend/java/parser.js.map +1 -0
  23. package/dist/src/frontend/java/testBuilder.d.ts +146 -0
  24. package/dist/src/frontend/java/testBuilder.js +464 -0
  25. package/dist/src/frontend/java/testBuilder.js.map +1 -0
  26. package/dist/src/frontend/java/types.d.ts +29 -0
  27. package/dist/src/frontend/java/types.js +3 -0
  28. package/dist/src/frontend/java/types.js.map +1 -0
  29. package/dist/src/frontend/javascript/parser.d.ts +8 -0
  30. package/dist/src/frontend/javascript/parser.js +1121 -0
  31. package/dist/src/frontend/javascript/parser.js.map +1 -0
  32. package/dist/src/index.d.ts +14 -0
  33. package/dist/src/index.js +76 -0
  34. package/dist/src/index.js.map +1 -0
  35. package/package.json +1 -1
@@ -0,0 +1,2369 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
15
+ }) : function(o, v) {
16
+ o["default"] = v;
17
+ });
18
+ var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
19
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
20
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
21
+ else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
22
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
23
+ };
24
+ var __importStar = (this && this.__importStar) || function (mod) {
25
+ if (mod && mod.__esModule) return mod;
26
+ var result = {};
27
+ if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
28
+ __setModuleDefault(result, mod);
29
+ return result;
30
+ };
31
+ Object.defineProperty(exports, "__esModule", { value: true });
32
+ exports.ASTBuilder = void 0;
33
+ const antlr4ts_1 = require("antlr4ts");
34
+ const AbstractParseTreeVisitor_1 = require("antlr4ts/tree/AbstractParseTreeVisitor");
35
+ const TerminalNode_1 = require("antlr4ts/tree/TerminalNode");
36
+ const JP = __importStar(require("./antlr/JavaParser"));
37
+ const UAST = __importStar(require("@ant-yasa/uast-spec"));
38
+ const uast_spec_1 = require("@ant-yasa/uast-spec");
39
+ const ErrorNode_1 = require("antlr4ts/tree/ErrorNode");
40
+ const _ = __importStar(require("lodash"));
41
+ const parser_1 = require("../javascript/parser");
42
+ const { literal: literalBuild, identifier: identifierBuild } = UAST;
43
+ class ParseTreeVisitor extends AbstractParseTreeVisitor_1.AbstractParseTreeVisitor {
44
+ options;
45
+ sourcefile;
46
+ constructor(options, sourcefile) {
47
+ super();
48
+ this.options = options;
49
+ this.sourcefile = sourcefile;
50
+ }
51
+ visit(tree) {
52
+ if (!tree)
53
+ return null;
54
+ const node = super.visit(tree);
55
+ if (!Array.isArray(node)) {
56
+ // @ts-ignore
57
+ node.loc = {
58
+ // @ts-ignore
59
+ start: { line: tree._start.line, column: tree._start._charPositionInLine + 1 },
60
+ // @ts-ignore
61
+ end: { line: tree._stop?.line, column: tree._stop?._charPositionInLine + 1 },
62
+ sourcefile: this.sourcefile
63
+ };
64
+ }
65
+ return node;
66
+ }
67
+ }
68
+ class ASTBuilder extends ParseTreeVisitor {
69
+ options;
70
+ result = null;
71
+ typesState = [];
72
+ qualifiedNamespaceState = [];
73
+ constructor(options, sourcefile) {
74
+ super(options, sourcefile);
75
+ this.options = options;
76
+ }
77
+ defaultResult() {
78
+ // throw new Error('Unknown node')
79
+ return UAST.noop();
80
+ }
81
+ aggregateResult() {
82
+ return UAST.noop();
83
+ }
84
+ //compilationUnit
85
+ // : packageDeclaration? importDeclaration* typeDeclaration*
86
+ // | moduleDeclaration EOF
87
+ visitCompilationUnit(ctx) {
88
+ const children = (ctx.children ?? []).filter((x) => !(x instanceof ErrorNode_1.ErrorNode) && !(x instanceof TerminalNode_1.TerminalNode));
89
+ const body = children.map((child) => this.visit(child));
90
+ const node = UAST.compileUnit(body, 'java', '17', this.sourcefile, uast_spec_1.version);
91
+ // visit package decl
92
+ const packageDeclarationContext = (ctx.children ?? []).find(x => x instanceof JP.PackageDeclarationContext);
93
+ if (packageDeclarationContext) {
94
+ const qualifiedName = packageDeclarationContext.qualifiedName();
95
+ node._meta.qualifiedName = toText(qualifiedName);
96
+ this.qualifiedNamespaceState.push(node._meta.qualifiedName);
97
+ }
98
+ else {
99
+ this.qualifiedNamespaceState.push('');
100
+ }
101
+ this.result = node;
102
+ this.completeLocInfo(node);
103
+ return node;
104
+ }
105
+ // packageDeclaration
106
+ // : annotation* PACKAGE qualifiedName ';'
107
+ // ;
108
+ visitPackageDeclaration(ctx) {
109
+ const qualifiedName = ctx.qualifiedName();
110
+ const identifiers = ctx.qualifiedName().identifier();
111
+ let node;
112
+ if (identifiers.length > 1) {
113
+ let memberAccess = UAST.memberAccess(UAST.identifier(toText(identifiers[identifiers.length - 2])), UAST.identifier(toText(identifiers[identifiers.length - 1])), false);
114
+ for (let i = identifiers.length - 3; i >= 0; i--) {
115
+ const obj = UAST.identifier(toText(identifiers[i]));
116
+ memberAccess = UAST.memberAccess(obj, memberAccess);
117
+ }
118
+ node = UAST.packageDeclaration(memberAccess);
119
+ }
120
+ else {
121
+ node = UAST.packageDeclaration(UAST.identifier(toText(qualifiedName)));
122
+ }
123
+ return node;
124
+ }
125
+ // modifier
126
+ // : classOrInterfaceModifier
127
+ // | NATIVE
128
+ // | SYNCHRONIZED
129
+ // | TRANSIENT
130
+ // | VOLATILE
131
+ // ;
132
+ visitModifier(ctx) {
133
+ return UAST.noop();
134
+ }
135
+ // classOrInterfaceModifier
136
+ // : annotation
137
+ // | PUBLIC
138
+ // | PROTECTED
139
+ // | PRIVATE
140
+ // | STATIC
141
+ // | ABSTRACT
142
+ // | FINAL // FINAL for class only -- does not apply to interfaces
143
+ // | STRICTFP
144
+ // | SEALED // Java17
145
+ // | NON_SEALED // Java17
146
+ // ;
147
+ visitClassOrInterfaceModifier(ctx) {
148
+ return UAST.noop();
149
+ }
150
+ // variableModifier java7
151
+ // : FINAL
152
+ // | annotation
153
+ // ;
154
+ //unused variableModifier
155
+ visitVariableModifier(ctx) {
156
+ return UAST.noop();
157
+ }
158
+ //typeParameters java7
159
+ // : '<' typeParameter (',' typeParameter)* '>'
160
+ // ;
161
+ //unused typeParameters
162
+ visitTypeParameters(ctx) {
163
+ return UAST.noop();
164
+ }
165
+ // typeParameter java7
166
+ // : annotation* identifier (EXTENDS annotation* typeBound)?
167
+ // ;
168
+ //unused typeParameter
169
+ visitTypeParameter(ctx) {
170
+ return UAST.noop();
171
+ }
172
+ // typeBound java7
173
+ // : typeType ('&' typeType)*
174
+ // ;
175
+ //unused typeBound
176
+ visitTypeBound(ctx) {
177
+ return UAST.noop();
178
+ }
179
+ //importDeclaration
180
+ // : IMPORT STATIC? qualifiedName ('.' '*')? ';'
181
+ // | ';'
182
+ // TODO static import
183
+ visitImportDeclaration(ctx) {
184
+ if (!ctx.IMPORT()) {
185
+ return UAST.noop();
186
+ }
187
+ const qualifiedName = toText(ctx.qualifiedName());
188
+ const qualifiedNameList = qualifiedName.split('.');
189
+ const tailName = qualifiedNameList.pop();
190
+ if (ctx.MUL()) {
191
+ // for import all case
192
+ // TODO avoid import sub package
193
+ const importExpr = UAST.importExpression(literalBuild(qualifiedName, 'string'));
194
+ return UAST.spreadElement(importExpr);
195
+ }
196
+ else {
197
+ // single import case
198
+ const classNameId = identifierBuild(tailName);
199
+ const qualifiedClassNameId = identifierBuild(qualifiedName);
200
+ const importExpr = UAST.importExpression(literalBuild(qualifiedName, 'string'), null, null);
201
+ return UAST.variableDeclaration(classNameId, importExpr, false, UAST.scopedType(qualifiedClassNameId, null));
202
+ }
203
+ }
204
+ //typeDeclaration
205
+ // : classOrInterfaceModifier*
206
+ // (classDeclaration | enumDeclaration | interfaceDeclaration | annotationTypeDeclaration | recordDeclaration)
207
+ // | ';'
208
+ visitTypeDeclaration(ctx) {
209
+ const children = ctx.children;
210
+ const typeDecl = children.pop();
211
+ if (typeDecl instanceof TerminalNode_1.TerminalNode) {
212
+ return UAST.noop();
213
+ }
214
+ const classDefinition = this.visit(typeDecl);
215
+ ctx.classOrInterfaceModifier().forEach(m => {
216
+ const annotationCtx = m.annotation();
217
+ if (annotationCtx) {
218
+ const meta = classDefinition._meta;
219
+ meta.annotations = meta.annotations || [];
220
+ const annotations = meta.annotations;
221
+ annotations.push(this.visit(annotationCtx));
222
+ }
223
+ else {
224
+ const meta = classDefinition._meta;
225
+ meta.modifiers = meta.modifiers ?? [];
226
+ const modifiers = meta.modifiers;
227
+ const modifierName = toText(m);
228
+ meta['is' + getUpperCase(modifierName)] = true;
229
+ modifiers.push(modifierName);
230
+ }
231
+ });
232
+ const isPublic = children.find(child => toText(child) === 'public');
233
+ if (isPublic) {
234
+ return UAST.exportStatement(classDefinition, classDefinition.id);
235
+ }
236
+ else {
237
+ return classDefinition;
238
+ }
239
+ }
240
+ //classDeclaration
241
+ // : CLASS identifier typeParameters?
242
+ // (EXTENDS typeType)?
243
+ // (IMPLEMENTS typeList)?
244
+ // (PERMITS typeList)? // Java17
245
+ // classBody
246
+ visitClassDeclaration(ctx) {
247
+ const idCtx = ctx.identifier();
248
+ this.qualifiedNamespaceState.push(toText(idCtx));
249
+ const body = this.visit(ctx.classBody());
250
+ let supers = [];
251
+ if (ctx.EXTENDS()) {
252
+ const typeTypeCtx = ctx.typeType();
253
+ const type = this.visit(typeTypeCtx);
254
+ supers.push(typeToIdentifier(type));
255
+ }
256
+ if (ctx.IMPLEMENTS()) {
257
+ const typeListCtx = ctx.typeList();
258
+ const s = this.visit(typeListCtx[0]);
259
+ supers = supers.concat(...s);
260
+ }
261
+ const node = UAST.classDefinition(this.visit(ctx.identifier()), body, supers);
262
+ this.qualifiedNamespaceState.pop();
263
+ return node;
264
+ }
265
+ //classBody
266
+ // : '{' classBodyDeclaration* '}'
267
+ visitClassBody(ctx) {
268
+ const body = [];
269
+ ctx.classBodyDeclaration().forEach(node => {
270
+ const decls = this.visit(node);
271
+ if (Array.isArray(decls)) {
272
+ body.push(...decls);
273
+ }
274
+ else {
275
+ body.push(decls);
276
+ }
277
+ });
278
+ return body;
279
+ }
280
+ //classBodyDeclaration
281
+ // : ';'
282
+ // | STATIC? block
283
+ // | modifier* memberDeclaration
284
+ visitClassBodyDeclaration(ctx) {
285
+ const md = ctx.memberDeclaration();
286
+ if (md) {
287
+ const res = this.visit(md);
288
+ const modifiersCtx = ctx.modifier();
289
+ if (Array.isArray(modifiersCtx)) {
290
+ modifiersCtx.forEach(modifier => {
291
+ const modifierText = toText(modifier);
292
+ if (Array.isArray(res)) {
293
+ res.forEach(r => {
294
+ r._meta.modifiers = r._meta.modifiers ?? [];
295
+ r._meta.modifiers.push(modifierText);
296
+ r._meta['is' + getUpperCase(modifierText)] = true;
297
+ });
298
+ }
299
+ else {
300
+ const meta = res._meta;
301
+ meta.modifiers = meta.modifiers || [];
302
+ meta.modifiers.push(modifierText);
303
+ res._meta['is' + getUpperCase(modifierText)] = true;
304
+ }
305
+ });
306
+ }
307
+ return res;
308
+ }
309
+ const block = ctx.block();
310
+ if (block) {
311
+ return this.visit(block);
312
+ }
313
+ return UAST.noop();
314
+ }
315
+ //memberDeclaration
316
+ visitMemberDeclaration(ctx) {
317
+ const childCtx = ctx.children[0];
318
+ return this.visit(childCtx);
319
+ }
320
+ //fieldDeclaration
321
+ // : typeType variableDeclarators ';'
322
+ visitFieldDeclaration(ctx) {
323
+ this.typesState.push(this.visit(ctx.typeType()));
324
+ const decls = this.visit(ctx.variableDeclarators());
325
+ this.typesState.pop();
326
+ return decls;
327
+ }
328
+ //constructorDeclaration
329
+ // : identifier formalParameters (THROWS qualifiedNameList)? constructorBody=block
330
+ visitConstructorDeclaration(ctx) {
331
+ const params = this.visit(ctx.formalParameters());
332
+ const qualifiedName = this.qualifiedNamespaceState.join('.');
333
+ const returnType = UAST.scopedType(UAST.identifier(qualifiedName), null);
334
+ const body = this.visit(ctx.block());
335
+ const res = UAST.functionDefinition(UAST.identifier('_CTOR_'), params, returnType, body, []);
336
+ res._meta.isConstructor = true;
337
+ return res;
338
+ }
339
+ // compactConstructorDeclaration
340
+ // : modifier* identifier constructorBody=block
341
+ // ;
342
+ visitCompactConstructorDeclaration(ctx) {
343
+ return UAST.noop();
344
+ }
345
+ // methodDeclaration
346
+ // : typeTypeOrVoid identifier formalParameters ('[' ']')*
347
+ // (THROWS qualifiedNameList)?
348
+ // methodBody
349
+ visitMethodDeclaration(ctx) {
350
+ const typeOrVoidCtx = ctx.typeTypeOrVoid();
351
+ const typeCtx = typeOrVoidCtx.typeType();
352
+ let type;
353
+ if (typeCtx) {
354
+ type = this.visit(typeCtx);
355
+ }
356
+ else {
357
+ type = UAST.primitiveType(UAST.identifier('void'));
358
+ }
359
+ const id = this.visit(ctx.identifier());
360
+ const params = this.visit(ctx.formalParameters());
361
+ const blockCtx = ctx.methodBody().block();
362
+ let body;
363
+ const modifiers = [];
364
+ if (blockCtx) {
365
+ body = this.visit(blockCtx);
366
+ }
367
+ else {
368
+ body = UAST.noop();
369
+ modifiers.push('abstract');
370
+ }
371
+ return UAST.functionDefinition(id, params, type, body, modifiers);
372
+ }
373
+ // methodBody
374
+ // : block
375
+ // | ';'
376
+ // ;
377
+ visitMethodBody(ctx) {
378
+ return UAST.noop();
379
+ }
380
+ // interfaceDeclaration
381
+ // : INTERFACE identifier typeParameters? (EXTENDS typeList)? (PERMITS typeList)? interfaceBody
382
+ visitInterfaceDeclaration(ctx) {
383
+ const id = this.visit(ctx.identifier());
384
+ let supers = [];
385
+ if (ctx.EXTENDS()) {
386
+ const typeListCtx = ctx.typeList()[0];
387
+ supers = this.visit(typeListCtx);
388
+ }
389
+ const body = this.visitInterfaceBody(ctx.interfaceBody());
390
+ const scope = UAST.scopedStatement(body);
391
+ return UAST.classDefinition(id, [scope], supers);
392
+ }
393
+ // interfaceBody
394
+ // : '{' interfaceBodyDeclaration* '}'
395
+ // ;
396
+ visitInterfaceBody(ctx) {
397
+ return ctx.interfaceBodyDeclaration().flatMap(d => {
398
+ const result = this.visit(d.interfaceMemberDeclaration());
399
+ if (result === null) {
400
+ return [];
401
+ }
402
+ return Array.isArray(result) ? result : [result];
403
+ });
404
+ }
405
+ // interfaceBodyDeclaration
406
+ // : modifier* interfaceMemberDeclaration
407
+ // | ';'
408
+ // ;
409
+ visitInterfaceBodyDeclaration(ctx) {
410
+ return UAST.noop();
411
+ }
412
+ // genericMethodDeclaration
413
+ visitGenericMethodDeclaration(ctx) {
414
+ return this.visit(ctx.methodDeclaration());
415
+ }
416
+ // genericConstructorDeclaration
417
+ visitGenericConstructorDeclaration(ctx) {
418
+ return this.visit(ctx.constructorDeclaration());
419
+ }
420
+ // recordDeclaration //Java17
421
+ // : RECORD identifier typeParameters? recordHeader
422
+ // (IMPLEMENTS typeList)?
423
+ // recordBody
424
+ visitRecordDeclaration(ctx) {
425
+ const id = this.visit(ctx.identifier());
426
+ const supers = this.safeVisit(ctx.typeList()) || [];
427
+ const body = this.visit(ctx.recordBody());
428
+ const defaultBody = this.visitRecordHeader(ctx.recordHeader());
429
+ body.push(...defaultBody);
430
+ return UAST.classDefinition(id, body, supers);
431
+ }
432
+ //recordHeader
433
+ // : '(' recordComponentList? ')'
434
+ // recordComponentList
435
+ // : recordComponent (',' recordComponent)*
436
+ // recordComponent
437
+ // : typeType identifier
438
+ visitRecordHeader(ctx) {
439
+ const params = [];
440
+ const body = ctx.recordComponentList()?.recordComponent().map(c => {
441
+ const type = this.visit(c.typeType());
442
+ const id = this.visit(c.identifier());
443
+ params.push(UAST.variableDeclaration(id, null, false, type));
444
+ const lhs = UAST.memberAccess(UAST.thisExpression(), id);
445
+ return UAST.assignmentExpression(lhs, id, '=');
446
+ }) || [];
447
+ const fdef = UAST.functionDefinition(UAST.identifier('__CTOR__'), params, UAST.primitiveType(UAST.identifier('void')), UAST.scopedStatement(body), []);
448
+ fdef._meta.isConstructor = true;
449
+ return [fdef];
450
+ }
451
+ // recordComponentList
452
+ // : recordComponent (',' recordComponent)*
453
+ // ;
454
+ visitRecordComponentList(ctx) {
455
+ return UAST.noop();
456
+ }
457
+ // recordComponent
458
+ // : typeType identifier
459
+ // ;
460
+ visitRecordComponent(ctx) {
461
+ return UAST.noop();
462
+ }
463
+ //recordBody
464
+ // : '{' (classBodyDeclaration | compactConstructorDeclaration)* '}'
465
+ visitRecordBody(ctx) {
466
+ const body = [];
467
+ ctx.classBodyDeclaration().forEach(d => {
468
+ const subBody = this.visit(d);
469
+ if (Array.isArray(subBody)) {
470
+ body.push(...subBody);
471
+ }
472
+ else {
473
+ body.push(subBody);
474
+ }
475
+ });
476
+ //compactConstructorDeclaration
477
+ // : modifier* identifier constructorBody=block
478
+ ctx.compactConstructorDeclaration().forEach(d => {
479
+ //TODO
480
+ });
481
+ return body;
482
+ }
483
+ // annotationTypeDeclaration
484
+ // : '@' INTERFACE identifier annotationTypeBody
485
+ visitAnnotationTypeDeclaration(ctx) {
486
+ const id = this.visit(ctx.identifier());
487
+ let body = ctx.annotationTypeBody().annotationTypeElementDeclaration().map(d => {
488
+ return this.visit(d);
489
+ });
490
+ body = _.flatten(body);
491
+ return UAST.classDefinition(id, body, []);
492
+ }
493
+ //annotationTypeElementDeclaration
494
+ // : modifier* annotationTypeElementRest
495
+ visitAnnotationTypeElementDeclaration(ctx) {
496
+ return this.visit(ctx.annotationTypeElementRest());
497
+ }
498
+ //annotationTypeElementRest
499
+ // : typeType annotationMethodOrConstantRest ';'
500
+ // | classDeclaration ';'?
501
+ // | interfaceDeclaration ';'?
502
+ // | enumDeclaration ';'?
503
+ // | annotationTypeDeclaration ';'?
504
+ // | recordDeclaration ';'? // Java17
505
+ visitAnnotationTypeElementRest(ctx) {
506
+ const typeCtx = ctx.typeType();
507
+ if (typeCtx) {
508
+ const leftType = this.visit(typeCtx);
509
+ this.typesState.push(leftType);
510
+ //annotationMethodOrConstantRest
511
+ // : annotationMethodRest
512
+ // | annotationConstantRest
513
+ const res = this.visit(ctx.annotationMethodOrConstantRest().children[0]);
514
+ this.typesState.pop();
515
+ return res;
516
+ }
517
+ else {
518
+ return this.visit(ctx.children[0]);
519
+ }
520
+ }
521
+ // annotationTypeBody
522
+ // : '{' (annotationTypeElementDeclaration)* '}'
523
+ // ;
524
+ visitAnnotationTypeBody(ctx) {
525
+ return UAST.noop();
526
+ }
527
+ // annotationMethodOrConstantRest
528
+ // : annotationMethodRest
529
+ // | annotationConstantRest
530
+ // ;
531
+ visitAnnotationMethodOrConstantRest(ctx) {
532
+ return UAST.noop();
533
+ }
534
+ //annotationMethodRest
535
+ // : identifier '(' ')' defaultValue?
536
+ visitAnnotationMethodRest(ctx) {
537
+ const type = this.typesState[this.typesState.length - 1];
538
+ return UAST.variableDeclaration(this.visit(ctx.identifier()), this.visit(ctx.defaultValue()?.elementValue()), false, type);
539
+ }
540
+ //annotationConstantRest
541
+ // : variableDeclarators
542
+ visitAnnotationConstantRest(ctx) {
543
+ return this.visit(ctx.variableDeclarators());
544
+ }
545
+ // defaultValue
546
+ // : DEFAULT elementValue
547
+ // ;
548
+ visitDefaultValue(ctx) {
549
+ return UAST.noop();
550
+ }
551
+ //elementValue
552
+ // : expression
553
+ // | annotation
554
+ // | elementValueArrayInitializer
555
+ visitElementValue(ctx) {
556
+ return this.visit(ctx.children[0]);
557
+ }
558
+ //annotation
559
+ // : ('@' qualifiedName | altAnnotationQualifiedName) ('(' ( elementValuePairs | elementValue )? ')')?
560
+ // will convert to
561
+ // (var annotationVarId = new qualifiedName(),annotationVar.a = expr1,annotationVar.b = expr2, annotationVar.id)
562
+ visitAnnotation(ctx) {
563
+ const qualifiedName = ctx.qualifiedName();
564
+ let qualifiedNameStr;
565
+ if (qualifiedName) {
566
+ qualifiedNameStr = toText(qualifiedName);
567
+ }
568
+ else {
569
+ qualifiedNameStr = ctx.altAnnotationQualifiedName().identifier().map(n => toText(n)).join('.');
570
+ }
571
+ const annotationVarName = (function getLast(list) {
572
+ return list[list.length - 1];
573
+ }(qualifiedNameStr.split('.')));
574
+ const annotationVarId = UAST.identifier(annotationVarName);
575
+ const qualifiedExpr = convertToMemberAccess(qualifiedNameStr);
576
+ //var annotationVarId = new qualifiedName()
577
+ const varDecl = UAST.variableDeclaration(annotationVarId, UAST.newExpression(qualifiedExpr, []), false, UAST.scopedType(UAST.identifier(qualifiedNameStr), null));
578
+ if (ctx.elementValue() || ctx.elementValuePairs()) {
579
+ const expr = this.safeVisit(ctx.elementValue()) || this._visitElementValuePairs(ctx.elementValuePairs(), annotationVarId);
580
+ return UAST.sequence([varDecl, expr, varDecl.id]);
581
+ }
582
+ else {
583
+ return varDecl;
584
+ }
585
+ }
586
+ _visitElementValuePairs(ctx, varId) {
587
+ const body = ctx.elementValuePair().map(e => {
588
+ const rhs = this.visit(e.elementValue());
589
+ const lhs = UAST.memberAccess(varId, this.visit(e.identifier()));
590
+ return UAST.assignmentExpression(lhs, rhs, '=');
591
+ });
592
+ return UAST.scopedStatement(body);
593
+ }
594
+ // altAnnotationQualifiedName
595
+ // : (identifier DOT)* '@' identifier
596
+ // ;
597
+ visitAltAnnotationQualifiedName(ctx) {
598
+ return UAST.noop();
599
+ }
600
+ // elementValuePairs
601
+ // : elementValuePair (',' elementValuePair)*
602
+ // ;
603
+ visitElementValuePairs(ctx) {
604
+ return UAST.noop();
605
+ }
606
+ // elementValuePair
607
+ // : identifier '=' elementValue
608
+ // ;
609
+ visitElementValuePair(ctx) {
610
+ return UAST.noop();
611
+ }
612
+ //enumDeclaration
613
+ // : ENUM identifier (IMPLEMENTS typeList)? '{' enumConstants? ','? enumBodyDeclarations? '}'
614
+ visitEnumDeclaration(ctx) {
615
+ const typeListCtx = ctx.typeList();
616
+ const supers = this.safeVisit(ctx.typeList()) || [];
617
+ const id = this.visit(ctx.identifier());
618
+ // important! enumBodyDeclarations should be processed before enumConstants
619
+ const body = [];
620
+ const bodyDeclarations = ctx.enumBodyDeclarations();
621
+ if (bodyDeclarations) {
622
+ bodyDeclarations.classBodyDeclaration().forEach(d => {
623
+ const member = this.visit(d);
624
+ if (Array.isArray(member)) {
625
+ body.push(...member);
626
+ }
627
+ else {
628
+ body.push(member);
629
+ }
630
+ });
631
+ }
632
+ //enumConstants
633
+ const enumConstantsCtx = ctx.enumConstants();
634
+ if (enumConstantsCtx) {
635
+ const constBody = this._visitEnumConstants(enumConstantsCtx, id);
636
+ body.push(...constBody);
637
+ }
638
+ return UAST.classDefinition(id, body, supers);
639
+ }
640
+ // enumConstants
641
+ // : enumConstant (',' enumConstant)*
642
+ // ;
643
+ visitEnumConstants(ctx) {
644
+ return UAST.noop();
645
+ }
646
+ // enumConstant
647
+ // : annotation* identifier arguments? classBody?
648
+ // ;
649
+ visitEnumConstant(ctx) {
650
+ return UAST.noop();
651
+ }
652
+ //enumConstants
653
+ // : enumConstant (',' enumConstant)*
654
+ //enumConstant
655
+ //: annotation* identifier arguments? classBody?
656
+ // will convert to
657
+ // public static enumType id = new (class <anonymous> extends superId { classBody })(arguments)
658
+ _visitEnumConstants(ctx, superId) {
659
+ return ctx.enumConstant().map(e => {
660
+ const id = this.visit(e.identifier());
661
+ const body = this.visit(e.classBody()) || [];
662
+ const cdef = UAST.classDefinition(id, body, [superId]);
663
+ const args = this.visit(e.arguments()?.expressionList()) || [];
664
+ const varInit = UAST.newExpression(cdef, args);
665
+ varInit._meta.isEnumImpl = true;
666
+ return varInit;
667
+ });
668
+ }
669
+ // enumBodyDeclarations
670
+ // : ';' classBodyDeclaration*
671
+ // ;
672
+ visitEnumBodyDeclarations(ctx) {
673
+ return UAST.noop();
674
+ }
675
+ //typeList
676
+ // : typeType (',' typeType)*
677
+ visitTypeList(ctx) {
678
+ return ctx.typeType().map(t => {
679
+ const type = this.visit(t);
680
+ return typeToIdentifier(type);
681
+ });
682
+ }
683
+ // : '{' blockStatement* '}'
684
+ visitBlock(ctx) {
685
+ const body = [];
686
+ const node = UAST.scopedStatement(body);
687
+ ctx.blockStatement().forEach(b => {
688
+ const node = this.visit(b);
689
+ if (Array.isArray(node)) {
690
+ body.push(...node);
691
+ }
692
+ else {
693
+ body.push(node);
694
+ }
695
+ });
696
+ return node;
697
+ }
698
+ //blockStatement
699
+ // : localVariableDeclaration ';'
700
+ // | localTypeDeclaration
701
+ // | statement
702
+ visitBlockStatement(ctx) {
703
+ return this.visit(ctx.children[0]);
704
+ }
705
+ //localVariableDeclaration
706
+ // : variableModifier* (VAR identifier '=' expression | typeType variableDeclarators)
707
+ //TODO variableModifier
708
+ visitLocalVariableDeclaration(ctx) {
709
+ const idCtx = ctx.identifier();
710
+ if (idCtx) {
711
+ // var case, e.g. var a = expr;
712
+ const expr = this.visit(ctx.expression());
713
+ const id = this.visit(idCtx);
714
+ return UAST.variableDeclaration(id, expr, false, UAST.dynamicType());
715
+ }
716
+ else {
717
+ // typeType case
718
+ const leftType = this.visit(ctx.typeType());
719
+ this.typesState.push(leftType);
720
+ const node = this.visit(ctx.variableDeclarators());
721
+ this.typesState.pop();
722
+ return node;
723
+ }
724
+ }
725
+ //statement
726
+ // : blockLabel=block
727
+ // | ASSERT expression (':' expression)? ';'
728
+ // | IF parExpression statement (ELSE statement)?
729
+ // | FOR '(' forControl ')' statement
730
+ // | WHILE parExpression statement
731
+ // | DO statement WHILE parExpression ';'
732
+ // | TRY block (catchClause+ finallyBlock? | finallyBlock)
733
+ // | TRY resourceSpecification block catchClause* finallyBlock?
734
+ // | SWITCH parExpression '{' switchBlockStatementGroup* switchLabel* '}'
735
+ // | SYNCHRONIZED parExpression block
736
+ // | RETURN expression? ';'
737
+ // | THROW expression ';'
738
+ // | BREAK identifier? ';'
739
+ // | CONTINUE identifier? ';'
740
+ // | YIELD expression ';' // Java17
741
+ // | SEMI
742
+ // | statementExpression=expression ';'
743
+ // | switchExpression ';'? // Java17
744
+ // | identifierLabel=identifier ':' statement
745
+ visitStatement(ctx) {
746
+ if (ctx._blockLabel) {
747
+ return this.visit(ctx._blockLabel);
748
+ }
749
+ if (ctx.ASSERT()) {
750
+ return this._visitAssertStatement(ctx.expression());
751
+ }
752
+ // | IF parExpression statement (ELSE statement)?
753
+ if (ctx.IF()) {
754
+ return this._visitIfStatement(ctx.parExpression(), ctx.statement());
755
+ }
756
+ if (ctx.FOR()) {
757
+ return this._visitForStatement(ctx.forControl(), ctx.statement());
758
+ }
759
+ // | WHILE parExpression statement
760
+ if (ctx.WHILE()) {
761
+ return this._visitWhileStatement(ctx.parExpression(), ctx.statement());
762
+ }
763
+ // | DO statement WHILE parExpression ';'
764
+ if (ctx.DO()) {
765
+ return this._visitDoStatement(ctx.statement(), ctx.parExpression());
766
+ }
767
+ // TRY block (catchClause+ finallyBlock? | finallyBlock)
768
+ // TRY resourceSpecification block catchClause* finallyBlock?
769
+ if (ctx.TRY()) {
770
+ const res = this._visitTryStatement(ctx.block(), ctx.catchClause(), ctx.finallyBlock());
771
+ const resourceSpecificationCtx = ctx.resourceSpecification();
772
+ if (resourceSpecificationCtx) {
773
+ const seq = this.visit(resourceSpecificationCtx.resources());
774
+ if (res.body.type === 'ScopedStatement') {
775
+ res.body.body.unshift(seq);
776
+ }
777
+ else {
778
+ const blockStmt = UAST.scopedStatement([seq, res.body]);
779
+ res.body = blockStmt;
780
+ }
781
+ res.body._meta.hasResources = true;
782
+ }
783
+ return res;
784
+ }
785
+ // SWITCH parExpression '{' switchBlockStatementGroup* switchLabel* '}'
786
+ if (ctx.SWITCH()) {
787
+ return this._visitSwitchStatement(ctx.parExpression(), ctx.switchBlockStatementGroup(), ctx.switchLabel());
788
+ }
789
+ // | SYNCHRONIZED parExpression block
790
+ if (ctx.SYNCHRONIZED()) {
791
+ return this.visitSynchronizedStatement(ctx.parExpression(), ctx.block());
792
+ }
793
+ // | RETURN expression? ';'
794
+ if (ctx.RETURN()) {
795
+ return this._visitReturnStatement(ctx.expression());
796
+ }
797
+ // | THROW expression ';'
798
+ if (ctx.THROW()) {
799
+ return this._visitThrowStatement(ctx.expression());
800
+ }
801
+ // | BREAK identifier? ';'
802
+ if (ctx.BREAK()) {
803
+ return this._visitBreakStatement(ctx.identifier());
804
+ }
805
+ // | CONTINUE identifier? ';'
806
+ if (ctx.CONTINUE()) {
807
+ return this._visitContinueStatement(ctx.identifier());
808
+ }
809
+ // | YIELD expression ';' // Java17
810
+ if (ctx.YIELD()) {
811
+ return this._visitYieldStatement(ctx.expression());
812
+ }
813
+ // | statementExpression=expression ';'
814
+ if (ctx._statementExpression) {
815
+ return this._visitStatementExpression(ctx._statementExpression);
816
+ }
817
+ // | switchExpression ';'? // Java17
818
+ if (ctx.switchExpression()) {
819
+ return this.visit(ctx.switchExpression());
820
+ }
821
+ // | identifierLabel=identifier ':' statement
822
+ if (ctx._identifierLabel) {
823
+ const stmt = this.visit(ctx.statement()[0]);
824
+ const id = this.visit(ctx._identifierLabel);
825
+ return UAST.scopedStatement([stmt], id);
826
+ }
827
+ // | SEMI
828
+ if (ctx.SEMI()) {
829
+ return UAST.noop();
830
+ }
831
+ }
832
+ // | ASSERT expression (':' expression)? ';'
833
+ _visitAssertStatement(expressionContexts) {
834
+ const args = expressionContexts.map(e => this.visit(e));
835
+ return UAST.callExpression(UAST.identifier('assert'), args);
836
+ }
837
+ _visitIfStatement(parExpressionContext, statementContexts) {
838
+ const test = this.visit(parExpressionContext);
839
+ const consequent = this.visit(statementContexts[0]);
840
+ let alternative;
841
+ if (statementContexts.length > 1) {
842
+ alternative = this.visit(statementContexts[1]);
843
+ }
844
+ return UAST.ifStatement(test, consequent, alternative);
845
+ }
846
+ _visitForStatement(forControlContext, statementContexts) {
847
+ //forControl
848
+ // : enhancedForControl
849
+ // | forInit? ';' expression? ';' forUpdate=expressionList?
850
+ if (!forControlContext.enhancedForControl()) {
851
+ let init;
852
+ let test;
853
+ let update;
854
+ const initCtx = forControlContext.forInit();
855
+ if (initCtx) {
856
+ init = this.visit(initCtx);
857
+ }
858
+ const testCtx = forControlContext.expression();
859
+ if (testCtx) {
860
+ test = this.visit(testCtx);
861
+ }
862
+ const updateCtx = forControlContext._forUpdate;
863
+ if (updateCtx) {
864
+ const updateList = this.visit(updateCtx);
865
+ if (updateList.length === 1) {
866
+ update = updateList[0];
867
+ }
868
+ else {
869
+ update = UAST.sequence(updateList);
870
+ }
871
+ }
872
+ const body = this.visit(statementContexts[0]);
873
+ return UAST.forStatement(init, test, update, body);
874
+ }
875
+ else {
876
+ // range statement
877
+ //enhancedForControl
878
+ // : variableModifier* (typeType | VAR) variableDeclaratorId ':' expression
879
+ const enhancedForControl = forControlContext.enhancedForControl();
880
+ let type;
881
+ if (enhancedForControl.VAR()) {
882
+ type = UAST.dynamicType();
883
+ }
884
+ else {
885
+ type = this.visit(enhancedForControl.typeType());
886
+ }
887
+ this.typesState.push(type);
888
+ const value = this.visit(enhancedForControl.variableDeclaratorId());
889
+ this.typesState.pop(); // for variableDeclaratorId
890
+ this.typesState.pop();
891
+ const right = this.visit(enhancedForControl.expression());
892
+ const body = this.visit(statementContexts[0]);
893
+ return UAST.rangeStatement(null, value, right, body);
894
+ }
895
+ }
896
+ // forControl
897
+ // : enhancedForControl
898
+ // | forInit? ';' expression? ';' forUpdate=expressionList?
899
+ // ;
900
+ visitForControl(ctx) {
901
+ return UAST.noop();
902
+ }
903
+ // enhancedForControl
904
+ // : variableModifier* (typeType | VAR) variableDeclaratorId ':' expression
905
+ // ;
906
+ visitEnhancedForControl(ctx) {
907
+ return UAST.noop();
908
+ }
909
+ // forInit
910
+ // : localVariableDeclaration
911
+ // | expressionList
912
+ // ;
913
+ visitForInit(ctx) {
914
+ const localVariableDeclaration = ctx.localVariableDeclaration();
915
+ if (localVariableDeclaration) {
916
+ const varList = this.visit(localVariableDeclaration);
917
+ if (Array.isArray(varList)) {
918
+ return UAST.sequence(varList);
919
+ }
920
+ else {
921
+ return varList;
922
+ }
923
+ }
924
+ else {
925
+ const seq = this.visit(ctx.expressionList());
926
+ if (seq.length > 1) {
927
+ return UAST.sequence(this.visit(ctx.expressionList()));
928
+ }
929
+ else if (seq.length === 1) {
930
+ return seq[0];
931
+ }
932
+ else {
933
+ return UAST.noop();
934
+ }
935
+ }
936
+ }
937
+ _visitWhileStatement(parExpressionContext, statementContexts) {
938
+ return this._visitWhileStatementInner(parExpressionContext, statementContexts, false);
939
+ }
940
+ _visitDoStatement(statementContexts, parExpressionContext) {
941
+ return this._visitWhileStatementInner(parExpressionContext, statementContexts, true);
942
+ }
943
+ _visitWhileStatementInner(parExpressionContext, statementContexts, isPost) {
944
+ const test = this.visit(parExpressionContext);
945
+ const body = this.visit(statementContexts[0]);
946
+ return UAST.whileStatement(test, body, isPost);
947
+ }
948
+ //resources
949
+ // : resource (';' resource)*
950
+ // ;
951
+ //
952
+ visitResources(resourcesCtx) {
953
+ const seqBody = [];
954
+ const seq = UAST.sequence(seqBody);
955
+ resourcesCtx.resource().map(resource => {
956
+ const qualifiedName = resource.qualifiedName();
957
+ if (qualifiedName) {
958
+ seqBody.push(convertToMemberAccess(toText(qualifiedName)));
959
+ }
960
+ else {
961
+ const identifier = (this.visit(resource.identifier()) || this.visit(resource.variableDeclaratorId()));
962
+ const varDecl = UAST.variableDeclaration(identifier, this.visit(resource.expression()), false, UAST.dynamicType());
963
+ seqBody.push(varDecl);
964
+ }
965
+ });
966
+ return seq;
967
+ }
968
+ // resource
969
+ // : variableModifier* ( classOrInterfaceType variableDeclaratorId | VAR identifier ) '=' expression
970
+ // | qualifiedName
971
+ // ;
972
+ visitResource(ctx) {
973
+ return UAST.noop();
974
+ }
975
+ //TRY block (catchClause+ finallyBlock? | finallyBlock)
976
+ _visitTryStatement(blockContext, catchClauseContexts, finallyBlockContext) {
977
+ const body = this.visit(blockContext);
978
+ let handlers;
979
+ if (catchClauseContexts) {
980
+ handlers = catchClauseContexts?.map(c => this.visit(c));
981
+ }
982
+ let _finally;
983
+ if (finallyBlockContext) {
984
+ _finally = this.visit(finallyBlockContext);
985
+ }
986
+ return UAST.tryStatement(body, handlers, _finally);
987
+ }
988
+ //catchClause
989
+ // : CATCH '(' variableModifier* catchType identifier ')' block
990
+ visitCatchClause(ctx) {
991
+ const qualifiedName = toText(ctx.catchType());
992
+ const type = UAST.scopedType(UAST.identifier(qualifiedName), null);
993
+ const varId = this.visit(ctx.identifier());
994
+ const varDecl = UAST.variableDeclaration(varId, null, false, type);
995
+ const body = this.visit(ctx.block());
996
+ return UAST.catchClause([varDecl], body);
997
+ }
998
+ // catchType
999
+ // : qualifiedName ('|' qualifiedName)*
1000
+ // ;
1001
+ visitCatchType(ctx) {
1002
+ return UAST.noop();
1003
+ }
1004
+ //finallyBlock
1005
+ // : FINALLY block
1006
+ visitFinallyBlock(ctx) {
1007
+ return this.visit(ctx.block());
1008
+ }
1009
+ // resourceSpecification
1010
+ // : '(' resources ';'? ')'
1011
+ // ;
1012
+ visitResourceSpecification(ctx) {
1013
+ return UAST.noop();
1014
+ }
1015
+ //SWITCH parExpression '{' switchBlockStatementGroup* switchLabel* '}'
1016
+ _visitSwitchStatement(parExpressionContext, switchBlockStatementGroupContexts, switchLabelContexts) {
1017
+ const discriminant = this.visit(parExpressionContext);
1018
+ const cases = switchBlockStatementGroupContexts.map(s => this.visit(s));
1019
+ return UAST.switchStatement(discriminant, cases);
1020
+ }
1021
+ //switchBlockStatementGroup
1022
+ // : switchLabel+ blockStatement+
1023
+ // TODO
1024
+ visitSwitchBlockStatementGroup(ctx) {
1025
+ const switchLabels = ctx.switchLabel();
1026
+ const blocks = ctx.blockStatement();
1027
+ const stmts = _.flatten(blocks.map(b => this.visit(b)));
1028
+ const body = UAST.scopedStatement(stmts);
1029
+ const cases = switchLabels.map(s => {
1030
+ return this.visit(s);
1031
+ });
1032
+ let test;
1033
+ cases.forEach(c => {
1034
+ if (!test) {
1035
+ test = c;
1036
+ }
1037
+ else {
1038
+ test = UAST.binaryExpression('|', test, c);
1039
+ }
1040
+ });
1041
+ return UAST.caseClause(test, body);
1042
+ }
1043
+ //switchLabel
1044
+ // : CASE (constantExpression=expression | enumConstantName=IDENTIFIER | typeType varName=identifier) ':'
1045
+ // | DEFAULT ':'
1046
+ visitSwitchLabel(ctx) {
1047
+ if (ctx.DEFAULT()) {
1048
+ return UAST.noop();
1049
+ }
1050
+ else if (ctx.typeType()) {
1051
+ const type = this.visit(ctx.typeType());
1052
+ const varId = this.visit(ctx._varName);
1053
+ return UAST.variableDeclaration(varId, null, false, type);
1054
+ }
1055
+ else if (ctx._constantExpression) {
1056
+ return this.visit(ctx._constantExpression);
1057
+ }
1058
+ else {
1059
+ //TODO
1060
+ return UAST.identifier('TODO');
1061
+ }
1062
+ }
1063
+ visitSynchronizedStatement(parExpressionContext, blockContext) {
1064
+ const block = this.visit(blockContext);
1065
+ const callExpr = UAST.callExpression(UAST.identifier('synchronized'), [this.visit(parExpressionContext)]);
1066
+ block.body.unshift(callExpr);
1067
+ block._meta.isSynchronized = true;
1068
+ return block;
1069
+ }
1070
+ _visitReturnStatement(expressionContexts) {
1071
+ let expr;
1072
+ if (expressionContexts) {
1073
+ expr = this.safeVisit(expressionContexts[0]);
1074
+ }
1075
+ return UAST.returnStatement(expr);
1076
+ }
1077
+ _visitThrowStatement(expressionContexts) {
1078
+ const expr = this.visit(expressionContexts[0]);
1079
+ return UAST.throwStatement(expr);
1080
+ }
1081
+ _visitBreakStatement(identifierContext) {
1082
+ let id;
1083
+ if (identifierContext) {
1084
+ id = this.visit(identifierContext);
1085
+ }
1086
+ return UAST.breakStatement(id);
1087
+ }
1088
+ _visitContinueStatement(identifierContext) {
1089
+ let id;
1090
+ if (identifierContext) {
1091
+ id = this.visit(identifierContext);
1092
+ }
1093
+ return UAST.continueStatement(id);
1094
+ }
1095
+ // | YIELD expression ';' // Java17
1096
+ _visitYieldStatement(expressionContexts) {
1097
+ const expr = this.visit(expressionContexts[0]);
1098
+ return UAST.returnStatement(expr, true);
1099
+ }
1100
+ _visitStatementExpression(_statementExpression) {
1101
+ const expr = this.visit(_statementExpression);
1102
+ return expr;
1103
+ }
1104
+ //formalParameters
1105
+ // : '(' ( receiverParameter?
1106
+ // | receiverParameter (',' formalParameterList)?
1107
+ // | formalParameterList?
1108
+ // ) ')'
1109
+ visitFormalParameters(ctx) {
1110
+ return this.safeVisit(ctx.formalParameterList()) || [];
1111
+ }
1112
+ //formalParameterList
1113
+ // : formalParameter (',' formalParameter)* (',' lastFormalParameter)?
1114
+ // | lastFormalParameter
1115
+ visitFormalParameterList(ctx) {
1116
+ const params = ctx.formalParameter().map(p => {
1117
+ return this.visit(p);
1118
+ });
1119
+ const lastFormalParameter = ctx.lastFormalParameter();
1120
+ if (lastFormalParameter) {
1121
+ params.push(this.visit(ctx.lastFormalParameter()));
1122
+ }
1123
+ return params;
1124
+ }
1125
+ //lastFormalParameter
1126
+ // : variableModifier* typeType annotation* '...' variableDeclaratorId
1127
+ visitLastFormalParameter(ctx) {
1128
+ const leftType = this.visit(ctx.typeType());
1129
+ this.typesState.push(leftType);
1130
+ const varId = this.visit(ctx.variableDeclaratorId());
1131
+ const type = this.typesState.pop();
1132
+ const node = UAST.variableDeclaration(varId, null, false, type);
1133
+ this.typesState.pop();
1134
+ if (ctx.ELLIPSIS()) {
1135
+ node._meta.rest = true;
1136
+ }
1137
+ return node;
1138
+ }
1139
+ //formalParameter
1140
+ // : variableModifier* typeType variableDeclaratorId
1141
+ // TODO variableModifier
1142
+ visitFormalParameter(ctx) {
1143
+ const leftType = this.visit(ctx.typeType());
1144
+ this.typesState.push(leftType);
1145
+ const varId = this.visit(ctx.variableDeclaratorId());
1146
+ const type = this.typesState.pop();
1147
+ const node = UAST.variableDeclaration(varId, null, false, type);
1148
+ this.typesState.pop();
1149
+ return node;
1150
+ }
1151
+ //variableDeclarators
1152
+ // : variableDeclarator (',' variableDeclarator)*
1153
+ visitVariableDeclarators(ctx) {
1154
+ const decls = ctx.variableDeclarator();
1155
+ return decls.map(d => this.visit(d));
1156
+ }
1157
+ //variableDeclarator
1158
+ // : variableDeclaratorId ('=' variableInitializer)?
1159
+ visitVariableDeclarator(ctx) {
1160
+ const varidCtx = ctx.variableDeclaratorId();
1161
+ const varid = this.visit(varidCtx);
1162
+ const initCtx = ctx.variableInitializer();
1163
+ let init;
1164
+ if (initCtx) {
1165
+ init = this.visit(initCtx);
1166
+ }
1167
+ const type = this.typesState.pop();
1168
+ return UAST.variableDeclaration(varid, init, false, type);
1169
+ }
1170
+ //variableDeclaratorId
1171
+ // : identifier ('[' ']')*
1172
+ // !important always remember pop typesState after visitVariableDeclaratorId!
1173
+ visitVariableDeclaratorId(ctx) {
1174
+ const type = this.typesState[this.typesState.length - 1];
1175
+ const arrayDimension = ctx.LBRACK()?.length;
1176
+ //TODO Array type
1177
+ this.typesState.push(type);
1178
+ return this.visit(ctx.identifier());
1179
+ }
1180
+ // EXPRESSIONS
1181
+ visitExpression(ctx) {
1182
+ const primary = ctx.primary();
1183
+ if (primary) {
1184
+ return this.visit(primary);
1185
+ }
1186
+ // | expression ('<' '<' | '>' '>' '>' | '>' '>') expression
1187
+ function tryGetShiftString(ctx) {
1188
+ if (ctx.GT().length === 2)
1189
+ return '>>';
1190
+ else if (ctx.GT().length === 3)
1191
+ return '>>>';
1192
+ else if (ctx.LT().length === 2)
1193
+ return '<<';
1194
+ else
1195
+ return undefined;
1196
+ }
1197
+ const bopText = tryGetShiftString(ctx);
1198
+ if (bopText) {
1199
+ const left = this.visit(ctx.expression()[0]);
1200
+ const right = this.visit(ctx.expression()[1]);
1201
+ // @ts-ignore
1202
+ return UAST.binaryExpression(bopText, left, right);
1203
+ }
1204
+ const bop = ctx._bop;
1205
+ if (bop) {
1206
+ const bopText = toText(bop);
1207
+ if (bopText === '.') {
1208
+ // e.g. a.b
1209
+ // member access
1210
+ const object = this.visit(ctx.expression()[0]);
1211
+ const identifier = ctx.identifier();
1212
+ const methodCall = ctx.methodCall();
1213
+ const explicitGenericInvocationCtx = ctx.explicitGenericInvocation();
1214
+ if (identifier) {
1215
+ const property = this.visit(identifier);
1216
+ return UAST.memberAccess(object, property, false);
1217
+ }
1218
+ else if (methodCall) {
1219
+ const call = this.visit(methodCall);
1220
+ const callee = call.callee;
1221
+ call.callee = UAST.memberAccess(object, callee, false);
1222
+ return call;
1223
+ }
1224
+ else if (explicitGenericInvocationCtx) {
1225
+ //explicitGenericInvocation
1226
+ const { object: prop, expression, args } = this._visitExplicitGenericInvocationSuffix(explicitGenericInvocationCtx.explicitGenericInvocationSuffix());
1227
+ const callee = prop ? UAST.memberAccess(UAST.memberAccess(object, prop), expression) : UAST.memberAccess(object, expression);
1228
+ return UAST.callExpression(callee, args);
1229
+ }
1230
+ else if (ctx.SUPER()) {
1231
+ //SUPER superSuffix
1232
+ const { expression, args } = this._visitSuperSuffix(ctx.superSuffix());
1233
+ if (expression) {
1234
+ return UAST.callExpression(UAST.memberAccess(UAST.superExpression(), expression), args);
1235
+ }
1236
+ else {
1237
+ return UAST.callExpression(UAST.superExpression(), args);
1238
+ }
1239
+ }
1240
+ else if (ctx.THIS()) {
1241
+ return UAST.memberAccess(object, UAST.thisExpression());
1242
+ }
1243
+ else if (ctx.NEW()) {
1244
+ // expression . NEW nonWildcardTypeArguments? innerCreator
1245
+ const prop = ctx.innerCreator().identifier();
1246
+ const argumentsCtx = ctx.innerCreator().classCreatorRest().arguments();
1247
+ const classBodyCtx = ctx.innerCreator().classCreatorRest().classBody();
1248
+ let args = [];
1249
+ const exprListCtx = argumentsCtx.expressionList();
1250
+ if (exprListCtx) {
1251
+ args = this.visit(exprListCtx);
1252
+ }
1253
+ if (!classBodyCtx) {
1254
+ return UAST.newExpression(UAST.memberAccess(object, this.visit(prop)), args);
1255
+ }
1256
+ else {
1257
+ // TODO new Foo.new Bar(){ //... }
1258
+ return UAST.newExpression(UAST.memberAccess(object, this.visit(prop)), args);
1259
+ }
1260
+ }
1261
+ else {
1262
+ throw new Error(`type ${toText(ctx)} is not supported`);
1263
+ }
1264
+ }
1265
+ // binary
1266
+ // | expression bop=('*'|'/'|'%') expression
1267
+ // | expression bop=('+'|'-') expression
1268
+ // | expression ('<' '<' | '>' '>' '>' | '>' '>') expression
1269
+ // | expression bop=('<=' | '>=' | '>' | '<') expression
1270
+ // | expression bop=INSTANCEOF (typeType | pattern)
1271
+ // | expression bop=('==' | '!=') expression
1272
+ // | expression bop='&' expression
1273
+ // | expression bop='^' expression
1274
+ // | expression bop='|' expression
1275
+ // | expression bop='&&' expression
1276
+ // | expression bop='||' expression
1277
+ // | <assoc=right> expression
1278
+ // bop=('=' | '+=' | '-=' | '*=' | '/=' | '&=' | '|=' | '^=' | '>>=' | '>>>=' | '<<=' | '%=')
1279
+ // expression
1280
+ else if (['*', '/', '%', '+', '-', '<=', '>=', '>', '<', '>>', '<<', '==', '!=', '&', '|', '^', '&&', '||'].indexOf(bopText) !== -1) {
1281
+ // e.g. a*b
1282
+ const left = this.visit(ctx.expression()[0]);
1283
+ const right = this.visit(ctx.expression()[1]);
1284
+ // @ts-ignore
1285
+ return UAST.binaryExpression(bopText, left, right);
1286
+ }
1287
+ else if (['=', '^=', '&=', '<<=', '>>=', '>>>=', '+=', '-=', '*=', '/=', '%=', ',=', '**=', '|='].indexOf(bopText) !== -1) {
1288
+ // e.g. a=b
1289
+ const left = this.visit(ctx.expression()[0]);
1290
+ const right = this.visit(ctx.expression()[1]);
1291
+ // @ts-ignore
1292
+ return UAST.assignmentExpression(left, right, bopText);
1293
+ }
1294
+ else if (bopText === 'instanceof') {
1295
+ const left = this.visit(ctx.expression()[0]);
1296
+ if (!ctx.pattern()) {
1297
+ const right = this.visit(ctx.typeType()[0]);
1298
+ return UAST.binaryExpression('instanceof', left, ('id' in right && right.id) || ('name' in right && right));
1299
+ }
1300
+ else {
1301
+ const patternCtx = ctx.pattern();
1302
+ const type = this.visit(patternCtx.typeType());
1303
+ const id = this.visit(patternCtx.identifier());
1304
+ const varDecl = UAST.variableDeclaration(id, left, false, type);
1305
+ const seqBody = [varDecl, UAST.binaryExpression('instanceof', left, id)];
1306
+ return UAST.sequence(seqBody);
1307
+ }
1308
+ }
1309
+ else if (bopText === '?') {
1310
+ //ternary e.g. a? b: c
1311
+ // | <assoc=right> expression bop='?' expression ':' expression
1312
+ const test = this.visit(ctx.expression()[0]);
1313
+ const cons = this.visit(ctx.expression()[1]);
1314
+ const alt = this.visit(ctx.expression()[2]);
1315
+ return UAST.conditionalExpression(test, cons, alt);
1316
+ }
1317
+ }
1318
+ // a[b]
1319
+ if (ctx.children[1] && toText(ctx.children[1]) === '[') {
1320
+ const object = this.visit(ctx.children[0]);
1321
+ const property = this.visit(ctx.children[2]);
1322
+ return UAST.memberAccess(object, property, true);
1323
+ }
1324
+ // methodCall
1325
+ const methodCall = ctx.methodCall();
1326
+ if (methodCall) {
1327
+ return this.visit(methodCall);
1328
+ }
1329
+ // new creator
1330
+ const creator = ctx.creator();
1331
+ if (creator) {
1332
+ return this.visit(creator);
1333
+ }
1334
+ // cast
1335
+ // | '(' annotation* typeType ('&' typeType)* ')' expression
1336
+ if (toText(ctx.children[0]) === '(') {
1337
+ //TODO handle multi typeType
1338
+ const typeTypeCtx = ctx.typeType();
1339
+ const type = this.visit(typeTypeCtx[0]);
1340
+ const expr = this.visit(ctx.expression()[0]);
1341
+ return UAST.castExpression(expr, type);
1342
+ }
1343
+ // unary
1344
+ // | expression postfix=('++' | '--')
1345
+ // | prefix=('+'|'-'|'++'|'--') expression
1346
+ // | prefix=('~'|'!') expression
1347
+ if (ctx._postfix) {
1348
+ return UAST.unaryExpression(toText(ctx._postfix), this.visit(ctx.expression()[0]), true);
1349
+ }
1350
+ if (ctx._prefix) {
1351
+ return UAST.unaryExpression(toText(ctx._prefix), this.visit(ctx.expression()[0]), false);
1352
+ }
1353
+ // | lambdaExpression // Java8
1354
+ const lambdaExpressionCtx = ctx.lambdaExpression();
1355
+ if (lambdaExpressionCtx) {
1356
+ return this.visit(lambdaExpressionCtx);
1357
+ }
1358
+ // | switchExpression // Java17
1359
+ const switchExpressionCtx = ctx.switchExpression();
1360
+ if (switchExpressionCtx) {
1361
+ return this.visit(switchExpressionCtx);
1362
+ }
1363
+ //
1364
+ // // Java 8 methodReference
1365
+ // | expression '::' typeArguments? identifier
1366
+ // | typeType '::' (typeArguments? identifier | NEW)
1367
+ // | classType '::' typeArguments? NEW
1368
+ const methodReference = ctx.children[1] ? toText(ctx.children[1]) : null;
1369
+ if (methodReference === '::') {
1370
+ const expressionCtx = ctx.expression();
1371
+ const typeCtx = ctx.typeType() ? ctx.typeType()[0] : null;
1372
+ const classTypeCtx = ctx.classType();
1373
+ if (typeCtx) {
1374
+ // typeType '::' (typeArguments? identifier | NEW)
1375
+ const type = this.visit(typeCtx);
1376
+ const object = convertToMemberAccess(('id' in type && type.id.name) || ('name' in type && type.name));
1377
+ let prop;
1378
+ if (ctx.NEW()) {
1379
+ prop = UAST.identifier('_CTOR_');
1380
+ }
1381
+ else {
1382
+ prop = this.visit(ctx.identifier());
1383
+ }
1384
+ return UAST.memberAccess(object, prop);
1385
+ }
1386
+ else if (classTypeCtx) {
1387
+ // classType '::' typeArguments? NEW
1388
+ const type = this.visit(classTypeCtx);
1389
+ return UAST.memberAccess(convertToMemberAccess(('id' in type && type.id.name) || ('name' in type && type.name)), UAST.identifier('_CTOR_'));
1390
+ }
1391
+ else {
1392
+ // expression '::' typeArguments? identifier
1393
+ const object = this.visit(expressionCtx[0]);
1394
+ const prop = this.visit(ctx.identifier());
1395
+ return UAST.memberAccess(object, prop);
1396
+ }
1397
+ }
1398
+ }
1399
+ //// Java8
1400
+ // lambdaExpression
1401
+ // : lambdaParameters '->' lambdaBody
1402
+ visitLambdaExpression(ctx) {
1403
+ // lambdaParameters
1404
+ // : identifier
1405
+ // | '(' formalParameterList? ')'
1406
+ // | '(' identifier (',' identifier)* ')'
1407
+ // | '(' lambdaLVTIList? ')'
1408
+ let params;
1409
+ const lambdaParametersCtx = ctx.lambdaParameters();
1410
+ const idsCtx = lambdaParametersCtx.identifier();
1411
+ const id = this.safeVisit(idsCtx.shift());
1412
+ const formalParameterListCtx = lambdaParametersCtx.formalParameterList();
1413
+ if (idsCtx.length !== 0) {
1414
+ params = idsCtx.map(idCtx => {
1415
+ const id = this.visit(idCtx);
1416
+ return UAST.variableDeclaration(id, null, false, UAST.dynamicType());
1417
+ });
1418
+ }
1419
+ else if (formalParameterListCtx) {
1420
+ params = this.visit(formalParameterListCtx);
1421
+ }
1422
+ else {
1423
+ const lambdaLVTIListCtx = lambdaParametersCtx.lambdaLVTIList();
1424
+ if (lambdaLVTIListCtx) {
1425
+ params = lambdaLVTIListCtx.lambdaLVTIParameter().map(pCtx => {
1426
+ const id = this.visit(pCtx.identifier());
1427
+ return UAST.variableDeclaration(id, null, false, UAST.dynamicType());
1428
+ });
1429
+ }
1430
+ else {
1431
+ params = [];
1432
+ }
1433
+ }
1434
+ //lambdaBody
1435
+ // : expression
1436
+ // | block
1437
+ const lambdaBodyCtx = ctx.lambdaBody();
1438
+ const exprCtx = lambdaBodyCtx.expression();
1439
+ if (exprCtx) {
1440
+ return UAST.functionDefinition(id, params, UAST.dynamicType(), UAST.scopedStatement([this.visit(exprCtx)], null), []);
1441
+ }
1442
+ else {
1443
+ return UAST.functionDefinition(id, params, UAST.dynamicType(), this.visit(lambdaBodyCtx.block()), []);
1444
+ }
1445
+ }
1446
+ // lambdaLVTIList
1447
+ // : lambdaLVTIParameter (',' lambdaLVTIParameter)*
1448
+ // ;
1449
+ visitLambdaLVTIList(ctx) {
1450
+ return UAST.noop();
1451
+ }
1452
+ // lambdaLVTIParameter
1453
+ // : variableModifier* VAR identifier
1454
+ // ;
1455
+ visitLambdaLVTIParameter(ctx) {
1456
+ return UAST.noop();
1457
+ }
1458
+ // lambdaParameters
1459
+ // : identifier
1460
+ // | '(' formalParameterList? ')'
1461
+ // | '(' identifier (',' identifier)* ')'
1462
+ // | '(' lambdaLVTIList? ')'
1463
+ // ;
1464
+ visitLambdaParameters(ctx) {
1465
+ return UAST.noop();
1466
+ }
1467
+ // lambdaBody
1468
+ // : expression
1469
+ // | block
1470
+ // ;
1471
+ visitLambdaBody(ctx) {
1472
+ return UAST.noop();
1473
+ }
1474
+ // qualifiedName
1475
+ // : identifier ('.' identifier)*
1476
+ // ;
1477
+ visitQualifiedName(ctx) {
1478
+ return UAST.noop();
1479
+ }
1480
+ // pattern
1481
+ // : variableModifier* typeType annotation* identifier
1482
+ // ;
1483
+ visitPattern(ctx) {
1484
+ return UAST.noop();
1485
+ }
1486
+ //classType
1487
+ // : (classOrInterfaceType '.')? annotation* identifier typeArguments?
1488
+ visitClassType(ctx) {
1489
+ const classOrInterfaceTypeCtx = ctx.classOrInterfaceType();
1490
+ let scopeType;
1491
+ if (classOrInterfaceTypeCtx) {
1492
+ scopeType = this.visit(classOrInterfaceTypeCtx);
1493
+ }
1494
+ return UAST.scopedType(this.visit(ctx.identifier()), scopeType);
1495
+ }
1496
+ //creator
1497
+ // : nonWildcardTypeArguments createdName classCreatorRest
1498
+ // | createdName (arrayCreatorRest | classCreatorRest)
1499
+ visitCreator(ctx) {
1500
+ let ids;
1501
+ const primitiveTypeCtx = ctx.createdName().primitiveType();
1502
+ if (primitiveTypeCtx) {
1503
+ ids = this.visit(primitiveTypeCtx).id.name;
1504
+ }
1505
+ else {
1506
+ ids = ctx.createdName().identifier().map(id => toText(id));
1507
+ ids = ids.join('.');
1508
+ }
1509
+ const callee = convertToMemberAccess(ids);
1510
+ const arrayCreatorRest = ctx.arrayCreatorRest();
1511
+ const classCreatorRestCtx = ctx.classCreatorRest();
1512
+ if (classCreatorRestCtx) {
1513
+ const argumentsCtx = classCreatorRestCtx.arguments();
1514
+ const classBodyCtx = classCreatorRestCtx.classBody();
1515
+ let args = [];
1516
+ const exprListCtx = argumentsCtx.expressionList();
1517
+ if (exprListCtx) {
1518
+ args = this.visit(exprListCtx);
1519
+ }
1520
+ if (!classBodyCtx) {
1521
+ return UAST.newExpression(callee, args);
1522
+ }
1523
+ else {
1524
+ //new anonymous interface implementation
1525
+ // e.g. new Runnable() {...}
1526
+ const seq = UAST.sequence([]);
1527
+ const seqList = seq.expressions;
1528
+ const tmpVarDecl = (0, parser_1.createTmpVariableDeclaration)(UAST.newExpression(callee, args));
1529
+ seqList.push(tmpVarDecl);
1530
+ const body = this.visit(classBodyCtx);
1531
+ for (const decl of body) {
1532
+ // TODO block?
1533
+ if (decl.type === 'FunctionDefinition' || decl.type === 'VariableDeclaration') {
1534
+ seqList.push(UAST.assignmentExpression(UAST.memberAccess(tmpVarDecl.id, decl.id), decl, '='));
1535
+ }
1536
+ }
1537
+ seqList.push(tmpVarDecl.id);
1538
+ // const cdef = UAST.classDefinition(UAST.identifier(ids), body, []);
1539
+ // return UAST.newExpression(cdef, args);
1540
+ return seq;
1541
+ }
1542
+ }
1543
+ else {
1544
+ // array init
1545
+ // e.g. int[] a = new int(){1,2,3,4,5}
1546
+ const init = arrayCreatorRest.arrayInitializer();
1547
+ if (init) {
1548
+ return this.visit(init);
1549
+ }
1550
+ else {
1551
+ return UAST.newExpression(callee, []);
1552
+ }
1553
+ }
1554
+ }
1555
+ // createdName
1556
+ // : identifier typeArgumentsOrDiamond? ('.' identifier typeArgumentsOrDiamond?)*
1557
+ // | primitiveType
1558
+ // ;
1559
+ visitCreatedName(ctx) {
1560
+ return UAST.noop();
1561
+ }
1562
+ // innerCreator
1563
+ // : identifier nonWildcardTypeArgumentsOrDiamond? classCreatorRest
1564
+ // ;
1565
+ visitInnerCreator(ctx) {
1566
+ return UAST.noop();
1567
+ }
1568
+ // arrayCreatorRest
1569
+ // : '[' (']' ('[' ']')* arrayInitializer | expression ']' ('[' expression ']')* ('[' ']')*)
1570
+ // ;
1571
+ visitArrayCreatorRest(ctx) {
1572
+ return UAST.noop();
1573
+ }
1574
+ // classCreatorRest
1575
+ // : arguments classBody?
1576
+ // ;
1577
+ visitClassCreatorRest(ctx) {
1578
+ return UAST.noop();
1579
+ }
1580
+ // explicitGenericInvocation
1581
+ // : nonWildcardTypeArguments explicitGenericInvocationSuffix
1582
+ // ;
1583
+ visitExplicitGenericInvocation(ctx) {
1584
+ return UAST.noop();
1585
+ }
1586
+ // typeArgumentsOrDiamond java7
1587
+ // : '<' '>'
1588
+ // | typeArguments
1589
+ // ;
1590
+ //unused typeArgumentsOrDiamond
1591
+ visitTypeArgumentsOrDiamond(ctx) {
1592
+ return UAST.noop();
1593
+ }
1594
+ // nonWildcardTypeArgumentsOrDiamond java17
1595
+ // : '<' '>'
1596
+ // | nonWildcardTypeArguments
1597
+ // ;
1598
+ //unused nonWildcardTypeArgumentsOrDiamond
1599
+ visitNonWildcardTypeArgumentsOrDiamond(ctx) {
1600
+ return UAST.noop();
1601
+ }
1602
+ // nonWildcardTypeArguments java8
1603
+ // : '<' typeList '>'
1604
+ // ;
1605
+ //unused nonWildcardTypeArguments
1606
+ visitNonWildcardTypeArguments(ctx) {
1607
+ return UAST.noop();
1608
+ }
1609
+ // typeArguments java7
1610
+ // : '<' typeArgument (',' typeArgument)* '>'
1611
+ // ;
1612
+ //unused typeArguments
1613
+ visitTypeArguments(ctx) {
1614
+ return UAST.noop();
1615
+ }
1616
+ // typeArgument java7
1617
+ // : typeType
1618
+ // | annotation* '?' ((EXTENDS | SUPER) typeType)?
1619
+ // ;
1620
+ //unused typeArgument
1621
+ visitTypeArgument(ctx) {
1622
+ return UAST.noop();
1623
+ }
1624
+ //arrayInitializer
1625
+ // : '{' (variableInitializer (',' variableInitializer)* (',')? )? '}'
1626
+ visitArrayInitializer(ctx) {
1627
+ const exprs = ctx.variableInitializer().map(v => this.visit(v));
1628
+ const props = exprs.map((e, i) => {
1629
+ return UAST.objectProperty(UAST.literal(i, 'number'), e);
1630
+ });
1631
+ return UAST.objectExpression(props, null);
1632
+ }
1633
+ //variableInitializer
1634
+ // : arrayInitializer
1635
+ // | expression
1636
+ visitVariableInitializer(ctx) {
1637
+ return this.visit(ctx.children[0]);
1638
+ }
1639
+ //methodCall
1640
+ // : identifier '(' expressionList? ')'
1641
+ // | THIS '(' expressionList? ')'
1642
+ // | SUPER '(' expressionList? ')'
1643
+ visitMethodCall(ctx) {
1644
+ let callee;
1645
+ let args = [];
1646
+ const expressionList = ctx.expressionList();
1647
+ if (expressionList) {
1648
+ args = this.visit(expressionList);
1649
+ }
1650
+ const identifier = ctx.identifier();
1651
+ if (identifier) {
1652
+ callee = this.visit(identifier);
1653
+ }
1654
+ else if (ctx.THIS()) {
1655
+ callee = UAST.thisExpression();
1656
+ }
1657
+ else {
1658
+ callee = UAST.superExpression();
1659
+ }
1660
+ return UAST.callExpression(callee, args);
1661
+ }
1662
+ //expressionList
1663
+ // : expression (',' expression)*
1664
+ visitExpressionList(ctx) {
1665
+ return ctx.expression().map(e => this.visit(e));
1666
+ }
1667
+ // Java17
1668
+ // switchExpression
1669
+ // : SWITCH parExpression '{' switchLabeledRule* '}'
1670
+ visitSwitchExpression(ctx) {
1671
+ const discriminant = this.visit(ctx.parExpression());
1672
+ const cases = ctx.switchLabeledRule().map(switchLabeledRuleCtx => {
1673
+ // switchLabeledRule
1674
+ // : CASE (expressionList | NULL_LITERAL | guardedPattern) (ARROW | COLON) switchRuleOutcome
1675
+ // | DEFAULT (ARROW | COLON) switchRuleOutcome
1676
+ const body = this.visit(switchLabeledRuleCtx.switchRuleOutcome());
1677
+ if (switchLabeledRuleCtx.DEFAULT()) {
1678
+ return UAST.caseClause(null, buildIIFE([], UAST.functionDefinition(null, [], UAST.dynamicType(), body, [])));
1679
+ }
1680
+ else {
1681
+ const exprListCtx = switchLabeledRuleCtx.expressionList();
1682
+ if (exprListCtx) {
1683
+ let test;
1684
+ const exprList = this.visit(exprListCtx);
1685
+ if (exprList.length === 1) {
1686
+ test = exprList[0];
1687
+ }
1688
+ else {
1689
+ test = UAST.sequence(exprList);
1690
+ }
1691
+ return UAST.caseClause(test, body);
1692
+ }
1693
+ const guardedPatternCtx = switchLabeledRuleCtx.guardedPattern();
1694
+ if (guardedPatternCtx) {
1695
+ const res = this._visitGuardedPatternContext(guardedPatternCtx, discriminant);
1696
+ return UAST.caseClause(res.test, buildIIFE(res.callParams, UAST.functionDefinition(null, res.params, UAST.dynamicType(), body, [])));
1697
+ }
1698
+ // NULL CASE
1699
+ return UAST.caseClause(UAST.literal(null, 'null'), body);
1700
+ }
1701
+ });
1702
+ return UAST.switchStatement(discriminant, cases);
1703
+ }
1704
+ // switchLabeledRule
1705
+ // : CASE (expressionList | NULL_LITERAL | guardedPattern) (ARROW | COLON) switchRuleOutcome
1706
+ // | DEFAULT (ARROW | COLON) switchRuleOutcome
1707
+ // ;
1708
+ visitSwitchLabeledRule(ctx) {
1709
+ return UAST.noop();
1710
+ }
1711
+ //explicitGenericInvocationSuffix
1712
+ // : SUPER superSuffix
1713
+ // | identifier arguments
1714
+ // ;
1715
+ _visitExplicitGenericInvocationSuffix(ctx) {
1716
+ if (ctx.SUPER()) {
1717
+ const { expression, args } = this._visitSuperSuffix(ctx.superSuffix());
1718
+ return {
1719
+ object: UAST.superExpression(),
1720
+ expression,
1721
+ args
1722
+ };
1723
+ }
1724
+ else {
1725
+ return {
1726
+ object: null,
1727
+ expression: this.visit(ctx.identifier()),
1728
+ args: this.visit(ctx.arguments().expressionList()) || [],
1729
+ };
1730
+ }
1731
+ }
1732
+ // explicitGenericInvocationSuffix
1733
+ // : SUPER superSuffix
1734
+ // | identifier arguments
1735
+ // ;
1736
+ visitExplicitGenericInvocationSuffix(ctx) {
1737
+ return UAST.noop();
1738
+ }
1739
+ // arguments
1740
+ // : '(' expressionList? ')'
1741
+ // ;
1742
+ visitArguments(ctx) {
1743
+ return UAST.noop();
1744
+ }
1745
+ //superSuffix
1746
+ // : arguments
1747
+ // | '.' typeArguments? identifier arguments?
1748
+ // ;
1749
+ _visitSuperSuffix(ctx) {
1750
+ const idCtx = ctx.identifier();
1751
+ if (idCtx) {
1752
+ return {
1753
+ expression: this.visit(idCtx),
1754
+ args: this.visit(ctx.arguments()?.expressionList()) || [],
1755
+ };
1756
+ }
1757
+ return {
1758
+ expression: null,
1759
+ args: this.visit(ctx.arguments()?.expressionList()) || [],
1760
+ };
1761
+ }
1762
+ // superSuffix
1763
+ // : arguments
1764
+ // | '.' typeArguments? identifier arguments?
1765
+ // ;
1766
+ visitSuperSuffix(ctx) {
1767
+ return UAST.noop();
1768
+ }
1769
+ //guardedPattern
1770
+ // : '(' guardedPattern ')'
1771
+ // | variableModifier* typeType annotation* identifier ('&&' expression)*
1772
+ // | guardedPattern '&&' expression
1773
+ //TODO _?
1774
+ _visitGuardedPatternContext(ctx, discriminant) {
1775
+ const typeCtx = ctx.typeType();
1776
+ const exprCtx = ctx.expression();
1777
+ if (typeCtx) {
1778
+ // switch discriminant
1779
+ // case Type c && (c == test) -> expr
1780
+ // caseClause will convert to
1781
+ // test: (var c, (typeof discriminant === Type)&& c == test)) body: (func(c){return expr})(dicscriminant))
1782
+ const type = this.visit(typeCtx);
1783
+ const id = this.visit(ctx.identifier());
1784
+ const seqBody = [];
1785
+ const seq = UAST.sequence(seqBody);
1786
+ const varDecl = UAST.variableDeclaration(id, null, false, UAST.dynamicType());
1787
+ seqBody.push(varDecl);
1788
+ // typeof discriminant === Type
1789
+ let test = UAST.binaryExpression('==', UAST.unaryExpression('typeof', discriminant), typeToIdentifier(type));
1790
+ // subTest && subTest ...
1791
+ const exprCtx = ctx.expression();
1792
+ exprCtx.forEach(e => {
1793
+ const subTest = this.visit(e);
1794
+ test = UAST.binaryExpression('&&', test, subTest);
1795
+ });
1796
+ seqBody.push(test);
1797
+ const params = [varDecl];
1798
+ const callParams = [id];
1799
+ return {
1800
+ test: seq,
1801
+ callParams,
1802
+ params
1803
+ };
1804
+ }
1805
+ else if (exprCtx && exprCtx.length > 0) {
1806
+ const res = this._visitGuardedPatternContext(ctx.guardedPattern(), discriminant);
1807
+ let test = res.test;
1808
+ const exprCtx = ctx.expression();
1809
+ exprCtx.forEach(e => {
1810
+ const subTest = this.visit(e);
1811
+ test = UAST.binaryExpression('&&', test, subTest);
1812
+ });
1813
+ res.test = test;
1814
+ return res;
1815
+ }
1816
+ else {
1817
+ return this._visitGuardedPatternContext(ctx.guardedPattern(), discriminant);
1818
+ }
1819
+ }
1820
+ // guardedPattern
1821
+ // : '(' guardedPattern ')'
1822
+ // | variableModifier* typeType annotation* identifier ('&&' expression)*
1823
+ // | guardedPattern '&&' expression
1824
+ // ;
1825
+ visitGuardedPattern(ctx) {
1826
+ return UAST.noop();
1827
+ }
1828
+ //switchRuleOutcome
1829
+ // : block
1830
+ // | blockStatement*
1831
+ visitSwitchRuleOutcome(ctx) {
1832
+ const blockCtx = ctx.block();
1833
+ if (blockCtx)
1834
+ return this.visit(blockCtx);
1835
+ const blockStatementCtx = ctx.blockStatement();
1836
+ const body = blockStatementCtx.map(b => this.visit(b));
1837
+ return UAST.scopedStatement(body, null);
1838
+ }
1839
+ //typeTypeOrVoid
1840
+ // : typeType
1841
+ // | VOID
1842
+ visitTypeTypeOrVoid(ctx) {
1843
+ if (ctx.VOID()) {
1844
+ return UAST.primitiveType(UAST.identifier('Void'));
1845
+ }
1846
+ return this.visit(ctx.typeType());
1847
+ }
1848
+ // primary
1849
+ // : '(' expression ')'
1850
+ // | THIS
1851
+ // | SUPER
1852
+ // | literal
1853
+ // | identifier
1854
+ // | typeTypeOrVoid '.' CLASS
1855
+ // | nonWildcardTypeArguments (explicitGenericInvocationSuffix | THIS arguments)
1856
+ visitPrimary(ctx) {
1857
+ const expr = ctx.expression();
1858
+ if (expr) {
1859
+ return this.visit(expr);
1860
+ }
1861
+ if (ctx.THIS()) {
1862
+ return UAST.thisExpression();
1863
+ }
1864
+ if (ctx.SUPER()) {
1865
+ return UAST.superExpression();
1866
+ }
1867
+ const lit = ctx.literal();
1868
+ if (lit)
1869
+ return this.visit(lit);
1870
+ const identifier = ctx.identifier();
1871
+ if (identifier)
1872
+ return this.visit(identifier);
1873
+ const typeTypeCtx = ctx.typeTypeOrVoid();
1874
+ if (typeTypeCtx) {
1875
+ const typeType = this.visit(typeTypeCtx);
1876
+ return UAST.memberAccess(convertToMemberAccess(('id' in typeType && typeType.id.name) || ('name' in typeType && typeType.name)), UAST.identifier('Class'), false);
1877
+ }
1878
+ throw new Error(`Primary type: ${toText(ctx)} not supported`);
1879
+ }
1880
+ //literal
1881
+ // : integerLiteral
1882
+ // | floatLiteral
1883
+ // | CHAR_LITERAL
1884
+ // | STRING_LITERAL
1885
+ // | BOOL_LITERAL
1886
+ // | NULL_LITERAL
1887
+ // | TEXT_BLOCK // Java17
1888
+ visitLiteral(ctx) {
1889
+ let lit = toText(ctx.children[0]);
1890
+ let litType;
1891
+ if (ctx.integerLiteral() || ctx.floatLiteral()) {
1892
+ litType = 'number';
1893
+ }
1894
+ else if (ctx.CHAR_LITERAL() || ctx.STRING_LITERAL() || ctx.TEXT_BLOCK()) {
1895
+ litType = 'string';
1896
+ lit = lit.slice(1, -1);
1897
+ }
1898
+ else if (ctx.BOOL_LITERAL()) {
1899
+ litType = 'boolean';
1900
+ }
1901
+ else { // NULL_LITERAL
1902
+ litType = 'null';
1903
+ }
1904
+ return UAST.literal(lit, litType);
1905
+ }
1906
+ // floatLiteral
1907
+ // : FLOAT_LITERAL
1908
+ // | HEX_FLOAT_LITERAL
1909
+ // ;
1910
+ visitFloatLiteral(ctx) {
1911
+ return UAST.literal(toText(ctx), 'number');
1912
+ }
1913
+ // integerLiteral
1914
+ // : DECIMAL_LITERAL
1915
+ // | HEX_LITERAL
1916
+ // | OCT_LITERAL
1917
+ // | BINARY_LITERAL
1918
+ // ;
1919
+ visitIntegerLiteral(ctx) {
1920
+ return UAST.literal(toText(ctx), 'number');
1921
+ }
1922
+ //parExpression
1923
+ // : '(' expression ')'
1924
+ visitParExpression(ctx) {
1925
+ return this.visit(ctx.expression());
1926
+ }
1927
+ //typeType
1928
+ // : annotation* (classOrInterfaceType | primitiveType) (annotation* '[' ']')*
1929
+ // ;
1930
+ visitTypeType(ctx) {
1931
+ const primitiveType = ctx.primitiveType();
1932
+ if (primitiveType) {
1933
+ return this.visit(primitiveType);
1934
+ }
1935
+ const classOrInterfaceType = ctx.classOrInterfaceType();
1936
+ if (classOrInterfaceType) {
1937
+ return this.visit(classOrInterfaceType);
1938
+ }
1939
+ throw new Error('Unexpected TypeType');
1940
+ }
1941
+ //primitiveType
1942
+ // : BOOLEAN
1943
+ // | CHAR
1944
+ // | BYTE
1945
+ // | SHORT
1946
+ // | INT
1947
+ // | LONG
1948
+ // | FLOAT
1949
+ // | DOUBLE
1950
+ // ;
1951
+ visitPrimitiveType(ctx) {
1952
+ return UAST.primitiveType(UAST.identifier(toText(ctx)));
1953
+ }
1954
+ //classOrInterfaceType
1955
+ // : (identifier typeArguments? '.')* typeIdentifier typeArguments?
1956
+ // ;
1957
+ visitClassOrInterfaceType(ctx) {
1958
+ const packageList = ctx.identifier();
1959
+ let qualifiedName = '';
1960
+ packageList.forEach(n => qualifiedName += toText(n) + '.');
1961
+ const typeNameId = toText(ctx.typeIdentifier());
1962
+ qualifiedName += typeNameId;
1963
+ return UAST.scopedType(UAST.identifier(qualifiedName), null);
1964
+ }
1965
+ // typeIdentifier // Identifiers that are not restricted for type declarations java7
1966
+ // : IDENTIFIER
1967
+ // | MODULE
1968
+ // | OPEN
1969
+ // | REQUIRES
1970
+ // | EXPORTS
1971
+ // | OPENS
1972
+ // | TO
1973
+ // | USES
1974
+ // | PROVIDES
1975
+ // | WITH
1976
+ // | TRANSITIVE
1977
+ // | SEALED
1978
+ // | PERMITS
1979
+ // | RECORD
1980
+ // ;
1981
+ visitTypeIdentifier(ctx) {
1982
+ return UAST.noop();
1983
+ }
1984
+ // identifier java7
1985
+ // : IDENTIFIER
1986
+ // | MODULE
1987
+ // | OPEN
1988
+ // | REQUIRES
1989
+ // | EXPORTS
1990
+ // | OPENS
1991
+ // | TO
1992
+ // | USES
1993
+ // | PROVIDES
1994
+ // | WITH
1995
+ // | TRANSITIVE
1996
+ // | YIELD
1997
+ // | SEALED
1998
+ // | PERMITS
1999
+ // | RECORD
2000
+ // | VAR
2001
+ // ;
2002
+ visitIdentifier(ctx) {
2003
+ return UAST.identifier(toText(ctx));
2004
+ }
2005
+ // constDeclaration java7
2006
+ // : typeType constantDeclarator (',' constantDeclarator)* ';'
2007
+ // ;
2008
+ visitConstDeclaration(ctx) {
2009
+ const results = [];
2010
+ const type = this.visit(ctx.typeType());
2011
+ ctx.constantDeclarator().forEach(c => {
2012
+ const initCtx = c.variableInitializer();
2013
+ let init;
2014
+ if (initCtx) {
2015
+ init = this.visit(initCtx);
2016
+ }
2017
+ const id = this.visitIdentifier(c.identifier());
2018
+ results.push(UAST.variableDeclaration(id, init, null, type));
2019
+ });
2020
+ return results;
2021
+ }
2022
+ // constantDeclarator java7
2023
+ // : identifier ('[' ']')* '=' variableInitializer
2024
+ // ;
2025
+ visitConstantDeclarator(ctx) {
2026
+ return UAST.noop();
2027
+ }
2028
+ // interfaceMethodDeclaration java7
2029
+ // : interfaceMethodModifier* interfaceCommonBodyDeclaration
2030
+ // ;
2031
+ visitInterfaceMethodDeclaration(ctx) {
2032
+ const commonBody = ctx.interfaceCommonBodyDeclaration();
2033
+ return this.visit(commonBody);
2034
+ }
2035
+ // interfaceMethodModifier java8
2036
+ // : annotation
2037
+ // | PUBLIC
2038
+ // | ABSTRACT
2039
+ // | DEFAULT
2040
+ // | STATIC
2041
+ // | STRICTFP
2042
+ // ;
2043
+ //unused interfaceMethodModifier
2044
+ visitInterfaceMethodModifier(ctx) {
2045
+ return UAST.noop();
2046
+ }
2047
+ // genericInterfaceMethodDeclaration java8
2048
+ // : interfaceMethodModifier* typeParameters interfaceCommonBodyDeclaration
2049
+ // ;
2050
+ visitGenericInterfaceMethodDeclaration(ctx) {
2051
+ const commonBody = ctx.interfaceCommonBodyDeclaration();
2052
+ return this.visit(commonBody);
2053
+ }
2054
+ // interfaceCommonBodyDeclaration java7
2055
+ // : annotation* typeTypeOrVoid identifier formalParameters ('[' ']')* (THROWS qualifiedNameList)? methodBody
2056
+ // ;
2057
+ visitInterfaceCommonBodyDeclaration(ctx) {
2058
+ const typeOrVoidCtx = ctx.typeTypeOrVoid();
2059
+ const typeCtx = typeOrVoidCtx.typeType();
2060
+ let type;
2061
+ if (typeCtx) {
2062
+ type = this.visit(typeCtx);
2063
+ }
2064
+ else {
2065
+ type = UAST.primitiveType(UAST.identifier('void'));
2066
+ }
2067
+ const id = this.visit(ctx.identifier());
2068
+ const params = this.visit(ctx.formalParameters());
2069
+ const blockCtx = ctx.methodBody().block();
2070
+ let body;
2071
+ const modifiers = [];
2072
+ if (blockCtx) {
2073
+ body = this.visit(blockCtx);
2074
+ }
2075
+ else {
2076
+ body = UAST.noop();
2077
+ modifiers.push('abstract');
2078
+ }
2079
+ return UAST.functionDefinition(id, params, type, body, modifiers);
2080
+ }
2081
+ //receiverParameter java8
2082
+ // : typeType (identifier '.')* THIS
2083
+ // ;
2084
+ //unused receiverParameter
2085
+ visitReceiverParameter(ctx) {
2086
+ return UAST.noop();
2087
+ }
2088
+ // elementValueArrayInitializer java8
2089
+ // : '{' (elementValue (',' elementValue)*)? (',')? '}'
2090
+ // ;
2091
+ visitElementValueArrayInitializer(ctx) {
2092
+ const exprs = ctx.elementValue();
2093
+ const props = exprs.map((e, i) => {
2094
+ return UAST.objectProperty(UAST.literal(i, 'number'), this.visit(e));
2095
+ });
2096
+ return UAST.objectExpression(props, null);
2097
+ }
2098
+ // interfaceMemberDeclaration java7
2099
+ // : constDeclaration
2100
+ // | interfaceMethodDeclaration
2101
+ // | genericInterfaceMethodDeclaration
2102
+ // | interfaceDeclaration
2103
+ // | annotationTypeDeclaration
2104
+ // | classDeclaration
2105
+ // | enumDeclaration
2106
+ // | recordDeclaration // Java17
2107
+ // ;
2108
+ visitInterfaceMemberDeclaration(ctx) {
2109
+ return this.visit(ctx.children[0]);
2110
+ }
2111
+ // localTypeDeclaration java7
2112
+ // : classOrInterfaceModifier*
2113
+ // (classDeclaration | interfaceDeclaration | recordDeclaration)
2114
+ // ;
2115
+ visitLocalTypeDeclaration(ctx) {
2116
+ const children = ctx.children;
2117
+ const typeDecl = children.pop();
2118
+ if (typeDecl instanceof TerminalNode_1.TerminalNode) {
2119
+ return UAST.noop();
2120
+ }
2121
+ const classDefinition = this.visit(typeDecl);
2122
+ ctx.classOrInterfaceModifier().forEach(m => {
2123
+ const annotationCtx = m.annotation();
2124
+ if (annotationCtx) {
2125
+ const meta = classDefinition._meta;
2126
+ meta.annotations = meta.annotations || [];
2127
+ const annotations = meta.annotations;
2128
+ annotations.push(this.visit(annotationCtx));
2129
+ }
2130
+ else {
2131
+ const meta = classDefinition._meta;
2132
+ meta.modifiers = meta.modifiers ?? [];
2133
+ const modifiers = meta.modifiers;
2134
+ const modifierName = toText(m);
2135
+ // eslint-disable-next-line @typescript-eslint/restrict-plus-operands
2136
+ meta['is' + getUpperCase(modifierName)] = true;
2137
+ modifiers.push(modifierName);
2138
+ }
2139
+ });
2140
+ const isPublic = children.find(child => toText(child) === 'public');
2141
+ if (isPublic) {
2142
+ return UAST.exportStatement(classDefinition, classDefinition.id);
2143
+ }
2144
+ else {
2145
+ return classDefinition;
2146
+ }
2147
+ }
2148
+ //moduleDeclaration java9
2149
+ // : OPEN? MODULE qualifiedName moduleBody
2150
+ // ;
2151
+ //unused moduleDeclaration
2152
+ visitModuleDeclaration(ctx) {
2153
+ return UAST.noop();
2154
+ }
2155
+ //moduleBody java9
2156
+ // : '{' moduleDirective* '}'
2157
+ // ;
2158
+ //unused moduleBody
2159
+ visitModuleBody(ctx) {
2160
+ return UAST.noop();
2161
+ }
2162
+ // moduleDirective java9
2163
+ // : REQUIRES requiresModifier* qualifiedName ';'
2164
+ // | EXPORTS qualifiedName (TO qualifiedName)? ';'
2165
+ // | OPENS qualifiedName (TO qualifiedName)? ';'
2166
+ // | USES qualifiedName ';'
2167
+ // | PROVIDES qualifiedName WITH qualifiedName ';'
2168
+ // ;
2169
+ //unused moduleDirective
2170
+ visitModuleDirective(ctx) {
2171
+ return UAST.noop();
2172
+ }
2173
+ // requiresModifier java9
2174
+ // : TRANSITIVE
2175
+ // | STATIC
2176
+ // ;
2177
+ //unused requiresModifier
2178
+ visitRequiresModifier(ctx) {
2179
+ return UAST.noop();
2180
+ }
2181
+ // qualifiedNameList java7
2182
+ // : qualifiedName (',' qualifiedName)*
2183
+ // ;
2184
+ //unused qualifiedNameList
2185
+ visitQualifiedNameList(ctx) {
2186
+ return UAST.noop();
2187
+ }
2188
+ safeVisit(ctx) {
2189
+ if (!ctx)
2190
+ return undefined;
2191
+ return this.visit(ctx);
2192
+ }
2193
+ completeLocInfo(node, upperLoc) {
2194
+ if (!node)
2195
+ return;
2196
+ if (Array.isArray(node)) {
2197
+ return node.map(n => this.completeLocInfo(n, upperLoc));
2198
+ }
2199
+ if (!node.type)
2200
+ return;
2201
+ const hasLoc = node.loc && node.loc.start && node.loc.end && node.loc.sourcefile;
2202
+ const loc = { start: { line: 1, column: 1 }, end: { line: 1, column: 1 }, sourcefile: this.sourcefile };
2203
+ let startLine = Number.MAX_SAFE_INTEGER;
2204
+ let startColumn = Number.MAX_SAFE_INTEGER;
2205
+ let endLine = 1;
2206
+ let endColumn = 1;
2207
+ for (const prop in node) {
2208
+ const locs = this.completeLocInfo(node[prop], hasLoc ? node.loc : upperLoc);
2209
+ if (!hasLoc) {
2210
+ if (!locs)
2211
+ continue;
2212
+ if (Array.isArray(locs)) {
2213
+ locs.forEach(loc => {
2214
+ if (loc) {
2215
+ startLine = Math.min(startLine, loc.start.line);
2216
+ startColumn = Math.min(startColumn, loc.start.column);
2217
+ endLine = Math.max(endLine, loc.end.line);
2218
+ endColumn = Math.max(endColumn, loc.end.column);
2219
+ }
2220
+ });
2221
+ }
2222
+ else {
2223
+ const loc = locs;
2224
+ startLine = Math.min(startLine, loc.start.line);
2225
+ startColumn = Math.min(startColumn, loc.start.column);
2226
+ endLine = Math.max(endLine, loc.end.line);
2227
+ endColumn = Math.max(endColumn, loc.end.column);
2228
+ }
2229
+ }
2230
+ }
2231
+ if (startLine === Number.MAX_SAFE_INTEGER && startColumn === Number.MAX_SAFE_INTEGER
2232
+ && endLine === 1 && endColumn === 1) {
2233
+ startLine = upperLoc?.start?.line ?? 1;
2234
+ startColumn = upperLoc?.start?.column ?? 1;
2235
+ endLine = upperLoc?.end?.line ?? 1;
2236
+ endColumn = upperLoc?.end?.column ?? 1;
2237
+ }
2238
+ loc.start.line = startLine;
2239
+ loc.start.column = startColumn;
2240
+ loc.end.line = endLine;
2241
+ loc.end.column = endColumn;
2242
+ if (!hasLoc)
2243
+ node.loc = loc;
2244
+ return node.loc;
2245
+ }
2246
+ }
2247
+ __decorate([
2248
+ addLoc
2249
+ ], ASTBuilder.prototype, "_visitElementValuePairs", null);
2250
+ __decorate([
2251
+ addLoc
2252
+ ], ASTBuilder.prototype, "_visitEnumConstants", null);
2253
+ __decorate([
2254
+ addLoc
2255
+ ], ASTBuilder.prototype, "visitStatement", null);
2256
+ __decorate([
2257
+ addLoc
2258
+ ], ASTBuilder.prototype, "_visitAssertStatement", null);
2259
+ __decorate([
2260
+ addLoc
2261
+ ], ASTBuilder.prototype, "_visitIfStatement", null);
2262
+ __decorate([
2263
+ addLoc
2264
+ ], ASTBuilder.prototype, "_visitForStatement", null);
2265
+ __decorate([
2266
+ addLoc
2267
+ ], ASTBuilder.prototype, "_visitWhileStatementInner", null);
2268
+ __decorate([
2269
+ addLoc
2270
+ ], ASTBuilder.prototype, "_visitTryStatement", null);
2271
+ __decorate([
2272
+ addLoc
2273
+ ], ASTBuilder.prototype, "_visitSwitchStatement", null);
2274
+ __decorate([
2275
+ addLoc
2276
+ ], ASTBuilder.prototype, "visitSynchronizedStatement", null);
2277
+ __decorate([
2278
+ addLoc
2279
+ ], ASTBuilder.prototype, "_visitReturnStatement", null);
2280
+ __decorate([
2281
+ addLoc
2282
+ ], ASTBuilder.prototype, "_visitThrowStatement", null);
2283
+ __decorate([
2284
+ addLoc
2285
+ ], ASTBuilder.prototype, "_visitBreakStatement", null);
2286
+ __decorate([
2287
+ addLoc
2288
+ ], ASTBuilder.prototype, "_visitContinueStatement", null);
2289
+ __decorate([
2290
+ addLoc
2291
+ ], ASTBuilder.prototype, "_visitYieldStatement", null);
2292
+ __decorate([
2293
+ addLoc
2294
+ ], ASTBuilder.prototype, "_visitStatementExpression", null);
2295
+ __decorate([
2296
+ addLoc
2297
+ ], ASTBuilder.prototype, "_visitExplicitGenericInvocationSuffix", null);
2298
+ __decorate([
2299
+ addLoc
2300
+ ], ASTBuilder.prototype, "_visitSuperSuffix", null);
2301
+ __decorate([
2302
+ addLoc
2303
+ ], ASTBuilder.prototype, "_visitGuardedPatternContext", null);
2304
+ exports.ASTBuilder = ASTBuilder;
2305
+ // convert qualified name to MemberAccess
2306
+ // e.g. 'com.java.A' will be converted to MemberAccess{object: 'com.java', property: 'A'}
2307
+ function convertToMemberAccess(qualifiedName) {
2308
+ const ids = qualifiedName.split('.');
2309
+ const packageName = ids.filter(id => id.charAt(0) === id.charAt(0).toLowerCase()).join('.');
2310
+ const classNames = ids.filter(id => id.charAt(0) === id.charAt(0).toUpperCase());
2311
+ if (packageName !== '') {
2312
+ classNames.unshift(packageName);
2313
+ }
2314
+ let node;
2315
+ classNames.forEach(id => {
2316
+ if (!node) {
2317
+ node = UAST.identifier(id);
2318
+ }
2319
+ else {
2320
+ node = UAST.memberAccess(node, UAST.identifier(id), false);
2321
+ }
2322
+ });
2323
+ return node;
2324
+ }
2325
+ //Immediately Invoked Function Expression
2326
+ function buildIIFE(params, fdef) {
2327
+ return UAST.callExpression(fdef, params);
2328
+ }
2329
+ function toTypeof(type) {
2330
+ return UAST.unaryExpression('typeof', typeToIdentifier(type));
2331
+ }
2332
+ function typeToIdentifier(type) {
2333
+ if (type.type === "ScopedType") {
2334
+ if (type.scope) {
2335
+ return UAST.identifier(typeToIdentifier(type.scope).name + type.id.name);
2336
+ }
2337
+ }
2338
+ return UAST.identifier(('id' in type && type.id.name) || ('name' in type && type.name));
2339
+ }
2340
+ function toText(ctx) {
2341
+ const text = ctx.text;
2342
+ if (text === undefined) {
2343
+ throw new Error('Assertion error: text should never be undefiend');
2344
+ }
2345
+ return text;
2346
+ }
2347
+ function addLoc(target, name, descriptor) {
2348
+ const oldValue = descriptor.value;
2349
+ descriptor.value = function (...args) {
2350
+ const node = oldValue.apply(this, args);
2351
+ const ctx = args[0];
2352
+ if (ctx instanceof antlr4ts_1.ParserRuleContext && node && !Array.isArray(node) && !node.loc) {
2353
+ // @ts-ignore
2354
+ node.loc = {
2355
+ // @ts-ignore
2356
+ start: { line: ctx._start.line, column: ctx._start._charPositionInLine + 1 },
2357
+ // @ts-ignore
2358
+ end: { line: ctx._stop.line, column: ctx._stop._charPositionInLine + 1 },
2359
+ sourcefile: this.sourcefile
2360
+ };
2361
+ }
2362
+ return node;
2363
+ };
2364
+ return descriptor;
2365
+ }
2366
+ function getUpperCase(str) {
2367
+ return str.charAt(0).toUpperCase() + str.slice(1);
2368
+ }
2369
+ //# sourceMappingURL=ASTBuilder.js.map