Codebase list jd-gui / 0af4a626-0b34-4685-a8a4-c18e8bd66f2d/upstream services / src / main / java / org / jd / gui / view / component / JavaFilePage.java
0af4a626-0b34-4685-a8a4-c18e8bd66f2d/upstream

Tree @0af4a626-0b34-4685-a8a4-c18e8bd66f2d/upstream (Download .tar.gz)

JavaFilePage.java @0af4a626-0b34-4685-a8a4-c18e8bd66f2d/upstreamraw · history · blame

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
/*
 * Copyright (c) 2008-2019 Emmanuel Dupuy.
 * This project is distributed under the GPLv3 license.
 * This is a Copyleft license that gives the user the right to use,
 * copy and modify the code freely for non-commercial purposes.
 */

package org.jd.gui.view.component;

import org.antlr.v4.runtime.ANTLRInputStream;
import org.antlr.v4.runtime.ParserRuleContext;
import org.antlr.v4.runtime.RuleContext;
import org.antlr.v4.runtime.Token;
import org.antlr.v4.runtime.tree.ParseTree;
import org.antlr.v4.runtime.tree.TerminalNode;
import org.fife.ui.rsyntaxtextarea.SyntaxConstants;
import org.jd.gui.api.API;
import org.jd.gui.api.model.Container;
import org.jd.gui.util.io.TextReader;
import org.jd.gui.util.parser.antlr.ANTLRJavaParser;
import org.jd.gui.util.parser.antlr.AbstractJavaListener;
import org.jd.gui.util.parser.antlr.JavaParser;

