aboutsummaryrefslogtreecommitdiff
path: root/src/main/java/moe/nea/zwirn/FieldSignatureFixer.java
blob: 7554a42d2aaddb45cd053db6e2f3e162cb72726b (plain)
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
package moe.nea.zwirn;

import net.fabricmc.stitch.commands.tinyv2.TinyClass;
import net.fabricmc.stitch.commands.tinyv2.TinyField;
import net.fabricmc.stitch.commands.tinyv2.TinyFile;
import org.jetbrains.annotations.NotNull;
import org.objectweb.asm.ClassReader;
import org.objectweb.asm.ClassVisitor;
import org.objectweb.asm.FieldVisitor;
import org.objectweb.asm.Opcodes;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.HashMap;
import java.util.Map;
import java.util.stream.Collectors;

public class FieldSignatureFixer {
    private final TinyFile tinyFile;
    private final Path classRoot;

    public FieldSignatureFixer(@NotNull TinyFile tinyFile, @NotNull Path classRoot) {
        this.tinyFile = tinyFile;
        this.classRoot = classRoot;
    }

    public TinyFile fix() {
        return new TinyFile(tinyFile.getHeader(),
                tinyFile.getClassEntries().stream().map(this::fixClass).collect(Collectors.toList())
        );
    }

    private TinyClass fixClass(TinyClass tinyClass) {
        var path = tinyClass.getClassNames().get(0).replace('.', '/') + ".class";
        var classPath = classRoot.resolve(path);
        Map<String, String> fieldNameToDescriptorMap = new HashMap<>();
        if (Files.exists(classPath))
            try (var is = Files.newInputStream(classPath)) {
                var reader = new ClassReader(is);
                var visitor = new FieldSignatureVisitor();
                reader.accept(visitor, 0);
                fieldNameToDescriptorMap.putAll(visitor.fieldNameToDescriptorMap);
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        return new TinyClass(
                tinyClass.getClassNames(),
                tinyClass.getMethods(),
                tinyClass.getFields().stream()
                        .map(it -> new TinyField(fieldNameToDescriptorMap.get(it.getFieldNames().get(0)), it.getFieldNames(), it.getComments()))
                        .collect(Collectors.toList()),
                tinyClass.getComments()
        );
    }

    static class FieldSignatureVisitor extends ClassVisitor {
        protected FieldSignatureVisitor() {
            super(Opcodes.ASM9);
        }

        public Map<String, String> fieldNameToDescriptorMap = new HashMap<>();

        @Override
        public FieldVisitor visitField(int access, String name, String descriptor, String signature, Object value) {
            fieldNameToDescriptorMap.put(name, descriptor);
            return super.visitField(access, name, descriptor, signature, value);
        }
    }
}