-
Notifications
You must be signed in to change notification settings - Fork 21
/
Copy pathMemoryMappingTree.java
2121 lines (1689 loc) · 56.1 KB
/
MemoryMappingTree.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) 2021 FabricMC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package net.fabricmc.mappingio.tree;
import java.io.IOException;
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.Deque;
import java.util.HashMap;
import java.util.HashSet;
import java.util.IdentityHashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import java.util.stream.Collectors;
import org.jetbrains.annotations.ApiStatus;
import org.jetbrains.annotations.Nullable;
import net.fabricmc.mappingio.MappedElementKind;
import net.fabricmc.mappingio.MappingFlag;
import net.fabricmc.mappingio.MappingVisitor;
import net.fabricmc.mappingio.adapter.MappingSourceNsSwitch;
/**
* {@link VisitableMappingTree} implementation that stores all data in memory.
*
* <p>Switching the source namespace with an existing destination namespace via
* {@link #setSrcNamespace(String)} or {@link #setDstNamespaces(List)} is not supported yet.
*/
public final class MemoryMappingTree implements VisitableMappingTree {
public MemoryMappingTree() {
this(false);
}
public MemoryMappingTree(boolean indexByDstNames) {
this.indexByDstNames = indexByDstNames;
}
public MemoryMappingTree(MappingTree src) {
if (src instanceof MemoryMappingTree) {
indexByDstNames = ((MemoryMappingTree) src).indexByDstNames;
}
setSrcNamespace(src.getSrcNamespace());
setDstNamespaces(src.getDstNamespaces());
for (MetadataEntry entry : src.getMetadata()) {
addMetadata(entry);
}
for (ClassMapping cls : src.getClasses()) {
addClass(cls);
}
}
/**
* Whether to index classes by their destination names, in addition to their source names.
*
* <p>Trades higher memory consumption for faster lookups by destination name.
*/
public void setIndexByDstNames(boolean indexByDstNames) {
assertNotInVisitPass();
if (indexByDstNames == this.indexByDstNames) return;
if (!indexByDstNames) {
classesByDstNames = null;
} else if (dstNamespaces != null) {
initClassesByDstNames();
}
this.indexByDstNames = indexByDstNames;
}
@SuppressWarnings("unchecked")
private void initClassesByDstNames() {
classesByDstNames = new Map[dstNamespaces.size()];
for (int i = 0; i < classesByDstNames.length; i++) {
classesByDstNames[i] = new HashMap<>(classesBySrcName.size());
}
for (ClassEntry cls : classesBySrcName.values()) {
for (int i = 0; i < cls.dstNames.length; i++) {
String dstName = cls.dstNames[i];
if (dstName != null) classesByDstNames[i].put(dstName, cls);
}
}
}
@ApiStatus.Experimental
public void setHierarchyInfoProvider(@Nullable HierarchyInfoProvider<?> provider) {
hierarchyInfo = provider;
if (provider != null) {
propagateNames(provider);
}
}
@Override
@Nullable
public String getSrcNamespace() {
return srcNamespace;
}
/**
* {@inheritDoc}
*
* @throws UnsupportedOperationException If the passed namespace name is already in use by one of the destination namespaces. This may change in a future release.
*/
@Override
@Nullable
public String setSrcNamespace(String namespace) {
assertNotInVisitPass();
if (dstNamespaces.contains(namespace)) {
throw new UnsupportedOperationException(String.format(
"Can't use name \"%s\" for the source namespace, as it's already in use by one of the destination namespaces %s."
+ " If a source namespace shuffle was the desired outcome, please resort to a %s instead; %s doesn't support this operation natively yet.",
namespace, dstNamespaces, MappingSourceNsSwitch.class.getSimpleName(), getClass().getSimpleName()));
}
String ret = srcNamespace;
srcNamespace = namespace;
return ret;
}
@Override
public List<String> getDstNamespaces() {
return dstNamespaces;
}
/**
* {@inheritDoc}
*
* @throws IllegalArgumentException If the passed namespace names contain duplicates.
* @throws UnsupportedOperationException If the passed namespace names contain the source namespace's name. This may change in a future release.
*/
@Override
public List<String> setDstNamespaces(List<String> namespaces) {
assertNotInVisitPass();
if (!classesBySrcName.isEmpty()) { // classes present, update existing dstNames
int newSize = namespaces.size();
int[] nameMap = new int[newSize];
Set<String> processedNamespaces = new HashSet<>(newSize);
Set<String> duplicateNamespaces = new HashSet<>(newSize);
for (int i = 0; i < newSize; i++) {
String newNs = namespaces.get(i);
if (newNs.equals(srcNamespace)) {
throw new UnsupportedOperationException(String.format(
"Can't use name \"%s\" for destination namespace %s, as it's already in use by the source namespace."
+ " If a source namespace shuffle was the desired outcome, please resort to a %s instead; %s doesn't support this operation natively yet.",
newNs, i, MappingSourceNsSwitch.class.getSimpleName(), getClass().getSimpleName()));
} else {
int oldNsIdx = dstNamespaces.indexOf(newNs);
nameMap[i] = oldNsIdx;
}
if (processedNamespaces.contains(newNs)) {
duplicateNamespaces.add(newNs);
}
processedNamespaces.add(newNs);
}
if (!duplicateNamespaces.isEmpty()) {
throw new IllegalArgumentException("Duplicate destination namespace names: " + duplicateNamespaces);
}
boolean useResize = true;
for (int i = 0; i < newSize; i++) {
int src = nameMap[i];
if (src != i && (src >= 0 || i >= dstNamespaces.size())) { // not a 1:1 copy with potential null extension
useResize = false;
break;
}
}
if (useResize) {
resizeDstNames(newSize);
} else {
updateDstNames(nameMap);
}
}
List<String> ret = dstNamespaces;
dstNamespaces = namespaces;
if (indexByDstNames) {
initClassesByDstNames();
}
return ret;
}
private void resizeDstNames(int newSize) {
for (ClassEntry cls : classesBySrcName.values()) {
cls.resizeDstNames(newSize);
for (FieldEntry field : cls.getFields()) {
field.resizeDstNames(newSize);
}
for (MethodEntry method : cls.getMethods()) {
method.resizeDstNames(newSize);
for (MethodArgEntry arg : method.getArgs()) {
arg.resizeDstNames(newSize);
}
for (MethodVarEntry var : method.getVars()) {
var.resizeDstNames(newSize);
}
}
}
}
private void updateDstNames(int[] nameMap) {
for (ClassEntry cls : classesBySrcName.values()) {
cls.updateDstNames(nameMap);
for (FieldEntry field : cls.getFields()) {
field.updateDstNames(nameMap);
}
for (MethodEntry method : cls.getMethods()) {
method.updateDstNames(nameMap);
for (MethodArgEntry arg : method.getArgs()) {
arg.updateDstNames(nameMap);
}
for (MethodVarEntry var : method.getVars()) {
var.updateDstNames(nameMap);
}
}
}
}
@Override
public List<? extends MetadataEntry> getMetadata() {
return metadata;
}
@Override
public List<? extends MetadataEntry> getMetadata(String key) {
return Collections.unmodifiableList(metadata.stream()
.filter(entry -> entry.getKey().equals(key))
.collect(Collectors.toList()));
}
@Override
public void addMetadata(MetadataEntry entry) {
metadata.add(entry);
}
@Override
public boolean removeMetadata(String key) {
return metadata.removeIf(entry -> entry.getKey().equals(key));
}
@Override
public Collection<? extends ClassMapping> getClasses() {
return classesView;
}
@Override
@Nullable
public ClassMapping getClass(String srcName) {
return classesBySrcName.get(srcName);
}
@Override
@Nullable
public ClassMapping getClass(String name, int namespace) {
if (namespace < 0 || !indexByDstNames) {
return VisitableMappingTree.super.getClass(name, namespace);
} else {
return classesByDstNames[namespace].get(name);
}
}
@Override
public ClassMapping addClass(ClassMapping cls) {
assertNotInVisitPass();
ClassEntry entry = cls instanceof ClassEntry && cls.getTree() == this ? (ClassEntry) cls : new ClassEntry(this, cls, getSrcNsEquivalent(cls));
ClassEntry ret = classesBySrcName.putIfAbsent(cls.getSrcName(), entry);
if (ret != null) {
ret.copyFrom(entry, true);
entry = ret;
}
if (indexByDstNames) {
for (int i = 0; i < entry.dstNames.length; i++) {
String dstName = entry.dstNames[i];
if (dstName != null) classesByDstNames[i].put(dstName, entry);
}
}
return entry;
}
private int getSrcNsEquivalent(ElementMapping mapping) {
int ret = mapping.getTree().getNamespaceId(srcNamespace);
if (ret == NULL_NAMESPACE_ID) throw new UnsupportedOperationException("can't find source namespace in referenced mapping tree");
return ret;
}
@Override
@Nullable
public ClassMapping removeClass(String srcName) {
assertNotInVisitPass();
ClassEntry ret = classesBySrcName.remove(srcName);
if (ret != null && indexByDstNames) {
for (int i = 0; i < ret.dstNames.length; i++) {
String dstName = ret.dstNames[i];
if (dstName != null) classesByDstNames[i].remove(dstName);
}
}
return ret;
}
@Override
public void accept(MappingVisitor visitor, VisitOrder order) throws IOException {
do {
if (visitor.visitHeader()) {
visitor.visitNamespaces(srcNamespace, dstNamespaces);
Collection<MetadataEntry> metadataToVisit = metadata;
if (visitor.getFlags().contains(MappingFlag.NEEDS_METADATA_UNIQUENESS)) {
Deque<MetadataEntry> uniqueMetadata = new ArrayDeque<>();
Set<String> addedKeys = new HashSet<>();
// Iterate last-to-first to construct a list of each key's latest occurrence.
for (int i = metadata.size() - 1; i >= 0; i--) {
MetadataEntry entry = metadata.get(i);
if (!addedKeys.contains(entry.getKey())) {
addedKeys.add(entry.getKey());
uniqueMetadata.addFirst(entry);
}
}
metadataToVisit = uniqueMetadata;
}
for (MetadataEntry entry : metadataToVisit) {
visitor.visitMetadata(entry.getKey(), entry.getValue());
}
}
if (visitor.visitContent()) {
Set<MappingFlag> flags = visitor.getFlags();
boolean supplyFieldDstDescs = flags.contains(MappingFlag.NEEDS_DST_FIELD_DESC);
boolean supplyMethodDstDescs = flags.contains(MappingFlag.NEEDS_DST_METHOD_DESC);
for (ClassEntry cls : order.sortClasses(classesBySrcName.values())) {
cls.accept(visitor, order, supplyFieldDstDescs, supplyMethodDstDescs);
}
}
} while (!visitor.visitEnd());
}
@Override
public void reset() {
inVisitPass = false;
srcNsMap = SRC_NAMESPACE_ID;
dstNameMap = null;
currentEntry = null;
currentClass = null;
currentMethod = null;
pendingClasses = null;
pendingMembers = null;
}
@Override
public void visitNamespaces(String srcNamespace, List<String> dstNamespaces) {
inVisitPass = true;
srcNsMap = SRC_NAMESPACE_ID;
dstNameMap = new int[dstNamespaces.size()];
if (this.srcNamespace != null) { // ns already set, try to merge
if (!srcNamespace.equals(this.srcNamespace)) {
srcNsMap = this.dstNamespaces.indexOf(srcNamespace);
if (srcNsMap < 0) {
reset();
throw new IllegalArgumentException("can't merge with disassociated src namespace"); // srcNamespace must already be present
}
}
int newDstNamespaces = 0;
for (int i = 0; i < dstNameMap.length; i++) {
String dstNs = dstNamespaces.get(i);
int idx;
if (dstNs.equals(this.srcNamespace)) {
idx = SRC_NAMESPACE_ID;
} else if (dstNs.equals(srcNamespace)) {
reset();
throw new IllegalArgumentException("namespace \"" + srcNamespace + "\" is present on both source and destination side simultaneously");
} else {
idx = this.dstNamespaces.indexOf(dstNs);
if (idx < 0) {
if (newDstNamespaces == 0) this.dstNamespaces = new ArrayList<>(this.dstNamespaces);
idx = this.dstNamespaces.size();
this.dstNamespaces.add(dstNs);
newDstNamespaces++;
}
}
dstNameMap[i] = idx;
}
if (newDstNamespaces > 0) {
int newSize = this.dstNamespaces.size();
resizeDstNames(newSize);
if (indexByDstNames) {
classesByDstNames = Arrays.copyOf(classesByDstNames, newSize);
for (int i = newSize - newDstNamespaces; i < classesByDstNames.length; i++) {
classesByDstNames[i] = new HashMap<>(classesBySrcName.size());
}
}
}
} else {
this.srcNamespace = srcNamespace;
this.dstNamespaces = dstNamespaces;
for (int i = 0; i < dstNameMap.length; i++) {
if (dstNamespaces.get(i).equals(srcNamespace)) {
reset();
throw new IllegalArgumentException("namespace \"" + srcNamespace + "\" is present on both source and destination side simultaneously");
}
dstNameMap[i] = i;
}
if (indexByDstNames) {
initClassesByDstNames();
}
}
}
@Override
public void visitMetadata(String key, @Nullable String value) {
MetadataEntryImpl entry = new MetadataEntryImpl(key, value);
metadata.add(entry);
}
@Override
public boolean visitClass(String srcName) {
currentMethod = null;
ClassEntry cls = (ClassEntry) getClass(srcName, srcNsMap);
if (cls == null) {
if (srcNsMap >= 0) { // tree-side srcName unknown
cls = queuePendingClass(srcName);
} else {
cls = new ClassEntry(this, srcName);
classesBySrcName.put(srcName, cls);
}
}
currentEntry = currentClass = cls;
return true;
}
@Override
public boolean visitField(String srcName, @Nullable String srcDesc) {
if (currentClass == null) throw new UnsupportedOperationException("Tried to visit field before owning class");
currentMethod = null;
FieldEntry field = currentClass.getField(srcName, srcDesc, srcNsMap);
if (field == null) {
if (srcNsMap >= 0) { // tree-side srcName unknown, can't create new entry directly
field = (FieldEntry) queuePendingMember(srcName, srcDesc, true);
} else {
field = new FieldEntry(currentClass, srcName, srcDesc);
field = currentClass.addFieldInternal(field);
}
} else if (srcDesc != null && field.srcDesc == null) {
if (srcNsMap >= 0) {
// delay descriptor computation until all classes have been supplied
queuePendingMember(srcName, srcDesc, true).setSrcName(field.getSrcName());
} else {
field.setSrcDescInternal(srcDesc);
}
}
currentEntry = field;
return true;
}
@Override
public boolean visitMethod(String srcName, @Nullable String srcDesc) {
if (currentClass == null) throw new UnsupportedOperationException("Tried to visit method before owning class");
MethodEntry method = currentClass.getMethod(srcName, srcDesc, srcNsMap);
if (method == null) {
if (srcNsMap >= 0) { // tree-side srcName unknown, can't create new entry directly
method = (MethodEntry) queuePendingMember(srcName, srcDesc, false);
} else {
method = new MethodEntry(currentClass, srcName, srcDesc);
method = currentClass.addMethodInternal(method);
}
} else if (isValidDescriptor(srcDesc, true) && !isValidDescriptor(method.srcDesc, true)) {
if (srcNsMap >= 0) {
// delay descriptor computation until all classes have been supplied
queuePendingMember(srcName, srcDesc, false).setSrcName(method.getSrcName());
} else {
method.setSrcDescInternal(srcDesc);
}
}
currentEntry = currentMethod = method;
return true;
}
private ClassEntry queuePendingClass(String name) {
if (pendingClasses == null) pendingClasses = new HashMap<>();
ClassEntry cls = pendingClasses.get(name);
if (cls == null) {
cls = new ClassEntry(this, null);
pendingClasses.put(name, cls);
}
assert srcNsMap >= 0;
cls.setDstNameInternal(name, srcNsMap);
return cls;
}
private MemberEntry<?> queuePendingMember(String name, @Nullable String desc, boolean isField) {
if (pendingMembers == null) pendingMembers = new HashMap<>();
GlobalMemberKey key = new GlobalMemberKey(currentClass, name, desc, isField);
MemberEntry<?> member = pendingMembers.get(key);
if (member == null) {
if (isField) {
member = new FieldEntry(currentClass, null, desc); // we're misusing the srcDesc field to store the dstDesc (as there is no dstDesc field)
} else {
member = new MethodEntry(currentClass, null, desc);
}
pendingMembers.put(key, member);
}
assert srcNsMap >= 0;
member.setDstNameInternal(name, srcNsMap);
return member;
}
private void addPendingClass(ClassEntry cls) {
if (cls.isSrcNameMissing()) {
return;
}
String srcName = cls.getSrcName();
ClassEntry existing = classesBySrcName.get(srcName);
if (existing == null) {
classesBySrcName.put(srcName, cls);
} else { // copy remaining data
existing.copyFrom(cls, true);
}
}
private void addPendingMember(MemberEntry<?> member) {
if (member.isSrcNameMissing() || member.getOwner().isSrcNameMissing()) {
return;
}
// Make sure the owner reference is pointing to an in-tree entry
ClassEntry owner = classesBySrcName.get(member.getOwner().getSrcName());
member.setOwner(owner);
boolean isField = member.getKind() == MappedElementKind.FIELD;
String srcName = member.getSrcName();
String dstDesc = member.getSrcDesc(); // pending members' srcDesc is actually their dst desc
String srcDesc = null;
if (isValidDescriptor(dstDesc, !isField)) {
srcDesc = mapDesc(dstDesc, srcNsMap, SRC_NAMESPACE_ID);
}
member.setSrcDescInternal(srcDesc);
if (isField) {
FieldEntry queuedField = (FieldEntry) member;
FieldEntry existingField = owner.getField(srcName, srcDesc);
if (existingField == null) {
owner.addFieldInternal(queuedField);
} else { // copy remaining data
existingField.copyFrom(queuedField, true);
}
} else {
MethodEntry queuedMethod = (MethodEntry) member;
MethodEntry existingMethod = owner.getMethod(srcName, srcDesc);
if (existingMethod == null) {
owner.addMethodInternal(queuedMethod);
} else { // copy remaining data
existingMethod.copyFrom(queuedMethod, true);
}
}
}
@Override
public boolean visitMethodArg(int argPosition, int lvIndex, @Nullable String srcName) {
if (currentMethod == null) throw new UnsupportedOperationException("Tried to visit method argument before owning method");
MethodArgEntry arg = currentMethod.getArg(argPosition, lvIndex, srcName);
if (arg == null) {
arg = new MethodArgEntry(currentMethod, argPosition, lvIndex, srcName);
arg = currentMethod.addArgInternal(arg);
} else {
if (argPosition >= 0 && arg.argPosition < 0) arg.setArgPositionInternal(argPosition);
if (lvIndex >= 0 && arg.lvIndex < 0) arg.setLvIndexInternal(lvIndex);
if (srcName != null) {
assert !srcName.isEmpty();
arg.setSrcName(srcName);
}
}
currentEntry = arg;
return true;
}
@Override
public boolean visitMethodVar(int lvtRowIndex, int lvIndex, int startOpIdx, int endOpIdx, @Nullable String srcName) {
if (currentMethod == null) throw new UnsupportedOperationException("Tried to visit method variable before owning method");
MethodVarEntry var = currentMethod.getVar(lvtRowIndex, lvIndex, startOpIdx, endOpIdx, srcName);
if (var == null) {
var = new MethodVarEntry(currentMethod, lvtRowIndex, lvIndex, startOpIdx, endOpIdx, srcName);
var = currentMethod.addVarInternal(var);
} else {
if (lvtRowIndex >= 0 && var.lvtRowIndex < 0) var.setLvtRowIndexInternal(lvtRowIndex);
if (lvIndex >= 0 && startOpIdx >= 0 && (var.lvIndex < 0 || var.startOpIdx < 0)) var.setLvIndexInternal(lvIndex, startOpIdx, endOpIdx);
if (srcName != null) {
assert !srcName.isEmpty();
var.setSrcName(srcName);
}
}
currentEntry = var;
return true;
}
@Override
public boolean visitEnd() {
// TODO: Don't discard pending elements which are still missing their tree-side src names, upcoming visit passes might provide them
if (pendingClasses != null) {
for (ClassEntry cls : pendingClasses.values()) {
addPendingClass(cls);
}
pendingClasses = null;
}
if (pendingMembers != null) {
for (MemberEntry<?> member : pendingMembers.values()) {
addPendingMember(member);
}
pendingMembers = null;
}
reset();
if (hierarchyInfo != null) {
propagateNames(hierarchyInfo);
}
return true;
}
private <T> void propagateNames(HierarchyInfoProvider<T> provider) {
int nsId = getNamespaceId(provider.getNamespace());
if (nsId == NULL_NAMESPACE_ID) return;
Set<MethodEntry> processed = Collections.newSetFromMap(new IdentityHashMap<>());
for (ClassEntry cls : classesBySrcName.values()) {
for (MethodEntry method : cls.getMethods()) {
String name = method.getName(nsId);
if (name == null || name.startsWith("<")) continue; // missing name, <clinit> or <init>
if (!processed.add(method)) continue;
T hierarchy = provider.getMethodHierarchy(method);
if (provider.getHierarchySize(hierarchy) <= 1) continue;
Collection<? extends MethodMapping> hierarchyMethods = provider.getHierarchyMethods(hierarchy, this);
if (hierarchyMethods.size() <= 1) continue;
String[] dstNames = new String[dstNamespaces.size()];
int rem = dstNames.length;
nameGatherLoop: for (MethodMapping m : hierarchyMethods) {
for (int i = 0; i < dstNames.length; i++) {
if (dstNames[i] != null) continue;
String curName = m.getDstName(i);
if (curName != null) {
dstNames[i] = curName;
if (--rem == 0) break nameGatherLoop;
}
}
}
for (MethodMapping m : hierarchyMethods) {
processed.add((MethodEntry) m);
for (int i = 0; i < dstNames.length; i++) {
String curName = dstNames[i];
if (curName != null) {
m.setDstName(curName, i);
}
}
}
}
}
}
@Override
public void visitDstName(MappedElementKind targetKind, int namespace, String name) {
namespace = dstNameMap[namespace];
if (currentEntry == null) throw new UnsupportedOperationException("Tried to visit mapped name before owner");
if (namespace < 0) {
if (name.equals(currentEntry.getSrcNameUnchecked())) return;
switch (currentEntry.getKind()) {
case CLASS:
assert currentClass == currentEntry;
case FIELD:
case METHOD:
if (currentEntry.isSrcNameMissing()) {
currentEntry.setSrcName(name);
return;
}
break;
case METHOD_ARG:
case METHOD_VAR:
currentEntry.setSrcName(name);
return;
}
throw new UnsupportedOperationException("can't change src name for "+currentEntry.getKind());
} else {
currentEntry.setDstNameInternal(name, namespace);
}
}
@Override
public void visitComment(MappedElementKind targetKind, String comment) {
Entry<?> entry;
switch (targetKind) {
case CLASS:
entry = currentClass;
break;
case METHOD:
entry = currentMethod;
break;
default:
entry = currentEntry;
}
if (entry == null) throw new UnsupportedOperationException("Tried to visit comment before owning target");
entry.setCommentInternal(comment);
}
private static boolean isValidDescriptor(String descriptor, boolean possiblyMethod) {
if (descriptor == null) {
return false;
}
if (possiblyMethod && descriptor.endsWith(")")) {
return false; // Parameter-only descriptor (Proguard?)
}
return true;
}
void assertNotInVisitPass() {
if (inVisitPass) {
throw new UnsupportedOperationException("Attempted illegal tree interaction via tree-API during an ongoing visitation pass");
}
}
abstract static class Entry<T extends Entry<T>> implements ElementMapping {
protected Entry(MemoryMappingTree tree, String srcName) {
this.tree = tree;
this.srcName = srcName;
this.dstNames = new String[tree.dstNamespaces.size()];
}
protected Entry(MemoryMappingTree tree, ElementMapping src, int srcNsEquivalent) {
this(tree, src.getName(srcNsEquivalent));
for (int i = 0; i < dstNames.length; i++) {
int dstNsEquivalent = src.getTree().getNamespaceId(tree.dstNamespaces.get(i));
if (dstNsEquivalent != NULL_NAMESPACE_ID) {
setDstNameInternal(src.getDstName(dstNsEquivalent), i);
}
}
setCommentInternal(src.getComment());
}
public abstract MappedElementKind getKind();
final boolean isSrcNameMissing() {
return srcName == null;
}
String getSrcNameUnchecked() {
return srcName;
}
@Override
public final String getSrcName() {
if (!missingSrcNameAllowed) {
assertSrcNamePresent();
}
return srcName;
}
protected final void assertSrcNamePresent() {
if (isSrcNameMissing()) {
throw new UnsupportedOperationException("Attempted illegal interaction with a pending entry still missing its tree-side source name");
}
}
void setSrcName(String name) {
if (!missingSrcNameAllowed && name == null) {
throw new UnsupportedOperationException("Source name cannot be null");
}
srcName = name;
}
@Override
@Nullable
public final String getDstName(int namespace) {
return dstNames[namespace];
}
@Override
public final void setDstName(String name, int namespace) {
tree.assertNotInVisitPass();
setDstNameInternal(name, namespace);
}
void setDstNameInternal(String name, int namespace) {
dstNames[namespace] = name;
}
void resizeDstNames(int newSize) {
dstNames = Arrays.copyOf(dstNames, newSize);
}
void updateDstNames(int[] map) {
String[] newDstNames = new String[map.length];
for (int i = 0; i < map.length; i++) {
int src = map[i];
if (src >= 0) {
newDstNames[i] = dstNames[src];
}
}
dstNames = newDstNames;
}
@Override
@Nullable
public final String getComment() {
return comment;
}
@Override
public final void setComment(String comment) {
tree.assertNotInVisitPass();
setCommentInternal(comment);
}
void setCommentInternal(String comment) {
this.comment = comment;
}
protected final boolean acceptElement(MappingVisitor visitor, @Nullable String[] dstDescs) throws IOException {
MappedElementKind kind = getKind();
for (int i = 0; i < dstNames.length; i++) {
String dstName = dstNames[i];
if (dstName != null) visitor.visitDstName(kind, i, dstName);
}
if (dstDescs != null) {
for (int i = 0; i < dstDescs.length; i++) {
String dstDesc = dstDescs[i];
if (dstDesc != null) visitor.visitDstDesc(kind, i, dstDesc);
}
}
if (!visitor.visitElementContent(kind)) {
return false;
}
if (comment != null) visitor.visitComment(kind, comment);
return true;
}
protected void copyFrom(T o, boolean replace) {
for (int i = 0; i < dstNames.length; i++) {
if (o.dstNames[i] != null && (replace || dstNames[i] == null)) {
dstNames[i] = o.dstNames[i];
}
}
if (o.comment != null && (replace || comment == null)) {
comment = o.comment;
}
}
private final boolean missingSrcNameAllowed = getKind().level > MappedElementKind.METHOD.level; // args and vars
protected final MemoryMappingTree tree;
private String srcName;
protected String[] dstNames;
protected String comment;
}
static final class ClassEntry extends Entry<ClassEntry> implements ClassMapping {
ClassEntry(MemoryMappingTree tree, String srcName) {
super(tree, srcName);
}
ClassEntry(MemoryMappingTree tree, ClassMapping src, int srcNsEquivalent) {
super(tree, src, srcNsEquivalent);