308 lines
13 KiB
Java
308 lines
13 KiB
Java
import com.google.gson.*;
|
|
import com.sun.source.tree.*;
|
|
import com.sun.source.util.*;
|
|
import java.nio.charset.StandardCharsets;
|
|
import java.nio.file.*;
|
|
import java.util.*;
|
|
import java.util.jar.*;
|
|
import javax.lang.model.element.*;
|
|
import javax.lang.model.type.*;
|
|
import javax.lang.model.util.*;
|
|
import javax.tools.*;
|
|
import org.objectweb.asm.*;
|
|
|
|
/**
|
|
* Compile-only declarations break the dependency cycle between Minecraft variants. The generated
|
|
* classes are never included in the application archive.
|
|
*/
|
|
public final class GenerateSourceDeclarations {
|
|
private static Types types;
|
|
private static Elements elements;
|
|
private static Map<String, String> sourceGroups = new HashMap<>();
|
|
private static Map<String, Map<String, String>> aliasTypes = new HashMap<>();
|
|
private static Map<String, String> consumerAliases = Map.of();
|
|
private static String currentOwnerGroup;
|
|
private static String consumerGroup;
|
|
|
|
private static String mappedBinary(TypeElement type) {
|
|
String name = binary(type);
|
|
if (currentOwnerGroup == null
|
|
|| consumerGroup == null
|
|
|| currentOwnerGroup.equals(consumerGroup)) return name;
|
|
String realType = aliasTypes.getOrDefault(currentOwnerGroup, Map.of()).get(name);
|
|
return realType == null ? name : consumerAliases.getOrDefault(realType, name);
|
|
}
|
|
|
|
private static String binary(TypeElement type) {
|
|
return elements.getBinaryName(type).toString().replace('.', '/');
|
|
}
|
|
|
|
private static String descriptor(TypeMirror type) {
|
|
return switch (type.getKind()) {
|
|
case BOOLEAN -> "Z";
|
|
case BYTE -> "B";
|
|
case SHORT -> "S";
|
|
case INT -> "I";
|
|
case LONG -> "J";
|
|
case CHAR -> "C";
|
|
case FLOAT -> "F";
|
|
case DOUBLE -> "D";
|
|
case VOID -> "V";
|
|
case ARRAY -> "[" + descriptor(((ArrayType) type).getComponentType());
|
|
case DECLARED, ERROR ->
|
|
"L" + mappedBinary((TypeElement) ((DeclaredType) type).asElement()) + ";";
|
|
case TYPEVAR, WILDCARD, INTERSECTION -> descriptor(types.erasure(type));
|
|
default -> "Ljava/lang/Object;";
|
|
};
|
|
}
|
|
|
|
private static String signature(TypeMirror type) {
|
|
if (type.getKind() == TypeKind.ARRAY)
|
|
return "[" + signature(((ArrayType) type).getComponentType());
|
|
if (type.getKind() == TypeKind.TYPEVAR)
|
|
return "T" + ((TypeVariable) type).asElement().getSimpleName() + ";";
|
|
if (type.getKind() == TypeKind.WILDCARD) {
|
|
WildcardType wildcard = (WildcardType) type;
|
|
if (wildcard.getExtendsBound() != null) return "+" + signature(wildcard.getExtendsBound());
|
|
if (wildcard.getSuperBound() != null) return "-" + signature(wildcard.getSuperBound());
|
|
return "*";
|
|
}
|
|
if (type instanceof DeclaredType declared && !declared.getTypeArguments().isEmpty()) {
|
|
StringBuilder result =
|
|
new StringBuilder("L" + mappedBinary((TypeElement) declared.asElement()) + "<");
|
|
for (TypeMirror argument : declared.getTypeArguments()) result.append(signature(argument));
|
|
return result.append(">;").toString();
|
|
}
|
|
return descriptor(type);
|
|
}
|
|
|
|
private static int access(Element element) {
|
|
int flags = 0;
|
|
for (Modifier modifier : element.getModifiers())
|
|
flags |=
|
|
switch (modifier) {
|
|
case PUBLIC -> Opcodes.ACC_PUBLIC;
|
|
case PROTECTED -> Opcodes.ACC_PROTECTED;
|
|
case PRIVATE -> Opcodes.ACC_PRIVATE;
|
|
case STATIC -> Opcodes.ACC_STATIC;
|
|
case FINAL -> Opcodes.ACC_FINAL;
|
|
case ABSTRACT -> Opcodes.ACC_ABSTRACT;
|
|
case SYNCHRONIZED -> Opcodes.ACC_SYNCHRONIZED;
|
|
case NATIVE -> Opcodes.ACC_NATIVE;
|
|
case STRICTFP -> Opcodes.ACC_STRICT;
|
|
case TRANSIENT -> Opcodes.ACC_TRANSIENT;
|
|
case VOLATILE -> Opcodes.ACC_VOLATILE;
|
|
default -> 0;
|
|
};
|
|
if (element.getKind() == ElementKind.ENUM || element.getKind() == ElementKind.ENUM_CONSTANT)
|
|
flags |= Opcodes.ACC_ENUM;
|
|
if (element.getKind() == ElementKind.INTERFACE
|
|
|| element.getKind() == ElementKind.ANNOTATION_TYPE)
|
|
flags |= Opcodes.ACC_INTERFACE | Opcodes.ACC_ABSTRACT;
|
|
if (element.getKind() == ElementKind.ANNOTATION_TYPE) flags |= Opcodes.ACC_ANNOTATION;
|
|
return flags;
|
|
}
|
|
|
|
private static String internal(TypeMirror type) {
|
|
return descriptor(type).substring(1, descriptor(type).length() - 1);
|
|
}
|
|
|
|
private static byte[] declaration(TypeElement type) {
|
|
currentOwnerGroup = sourceGroups.get(binary(type).split("\\$")[0]);
|
|
ClassWriter writer = new ClassWriter(0);
|
|
TypeMirror parent = type.getSuperclass();
|
|
String superclass = parent.getKind() == TypeKind.NONE ? "java/lang/Object" : internal(parent);
|
|
StringBuilder classSignature =
|
|
new StringBuilder(
|
|
parent.getKind() == TypeKind.NONE ? "Ljava/lang/Object;" : signature(parent));
|
|
String[] interfaces =
|
|
type.getInterfaces().stream()
|
|
.map(GenerateSourceDeclarations::internal)
|
|
.toArray(String[]::new);
|
|
for (TypeMirror contract : type.getInterfaces()) classSignature.append(signature(contract));
|
|
int flags = access(type);
|
|
if ((flags & Opcodes.ACC_INTERFACE) == 0) flags |= Opcodes.ACC_SUPER;
|
|
writer.visit(
|
|
Opcodes.V17, flags, binary(type), classSignature.toString(), superclass, interfaces);
|
|
if (type.getNestingKind() == NestingKind.MEMBER
|
|
&& type.getEnclosingElement() instanceof TypeElement owner) {
|
|
writer.visitInnerClass(
|
|
binary(type), binary(owner), type.getSimpleName().toString(), access(type));
|
|
}
|
|
for (Element enclosed : type.getEnclosedElements()) {
|
|
if (enclosed instanceof TypeElement nested) {
|
|
writer.visitInnerClass(
|
|
binary(nested), binary(type), nested.getSimpleName().toString(), access(nested));
|
|
} else if (enclosed instanceof VariableElement field) {
|
|
Object constant = field.getConstantValue();
|
|
if (constant instanceof Boolean value) constant = value ? 1 : 0;
|
|
else if (constant instanceof Character value) constant = (int) value.charValue();
|
|
else if (constant instanceof Byte value) constant = value.intValue();
|
|
else if (constant instanceof Short value) constant = value.intValue();
|
|
writer
|
|
.visitField(
|
|
access(field),
|
|
field.getSimpleName().toString(),
|
|
descriptor(field.asType()),
|
|
signature(field.asType()),
|
|
constant)
|
|
.visitEnd();
|
|
} else if (enclosed instanceof ExecutableElement method) {
|
|
String name =
|
|
method.getKind() == ElementKind.CONSTRUCTOR
|
|
? "<init>"
|
|
: method.getSimpleName().toString();
|
|
StringBuilder desc = new StringBuilder("(");
|
|
StringBuilder sig = new StringBuilder("(");
|
|
for (VariableElement parameter : method.getParameters()) {
|
|
desc.append(descriptor(parameter.asType()));
|
|
sig.append(signature(parameter.asType()));
|
|
}
|
|
desc.append(')').append(descriptor(method.getReturnType()));
|
|
sig.append(')').append(signature(method.getReturnType()));
|
|
int methodFlags = access(method);
|
|
if (method.isVarArgs()) methodFlags |= Opcodes.ACC_VARARGS;
|
|
MethodVisitor visitor =
|
|
writer.visitMethod(
|
|
methodFlags,
|
|
name,
|
|
desc.toString(),
|
|
sig.toString(),
|
|
method.getThrownTypes().stream()
|
|
.map(GenerateSourceDeclarations::internal)
|
|
.toArray(String[]::new));
|
|
for (VariableElement parameter : method.getParameters())
|
|
visitor.visitParameter(parameter.getSimpleName().toString(), access(parameter));
|
|
if ((methodFlags & (Opcodes.ACC_ABSTRACT | Opcodes.ACC_NATIVE)) == 0) {
|
|
visitor.visitCode();
|
|
visitor.visitTypeInsn(Opcodes.NEW, "java/lang/UnsupportedOperationException");
|
|
visitor.visitInsn(Opcodes.DUP);
|
|
visitor.visitLdcInsn("Compile-only source declaration");
|
|
visitor.visitMethodInsn(
|
|
Opcodes.INVOKESPECIAL,
|
|
"java/lang/UnsupportedOperationException",
|
|
"<init>",
|
|
"(Ljava/lang/String;)V",
|
|
false);
|
|
visitor.visitInsn(Opcodes.ATHROW);
|
|
int locals = (methodFlags & Opcodes.ACC_STATIC) == 0 ? 1 : 0;
|
|
for (org.objectweb.asm.Type argument :
|
|
org.objectweb.asm.Type.getArgumentTypes(desc.toString()))
|
|
locals += argument.getSize();
|
|
visitor.visitMaxs(3, locals);
|
|
}
|
|
visitor.visitEnd();
|
|
}
|
|
}
|
|
writer.visitEnd();
|
|
return writer.toByteArray();
|
|
}
|
|
|
|
public static void main(String[] arguments) throws Exception {
|
|
Path sources = Path.of(arguments[0]);
|
|
Path output = Path.of(arguments[1]);
|
|
String classpath = arguments[2];
|
|
if (arguments.length >= 5) {
|
|
JsonObject groups =
|
|
JsonParser.parseString(Files.readString(Path.of(arguments[3])))
|
|
.getAsJsonObject()
|
|
.getAsJsonObject("groups");
|
|
for (var group : groups.entrySet())
|
|
for (JsonElement item : group.getValue().getAsJsonArray()) {
|
|
String path = item.getAsString();
|
|
sourceGroups.put(path.substring(0, path.length() - 5), group.getKey());
|
|
}
|
|
JsonObject aliases =
|
|
JsonParser.parseString(Files.readString(Path.of(arguments[4]))).getAsJsonObject();
|
|
for (var group : aliases.entrySet()) {
|
|
Map<String, String> types = new HashMap<>();
|
|
for (var alias : group.getValue().getAsJsonObject().entrySet())
|
|
types.put(alias.getKey(), alias.getValue().getAsString());
|
|
aliasTypes.put(group.getKey(), types);
|
|
}
|
|
}
|
|
JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
|
|
DiagnosticCollector<JavaFileObject> diagnostics = new DiagnosticCollector<>();
|
|
List<Path> files;
|
|
try (var stream = Files.walk(sources)) {
|
|
files = stream.filter(path -> path.toString().endsWith(".java")).sorted().toList();
|
|
}
|
|
try (StandardJavaFileManager manager =
|
|
compiler.getStandardFileManager(diagnostics, null, StandardCharsets.UTF_8)) {
|
|
JavacTask task =
|
|
(JavacTask)
|
|
compiler.getTask(
|
|
null,
|
|
manager,
|
|
diagnostics,
|
|
List.of(
|
|
"--release",
|
|
"17",
|
|
"-proc:none",
|
|
"-classpath",
|
|
classpath,
|
|
"-Xmaxerrs",
|
|
"20000"),
|
|
null,
|
|
manager.getJavaFileObjectsFromPaths(files));
|
|
List<CompilationUnitTree> units = new ArrayList<>();
|
|
for (CompilationUnitTree unit : task.parse()) units.add(unit);
|
|
try {
|
|
task.analyze();
|
|
} catch (RuntimeException exception) {
|
|
throw new IllegalStateException("Cannot read source declarations", exception);
|
|
}
|
|
Trees trees = Trees.instance(task);
|
|
types = task.getTypes();
|
|
elements = task.getElements();
|
|
SortedMap<String, TypeElement> declaredTypes = new TreeMap<>();
|
|
for (CompilationUnitTree unit : units)
|
|
new TreePathScanner<Void, Void>() {
|
|
@Override
|
|
public Void visitClass(ClassTree tree, Void ignored) {
|
|
Element element = trees.getElement(getCurrentPath());
|
|
if (element instanceof TypeElement type
|
|
&& (type.getNestingKind() == NestingKind.TOP_LEVEL
|
|
|| type.getNestingKind() == NestingKind.MEMBER)) {
|
|
declaredTypes.put(binary(type), type);
|
|
}
|
|
return super.visitClass(tree, ignored);
|
|
}
|
|
}.scan(unit, null);
|
|
List<String> consumers = new ArrayList<>();
|
|
consumers.add(null);
|
|
consumers.addAll(new TreeSet<>(sourceGroups.values()));
|
|
for (String consumer : consumers) {
|
|
consumerGroup = consumer;
|
|
Map<String, String> reverse = new HashMap<>();
|
|
for (var alias : aliasTypes.getOrDefault(consumer, Map.of()).entrySet())
|
|
reverse.put(alias.getValue(), alias.getKey());
|
|
consumerAliases = reverse;
|
|
Path target =
|
|
consumer == null
|
|
? output
|
|
: output.getParent().resolve("versions/source-declarations-" + consumer + ".jar");
|
|
Files.createDirectories(target.getParent());
|
|
Path temporary = Files.createTempFile(target.getParent(), "source-declarations-", ".jar");
|
|
try (JarOutputStream jar = new JarOutputStream(Files.newOutputStream(temporary))) {
|
|
for (var entry : declaredTypes.entrySet()) {
|
|
JarEntry item = new JarEntry(entry.getKey() + ".class");
|
|
item.setTime(0);
|
|
jar.putNextEntry(item);
|
|
jar.write(declaration(entry.getValue()));
|
|
jar.closeEntry();
|
|
}
|
|
}
|
|
Files.move(
|
|
temporary, target, StandardCopyOption.REPLACE_EXISTING, StandardCopyOption.ATOMIC_MOVE);
|
|
}
|
|
System.out.println(
|
|
"Generated "
|
|
+ declaredTypes.size()
|
|
+ " compile-only source declarations for "
|
|
+ consumers.size()
|
|
+ " compilation groups");
|
|
}
|
|
}
|
|
}
|