/
ReferenceExtractor.java
1459 lines (1343 loc) · 44 KB
/
ReferenceExtractor.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*******************************************************************************
* Copyright (c) 2007, 2020 IBM Corporation and others.
*
* This program and the accompanying materials
* are made available under the terms of the Eclipse Public License 2.0
* which accompanies this distribution, and is available at
* https://www.eclipse.org/legal/epl-2.0/
*
* SPDX-License-Identifier: EPL-2.0
*
* Contributors:
* IBM Corporation - initial API and implementation
*******************************************************************************/
package org.eclipse.pde.api.tools.internal.builder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import java.util.SortedSet;
import java.util.Stack;
import java.util.TreeSet;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.Status;
import org.eclipse.osgi.util.NLS;
import org.eclipse.pde.api.tools.internal.model.AbstractApiTypeRoot;
import org.eclipse.pde.api.tools.internal.provisional.ApiPlugin;
import org.eclipse.pde.api.tools.internal.provisional.builder.IReference;
import org.eclipse.pde.api.tools.internal.provisional.model.IApiBaseline;
import org.eclipse.pde.api.tools.internal.provisional.model.IApiComponent;
import org.eclipse.pde.api.tools.internal.provisional.model.IApiField;
import org.eclipse.pde.api.tools.internal.provisional.model.IApiMember;
import org.eclipse.pde.api.tools.internal.provisional.model.IApiMethod;
import org.eclipse.pde.api.tools.internal.provisional.model.IApiType;
import org.eclipse.pde.api.tools.internal.util.Signatures;
import org.eclipse.pde.api.tools.internal.util.Util;
import org.objectweb.asm.AnnotationVisitor;
import org.objectweb.asm.Attribute;
import org.objectweb.asm.ClassReader;
import org.objectweb.asm.ClassVisitor;
import org.objectweb.asm.FieldVisitor;
import org.objectweb.asm.Handle;
import org.objectweb.asm.Label;
import org.objectweb.asm.MethodVisitor;
import org.objectweb.asm.Opcodes;
import org.objectweb.asm.Type;
import org.objectweb.asm.TypePath;
import org.objectweb.asm.signature.SignatureReader;
import org.objectweb.asm.signature.SignatureVisitor;
import org.objectweb.asm.tree.ClassNode;
/**
* Extracts references from a class file
*
* @since 1.0.0
*/
public class ReferenceExtractor extends ClassVisitor {
/**
* A visitor for visiting java 5+ signatures
*
* ClassSignature = (visitFormalTypeParameter visitClassBound?
* visitInterfaceBound* )* (visitSuperClass visitInterface* )
* MethodSignature = (visitFormalTypeParameter visitClassBound?
* visitInterfaceBound* )* (visitParameterType visitReturnType
* visitExceptionType* ) TypeSignature = visitBaseType | visitTypeVariable |
* visitArrayType | (visitClassType visitTypeArgument* (visitInnerClassType
* visitTypeArgument* )* visitEnd</tt> ) )
*/
class ClassFileSignatureVisitor extends SignatureVisitor {
protected int kind = -1;
protected int originalkind = -1;
protected int argumentcount = 0;
protected int type = 0;
protected String signature = null;
protected String name = null;
protected List<Reference> references;
public ClassFileSignatureVisitor() {
super(Util.LATEST_OPCODES_ASM);
this.references = new ArrayList<>();
}
/**
* Resets the visitor to its initial state. This method should be called
* after processing is done with the visitor
*/
protected void reset() {
// do not reset argument count, as it is needed once the signature
// visitor is done
this.kind = -1;
this.originalkind = -1;
this.name = null;
this.signature = null;
this.type = 0;
this.references.clear();
}
/**
* Processes the type specified by the name for the current signature
* context. The kind flag is set to a parameterized type as subsequent
* calls to this method without visiting other nodes only occurs when we
* are processing parameterized types of generic declarations
*
* @param name the name of the type
*/
protected void processType(String name) {
Type type = ReferenceExtractor.this.resolveType(Type.getObjectType(name).getDescriptor());
if (type != null) {
String tname = type.getClassName();
if (tname.equals("E") || tname.equals("T")) { //$NON-NLS-1$//$NON-NLS-2$
type = Type.getObjectType("java.lang.Object"); //$NON-NLS-1$
tname = type.getClassName();
}
if (ReferenceExtractor.this.consider(tname) && this.kind != -1) {
if (this.name != null && this.signature != null) {
this.references.add(Reference.typeReference(ReferenceExtractor.this.getMember(), tname, this.signature, this.kind));
}
}
}
this.kind = this.originalkind;
}
@Override
public void visitClassType(String name) {
this.processType(name);
}
@Override
public void visitFormalTypeParameter(String name) {
if (this.type != TYPE) {
this.processType(name);
}
}
@Override
public void visitTypeVariable(String name) {
//
}
@Override
public void visitInnerClassType(String name) {
this.processType(name);
}
@Override
public SignatureVisitor visitParameterType() {
this.argumentcount++;
this.kind = IReference.REF_PARAMETER;
return this;
}
@Override
public SignatureVisitor visitInterface() {
this.kind = IReference.REF_IMPLEMENTS;
return this;
}
@Override
public SignatureVisitor visitExceptionType() {
this.kind = IReference.REF_THROWS;
return this;
}
@Override
public SignatureVisitor visitArrayType() {
return this;
}
@Override
public SignatureVisitor visitReturnType() {
this.kind = IReference.REF_RETURNTYPE;
return this;
}
@Override
public SignatureVisitor visitClassBound() {
this.kind = IReference.REF_PARAMETERIZED_TYPEDECL;
return this;
}
@Override
public SignatureVisitor visitInterfaceBound() {
this.kind = IReference.REF_PARAMETERIZED_TYPEDECL;
return this;
}
@Override
public SignatureVisitor visitSuperclass() {
this.kind = IReference.REF_EXTENDS;
return this;
}
@Override
public SignatureVisitor visitTypeArgument(char wildcard) {
return this;
}
@Override
public void visitEnd() {
//
}
@Override
public void visitBaseType(char descriptor) {
argumentcount++;
if (descriptor == 'J' || descriptor == 'D') {
argumentcount++;
}
}
@Override
public void visitTypeArgument() {
//
}
}
/**
* Visitor used to visit the methods of a type [ visitCode ( visitFrame |
* visit<i>X</i>Insn | visitLabel | visitTryCatchBlock | visitLocalVariable
* | visitLineNumber)* visitMaxs ] visitEnd
*/
class ClassFileMethodVisitor extends MethodVisitor {
int argumentcount = 0;
LinePositionTracker linePositionTracker;
/**
* Most recent string literal encountered. Used to infer
* Class.forName("...") references.
*/
String stringLiteral;
String methodName;
int lastLineNumber;
boolean implicitConstructor = false;
LocalLineNumberMarker localVariableMarker;
HashMap<Label, List<LocalLineNumberMarker>> labelsToLocalMarkers;
/**
* Constructor
*
* @param mv
*/
public ClassFileMethodVisitor(MethodVisitor mv, String name, int argumentcount) {
super(Util.LATEST_OPCODES_ASM, mv);
this.argumentcount = argumentcount;
this.linePositionTracker = new LinePositionTracker();
this.lastLineNumber = -1;
this.labelsToLocalMarkers = new HashMap<>();
this.methodName = name;
}
@Override
public void visitEnd() {
this.implicitConstructor = false;
this.argumentcount = 0;
ReferenceExtractor.this.exitMember();
this.linePositionTracker.computeLineNumbers();
this.labelsToLocalMarkers = null;
}
@Override
public void visitVarInsn(int opcode, int var) {
this.stringLiteral = null;
if (opcode == Opcodes.ASTORE && this.lastLineNumber != -1) {
this.localVariableMarker = new LocalLineNumberMarker(this.lastLineNumber, var);
}
}
@Override
public void visitFieldInsn(int opcode, String owner, String name, String desc) {
int refType = switch (opcode) {
case Opcodes.PUTSTATIC -> IReference.REF_PUTSTATIC;
case Opcodes.PUTFIELD -> IReference.REF_PUTFIELD;
case Opcodes.GETSTATIC -> IReference.REF_GETSTATIC;
case Opcodes.GETFIELD -> IReference.REF_GETFIELD;
default -> -1;
};
if (refType != -1) {
Reference reference = ReferenceExtractor.this.addFieldReference(Type.getObjectType(owner), name, refType);
if (reference != null) {
this.linePositionTracker.addLocation(reference);
if (refType == IReference.REF_GETFIELD || refType == IReference.REF_PUTFIELD) {
ReferenceExtractor.this.fieldtracker.addField(reference);
}
}
}
}
@Override
public void visitTryCatchBlock(Label start, Label end, Label handler, String type) {
if (type != null) {
Type ctype = Type.getObjectType(type);
Reference reference = ReferenceExtractor.this.addTypeReference(ctype, IReference.REF_CATCHEXCEPTION);
if (reference != null) {
this.linePositionTracker.addCatchLabelInfos(reference, handler);
this.linePositionTracker.addLocation(reference);
}
}
}
@Override
public void visitLabel(Label label) {
this.linePositionTracker.addLabel(label);
if (this.localVariableMarker != null) {
List<LocalLineNumberMarker> list = this.labelsToLocalMarkers.get(label);
if (list != null) {
list.add(this.localVariableMarker);
} else {
list = new ArrayList<>();
list.add(this.localVariableMarker);
this.labelsToLocalMarkers.put(label, list);
}
this.localVariableMarker = null;
}
}
@Override
public void visitMethodInsn(int opcode, String owner, String name, String desc, boolean inf) {
Type declaringType = Type.getObjectType(owner);
int kind = -1;
int flags = 0;
switch (opcode) {
case Opcodes.INVOKESPECIAL -> {
kind = ("<init>".equals(name) ? IReference.REF_CONSTRUCTORMETHOD : IReference.REF_SPECIALMETHOD); //$NON-NLS-1$
if (kind == IReference.REF_CONSTRUCTORMETHOD) {
if (!implicitConstructor && this.methodName.equals("<init>") && !fSuperStack.isEmpty() && (fSuperStack.peek()).equals(declaringType.getClassName())) { //$NON-NLS-1$
implicitConstructor = true;
kind = IReference.REF_SUPER_CONSTRUCTORMETHOD;
} else {
Reference reference = ReferenceExtractor.this.addTypeReference(declaringType, IReference.REF_INSTANTIATE);
if (reference != null) {
this.linePositionTracker.addLocation(reference);
}
}
}
}
case Opcodes.INVOKESTATIC -> {
kind = IReference.REF_STATICMETHOD;
// check for reference to a class literal
if (name.equals("forName")) { //$NON-NLS-1$
if (ReferenceExtractor.this.processName(owner).equals("java.lang.Class")) { //$NON-NLS-1$
if (this.stringLiteral != null) {
try {
Type classLiteral = Type.getObjectType(this.stringLiteral);
Reference reference = ReferenceExtractor.this.addTypeReference(classLiteral, IReference.REF_CONSTANTPOOL);
if (reference != null) {
this.linePositionTracker.addLocation(reference);
}
} catch (Exception e) {
// do nothing, but prevent bogus strings
// from causing problems in ASM
// https://bugs.eclipse.org/bugs/show_bug.cgi?id=399898
}
}
}
}
}
case Opcodes.INVOKEVIRTUAL -> {
kind = IReference.REF_VIRTUALMETHOD;
// try to determine if this is a default method
if (fVersion >= Opcodes.V1_8) {
IApiMember member = ReferenceExtractor.this.getMember();
if (member != null) {
try {
IApiComponent comp = fType.getApiComponent();
if (comp != null) {
String owner_sig = processName(owner);
AbstractApiTypeRoot root = (AbstractApiTypeRoot) comp.findTypeRoot(owner_sig);
if (root == null) {
// a quick look did not find it, now ask
// for the components that provide the
// package
IApiBaseline baseline = comp.getBaseline();
IApiComponent[] comps = baseline.resolvePackage(comp, Signatures.getPackageName(owner_sig));
for (IApiComponent c : comps) {
root = (AbstractApiTypeRoot) c.findTypeRoot(owner_sig);
if (root != null) {
break;
}
}
}
if (root != null) {
IApiType type = root.getStructure();
if (type != null && (!"<init>".equals(name)) //$NON-NLS-1$
&& getDefaultDefined(type, name, desc, false) != null) {
flags = IReference.F_DEFAULT_METHOD;
}
}
}
} catch (CoreException ce) {
// do nothing, give up
}
}
}
}
case Opcodes.INVOKEINTERFACE -> {
kind = IReference.REF_INTERFACEMETHOD;
}
default -> { /**/ }
}
if (kind != -1) {
Reference reference = ReferenceExtractor.this.addMethodReference(declaringType, name, desc, kind, flags);
if (reference != null) {
this.linePositionTracker.addLocation(reference);
if (kind == IReference.REF_STATICMETHOD) {
ReferenceExtractor.this.fieldtracker.addAccessor(reference);
}
}
}
this.stringLiteral = null;
}
@Override
public void visitInvokeDynamicInsn(String name, String desc, Handle bsm, Object... bsmArgs) {
for (Object arg : bsmArgs) {
if (arg instanceof Handle handle) {
Type declaringType = Type.getObjectType(handle.getOwner());
Reference reference = ReferenceExtractor.this.addMethodReference(declaringType, handle.getName(), handle.getDesc(), IReference.REF_VIRTUALMETHOD, 0);
if (reference != null) {
this.linePositionTracker.addLocation(reference);
}
}
}
}
@Override
public AnnotationVisitor visitInsnAnnotation(int typeRef, TypePath typePath, String desc, boolean visible) {
return null;
}
@Override
public void visitMultiANewArrayInsn(String desc, int dims) {
Type type = this.getTypeFromDescription(desc);
Reference reference = ReferenceExtractor.this.addTypeReference(type, IReference.REF_ARRAYALLOC);
if (reference != null) {
this.linePositionTracker.addLocation(reference);
}
}
@Override
public void visitLineNumber(int line, Label start) {
this.lastLineNumber = line;
this.linePositionTracker.addLineInfo(line, start);
}
@Override
public String toString() {
StringBuilder buffer = new StringBuilder();
buffer.append("Method visitor for: "); //$NON-NLS-1$
buffer.append(methodName);
buffer.append("\nCurrent line number: "); //$NON-NLS-1$
buffer.append(lastLineNumber);
return buffer.toString();
}
/**
* Creates a type from a type description. Works around bugs creating
* types from array type signatures in ASM.
*
* @param desc signature
* @return Type
*/
private Type getTypeFromDescription(String desc) {
String ldesc = desc;
while (ldesc.charAt(0) == '[') {
ldesc = ldesc.substring(1);
}
Type type = null;
if (ldesc.endsWith(";")) { //$NON-NLS-1$
type = Type.getType(ldesc);
} else {
type = Type.getObjectType(ldesc);
}
return type;
}
@Override
public void visitTypeInsn(int opcode, String desc) {
Type type = this.getTypeFromDescription(desc);
int kind = -1;
switch (opcode) {
case Opcodes.ANEWARRAY -> {
kind = IReference.REF_ARRAYALLOC;
}
case Opcodes.CHECKCAST -> {
kind = IReference.REF_CHECKCAST;
}
case Opcodes.INSTANCEOF -> {
kind = IReference.REF_INSTANCEOF;
}
case Opcodes.NEW -> {
// we can omit the NEW case as it is caught by the
// constructor call
// handle it only for anonymous / local types
List<Reference> refs = fAnonymousTypes.get(processName(type.getInternalName()));
if (refs != null) {
for (Reference reference : refs) {
this.linePositionTracker.addLocation(reference);
}
}
}
default -> { /**/ }
}
if (kind != -1) {
Reference reference = ReferenceExtractor.this.addTypeReference(type, kind);
if (reference != null) {
this.linePositionTracker.addLocation(reference);
}
}
}
@Override
public void visitLocalVariable(String name, String desc, String signature, Label start, Label end, int index) {
if (desc.length() == 1) {
// base type
return;
}
if (index > this.argumentcount) {
List<LocalLineNumberMarker> list = this.labelsToLocalMarkers.get(start);
int lineNumber = -1;
if (list != null) {
// list of potential localMarker
// iterate the list to find the one that matches the
// index
LocalLineNumberMarker removeMarker = null;
loop: for (LocalLineNumberMarker marker : list) {
if (marker.varIndex == index) {
lineNumber = marker.lineNumber;
removeMarker = marker;
break loop;
}
}
if (removeMarker != null) {
list.remove(removeMarker);
if (list.isEmpty()) {
this.labelsToLocalMarkers.remove(start);
}
}
}
if (lineNumber == -1) {
return;
}
if (signature != null) {
List<Reference> references = ReferenceExtractor.this.processSignature(name, signature, IReference.REF_PARAMETERIZED_VARIABLE, METHOD);
for (Reference reference : references) {
reference.setLineNumber(lineNumber);
}
} else {
Type type = Type.getType(desc);
if (type.getSort() == Type.OBJECT) {
Reference reference = ReferenceExtractor.this.addTypeReference(type, IReference.REF_LOCALVARIABLEDECL);
if (reference != null) {
reference.setLineNumber(lineNumber);
}
}
}
}
}
@Override
public void visitLdcInsn(Object cst) {
if (cst instanceof Type type) {
Reference reference = ReferenceExtractor.this.addTypeReference(type, IReference.REF_CONSTANTPOOL);
if (reference != null) {
this.linePositionTracker.addLocation(reference);
}
} else if (cst instanceof String str) {
this.stringLiteral = (Util.EMPTY_STRING.equals(str) ? null : str);
}
}
@Override
public AnnotationVisitor visitAnnotation(String desc, boolean visible) {
Type ctype = this.getTypeFromDescription(desc);
Reference reference = ReferenceExtractor.this.addTypeReference(ctype, IReference.REF_ANNOTATION_USE);
if (reference != null) {
linePositionTracker.addLocation(reference);
}
return null;
}
}
/**
* {@link FieldVisitor} to track use of types in annotations
*
* @since 1.0.600
*/
class ClassFileFieldVisitor extends FieldVisitor {
ClassFileFieldVisitor() {
super(Util.LATEST_OPCODES_ASM);
}
@Override
public AnnotationVisitor visitAnnotation(String desc, boolean visible) {
addTypeReference(Type.getType(desc), IReference.REF_ANNOTATION_USE);
return null;
}
@Override
public void visitAttribute(Attribute attr) {
//
}
@Override
public void visitEnd() {
exitMember();
}
}
/**
* @since 1.1
*/
static class FieldTracker {
HashMap<String, List<Reference>> accessors = new HashMap<>();
ArrayList<Reference> fields = new ArrayList<>();
ReferenceExtractor extractor = null;
/**
* Constructor
*/
public FieldTracker(ReferenceExtractor extractor) {
this.extractor = extractor;
}
/**
* Add a field to be tracked
*
* @param field
*/
public void addField(Reference ref) {
if (ref != null) {
fields.add(ref);
}
}
/**
* Add an accessor to be tracked
*
* @param accessor
*/
public void addAccessor(Reference ref) {
if (ref != null) {
String key = ref.getReferencedMemberName();
List<Reference> refs = accessors.get(key);
if (refs == null) {
refs = new ArrayList<>();
accessors.put(key, refs);
}
refs.add(ref);
}
}
/**
* Resolve any synthetic field access to their accessor
*/
public void resolveSyntheticFields() {
for (Reference field : fields) {
List<Reference> refs = accessors.get(field.getMember().getName());
if (refs != null) {
for (Reference accessor : refs) {
Reference refer = Reference.fieldReference(accessor.getMember(), field.getReferencedTypeName(), field.getReferencedMemberName(), field.getReferenceKind());
refer.setLineNumber(accessor.getLineNumber());
this.extractor.collector.add(refer);
}
// we resolved it, remove it
this.extractor.collector.remove(field);
}
}
}
}
static class LinePositionTracker {
List<Object> labelsAndLocations;
SortedSet<LineInfo> lineInfos;
List<LabelInfo> catchLabelInfos;
HashMap<Label, Integer> lineMap;
public LinePositionTracker() {
this.labelsAndLocations = new ArrayList<>();
this.lineInfos = new TreeSet<>();
this.catchLabelInfos = new ArrayList<>();
this.lineMap = new HashMap<>();
}
void addLocation(Reference location) {
this.labelsAndLocations.add(location);
}
void addLineInfo(int line, Label label) {
this.lineInfos.add(new LineInfo(line, label));
this.lineMap.put(label, Integer.valueOf(line));
}
void addCatchLabelInfos(Reference location, Label label) {
this.catchLabelInfos.add(new LabelInfo(location, label));
}
void addLabel(Label label) {
this.labelsAndLocations.add(label);
}
public void computeLineNumbers() {
if (this.lineInfos.size() < 1 || this.labelsAndLocations.size() < 1) {
// nothing to do
return;
}
Iterator<LineInfo> lineInfosIterator = this.lineInfos.iterator();
LineInfo firstLineInfo = lineInfosIterator.next();
int currentLineNumber = firstLineInfo.line;
List<LabelInfo> remainingCatchLabelInfos = new ArrayList<>();
for (LabelInfo catchLabelInfo : this.catchLabelInfos) {
Integer lineValue = this.lineMap.get(catchLabelInfo.label);
if (lineValue != null) {
catchLabelInfo.location.setLineNumber(lineValue.intValue());
} else {
remainingCatchLabelInfos.add(catchLabelInfo);
}
}
// Iterate over List of Labels and SourceLocations.
List<Object> computedEntries = new ArrayList<>();
for (Object current : this.labelsAndLocations) {
if (current instanceof Label) {
// label
Integer lineValue = this.lineMap.get(current);
if (lineValue != null) {
computedEntries.add(new LineInfo(lineValue.intValue(), (Label) current));
} else {
computedEntries.add(current);
}
} else {
// location
computedEntries.add(current);
}
}
List<LabelInfo> remaingEntriesTemp;
for (Object current : computedEntries) {
if (current instanceof Label) {
// try to set the line number for remaining catch labels
if (remainingCatchLabelInfos != null) {
remaingEntriesTemp = new ArrayList<>();
loop: for (LabelInfo catchLabelInfo : remainingCatchLabelInfos) {
if (!current.equals(catchLabelInfo.label)) {
remaingEntriesTemp.add(catchLabelInfo);
continue loop;
}
catchLabelInfo.location.setLineNumber(currentLineNumber);
}
if (remaingEntriesTemp.isEmpty()) {
remainingCatchLabelInfos = null;
} else {
remainingCatchLabelInfos = remaingEntriesTemp;
}
}
} else if (current instanceof Reference ref) {
if (ref.getLineNumber() == -1) {
ref.setLineNumber(currentLineNumber);
} else {
currentLineNumber = ref.getLineNumber();
}
} else if (current instanceof LineInfo lineInfo) {
currentLineNumber = lineInfo.line;
}
}
}
}
static class LabelInfo {
public Reference location;
public Label label;
public LabelInfo(Reference location, Label label) {
this.location = location;
this.label = label;
}
@Override
public String toString() {
StringBuilder buffer = new StringBuilder();
buffer.append('(').append(this.label).append(',').append(this.location).append(')');
return String.valueOf(buffer);
}
}
static class LineInfo implements Comparable<Object> {
int line;
Label label;
LineInfo(int line, Label label) {
this.line = line;
this.label = label;
}
@Override
public int compareTo(Object o) {
return this.line - ((LineInfo) o).line;
}
@Override
public boolean equals(Object obj) {
if (obj instanceof LineInfo lineInfo2) {
return this.line == lineInfo2.line && this.label.equals(lineInfo2.label);
}
return super.equals(obj);
}
@Override
public int hashCode() {
return this.line + (this.label != null ? this.label.hashCode() : 0);
}
@Override
public String toString() {
StringBuilder buffer = new StringBuilder();
buffer.append('(').append(this.line).append(',').append(this.label).append(')');
return String.valueOf(buffer);
}
}
static class LocalLineNumberMarker {
int lineNumber;
int varIndex;
public LocalLineNumberMarker(int line, int varIndex) {
this.lineNumber = line;
this.varIndex = varIndex;
}
@Override
public boolean equals(Object obj) {
if (obj instanceof LocalLineNumberMarker marker) {
return this.lineNumber == marker.lineNumber && this.varIndex == marker.varIndex;
}
return false;
}
@Override
public int hashCode() {
return this.varIndex;
}
}
/**
* The list we collect references in. Entries in the list are of the type
* {@link org.eclipse.pde.api.tools.internal.provisional.builder.IReference}
*/
Set<Reference> collector = null;
/**
* The full internal name of the class we are extracting references from
*/
private String classname = null;
/**
* Current type being visited.
*/
IApiType fType;
/**
* Stack of members being visited. When a member is entered its element
* descriptor is pushed onto the stack. When a member is exited, the stack
* is popped.
*/
Stack<IApiMember> fMemberStack = new Stack<>();
/**
* Stack of super types *names* (String) being visited. When a type is
* entered, its super type is pushed onto the stack. When a type is exited,
* the stack is popped.
*/
Stack<String> fSuperStack = new Stack<>();
/**
* Mapping of anonymous type names to their reference
*/
HashMap<String, List<Reference>> fAnonymousTypes = new HashMap<>();
/**
* Whether to extract references to elements within the classfile being
* scanned.
*/
private boolean fIncludeLocalRefs = false;
/**
* Bit mask of {@link ReferenceModifiers} to extract.
*/
private int fReferenceKinds = 0;
/**
* Track synthetic field / accessor
*
* @since 1.1
*/
FieldTracker fieldtracker = null;
/**
* The version for the class being visited
*
* @since 1.0.600
*/
private int fVersion;
/**
* Bit mask that determines if we need to visit members
*/
private static final int VISIT_MEMBERS_MASK = IReference.MASK_REF_ALL ^ (IReference.REF_EXTENDS | IReference.REF_IMPLEMENTS);
/**
* If members should be visited for type visits
*/
private boolean fIsVisitMembers = false;
/**
* Current field being visited, or <code>null</code> (when not within a
* field).
*/
private ClassFileSignatureVisitor signaturevisitor = new ClassFileSignatureVisitor();
static int TYPE = 0, FIELD = 1, METHOD = 2;
/**
* {@link FieldVisitor} used to track and collect references to annotation
* types
*
* @since 1.0.600
*/
private ClassFileFieldVisitor fieldvisitor = new ClassFileFieldVisitor();
/**
* Constructor
*
* @param type the type to extract references from
* @param collector the listing of references to annotate from this pass
* @param referenceKinds kinds of references to extract as defined by
* {@link ReferenceModifiers}
*/
public ReferenceExtractor(IApiType type, Set<Reference> collector, int referenceKinds) {
super(Util.LATEST_OPCODES_ASM, new ClassNode());
fType = type;
this.collector = collector;
fReferenceKinds = referenceKinds;
fIsVisitMembers = (VISIT_MEMBERS_MASK & fReferenceKinds) != 0;
fieldtracker = new FieldTracker(this);
}
/**
* Constructor
*
* @param type
* @param collector
* @param referenceKinds
* @param tracker
*/
protected ReferenceExtractor(IApiType type, Set<Reference> collector, int referenceKinds, FieldTracker tracker) {
super(Util.LATEST_OPCODES_ASM, new ClassNode());
fType = type;
this.collector = collector;
fReferenceKinds = referenceKinds;
fIsVisitMembers = (VISIT_MEMBERS_MASK & fReferenceKinds) != 0;
fieldtracker = tracker;
}
@Override
public String toString() {
StringBuilder buffer = new StringBuilder();
buffer.append("Reference extractor for: "); //$NON-NLS-1$
buffer.append(fType.getName());
buffer.append("\n"); //$NON-NLS-1$
buffer.append("Reference kinds: "); //$NON-NLS-1$
buffer.append(Reference.getReferenceText(fReferenceKinds));
buffer.append("\n"); //$NON-NLS-1$
buffer.append("Is visiting members: "); //$NON-NLS-1$
buffer.append(fIsVisitMembers);
return buffer.toString();
}
/**
* Returns whether to consider a reference to the specified type. Configured
* by setting to include references within the same class file.
*
* @param owner
* @return true if considered, false otherwise
*/
protected boolean consider(String owner) {
if (this.fIncludeLocalRefs) {
return true;
}
return !(this.classname.equals(owner) || this.classname.startsWith(owner) || "<clinit>".equals(owner) || "this".equals(owner)); //$NON-NLS-1$ //$NON-NLS-2$
}
/**
* Returns whether the specified reference should be considered when
* extracting references. Configured by setting on whether to include
* references within the same class file.