import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class JavaFilePage extends TypePage {

    public JavaFilePage(API api, Container.Entry entry) {
        super(api, entry);
        // Load content file
        String text = TextReader.getText(entry.getInputStream()).replace("\r\n", "\n").replace('\r', '\n');
        // Parse
        DeclarationListener declarationListener = new DeclarationListener(entry);
        ReferenceListener referenceListener = new ReferenceListener(entry);

        ANTLRJavaParser.parse(new ANTLRInputStream(text), declarationListener);
        referenceListener.init(declarationListener);
        ANTLRJavaParser.parse(new ANTLRInputStream(text), referenceListener);
        // Display
        setText(text);
        initLineNumbers();
    }

    public String getSyntaxStyle() { return SyntaxConstants.SYNTAX_STYLE_JAVA; }

    // --- ContentSavable --- //
    public String getFileName() {
        String path = entry.getPath();
        int index = path.lastIndexOf('/');
        return path.substring(index+1);
    }

    public class DeclarationListener extends AbstractJavaListener {
        protected StringBuilder sbTypeDeclaration = new StringBuilder();
        protected String currentInternalTypeName;

        public DeclarationListener(Container.Entry entry) { super(entry); }

        public HashMap<String, String> getNameToInternalTypeName() { return super.nameToInternalTypeName; }

        // --- Add declarations --- //
        public void enterPackageDeclaration(JavaParser.PackageDeclarationContext ctx) {
            super.enterPackageDeclaration(ctx);

            if (! packageName.isEmpty()) {
                sbTypeDeclaration.append(packageName).append('/');
            }
        }

        public void enterImportDeclaration(JavaParser.ImportDeclarationContext ctx) {
            List<TerminalNode> identifiers = ctx.qualifiedName().Identifier();
            String internalTypeName = concatIdentifiers(identifiers);
            String typeName = identifiers.get(identifiers.size()-1).getSymbol().getText();

            nameToInternalTypeName.put(typeName, internalTypeName);
        }

        public void enterClassDeclaration(JavaParser.ClassDeclarationContext ctx) { enterTypeDeclaration(ctx); }
        public void exitClassDeclaration(JavaParser.ClassDeclarationContext ctx) { exitTypeDeclaration(); }

        public void enterEnumDeclaration(JavaParser.EnumDeclarationContext ctx) { enterTypeDeclaration(ctx); }
        public void exitEnumDeclaration(JavaParser.EnumDeclarationContext ctx) { exitTypeDeclaration(); }

        public void enterInterfaceDeclaration(JavaParser.InterfaceDeclarationContext ctx) { enterTypeDeclaration(ctx); }
        public void exitInterfaceDeclaration(JavaParser.InterfaceDeclarationContext ctx) { exitTypeDeclaration(); }

        public void enterAnnotationTypeDeclaration(JavaParser.AnnotationTypeDeclarationContext ctx) { enterTypeDeclaration(ctx); }
        public void exitAnnotationTypeDeclaration(JavaParser.AnnotationTypeDeclarationContext ctx) { exitTypeDeclaration(); }

        public void enterTypeDeclaration(ParserRuleContext ctx) {
            // Type declaration
            TerminalNode identifier = ctx.getToken(JavaParser.Identifier, 0);
            String typeName = identifier.getText();
            int position = identifier.getSymbol().getStartIndex();
            int length = sbTypeDeclaration.length();

            if ((length == 0) || (sbTypeDeclaration.charAt(length-1) == '/')) {
                sbTypeDeclaration.append(typeName);
            } else {
                sbTypeDeclaration.append('$').append(typeName);
            }

            currentInternalTypeName = sbTypeDeclaration.toString();
            nameToInternalTypeName.put(typeName, currentInternalTypeName);

            // Super type reference
            JavaParser.TypeContext superType = ctx.getRuleContext(JavaParser.TypeContext.class, 0);
            String superInternalTypeName = (superType != null) ? resolveInternalTypeName(superType.classOrInterfaceType().Identifier()) : null;
            TypeDeclarationData data = new TypeDeclarationData(position, typeName.length(), currentInternalTypeName, null, null, superInternalTypeName);

            declarations.put(currentInternalTypeName, data);
            typeDeclarations.put(position, data);
        }

        public void exitTypeDeclaration() {
            int index = sbTypeDeclaration.lastIndexOf("$");

            if (index == -1) {
                index = sbTypeDeclaration.lastIndexOf("/") + 1;
            }

            if (index == -1) {
                sbTypeDeclaration.setLength(0);
            } else {
                sbTypeDeclaration.setLength(index);
            }

            currentInternalTypeName = sbTypeDeclaration.toString();
        }

        public void enterClassBodyDeclaration(JavaParser.ClassBodyDeclarationContext ctx) {
            if (ctx.getChildCount() == 2) {
                ParseTree first = ctx.getChild(0);

                if (first instanceof TerminalNode) {
                    TerminalNode f = (TerminalNode)first;

                    if (f.getSymbol().getType() == JavaParser.STATIC) {
                        String name = f.getText();
                        int position = f.getSymbol().getStartIndex();
                        declarations.put(currentInternalTypeName + "-<clinit>-()V", new TypePage.DeclarationData(position, 6, currentInternalTypeName, name, "()V"));
                    }
                }
            }
        }

        public void enterConstDeclaration(JavaParser.ConstDeclarationContext ctx) {
            JavaParser.TypeContext typeContext = ctx.type();

            for (JavaParser.ConstantDeclaratorContext constantDeclaratorContext : ctx.constantDeclarator()) {
                TerminalNode identifier = constantDeclaratorContext.Identifier();
                String name = identifier.getText();
                int dimensionOnVariable = countDimension(constantDeclaratorContext.children);
                String descriptor = createDescriptor(typeContext, dimensionOnVariable);
                int position = identifier.getSymbol().getStartIndex();

                declarations.put(currentInternalTypeName + '-' + name + '-' + descriptor, new TypePage.DeclarationData(position, name.length(), currentInternalTypeName, name, descriptor));
            }
        }

        public void enterFieldDeclaration(JavaParser.FieldDeclarationContext ctx) {
            JavaParser.TypeContext typeContext = ctx.type();

            for (JavaParser.VariableDeclaratorContext declaration : ctx.variableDeclarators().variableDeclarator()) {
                JavaParser.VariableDeclaratorIdContext variableDeclaratorId = declaration.variableDeclaratorId();
                TerminalNode identifier = variableDeclaratorId.Identifier();
                String name = identifier.getText();
                int dimensionOnVariable = countDimension(variableDeclaratorId.children);
                String descriptor = createDescriptor(typeContext, dimensionOnVariable);
                int position = identifier.getSymbol().getStartIndex();
                TypePage.DeclarationData data = new TypePage.DeclarationData(position, name.length(), currentInternalTypeName, name, descriptor);

                declarations.put(currentInternalTypeName + '-' + name + '-' + descriptor, data);
            }
        }

        public void enterMethodDeclaration(JavaParser.MethodDeclarationContext ctx) {
            enterMethodDeclaration(ctx, ctx.Identifier(), ctx.formalParameters(), ctx.type());
        }

        public void enterInterfaceMethodDeclaration(JavaParser.InterfaceMethodDeclarationContext ctx) {
            enterMethodDeclaration(ctx, ctx.Identifier(), ctx.formalParameters(), ctx.type());
        }

        public void enterMethodDeclaration(
                ParserRuleContext ctx, TerminalNode identifier,
                JavaParser.FormalParametersContext formalParameters, JavaParser.TypeContext returnType) {

            String name = identifier.getText();
            String paramDescriptors = createParamDescriptors(formalParameters.formalParameterList());
            String returnDescriptor = createDescriptor(returnType, 0);
            String descriptor = paramDescriptors + returnDescriptor;
            int position = identifier.getSymbol().getStartIndex();

            declarations.put(currentInternalTypeName + '-' + name + '-' + descriptor, new TypePage.DeclarationData(position, name.length(), currentInternalTypeName, name, descriptor));
        }

        public void enterConstructorDeclaration(JavaParser.ConstructorDeclarationContext ctx) {
            TerminalNode identifier = ctx.Identifier();
            String name = identifier.getText();
            String paramDescriptors = createParamDescriptors(ctx.formalParameters().formalParameterList());
            String descriptor = paramDescriptors + "V";
            int position = identifier.getSymbol().getStartIndex();

            declarations.put(currentInternalTypeName + "-<init>-" + descriptor, new TypePage.DeclarationData(position, name.length(), currentInternalTypeName, name, descriptor));
        }

        public String createParamDescriptors(JavaParser.FormalParameterListContext formalParameterList) {
            StringBuilder paramDescriptors = null;

            if (formalParameterList != null) {
                List<JavaParser.FormalParameterContext> formalParameters = formalParameterList.formalParameter();
                paramDescriptors = new StringBuilder("(");

                for (JavaParser.FormalParameterContext formalParameter : formalParameters) {
                    int dimensionOnParameter = countDimension(formalParameter.variableDeclaratorId().children);
                    String descriptor = createDescriptor(formalParameter.type(), dimensionOnParameter);

                    paramDescriptors.append(descriptor);
                }
            }

            return (paramDescriptors == null) ? "()" : paramDescriptors.append(')').toString();
        }
    }

    public class ReferenceListener extends AbstractJavaListener {
        protected StringBuilder sbTypeDeclaration = new StringBuilder();
        protected HashMap<String, TypePage.ReferenceData> referencesCache = new HashMap<>();
        protected String currentInternalTypeName;
        protected Context currentContext = null;

        public ReferenceListener(Container.Entry entry) { super(entry); }

        public void init(DeclarationListener declarationListener) {
            this.nameToInternalTypeName.putAll(declarationListener.getNameToInternalTypeName());
        }

        // --- Add declarations --- //
        public void enterPackageDeclaration(JavaParser.PackageDeclarationContext ctx) {
            super.enterPackageDeclaration(ctx);

            if (! packageName.isEmpty()) {
                sbTypeDeclaration.append(packageName).append('/');
            }
        }

        public void enterImportDeclaration(JavaParser.ImportDeclarationContext ctx) {
            List<TerminalNode> identifiers = ctx.qualifiedName().Identifier();
            int position = identifiers.get(0).getSymbol().getStartIndex();
            String internalTypeName = concatIdentifiers(identifiers);

            addHyperlink(new TypePage.HyperlinkReferenceData(position, internalTypeName.length(), newReferenceData(internalTypeName, null, null, null)));
        }

        public void enterClassDeclaration(JavaParser.ClassDeclarationContext ctx) { enterTypeDeclaration(ctx); }
        public void exitClassDeclaration(JavaParser.ClassDeclarationContext ctx) { exitTypeDeclaration(); }

        public void enterEnumDeclaration(JavaParser.EnumDeclarationContext ctx) { enterTypeDeclaration(ctx); }
        public void exitEnumDeclaration(JavaParser.EnumDeclarationContext ctx) { exitTypeDeclaration(); }

        public void enterInterfaceDeclaration(JavaParser.InterfaceDeclarationContext ctx) { enterTypeDeclaration(ctx); }
        public void exitInterfaceDeclaration(JavaParser.InterfaceDeclarationContext ctx) { exitTypeDeclaration(); }

        public void enterAnnotationTypeDeclaration(JavaParser.AnnotationTypeDeclarationContext ctx) { enterTypeDeclaration(ctx); }
        public void exitAnnotationTypeDeclaration(JavaParser.AnnotationTypeDeclarationContext ctx) { exitTypeDeclaration(); }

        public void enterTypeDeclaration(ParserRuleContext ctx) {
            // Type declaration
            TerminalNode identifier = ctx.getToken(JavaParser.Identifier, 0);
            String typeName = identifier.getText();
            int length = sbTypeDeclaration.length();

            if ((length == 0) || (sbTypeDeclaration.charAt(length-1) == '/')) {
                sbTypeDeclaration.append(typeName);
            } else {
                sbTypeDeclaration.append('$').append(typeName);
            }

            currentInternalTypeName = sbTypeDeclaration.toString();
            currentContext = new Context(currentContext);
        }

        public void exitTypeDeclaration() {
            int index = sbTypeDeclaration.lastIndexOf("$");

            if (index == -1) {
                index = sbTypeDeclaration.lastIndexOf("/") + 1;
            }

            if (index == -1) {
                sbTypeDeclaration.setLength(0);
            } else {
                sbTypeDeclaration.setLength(index);
            }

            currentInternalTypeName = sbTypeDeclaration.toString();
        }

        public void enterFormalParameters(JavaParser.FormalParametersContext ctx) {
            JavaParser.FormalParameterListContext formalParameterList = ctx.formalParameterList();

            if (formalParameterList != null) {
                List<JavaParser.FormalParameterContext> formalParameters = formalParameterList.formalParameter();

                for (JavaParser.FormalParameterContext formalParameter : formalParameters) {
                    int dimensionOnParameter = countDimension(formalParameter.variableDeclaratorId().children);
                    String descriptor = createDescriptor(formalParameter.type(), dimensionOnParameter);
                    String name = formalParameter.variableDeclaratorId().Identifier().getSymbol().getText();

                    currentContext.nameToDescriptor.put(name, descriptor);
                }
            }
        }

        // --- Add references --- //
        public void enterType(JavaParser.TypeContext ctx) {
            // Add type reference
            JavaParser.ClassOrInterfaceTypeContext classOrInterfaceType = ctx.classOrInterfaceType();

            if (classOrInterfaceType != null) {
                List<TerminalNode> identifiers = classOrInterfaceType.Identifier();
                String name = concatIdentifiers(identifiers);
                String internalTypeName = resolveInternalTypeName(identifiers);
                int position = identifiers.get(0).getSymbol().getStartIndex();

                addHyperlink(new TypePage.HyperlinkReferenceData(position, name.length(), newReferenceData(internalTypeName, null, null, currentInternalTypeName)));
            }
        }

        public void enterLocalVariableDeclaration(JavaParser.LocalVariableDeclarationContext ctx) {
            JavaParser.TypeContext typeContext = ctx.type();

            for (JavaParser.VariableDeclaratorContext variableDeclarator : ctx.variableDeclarators().variableDeclarator()) {
                JavaParser.VariableDeclaratorIdContext variableDeclaratorId = variableDeclarator.variableDeclaratorId();
                int dimensionOnVariable = countDimension(variableDeclaratorId.children);
                String descriptor = createDescriptor(typeContext, dimensionOnVariable);
                String name = variableDeclarator.variableDeclaratorId().Identifier().getSymbol().getText();

                currentContext.nameToDescriptor.put(name, descriptor);
            }
        }

        public void enterCreator(JavaParser.CreatorContext ctx) {
            enterNewExpression(ctx.createdName().Identifier(), ctx.classCreatorRest());
        }

        public void enterInnerCreator(JavaParser.InnerCreatorContext ctx) {
            enterNewExpression(Collections.singletonList(ctx.Identifier()), ctx.classCreatorRest());
        }

        public void enterNewExpression(List<TerminalNode> identifiers, JavaParser.ClassCreatorRestContext classCreatorRest) {
            if (identifiers.size() > 0) {
                String name = concatIdentifiers(identifiers);
                String internalTypeName = resolveInternalTypeName(identifiers);
                int position = identifiers.get(0).getSymbol().getStartIndex();

                if (classCreatorRest != null) {
                    // Constructor call -> Add a link to the constructor declaration
                    JavaParser.ExpressionListContext expressionList = classCreatorRest.arguments().expressionList();
                    String descriptor = (expressionList != null) ? getParametersDescriptor(expressionList).append('V').toString() : "()V";

                    addHyperlink(new TypePage.HyperlinkReferenceData(position, name.length(), newReferenceData(internalTypeName, "<init>", descriptor, currentInternalTypeName)));
                } else {
                    // New type array -> Add a link to the type declaration
                    addHyperlink(new TypePage.HyperlinkReferenceData(position, name.length(), newReferenceData(internalTypeName, null, null, currentInternalTypeName)));
                }
            }
        }

        public void enterExpression(JavaParser.ExpressionContext ctx) {
            switch (ctx.getChildCount()) {
                case 1:
                    TerminalNode identifier0 = getToken(ctx.children, JavaParser.Identifier, 0);

                    if (identifier0 != null) {
                        if (isAField(ctx)) {
                            JavaParser.PrimaryContext primaryContext = ctx.primary();

                            if (primaryContext != null) {
                                String fieldName = primaryContext.literal().StringLiteral().getText();

                                if (currentContext.getDescriptor(fieldName) == null) {
                                    // Not a local variable or a method parameter
                                    String fieldTypeName = searchInternalTypeNameForThisFieldName(currentInternalTypeName, fieldName);
                                    int position = ctx.Identifier().getSymbol().getStartIndex();

                                    addHyperlink(new TypePage.HyperlinkReferenceData(position, fieldName.length(), newReferenceData(fieldTypeName, fieldName, "?", currentInternalTypeName)));
                                }
                            }
                        }
                    } else if (ctx.primary() != null) {
                        TerminalNode identifier = ctx.primary().Identifier();

                        if (identifier != null) {
                            Token symbol = identifier.getSymbol();
                            String name = symbol.getText();
                            String internalTypeName = nameToInternalTypeName.get(name);

                            if (internalTypeName != null) {
                                int position = symbol.getStartIndex();

                                addHyperlink(new TypePage.HyperlinkReferenceData(position, name.length(), newReferenceData(internalTypeName, null, null, currentInternalTypeName)));
                            }
                        }
                    }
                    break;
                case 3:
                    if (getToken(ctx.children, JavaParser.DOT, 1) != null) {
                        // Search "expression '.' Identifier" : field reference
                        TerminalNode identifier3 = getToken(ctx.children, JavaParser.Identifier, 2);

                        if ((identifier3 != null) && isAField(ctx)) {
                            String fieldTypeName = getInternalTypeName(ctx.getChild(0));

                            if (fieldTypeName != null) {
                                int position = identifier3.getSymbol().getStartIndex();
                                String fieldName = identifier3.getText();

                                addHyperlink(new TypePage.HyperlinkReferenceData(position, fieldName.length(), newReferenceData(fieldTypeName, fieldName, "?", currentInternalTypeName)));
                            }
                        }
                    } else if (getToken(ctx.children, JavaParser.LPAREN, 1) != null) {
                        // Search "expression '(' ')'" : method reference
                        if (getToken(ctx.children, JavaParser.RPAREN, 2) != null) {
                            enterCallMethodExpression(ctx, null);
                        }
                    }
                    break;
                case 4:
                    if (getToken(ctx.children, JavaParser.LPAREN, 1) != null) {
                        // Search "expression '(' expressionList ')'" : method reference
                        if (getToken(ctx.children, JavaParser.RPAREN, 3) != null) {
                            JavaParser.ExpressionListContext expressionListContext = ctx.expressionList();

                            if ((expressionListContext != null) && (expressionListContext == ctx.children.get(2))) {
                                enterCallMethodExpression(ctx, expressionListContext);
                            }
                        }
                    }
                    break;
            }
        }

        public void enterCallMethodExpression(JavaParser.ExpressionContext ctx, JavaParser.ExpressionListContext expressionListContext) {
            ParseTree first = ctx.children.get(0);

            if (first instanceof JavaParser.ExpressionContext) {
                JavaParser.ExpressionContext f = (JavaParser.ExpressionContext)first;

                switch (f.getChildCount()) {
                    case 1:
                        JavaParser.PrimaryContext primary = f.primary();
                        TerminalNode identifier = primary.Identifier();

                        if (identifier != null) {
                            Token symbol = identifier.getSymbol();

                            if (symbol != null) {
                                String methodName = symbol.getText();
                                String methodTypeName = searchInternalTypeNameForThisMethodName(currentInternalTypeName, methodName);

                                if (methodTypeName != null) {
                                    int position = symbol.getStartIndex();
                                    String methodDescriptor = (expressionListContext != null) ? getParametersDescriptor(expressionListContext).append('?').toString() : "()?";

                                    addHyperlink(new TypePage.HyperlinkReferenceData(position, methodName.length(), newReferenceData(methodTypeName, methodName, methodDescriptor, currentInternalTypeName)));
                                }
                            }
                        } else {
                            Token symbol = primary.getChild(TerminalNode.class, 0).getSymbol();

                            if (symbol != null) {
                                switch (symbol.getType()) {
                                    case JavaParser.THIS:
                                        int position = symbol.getStartIndex();
                                        String methodDescriptor = (expressionListContext != null) ? getParametersDescriptor(expressionListContext).append('?').toString() : "()?";

                                        addHyperlink(new TypePage.HyperlinkReferenceData(position, 4, newReferenceData(currentInternalTypeName, "<init>", methodDescriptor, currentInternalTypeName)));
                                        break;
                                    case JavaParser.SUPER:
                                        DeclarationData data = declarations.get(currentInternalTypeName);

                                        if (data instanceof TypeDeclarationData) {
                                            position = symbol.getStartIndex();
                                            String methodTypeName = ((TypeDeclarationData) data).superTypeName;
                                            methodDescriptor = (expressionListContext != null) ? getParametersDescriptor(expressionListContext).append('?').toString() : "()?";

                                            addHyperlink(new TypePage.HyperlinkReferenceData(position, 5, newReferenceData(methodTypeName, "<init>", methodDescriptor, currentInternalTypeName)));
                                        }
                                        break;
                                }
                            }
                        }
                        break;
                    case 3:
                        // Search "expression '.' Identifier"
                        ParseTree dot = first.getChild(1);

                        if ((dot instanceof TerminalNode) && (((TerminalNode)dot).getSymbol().getType() == JavaParser.DOT)) {
                            ParseTree identifier3 = first.getChild(2);

                            if (identifier3 instanceof TerminalNode) {
                                TerminalNode i3 = (TerminalNode)identifier3;

                                if (i3.getSymbol().getType() == JavaParser.Identifier) {
                                    String methodTypeName = getInternalTypeName(first.getChild(0));

                                    if (methodTypeName != null) {
                                        int position = i3.getSymbol().getStartIndex();
                                        String methodName = i3.getText();
                                        String methodDescriptor = (expressionListContext != null) ? getParametersDescriptor(expressionListContext).append('?').toString() : "()?";

                                        addHyperlink(new TypePage.HyperlinkReferenceData(position, methodName.length(), newReferenceData(methodTypeName, methodName, methodDescriptor, currentInternalTypeName)));
                                    }
                                }
                            }
                        }
                        break;
                }
            }
        }

        public StringBuilder getParametersDescriptor(JavaParser.ExpressionListContext expressionListContext) {
            StringBuilder sb = new StringBuilder('(');
            for (JavaParser.ExpressionContext exp : expressionListContext.expression()) sb.append('?');
            sb.append(')');
            return sb;
        }

        public boolean isAField(JavaParser.ExpressionContext ctx) {
            RuleContext parent = ctx.parent;

            if (parent instanceof JavaParser.ExpressionContext) {
                int size = parent.getChildCount();

                if (parent.getChild(size - 1) != ctx) {
                    for (int i=0; i<size; i++) {
                        if (parent.getChild(i) == ctx) {
                            ParseTree next = parent.getChild(i+1);

                            if (next instanceof TerminalNode) {
                                switch (((TerminalNode)next).getSymbol().getType()) {
                                    case JavaParser.DOT:
                                    case JavaParser.LPAREN:
                                        return false;
                                }
                            }
                        }
                    }
                }
            }

            return true;
        }

        public String getInternalTypeName(ParseTree pt) {
            if (pt instanceof JavaParser.ExpressionContext) {

                if (pt.getChildCount() == 1) {
                    JavaParser.PrimaryContext primary = ((JavaParser.ExpressionContext)pt).primary();
                    TerminalNode identifier = primary.Identifier();

                    if (identifier != null) {
                        String name = identifier.getSymbol().getText();
                        String descriptor = (currentContext == null) ? null : currentContext.getDescriptor(name);

                        if (descriptor != null) {
                            // Is a local variable or a method parameter
                            if (descriptor.charAt(0) == 'L') {
                                return descriptor.substring(1, descriptor.length() - 1);
                            }
                        } else if (currentInternalTypeName != null) {
                            String internalTypeName = searchInternalTypeNameForThisFieldName(currentInternalTypeName, name);

                            if (internalTypeName != null) {
                                // Is a field
                                return internalTypeName;
                            } else {
                                internalTypeName = resolveInternalTypeName(Collections.singletonList(identifier));

                                if (internalTypeName != null) {
                                    // Is a type
                                    return internalTypeName;
                                } else {
                                    // Not found
                                    return null;
                                }
                            }
                        }
                    } else {
                        TerminalNode tn = primary.getChild(TerminalNode.class, 0);
                        Token symbol = (tn == null) ? null : tn.getSymbol();

                        if (symbol != null) {
                            switch (symbol.getType()) {
                                case JavaParser.THIS:
                                    return currentInternalTypeName;
                                case JavaParser.SUPER:
                                    DeclarationData data = declarations.get(currentInternalTypeName);

                                    if (data instanceof TypeDeclarationData) {
                                        return ((TypeDeclarationData)data).superTypeName;
                                    } else {
                                        return null;
                                    }
                            }
                        }
                    }
                }
            }

            return null;
        }

        public String searchInternalTypeNameForThisFieldName(String internalTypeName, String name) {
            String prefix = internalTypeName + '-' + name + '-';
            int length = prefix.length();

            for (Map.Entry<String, DeclarationData> entry : declarations.entrySet()) {
                if (entry.getKey().startsWith(prefix) && (entry.getKey().charAt(length) != '(')) {
                    return entry.getValue().typeName;
                }
            }

            // Not found
            int index = internalTypeName.lastIndexOf('$');

            if (index != -1) {
                // Search in the outer type
                internalTypeName = internalTypeName.substring(0, index);

                return searchInternalTypeNameForThisFieldName(internalTypeName, name);
            }

            // Not found
            return null;
        }

        public String searchInternalTypeNameForThisMethodName(String internalTypeName, String name) {
            String prefix = internalTypeName + '-' + name + "-(";

            for (Map.Entry<String, DeclarationData> entry : declarations.entrySet()) {
                if (entry.getKey().startsWith(prefix)) {
                    return entry.getValue().typeName;
                }
            }

            // Not found
            int index = internalTypeName.lastIndexOf('$');

            if (index != -1) {
                // Search in the outer type
                internalTypeName = internalTypeName.substring(0, index);

                return searchInternalTypeNameForThisMethodName(internalTypeName, name);
            }

            // Not found
            return null;
        }

        public TerminalNode getToken(List<ParseTree> children, int type, int i) {
            ParseTree pt = children.get(i);

            if (pt instanceof TerminalNode) {
                if (((TerminalNode)pt).getSymbol().getType() == type) {
                    return (TerminalNode)pt;
                }
            }

            return null;
        }

        public void enterBlock(JavaParser.BlockContext ctx) {
            currentContext = new Context(currentContext);
        }

        public void exitBlock(JavaParser.BlockContext ctx) {
            currentContext = currentContext.outerContext;
        }

        public TypePage.ReferenceData newReferenceData(String internalName, String name, String descriptor, String scopeInternalName) {
            String key = internalName + '-' + name + '-'+ descriptor + '-' + scopeInternalName;
            TypePage.ReferenceData reference = referencesCache.get(key);

            if (reference == null) {
                reference = new TypePage.ReferenceData(internalName, name, descriptor, scopeInternalName);
                referencesCache.put(key, reference);
                references.add(reference);
            }

            return reference;
        }

        // --- Add strings --- //
        public void enterLiteral(JavaParser.LiteralContext ctx) {
            TerminalNode stringLiteral = ctx.StringLiteral();

            if (stringLiteral != null) {
                String str = stringLiteral.getSymbol().getText();
                int position = stringLiteral.getSymbol().getStartIndex();

                strings.add(new TypePage.StringData(position, str.length(), str, currentInternalTypeName));
            }
        }
    }

    public static class Context {
        protected Context outerContext;

        protected HashMap<String, String> nameToDescriptor = new HashMap<>();

        public Context(Context outerContext) {
            this.outerContext = outerContext;
        }

        /**
         * @param name Parameter or variable name
         * @return Qualified type name
         */
        public String getDescriptor(String name) {
            String descriptor = nameToDescriptor.get(name);

            if ((descriptor == null) && (outerContext != null)) {
                descriptor = outerContext.getDescriptor(name);
            }

            return descriptor;
        }
    }

    public static class TypeDeclarationData extends TypePage.DeclarationData {
        protected String superTypeName;

        public TypeDeclarationData(int startPosition, int length, String type, String name, String descriptor, String superTypeName) {
            super(startPosition, length, type, name, descriptor);

            this.superTypeName = superTypeName;
        }
    }
}