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
|
package com.replaymod.gradle.remap;
import org.eclipse.jdt.core.JavaCore;
import org.eclipse.jdt.core.compiler.IProblem;
import org.eclipse.jdt.core.dom.*;
import org.eclipse.jface.text.BadLocationException;
import org.eclipse.jface.text.Document;
import org.eclipse.text.edits.TextEdit;
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardOpenOption;
import java.util.ArrayDeque;
import java.util.Arrays;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.function.Function;
import java.util.stream.Collectors;
import java.util.stream.Stream;
class Transformer {
private Map<String, Mapping> map;
private String[] classpath;
private boolean fail;
public static void main(String[] args) throws IOException, BadLocationException {
Map<String, Mapping> mappings;
if (args[0].isEmpty()) {
mappings = new HashMap<>();
} else {
mappings = readMappings(new File(args[0]), args[1].equals("true"));
}
Transformer transformer = new Transformer(mappings);
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
String[] classpath = new String[Integer.parseInt(args[2])];
for (int i = 0; i < classpath.length; i++) {
classpath[i] = reader.readLine();
}
transformer.setClasspath(classpath);
Map<String, String> sources = new HashMap<>();
while (true) {
String name = reader.readLine();
if (name == null || name.isEmpty()) {
break;
}
String[] lines = new String[Integer.parseInt(reader.readLine())];
for (int i = 0; i < lines.length; i++) {
lines[i] = reader.readLine();
}
String source = String.join("\n", lines);
sources.put(name, source);
}
Map<String, String> results = transformer.remap(sources);
for (String name : sources.keySet()) {
System.out.println(name);
String[] lines = results.get(name).split("\n");
System.out.println(lines.length);
for (String line : lines) {
System.out.println(line);
}
}
if (transformer.fail) {
System.exit(1);
}
}
public Transformer(Map<String, Mapping> mappings) {
this.map = mappings;
}
public String[] getClasspath() {
return classpath;
}
public void setClasspath(String[] classpath) {
this.classpath = classpath;
}
public Map<String, String> remap(Map<String, String> sources) throws BadLocationException, IOException {
ASTParser parser = ASTParser.newParser(AST.JLS8);
Map<String, String> options = JavaCore.getDefaultOptions();
JavaCore.setComplianceOptions("1.8", options);
parser.setCompilerOptions(options);
parser.setEnvironment(classpath, null, null, true);
parser.setResolveBindings(true);
parser.setBindingsRecovery(true);
Path tmpDir = Files.createTempDirectory("remap");
try {
Map<String, String> filePathToName = new HashMap<>();
String[] compilationUnits = new String[sources.size()];
String[] encodings = new String[compilationUnits.length];
int i = 0;
for (Entry<String, String> entry : sources.entrySet()) {
String unitName = entry.getKey();
String source = entry.getValue();
Path path = tmpDir.resolve(unitName);
Files.createDirectories(path.getParent());
Files.write(path, source.getBytes(StandardCharsets.UTF_8), StandardOpenOption.CREATE);
String filePath = path.toString();
filePathToName.put(filePath, unitName);
compilationUnits[i] = filePath;
encodings[i] = "UTF-8";
i++;
}
Map<String, CompilationUnit> cus = new HashMap<>();
parser.createASTs(compilationUnits, encodings, new String[0], new FileASTRequestor() {
@Override
public void acceptAST(String sourceFilePath, CompilationUnit cu) {
String unitName = filePathToName.get(sourceFilePath);
for (IProblem problem : cu.getProblems()) {
if (problem.isError()) {
System.err.println(unitName + ":" + problem.getSourceLineNumber() + ": " + problem.getMessage());
}
}
cus.put(unitName, cu);
}
}, null);
Map<String, String> results = new HashMap<>();
for (Entry<String, CompilationUnit> entry : cus.entrySet()) {
String unitName = entry.getKey();
CompilationUnit cu = entry.getValue();
cu.recordModifications();
if (remapClass(unitName, cu)) {
Document document = new Document(sources.get(unitName));
TextEdit edit = cu.rewrite(document, JavaCore.getDefaultOptions());
edit.apply(document);
results.put(unitName, document.get());
} else {
results.put(unitName, sources.get(unitName));
}
}
return results;
} finally {
Files.walk(tmpDir).map(Path::toFile).sorted(Comparator.reverseOrder()).forEach(File::delete);
}
}
private static final String CLASS_MIXIN = "org.spongepowered.asm.mixin.Mixin";
private static final String CLASS_ACCESSOR = "org.spongepowered.asm.mixin.gen.Accessor";
private static final String CLASS_AT = "org.spongepowered.asm.mixin.injection.At";
private static final String CLASS_INJECT = "org.spongepowered.asm.mixin.injection.Inject";
private static final String CLASS_REDIRECT = "org.spongepowered.asm.mixin.injection.Redirect";
// Note: Supports only Mixins with a single target (ignores others) and only ones specified via class literals
private ITypeBinding getMixinTarget(IAnnotationBinding annotation) {
for (IMemberValuePairBinding pair : annotation.getDeclaredMemberValuePairs()) {
if (pair.getName().equals("value")) {
return (ITypeBinding) ((Object[]) pair.getValue())[0];
}
}
return null;
}
private boolean remapAccessors(CompilationUnit cu, Mapping mapping) {
AtomicBoolean changed = new AtomicBoolean(false);
AST ast = cu.getAST();
cu.accept(new ASTVisitor() {
@Override
public boolean visit(MethodDeclaration node) {
int annotationIndex = -1;
Annotation annotationNode = null;
IAnnotationBinding annotation = null;
for (int i = 0; i < node.modifiers().size(); i++) {
Object obj = node.modifiers().get(i);
if (!(obj instanceof Annotation)) {
continue;
}
annotationNode = (Annotation) obj;
annotation = annotationNode.resolveAnnotationBinding();
if (annotation != null && annotation.getAnnotationType().getQualifiedName().equals(CLASS_ACCESSOR)) {
annotationIndex = i;
break;
}
}
if (annotationIndex == -1) return false;
String targetByName = node.getName().getIdentifier();
if (targetByName.startsWith("is")) {
targetByName = targetByName.substring(2);
} else if (targetByName.startsWith("get") || targetByName.startsWith("set")) {
targetByName = targetByName.substring(3);
} else {
targetByName = null;
}
if (targetByName != null) {
targetByName = targetByName.substring(0, 1).toLowerCase() + targetByName.substring(1);
}
String target = Arrays.stream(annotation.getDeclaredMemberValuePairs())
.filter(it -> it.getName().equals("value"))
.map(it -> (String) it.getValue())
.findAny()
.orElse(targetByName);
if (target == null) {
throw new IllegalArgumentException("Cannot determine accessor target for " + node);
}
String mapped = mapping.fields.get(target);
if (mapped != null && !mapped.equals(target)) {
Annotation newAnnotation;
// Update accessor target
if (mapped.equals(targetByName)) {
// Mapped name matches implied target, can just remove the explict target
newAnnotation = ast.newMarkerAnnotation();
} else {
// Mapped name does not match implied target, need to set the target as annotation value
SingleMemberAnnotation singleMemberAnnotation = ast.newSingleMemberAnnotation();
StringLiteral value = ast.newStringLiteral();
value.setLiteralValue(mapped);
singleMemberAnnotation.setValue(value);
newAnnotation = singleMemberAnnotation;
}
newAnnotation.setTypeName(ast.newName(annotationNode.getTypeName().getFullyQualifiedName()));
//noinspection unchecked
node.modifiers().set(annotationIndex, newAnnotation);
changed.set(true);
}
return false;
}
});
return changed.get();
}
private boolean remapInjectsAndRedirects(CompilationUnit cu, Mapping mapping) {
AtomicBoolean changed = new AtomicBoolean(false);
cu.accept(new ASTVisitor() {
@Override
public boolean visit(MethodDeclaration node) {
NormalAnnotation annotationNode = null;
for (Object obj : node.modifiers()) {
if (!(obj instanceof NormalAnnotation)) {
continue;
}
annotationNode = (NormalAnnotation) obj;
IAnnotationBinding annotation = annotationNode.resolveAnnotationBinding();
if (annotation != null) {
String qualifiedName = annotation.getAnnotationType().getQualifiedName();
if (qualifiedName.equals(CLASS_INJECT) || qualifiedName.equals(CLASS_REDIRECT)) {
break;
}
}
annotationNode = null;
}
if (annotationNode == null) return false;
//noinspection unchecked
for (MemberValuePair pair : (List<MemberValuePair>) annotationNode.values()) {
if (!pair.getName().getIdentifier().equals("method")) continue;
Object expr = pair.getValue();
// Note: mixin supports multiple targets, we do not (yet)
if (!(expr instanceof StringLiteral)) continue;
StringLiteral methodNode = (StringLiteral) expr;
String method = methodNode.getLiteralValue();
String mapped = mapping.methods.get(method);
if (mapped != null && !mapped.equals(method)) {
methodNode.setLiteralValue(mapped);
changed.set(true);
}
}
return false;
}
});
return changed.get();
}
private Mapping remapInternalType(String internalType, StringBuilder result) {
if (internalType.charAt(0) == 'L') {
String type = internalType.substring(1, internalType.length() - 1).replace('/', '.');
Mapping mapping = map.get(type);
if (mapping != null) {
result.append('L').append(mapping.newName.replace('.', '/')).append(';');
return mapping;
}
}
result.append(internalType);
return null;
}
private String remapFullyQualifiedMethodOrField(String signature) {
int ownerEnd = signature.indexOf(';');
int argsBegin = signature.indexOf('(');
int argsEnd = signature.indexOf(')');
boolean method = argsBegin != -1;
if (!method) {
argsBegin = argsEnd = signature.indexOf(':');
}
String owner = signature.substring(0, ownerEnd + 1);
String name = signature.substring(ownerEnd + 1, argsBegin);
String returnType = signature.substring(argsEnd + 1);
StringBuilder builder = new StringBuilder(signature.length() + 32);
Mapping mapping = remapInternalType(owner, builder);
String mapped = null;
if (mapping != null) {
mapped = (method ? mapping.methods : mapping.fields).get(name);
}
builder.append(mapped != null ? mapped : name);
if (method) {
builder.append('(');
String args = signature.substring(argsBegin + 1, argsEnd);
for (int i = 0; i < args.length(); i++) {
char c = args.charAt(i);
if (c != 'L') {
builder.append(c);
continue;
}
int end = args.indexOf(';', i);
String arg = args.substring(i, end + 1);
remapInternalType(arg, builder);
i = end;
}
builder.append(')');
} else {
builder.append(':');
}
remapInternalType(returnType, builder);
return builder.toString();
}
private boolean remapAtTargets(CompilationUnit cu) {
AtomicBoolean changed = new AtomicBoolean(false);
cu.accept(new ASTVisitor() {
@Override
public boolean visit(NormalAnnotation node) {
IAnnotationBinding annotation = node.resolveAnnotationBinding();
if (annotation == null) return true;
String qualifiedName = annotation.getAnnotationType().getQualifiedName();
if (!qualifiedName.equals(CLASS_AT)) return true;
//noinspection unchecked
for (MemberValuePair pair : (List<MemberValuePair>) node.values()) {
if (!pair.getName().getIdentifier().equals("target")) continue;
StringLiteral value = (StringLiteral) pair.getValue();
String signature = value.getLiteralValue();
String newSignature = remapFullyQualifiedMethodOrField(signature);
if (!newSignature.equals(signature)) {
value.setLiteralValue(newSignature);
changed.set(true);
}
}
return false;
}
});
return changed.get();
}
private static String stripGenerics(String name) {
int paramIndex = name.indexOf('<');
return paramIndex != -1 ? name.substring(0, paramIndex) : name;
}
private boolean remapClass(String unitName, CompilationUnit cu) {
AtomicBoolean changed = new AtomicBoolean(false);
Map<String, Mapping> mixinMappings = new HashMap<>();
cu.accept(new ASTVisitor() {
@Override
public boolean visit(TypeDeclaration node) {
ITypeBinding type = node.resolveBinding();
if (type == null) return false;
IAnnotationBinding binding = null;
for (Object modifier : node.modifiers()) {
if (modifier instanceof Annotation) {
binding = ((Annotation) modifier).resolveAnnotationBinding();
if (binding != null && !binding.getAnnotationType().getQualifiedName().equals(CLASS_MIXIN)) {
binding = null;
}
}
}
if (binding == null) return false;
if (remapAtTargets(cu)) {
changed.set(true);
}
ITypeBinding target = getMixinTarget(binding);
if (target == null) return false;
Mapping mapping = map.get(target.getQualifiedName());
if (mapping == null) return false;
mixinMappings.put(type.getQualifiedName(), mapping);
if (!mapping.fields.isEmpty()) {
if (remapAccessors(cu, mapping)) {
changed.set(true);
}
}
if (!mapping.methods.isEmpty()) {
if (remapInjectsAndRedirects(cu, mapping)) {
changed.set(true);
}
}
return false;
}
});
cu.accept(new ASTVisitor() {
@Override
public boolean visit(ImportDeclaration node) {
String name = node.getName().getFullyQualifiedName();
Mapping mapping = map.get(name);
String mapped = mapping == null ? null : mapping.newName;
if (mapped != null && !mapped.equals(name)) {
node.setName(node.getAST().newName(mapped));
changed.set(true);
}
return false;
}
});
cu.accept(new ASTVisitor() {
@Override
public boolean visit(ImportDeclaration node) {
return false;
}
@Override
public boolean visit(QualifiedName node) {
String name = node.getFullyQualifiedName();
Mapping mapping = map.get(name);
String mapped = mapping == null ? null : mapping.newName;
if (mapped != null && !mapped.equals(name)) {
node.setQualifier(node.getAST().newName(mapped.substring(0, mapped.lastIndexOf('.'))));
node.setName(node.getAST().newSimpleName(mapped.substring(mapped.lastIndexOf('.') + 1)));
changed.set(true);
return false;
} else {
return true;
}
}
@Override
public boolean visit(SimpleName node) {
return visitName(node.resolveBinding(), node);
}
private boolean visitName(IBinding binding, SimpleName node) {
String mapped;
if (binding instanceof IVariableBinding) {
ITypeBinding declaringClass = ((IVariableBinding) binding).getDeclaringClass();
if (declaringClass == null) return true;
String name = stripGenerics(declaringClass.getQualifiedName());
if (name.isEmpty()) return true;
Mapping mapping = mixinMappings.get(name);
if (mapping == null) {
mapping = map.get(name);
}
if (mapping == null) return true;
mapped = mapping.fields.get(node.getIdentifier());
if (mapped != null) {
ASTNode parent = node.getParent();
if (!(parent instanceof FieldAccess // qualified access is fine
|| parent instanceof QualifiedName // qualified access is fine
|| parent instanceof VariableDeclarationFragment // shadow member declarations are fine
|| parent instanceof SwitchCase) // referencing constants in case statements is fine
) {
System.err.println(unitName + ": Implicit member reference to remapped field \"" + node.getIdentifier() + "\". " +
"This can cause issues if the remapped reference becomes shadowed by a local variable and is therefore forbidden. " +
"Use \"this." + node.getIdentifier() + "\" instead.");
fail = true;
}
}
} else if (binding instanceof IMethodBinding) {
ITypeBinding declaringClass = ((IMethodBinding) binding).getDeclaringClass();
if (declaringClass == null) return true;
ArrayDeque<ITypeBinding> parentQueue = new ArrayDeque<>();
parentQueue.offer(declaringClass);
Mapping mapping = null;
String name = stripGenerics(declaringClass.getQualifiedName());
if (!name.isEmpty()) {
mapping = mixinMappings.get(name);
}
while (true) {
if (mapping != null) {
mapped = mapping.methods.get(node.getIdentifier());
if (mapped != null) {
break;
}
mapping = null;
}
ITypeBinding superClass = declaringClass.getSuperclass();
if (superClass != null) {
parentQueue.offer(superClass);
}
for (ITypeBinding anInterface : declaringClass.getInterfaces()) {
parentQueue.offer(anInterface);
}
while (mapping == null) {
declaringClass = parentQueue.poll();
if (declaringClass == null) return true;
name = stripGenerics(declaringClass.getQualifiedName());
if (name.isEmpty()) continue;
mapping = map.get(name);
}
}
} else if (binding instanceof ITypeBinding) {
String name = stripGenerics(((ITypeBinding) binding).getQualifiedName());
if (name.isEmpty()) return true;
Mapping mapping = map.get(name);
if (mapping == null) return true;
mapped = mapping.newName;
mapped = mapped.substring(mapped.lastIndexOf('.') + 1);
} else {
return true;
}
if (mapped != null && !mapped.equals(node.getIdentifier())) {
node.setIdentifier(mapped);
changed.set(true);
}
return true;
}
@Override
public boolean visit(MethodDeclaration node) {
if (node.getBody() != null && node.getLength() == node.getBody().getLength()) {
// Body exists but is same length as overall definition? -> method was probably generated by lombok
return false;
}
return super.visit(node);
}
});
return changed.get();
}
public static class Mapping {
public String oldName;
public String newName;
public Map<String, String> fields = new HashMap<>();
public Map<String, String> methods = new HashMap<>();
}
public static Map<String, Mapping> readMappings(File mappingFile, boolean invert) throws IOException {
Map<String, Mapping> mappings = new HashMap<>();
Map<String, Mapping> revMappings = new HashMap<>();
int lineNumber = 0;
for (String line : Files.readAllLines(mappingFile.toPath(), StandardCharsets.UTF_8)) {
lineNumber++;
if (line.trim().startsWith("#") || line.trim().isEmpty()) continue;
String[] parts = line.split(" ");
if (parts.length < 2 || line.contains(";")) {
throw new IllegalArgumentException("Failed to parse line " + lineNumber + " in " + mappingFile.getPath() + ".");
}
Mapping mapping = mappings.get(parts[0]);
if (mapping == null) {
mapping = new Mapping();
mapping.oldName = mapping.newName = parts[0];
mappings.put(mapping.oldName, mapping);
}
if (parts.length == 2) {
// Class mapping
mapping.newName = parts[1];
// Possibly merge with reverse mapping
Mapping revMapping = revMappings.remove(mapping.newName);
if (revMapping != null) {
mapping.fields.putAll(revMapping.fields);
mapping.methods.putAll(revMapping.methods);
}
revMappings.put(mapping.newName, mapping);
} else if (parts.length == 3 || parts.length == 4) {
String fromName = parts[1];
String toName;
Mapping revMapping;
if (parts.length == 4) {
toName = parts[3];
revMapping = revMappings.get(parts[2]);
if (revMapping == null) {
revMapping = new Mapping();
revMapping.oldName = revMapping.newName = parts[2];
revMappings.put(revMapping.newName, revMapping);
}
} else {
toName = parts[2];
revMapping = mapping;
}
if (fromName.endsWith("()")) {
// Method mapping
fromName = fromName.substring(0, fromName.length() - 2);
toName = toName.substring(0, toName.length() - 2);
mapping.methods.put(fromName, toName);
revMapping.methods.put(fromName, toName);
} else {
// Field mapping
mapping.fields.put(fromName, toName);
revMapping.fields.put(fromName, toName);
}
} else {
throw new IllegalArgumentException("Failed to parse line " + lineNumber + " in " + mappingFile.getPath() + ".");
}
}
if (invert) {
Stream.concat(
mappings.values().stream(),
revMappings.values().stream()
).distinct().forEach(it -> {
String oldName = it.oldName;
it.oldName = it.newName;
it.newName = oldName;
it.fields = it.fields.entrySet().stream().collect(Collectors.toMap(Entry::getValue, Entry::getKey));
it.methods = it.methods.entrySet().stream().collect(Collectors.toMap(Entry::getValue, Entry::getKey));
});
}
return Stream.concat(
mappings.values().stream(),
revMappings.values().stream()
).collect(Collectors.toMap(mapping -> mapping.oldName, Function.identity(), (mapping, other) -> {
if (!other.oldName.equals(other.newName)) {
if (!mapping.oldName.equals(mapping.newName)
&& !other.oldName.equals(mapping.oldName)
&& !other.newName.equals(mapping.newName)) {
throw new IllegalArgumentException("Conflicting mappings: "
+ mapping.oldName + " -> " + mapping.newName
+ " and " + other.oldName + " -> " + other.newName);
}
mapping.oldName = other.oldName;
mapping.newName = other.newName;
}
mapping.fields.putAll(other.fields);
mapping.methods.putAll(other.methods);
return mapping;
}));
}
}
|