From 8740e51230e47d091871a763cd75d629b278c8ed Mon Sep 17 00:00:00 2001 From: illuminator3 Date: Thu, 17 Nov 2022 09:54:18 +0100 Subject: [PATCH 1/4] Bytecode command initial work * Initial commit of the bytecode command * Fix sonar violations in BytecodeCommand.java * I forgot to commit the changes in Application.java :pepega: * Change module name from imc -> inmemorycompiler (Request from Zabuzard) * Changed map name to something more self-explanatory (Request from Zabuzard) * Make string constants static (Request from Zabuzard) * Add comments explaining what certain parts do (Request from Zabuzard) * Change parameter name from gevent -> genericEvent (Request from Zabuzard) * Apply spotless * Add error checking (Request from Zabuzard) * Add comment (Request from Zabuzard) * Unwrap asList invocation * Added @NotNull annotations (Request from Zabuzard) * Add error checking (Request from Zabuzard) * Add @NotNull annotations (Request from Zabuzard) * Change rex to e (Request from Zabuzard) * Change toString -> getMessage (Request from Zabuzard) * Use constant instead of a magic value (Request from Zabuzard) * Add @NotNull annotation (Request from Zabuzard) * Add @NotNull annotation (Request from Zabuzard) * Change naming of parameters (Request from Zabuzard) * Change method name from makeCollection -> iterToCollection (Request from Zabuzard) * Improve map name (Request from Zabuzard) * Add @NotNull annotation (Request from Zabuzard) * Add @NotNull annotation (Request from Zabuzard) * Remove cast * Add @NotNull annotation (Request from Zabuzard) * Add @NotNull annotation (Request from Zabuzard) * Add javadoc (Request from Zabuzard) * Add @NotNull annotation (Request from Zabuzard) * Apply spotless * Change parameter name * Make use of TextChannel#purgeMessagesById (Request from Tijs) * Pass initial capacity to ArrayList constructor (Request from Tijs) * Use LongStream in combination with purgeMessagesById * Forgot to remove the outdated code * Follow naming convention for constants and add javadoc * Use `ListenerAdapter` and dedicated event methods * Map to string (+ spotless) * Add the @NotNull annotation everywhere (Request from Zabuzard) * Use array generator instead of creating a new array (Request from Zabuzard) * Made requested changes * Forgot NotNull's * Apply spotless * Add NotNull annotations * Change field name * Use already present constant * Use isEmpty instead of checking for size == 0 * Expand javadoc * Change method name * Add comment * Use already present classes to achieve the same thing * Applied spotless * Make daddy CodeQL happy OwO * Put comment above return * Clean up code * Change public to private * Don't declare fields on the same line * Exclude reflection sonar rule * Change array creation to object cast * Rename method parameters * Don't declare fields in the "same" line * Move suppression of sonarcloud warning to class level * Use method reference instead of creating a new array * Apply spotless * tijs is cute * still had this in here from debugging * make daddy sonarcloud happy * oh spotless wasn't done yet while I was committing :skull: * it's the future baby * lmao shit doesn't even compile * fuck you spotless * Update application/src/main/java/org/togetherjava/tjbot/commands/bytecode/BytecodeCommand.java Co-authored-by: Tais993 <49957334+Tais993@users.noreply.github.com> * jingle bells batman smells * Revert "jingle bells batman smells" This reverts commit b91b3a5e5c36462b2018eba731daf6dd8db92dca. * add syntax highlighting * requested changes * spotless * Merge branch 'develop' into feature/bytecode-command Co-authored-by: illuminator3 Co-authored-by: Tais993 <49957334+Tais993@users.noreply.github.com> --- application/build.gradle | 11 + .../togetherjava/tjbot/commands/Features.java | 2 + .../tjbot/commands/MessageReceiver.java | 2 +- .../commands/bytecode/BytecodeCommand.java | 269 ++++++++++++++++++ .../tjbot/commands/bytecode/package-info.java | 10 + inmemorycompiler/build.gradle | 17 ++ .../tjbot/imc/ByteJavaFileObjectLoader.java | 37 +++ .../tjbot/imc/CompilationResult.java | 71 +++++ .../togetherjava/tjbot/imc/CompileInfo.java | 31 ++ .../tjbot/imc/InMemoryByteJavaFileObject.java | 29 ++ .../tjbot/imc/InMemoryCompiler.java | 86 ++++++ .../tjbot/imc/InMemoryJavacFileManager.java | 40 +++ .../togetherjava/tjbot/imc/JavacOption.java | 27 ++ .../togetherjava/tjbot/imc/package-info.java | 11 + .../tjbot/javap/IMJavapFileManager.java | 40 +++ .../org/togetherjava/tjbot/javap/Javap.java | 140 +++++++++ .../togetherjava/tjbot/javap/JavapOption.java | 31 ++ .../tjbot/javap/ReflectionException.java | 11 + .../tjbot/javap/package-info.java | 7 + settings.gradle | 1 + utils/build.gradle | 2 +- 21 files changed, 873 insertions(+), 2 deletions(-) create mode 100644 application/src/main/java/org/togetherjava/tjbot/commands/bytecode/BytecodeCommand.java create mode 100644 application/src/main/java/org/togetherjava/tjbot/commands/bytecode/package-info.java create mode 100644 inmemorycompiler/build.gradle create mode 100644 inmemorycompiler/src/main/java/org/togetherjava/tjbot/imc/ByteJavaFileObjectLoader.java create mode 100644 inmemorycompiler/src/main/java/org/togetherjava/tjbot/imc/CompilationResult.java create mode 100644 inmemorycompiler/src/main/java/org/togetherjava/tjbot/imc/CompileInfo.java create mode 100644 inmemorycompiler/src/main/java/org/togetherjava/tjbot/imc/InMemoryByteJavaFileObject.java create mode 100644 inmemorycompiler/src/main/java/org/togetherjava/tjbot/imc/InMemoryCompiler.java create mode 100644 inmemorycompiler/src/main/java/org/togetherjava/tjbot/imc/InMemoryJavacFileManager.java create mode 100644 inmemorycompiler/src/main/java/org/togetherjava/tjbot/imc/JavacOption.java create mode 100644 inmemorycompiler/src/main/java/org/togetherjava/tjbot/imc/package-info.java create mode 100644 inmemorycompiler/src/main/java/org/togetherjava/tjbot/javap/IMJavapFileManager.java create mode 100644 inmemorycompiler/src/main/java/org/togetherjava/tjbot/javap/Javap.java create mode 100644 inmemorycompiler/src/main/java/org/togetherjava/tjbot/javap/JavapOption.java create mode 100644 inmemorycompiler/src/main/java/org/togetherjava/tjbot/javap/ReflectionException.java create mode 100644 inmemorycompiler/src/main/java/org/togetherjava/tjbot/javap/package-info.java diff --git a/application/build.gradle b/application/build.gradle index 9924efdbb9..0891de12b8 100644 --- a/application/build.gradle +++ b/application/build.gradle @@ -43,6 +43,7 @@ dependencies { implementation 'org.jetbrains:annotations:23.0.0' implementation project(':database') + implementation project(':inmemorycompiler') implementation project(':utils') implementation project(':formatter') @@ -82,4 +83,14 @@ dependencies { application { mainClass = 'org.togetherjava.tjbot.BootstrapLauncher' + + applicationDefaultJvmArgs = [ + '--add-opens=jdk.jdeps/com.sun.tools.javap=ALL-UNNAMED' + ] +} + +run { + jvmArgs = [ + '--add-opens=jdk.jdeps/com.sun.tools.javap=ALL-UNNAMED' + ] } diff --git a/application/src/main/java/org/togetherjava/tjbot/commands/Features.java b/application/src/main/java/org/togetherjava/tjbot/commands/Features.java index 76cdd928b7..8207cdb305 100644 --- a/application/src/main/java/org/togetherjava/tjbot/commands/Features.java +++ b/application/src/main/java/org/togetherjava/tjbot/commands/Features.java @@ -6,6 +6,7 @@ import org.togetherjava.tjbot.commands.basic.RoleSelectCommand; import org.togetherjava.tjbot.commands.basic.SuggestionsUpDownVoter; import org.togetherjava.tjbot.commands.basic.VcActivityCommand; +import org.togetherjava.tjbot.commands.bytecode.BytecodeCommand; import org.togetherjava.tjbot.commands.code.CodeMessageAutoDetection; import org.togetherjava.tjbot.commands.code.CodeMessageHandler; import org.togetherjava.tjbot.commands.code.CodeMessageManualDetection; @@ -142,6 +143,7 @@ public static Collection createFeatures(JDA jda, Database database, Con // Mixtures features.add(new HelpThreadOverviewUpdater(config, helpSystemHelper)); + features.add(new BytecodeCommand()); return features; } diff --git a/application/src/main/java/org/togetherjava/tjbot/commands/MessageReceiver.java b/application/src/main/java/org/togetherjava/tjbot/commands/MessageReceiver.java index 35843ead1c..87e0188c58 100644 --- a/application/src/main/java/org/togetherjava/tjbot/commands/MessageReceiver.java +++ b/application/src/main/java/org/togetherjava/tjbot/commands/MessageReceiver.java @@ -7,7 +7,7 @@ import java.util.regex.Pattern; /** - * Receives incoming Discord guild messages from channels matching a given pattern. + * Receives incoming Discord guild messages from channels, which optionally match a given pattern. *

* All message receivers have to implement this interface. For convenience, there is a * {@link MessageReceiverAdapter} available that implemented most methods already. A new receiver diff --git a/application/src/main/java/org/togetherjava/tjbot/commands/bytecode/BytecodeCommand.java b/application/src/main/java/org/togetherjava/tjbot/commands/bytecode/BytecodeCommand.java new file mode 100644 index 0000000000..906536f8ce --- /dev/null +++ b/application/src/main/java/org/togetherjava/tjbot/commands/bytecode/BytecodeCommand.java @@ -0,0 +1,269 @@ +package org.togetherjava.tjbot.commands.bytecode; + +import net.dv8tion.jda.api.entities.Message; +import net.dv8tion.jda.api.entities.TextChannel; +import net.dv8tion.jda.api.events.interaction.command.MessageContextInteractionEvent; +import net.dv8tion.jda.api.events.message.MessageDeleteEvent; +import net.dv8tion.jda.api.events.message.MessageReceivedEvent; +import net.dv8tion.jda.api.events.message.MessageUpdateEvent; +import net.dv8tion.jda.api.interactions.InteractionHook; +import net.dv8tion.jda.api.interactions.commands.build.Commands; + +import org.togetherjava.tjbot.commands.BotCommandAdapter; +import org.togetherjava.tjbot.commands.CommandVisibility; +import org.togetherjava.tjbot.commands.MessageContextCommand; +import org.togetherjava.tjbot.commands.MessageReceiver; +import org.togetherjava.tjbot.imc.CompilationResult; +import org.togetherjava.tjbot.imc.CompileInfo; +import org.togetherjava.tjbot.imc.InMemoryCompiler; +import org.togetherjava.tjbot.imc.JavacOption; +import org.togetherjava.tjbot.javap.Javap; +import org.togetherjava.tjbot.javap.JavapOption; + +import javax.tools.Diagnostic; + +import java.util.*; +import java.util.regex.Matcher; +import java.util.regex.Pattern; +import java.util.stream.Collectors; + +/** + * Bytecode command that uses the message context commands Example usage: + *

+ * + *

+ * {@code
+ *     ```java
+ *     class Test {
+ *         public void foo() {
+ *             System.out.println("Hello World!");
+ *         }
+ *     }
+ *     ```
+ * }
+ * 
+ * + * then apply the application + */ +public final class BytecodeCommand extends BotCommandAdapter + implements MessageContextCommand, MessageReceiver { + private static final String CODE_BLOCK_OPENING = "```rust\n"; + private static final String CODE_BLOCK_CLOSING = "\n```"; + private static final Pattern ANY_CHANNEL_NAME = Pattern.compile(".*"); + + private final Pattern codeBlockExtractorPattern = + Pattern.compile("```(?:java)?\\s*([\\w\\W]+)```|``?([\\w\\W]+)``?"); + private final Map> userToBotMessages = new HashMap<>(); + + public BytecodeCommand() { + super(Commands.message("View bytecode"), CommandVisibility.GUILD); + } + + @Override + public Pattern getChannelNamePattern() { + return ANY_CHANNEL_NAME; + } + + @Override + public void onMessageContext(MessageContextInteractionEvent event) { + Message message = event.getTarget(); + String content = message.getContentRaw(); + + event.reply("Compiling...") + .mentionRepliedUser(false) + .flatMap(InteractionHook::retrieveOriginal) + .queue(compReply -> compile(message, compReply, parseCommandFromMessage(content))); + } + + @Override + public void onMessageDeleted(MessageDeleteEvent event) { + long mesageIdLong = event.getMessageIdLong(); + + if (userToBotMessages.containsKey(mesageIdLong)) { + deleteMyMessages(mesageIdLong, event.getTextChannel()); + } + } + + @Override + public void onMessageReceived(MessageReceivedEvent event) { + // Method isn't needed, context-commands are used for the initial message + } + + @Override + public void onMessageUpdated(MessageUpdateEvent event) { + Message message = event.getMessage(); + long messageIdLong = event.getMessageIdLong(); + + if (!userToBotMessages.containsKey(messageIdLong)) { + return; + } + + TextChannel textChannel = message.getTextChannel(); + List botMessages = userToBotMessages.get(messageIdLong); + + if (botMessages.isEmpty()) { + message.reply("An unknown error occurred").queue(); + + return; + } + + textChannel.retrieveMessageById(botMessages.get(0)).queue(botMessage -> { + textChannel.purgeMessagesById(botMessages.stream() + .skip(1) // skip the first bot message to edit it + .map(String::valueOf) + .toList()); + + botMessage.editMessage("Recompiling...").queue(); + + compile(message, botMessage, parseCommandFromMessage(message.getContentRaw())); + }); + } + + private void deleteMyMessages(Long msgId, TextChannel channel) { + if (!userToBotMessages.containsKey(msgId)) { + return; + } + + channel + .purgeMessagesById(userToBotMessages.get(msgId).stream().map(String::valueOf).toList()); + + userToBotMessages.remove(msgId); + } + + private void compile(Message userMessage, Message botMessage, String content) { + userToBotMessages.put(userMessage.getIdLong(), List.of(botMessage.getIdLong())); + + CompilationResult result; + + try { + result = InMemoryCompiler.compile(content, JavacOption.DEBUG_ALL); + } catch (RuntimeException e) { + botMessage + .editMessage("A fatal error has occurred during compilation. %s" + .formatted(e.getMessage())) + .mentionRepliedUser(false) + .queue(); + + return; + } + + if (!result.success()) { + botMessage + .editMessage("Compilation failed." + CODE_BLOCK_OPENING + + iterToCollection(result.compileInfos()).stream() + .map(CompileInfo::diagnostic) + .map(Diagnostic::toString) + .collect(Collectors.joining("\n")) + + CODE_BLOCK_CLOSING) + .mentionRepliedUser(false) + .queue(); + + return; + } + + botMessage.editMessage("Compilation was successfull! Disassembling...") + .mentionRepliedUser(false) + .queue(disReply -> { + String disassembled; + + try { + disassembled = Javap.disassemble(result.bytes(), JavapOption.VERBOSE); + } catch (RuntimeException e) { + botMessage + .editMessage("A fatal error has occurred during disassembly. %s" + .formatted(e.getMessage())) + .mentionRepliedUser(false) + .queue(); + + return; + } + + String msgResult = surroundInCodeBlock(disassembled); + + disReply.delete().queue(); + + if (msgResult.length() <= Message.MAX_CONTENT_LENGTH) { + userMessage.reply(msgResult) + .mentionRepliedUser(false) + .queue(msg -> userToBotMessages.put(userMessage.getIdLong(), + List.of(msg.getIdLong()))); + + return; + } + + List msgResults = explodeEvery(disassembled, + Message.MAX_CONTENT_LENGTH - surroundInCodeBlock("").length()); + Iterator iterator = msgResults.iterator(); + List messageIds = new ArrayList<>(msgResults.size()); + + if (iterator.hasNext()) { + userMessage.reply(surroundInCodeBlock(iterator.next())) + .mentionRepliedUser(false) + .queue(msg -> messageIds.add(msg.getIdLong())); + } + + while (iterator.hasNext()) { + disReply.getTextChannel() + .sendMessage(surroundInCodeBlock(iterator.next())) + .queue(msg -> messageIds.add(msg.getIdLong())); + } + + userToBotMessages.put(userMessage.getIdLong(), messageIds); + }); + } + + private String surroundInCodeBlock(String s) { + return CODE_BLOCK_OPENING + s + CODE_BLOCK_CLOSING; + } + + /** + * Example: + * + *
+     * {@code
+     * takeApart("Hello\nWorld!", 3) returns List("Hel", "lo", "Wor", "ld!")
+     * }
+     * 
+ */ + private List explodeEvery(String message, int maxPartLength) { + List result = new ArrayList<>(); + String[] lines = message.split("\n"); + int currentLength = 0; + StringBuilder buffer = new StringBuilder(); + + for (String line : lines) { + if (currentLength + line.length() > maxPartLength) { + result.add(buffer.toString()); + buffer = new StringBuilder(); + currentLength = 0; + } + + buffer.append(line); + currentLength += line.length(); + } + + if (!buffer.isEmpty()) { + result.add(buffer.toString()); + } + + return result; + } + + private Collection iterToCollection(Iterable iter) { + Collection list = new ArrayList<>(); + + iter.forEach(list::add); + + return list; + } + + private String parseCommandFromMessage(String messageContent) { + Matcher codeBlockMatcher = codeBlockExtractorPattern.matcher(messageContent); + + if (codeBlockMatcher.find()) { + return codeBlockMatcher.group(1); + } + + return messageContent; + } +} diff --git a/application/src/main/java/org/togetherjava/tjbot/commands/bytecode/package-info.java b/application/src/main/java/org/togetherjava/tjbot/commands/bytecode/package-info.java new file mode 100644 index 0000000000..729e166d73 --- /dev/null +++ b/application/src/main/java/org/togetherjava/tjbot/commands/bytecode/package-info.java @@ -0,0 +1,10 @@ +/** + * This package offers the {@link org.togetherjava.tjbot.commands.bytecode.BytecodeCommand}. + */ +@MethodsReturnNonnullByDefault +@ParametersAreNonnullByDefault +package org.togetherjava.tjbot.commands.bytecode; + +import org.togetherjava.tjbot.annotations.MethodsReturnNonnullByDefault; + +import javax.annotation.ParametersAreNonnullByDefault; diff --git a/inmemorycompiler/build.gradle b/inmemorycompiler/build.gradle new file mode 100644 index 0000000000..282261f5b1 --- /dev/null +++ b/inmemorycompiler/build.gradle @@ -0,0 +1,17 @@ +plugins { + id 'java' +} + +dependencies { + implementation 'org.jetbrains:annotations:23.0.0' + implementation 'com.google.code.findbugs:jsr305:3.0.2' + + implementation project(':utils') + + testImplementation 'org.junit.jupiter:junit-jupiter-api:5.8.1' + testRuntimeOnly 'org.junit.jupiter:junit-jupiter-engine:5.8.1' +} + +test { + useJUnitPlatform() +} diff --git a/inmemorycompiler/src/main/java/org/togetherjava/tjbot/imc/ByteJavaFileObjectLoader.java b/inmemorycompiler/src/main/java/org/togetherjava/tjbot/imc/ByteJavaFileObjectLoader.java new file mode 100644 index 0000000000..f794b3a5c4 --- /dev/null +++ b/inmemorycompiler/src/main/java/org/togetherjava/tjbot/imc/ByteJavaFileObjectLoader.java @@ -0,0 +1,37 @@ +package org.togetherjava.tjbot.imc; + +import java.util.LinkedHashMap; +import java.util.Map; + +class ByteJavaFileObjectLoader extends ClassLoader { + private final Map nameToClassJFO = new LinkedHashMap<>(); + + public ByteJavaFileObjectLoader(ClassLoader parent) { + super(parent); + } + + public InMemoryByteJavaFileObject registerJFO(InMemoryByteJavaFileObject jfo) { + nameToClassJFO.put(jfo.getName(), jfo); + + return jfo; + } + + /** + * Only meant to be used for registering and getting, not finding. There are no plans to + * implement this, and it is also not needed. + * + * @throws UnsupportedOperationException always + */ + @Override + protected Class findClass(String name) throws UnsupportedOperationException { + throw new UnsupportedOperationException(); + } + + public byte[] getLastBytes() { + return last(nameToClassJFO.values().toArray(InMemoryByteJavaFileObject[]::new)).getBytes(); + } + + private E last(E[] col) { + return col[col.length - 1]; + } +} diff --git a/inmemorycompiler/src/main/java/org/togetherjava/tjbot/imc/CompilationResult.java b/inmemorycompiler/src/main/java/org/togetherjava/tjbot/imc/CompilationResult.java new file mode 100644 index 0000000000..26710875fd --- /dev/null +++ b/inmemorycompiler/src/main/java/org/togetherjava/tjbot/imc/CompilationResult.java @@ -0,0 +1,71 @@ +package org.togetherjava.tjbot.imc; + +import java.util.Arrays; +import java.util.Collections; + +/** + * Class representing a compilation result of {@link InMemoryCompiler} + */ +public record CompilationResult(boolean success, byte[] bytes, Iterable compileInfos) { + + private static final CompilationResult EMPTY_RESULT = + new CompilationResult(false, new byte[0], Collections.emptyList()); + + /** + * @return an empty compilation result + */ + public static CompilationResult empty() { + return EMPTY_RESULT; + } + + /** + * Creates an unsuccessful compilation result + * + * @param compileInfos compilation infos + * @return the generated compilation result + */ + public static CompilationResult fail(Iterable compileInfos) { + return new CompilationResult(false, new byte[0], compileInfos); + } + + /** + * Creates a successful compilation result + * + * @param bytes classfile bytecode + * @param compileInfos compilation infos + * @return the generated compilation result + */ + public static CompilationResult success(byte[] bytes, Iterable compileInfos) { + return new CompilationResult(true, bytes, compileInfos); + } + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + + if (!(o instanceof CompilationResult that) || success != that.success + || !Arrays.equals(bytes, that.bytes)) { + return false; + } + + return compileInfos.equals(that.compileInfos); + } + + @Override + public int hashCode() { + int result = (success ? 1 : 0); + + result = 31 * result + Arrays.hashCode(bytes); + result = 31 * result + compileInfos.hashCode(); + + return result; + } + + @Override + public String toString() { + return "CompilationResult{" + "success=" + success + ", bytes=" + Arrays.toString(bytes) + + ", compileInfos=" + compileInfos + '}'; + } +} diff --git a/inmemorycompiler/src/main/java/org/togetherjava/tjbot/imc/CompileInfo.java b/inmemorycompiler/src/main/java/org/togetherjava/tjbot/imc/CompileInfo.java new file mode 100644 index 0000000000..f2f5d50e1c --- /dev/null +++ b/inmemorycompiler/src/main/java/org/togetherjava/tjbot/imc/CompileInfo.java @@ -0,0 +1,31 @@ +package org.togetherjava.tjbot.imc; + +import javax.tools.Diagnostic; + +import java.util.Objects; + +/** + * Wrapper class for a {@link Diagnostic} of unknown type + * + * @see javax.tools.Diagnostic + */ +public record CompileInfo(Diagnostic diagnostic) { + @Override + public boolean equals(Object o) { + if (this == o) + return true; + if (!(o instanceof CompileInfo that)) + return false; + return diagnostic.equals(that.diagnostic); + } + + @Override + public int hashCode() { + return Objects.hash(diagnostic); + } + + @Override + public String toString() { + return "CompileInfo{" + "diagnostic=" + diagnostic + '}'; + } +} diff --git a/inmemorycompiler/src/main/java/org/togetherjava/tjbot/imc/InMemoryByteJavaFileObject.java b/inmemorycompiler/src/main/java/org/togetherjava/tjbot/imc/InMemoryByteJavaFileObject.java new file mode 100644 index 0000000000..2c6817c4a7 --- /dev/null +++ b/inmemorycompiler/src/main/java/org/togetherjava/tjbot/imc/InMemoryByteJavaFileObject.java @@ -0,0 +1,29 @@ +package org.togetherjava.tjbot.imc; + +import javax.tools.SimpleJavaFileObject; + +import java.io.ByteArrayOutputStream; +import java.io.OutputStream; +import java.net.URI; + +/** + * Represents a {@link SimpleJavaFileObject} that exists purely in memory. + * + * @see javax.tools.SimpleJavaFileObject + */ +class InMemoryByteJavaFileObject extends SimpleJavaFileObject { + private final ByteArrayOutputStream baos = new ByteArrayOutputStream(); + + public InMemoryByteJavaFileObject(String className) { + super(URI.create(className), Kind.CLASS); + } + + @Override + public OutputStream openOutputStream() { + return baos; + } + + public byte[] getBytes() { + return baos.toByteArray(); + } +} diff --git a/inmemorycompiler/src/main/java/org/togetherjava/tjbot/imc/InMemoryCompiler.java b/inmemorycompiler/src/main/java/org/togetherjava/tjbot/imc/InMemoryCompiler.java new file mode 100644 index 0000000000..782a527d5a --- /dev/null +++ b/inmemorycompiler/src/main/java/org/togetherjava/tjbot/imc/InMemoryCompiler.java @@ -0,0 +1,86 @@ +package org.togetherjava.tjbot.imc; + +import org.jetbrains.annotations.Nullable; + +import javax.tools.*; + +import java.io.Writer; +import java.net.URI; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; + +/** + * Javac interface that keeps everything in memory. + * + * @see javax.tools.JavaCompiler + */ +public final class InMemoryCompiler { + // Hide constructor + private InMemoryCompiler() {} + + private static final String TEMP_CLASS_NAME = "tmp"; + private static final JavaCompiler javac = ToolProvider.getSystemJavaCompiler(); + private static final JavaFileManager standardFileManager = + javac.getStandardFileManager(null, null, null); + private static final ByteJavaFileObjectLoader bcl = + new ByteJavaFileObjectLoader(ClassLoader.getSystemClassLoader()); + + /** + * Compiles a given code snippet with certain javac executable arguments + * + * @param code code to compile + * @param javacOptions javac options to use + * @return the compiled code in form of a {@link CompilationResult} + */ + public static CompilationResult compile(@Nullable String code, JavacOption... javacOptions) { + if (code == null || code.isEmpty()) { + return CompilationResult.empty(); + } + + DiagnosticCollector collector = new DiagnosticCollector<>(); + boolean hasSucceeded = javac + .getTask(null, new InMemoryJavacFileManager(standardFileManager, bcl), collector, + Arrays.stream(javacOptions).map(JavacOption::getOption).toList(), null, + List.of(genCompilationUnitJFO(code))) + .call(); + + List compileInfos = new ArrayList<>(); + + if (!collector.getDiagnostics().isEmpty()) { + for (Diagnostic diagnostic : collector.getDiagnostics()) { + compileInfos.add(new CompileInfo(diagnostic)); + } + } + + if (!hasSucceeded) { + return CompilationResult.fail(compileInfos); + } + + return CompilationResult.success(bcl.getLastBytes(), compileInfos); + } + + /** + * Generates a single compilation unit in form of a {@link SimpleJavaFileObject} for + * {@link JavaCompiler#getTask(Writer, JavaFileManager, DiagnosticListener, Iterable, Iterable, Iterable)} + * + * @param content content of the imfjo + * @return the generated compilation unit + */ + private static SimpleJavaFileObject genCompilationUnitJFO(String content) { + // random protocol, any works + return new SimpleJavaFileObject(URI.create("string:///" + TEMP_CLASS_NAME.replace('.', '/') + + JavaFileObject.Kind.SOURCE.extension), JavaFileObject.Kind.SOURCE) { + /** + * Returns the content given in the generation of this {@code SimpleJavaFileObject} + * + * @param ignoreEncodingErrors does nothing + * @return content + */ + @Override + public String getCharContent(boolean ignoreEncodingErrors) { + return content; + } + }; + } +} diff --git a/inmemorycompiler/src/main/java/org/togetherjava/tjbot/imc/InMemoryJavacFileManager.java b/inmemorycompiler/src/main/java/org/togetherjava/tjbot/imc/InMemoryJavacFileManager.java new file mode 100644 index 0000000000..520b01b89f --- /dev/null +++ b/inmemorycompiler/src/main/java/org/togetherjava/tjbot/imc/InMemoryJavacFileManager.java @@ -0,0 +1,40 @@ +package org.togetherjava.tjbot.imc; + +import org.jetbrains.annotations.Nullable; + +import javax.tools.FileObject; +import javax.tools.ForwardingJavaFileManager; +import javax.tools.JavaFileManager; +import javax.tools.JavaFileObject; + +/** + * File manager that tries to keep every java file output in memory + * + * @see JavaFileManager + * @see ByteJavaFileObjectLoader + */ +class InMemoryJavacFileManager extends ForwardingJavaFileManager { + private final ByteJavaFileObjectLoader classLoader; + + protected InMemoryJavacFileManager(JavaFileManager fileManager, + ByteJavaFileObjectLoader classLoader) { + super(fileManager); + + this.classLoader = classLoader; + } + + @Override + public JavaFileObject getJavaFileForOutput(@Nullable Location location, String className, + @Nullable JavaFileObject.Kind kind, @Nullable FileObject sibling) { + return classLoader.registerJFO(new InMemoryByteJavaFileObject(className)); + } + + public ByteJavaFileObjectLoader getClassLoader() { + return classLoader; + } + + @Override + public ByteJavaFileObjectLoader getClassLoader(@Nullable Location location) { + return getClassLoader(); + } +} diff --git a/inmemorycompiler/src/main/java/org/togetherjava/tjbot/imc/JavacOption.java b/inmemorycompiler/src/main/java/org/togetherjava/tjbot/imc/JavacOption.java new file mode 100644 index 0000000000..478feb7169 --- /dev/null +++ b/inmemorycompiler/src/main/java/org/togetherjava/tjbot/imc/JavacOption.java @@ -0,0 +1,27 @@ +package org.togetherjava.tjbot.imc; + +/** + * Enum that represents every possible javac executable option that does not include an argument. + */ +public enum JavacOption { + DEBUG_ALL("-g"), + DEBUG_NONE("-g:none"), + NOWARN("-nowarn"), + VERBOSE("-verbose"), + DEPRECATION("-deprecation"), + PARAMETERS("-parameters"), + WERROR("-Werror"); + + private final String option; + + JavacOption(String option) { + this.option = option; + } + + /** + * @return textual representation of the option + */ + public String getOption() { + return option; + } +} diff --git a/inmemorycompiler/src/main/java/org/togetherjava/tjbot/imc/package-info.java b/inmemorycompiler/src/main/java/org/togetherjava/tjbot/imc/package-info.java new file mode 100644 index 0000000000..87b4fbb59c --- /dev/null +++ b/inmemorycompiler/src/main/java/org/togetherjava/tjbot/imc/package-info.java @@ -0,0 +1,11 @@ +/** + * This package provides utility classes to compile Java code fully in memory. (IMC stands for + * In-Memory-Compiler) + */ +@MethodsReturnNonnullByDefault +@ParametersAreNonnullByDefault +package org.togetherjava.tjbot.imc; + +import org.togetherjava.tjbot.annotations.MethodsReturnNonnullByDefault; + +import javax.annotation.ParametersAreNonnullByDefault; diff --git a/inmemorycompiler/src/main/java/org/togetherjava/tjbot/javap/IMJavapFileManager.java b/inmemorycompiler/src/main/java/org/togetherjava/tjbot/javap/IMJavapFileManager.java new file mode 100644 index 0000000000..bb14be4412 --- /dev/null +++ b/inmemorycompiler/src/main/java/org/togetherjava/tjbot/javap/IMJavapFileManager.java @@ -0,0 +1,40 @@ +package org.togetherjava.tjbot.javap; + +import org.jetbrains.annotations.Nullable; + +import javax.tools.ForwardingJavaFileManager; +import javax.tools.JavaFileManager; +import javax.tools.JavaFileObject; +import javax.tools.SimpleJavaFileObject; + +import java.io.ByteArrayInputStream; +import java.io.InputStream; +import java.net.URI; + +/** + * File manager that returns given bytes for requests to ANY java file input + * + * @see JavaFileManager + */ +class IMJavapFileManager extends ForwardingJavaFileManager { + private final byte[] bytes; + private final String fileName; + + protected IMJavapFileManager(JavaFileManager fileManager, byte[] bytes, String fileName) { + super(fileManager); + + this.bytes = bytes; + this.fileName = fileName; + } + + @Override + public JavaFileObject getJavaFileForInput(@Nullable Location location, + @Nullable String className, JavaFileObject.Kind kind) { + return new SimpleJavaFileObject(URI.create("file:///%s".formatted(fileName)), kind) { + @Override + public InputStream openInputStream() { + return new ByteArrayInputStream(bytes); + } + }; + } +} diff --git a/inmemorycompiler/src/main/java/org/togetherjava/tjbot/javap/Javap.java b/inmemorycompiler/src/main/java/org/togetherjava/tjbot/javap/Javap.java new file mode 100644 index 0000000000..e4d5762cf8 --- /dev/null +++ b/inmemorycompiler/src/main/java/org/togetherjava/tjbot/javap/Javap.java @@ -0,0 +1,140 @@ +package org.togetherjava.tjbot.javap; + +import javax.tools.DiagnosticListener; +import javax.tools.JavaFileManager; +import javax.tools.JavaFileObject; + +import java.io.PrintWriter; +import java.io.StringWriter; +import java.io.Writer; +import java.lang.reflect.Field; +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Method; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import java.util.stream.Collectors; + +/** + * A javap-interface that uses reflection to access locked-down classes of the jdk.jdeps module and + * keep everything in-memory + */ +// Disables "Reflection should not be used to increase accessibility of classes, methods, or fields" +// rule (Reflection is required for the Javap class to work). +@SuppressWarnings({"java:S3011"}) +public final class Javap { + // Hide constructor + private Javap() {} + + private static final String TEMP_FILE_NAME = "tmp"; + private static final String ANNOYING_WARNING_MESSAGE = + "Warning: File /%s does not contain class % javapFileManagerCls; + private static final Class javapTaskCls; + + private static final Method javapFileManagerCreateMethod; + private static final Method javapTaskRunMethod; + private static final Method javapTaskGetDiagnosticListenerForWriterMethod; + + private static final Field javapTaskDefaultFileManagerField; + private static final Field javapTaskLogField; + + static { + try { + javapFileManagerCls = Class.forName("com.sun.tools.javap.JavapFileManager"); + javapFileManagerCreateMethod = javapFileManagerCls.getDeclaredMethod("create", + DiagnosticListener.class, PrintWriter.class); + + javapTaskCls = Class.forName("com.sun.tools.javap.JavapTask"); + javapTaskDefaultFileManagerField = javapTaskCls.getDeclaredField("defaultFileManager"); + javapTaskLogField = javapTaskCls.getDeclaredField("log"); + javapTaskRunMethod = javapTaskCls.getDeclaredMethod("run", String[].class); + javapTaskGetDiagnosticListenerForWriterMethod = + javapTaskCls.getDeclaredMethod("getDiagnosticListenerForWriter", Writer.class); + + javapFileManagerCreateMethod.setAccessible(true); + javapTaskDefaultFileManagerField.setAccessible(true); + javapTaskLogField.setAccessible(true); + javapTaskRunMethod.setAccessible(true); + javapTaskGetDiagnosticListenerForWriterMethod.setAccessible(true); + } catch (ClassNotFoundException | NoSuchMethodException | NoSuchFieldException ex) { + throw new ReflectionException( + "A fatal exception has occurred while using reflection in the non-static initializer of org.togetherjava.tjbot.javap.Javap", + ex); + } + } + + /** + * Disassembles the given classfile bytecode with given program arguments + * + * @param bytes classfile bytecode + * @param options options to give to javap + * @return disassembled view + * @throws ReflectionException if an exception occurs while doing reflection black magic + */ + public static String disassemble(byte[] bytes, JavapOption... options) + throws ReflectionException { + StringWriter stringWriter = new StringWriter(); + PrintWriter log = new PrintWriter(stringWriter); + + try { + Object javapTaskInstance = createJavapTaskObject(); + + javapTaskDefaultFileManagerField.set(javapTaskInstance, new IMJavapFileManager( + getDefaultFileManager(javapTaskInstance, log), bytes, TEMP_FILE_NAME)); + + javapTaskLogField.set(javapTaskInstance, log); + + List invokeOptions = Arrays.stream(options) + .map(JavapOption::getOption) + .collect(Collectors.toCollection(ArrayList::new)); + + invokeOptions.add(TEMP_FILE_NAME); + + javapTaskRunMethod.invoke(javapTaskInstance, + (Object) invokeOptions.toArray(String[]::new)); + } catch (InvocationTargetException | NoSuchMethodException | InstantiationException + | IllegalAccessException ex) { + throw new ReflectionException("A fatal exception has occurred while using reflection", + ex); + } + + return stringWriter.toString() + .replace(ANNOYING_WARNING_MESSAGE.formatted(TEMP_FILE_NAME), ""); + } + + /** + * Gets the default file manager instance from a {@link com.sun.tools.javap.JavapTask} and a + * {@link PrintWriter} using + * {@link com.sun.tools.javap.JavapFileManager#create(DiagnosticListener, PrintWriter)} + */ + private static JavaFileManager getDefaultFileManager(Object javapTaskInstance, PrintWriter log) + throws InvocationTargetException, IllegalAccessException { + return (JavaFileManager) javapFileManagerCreateMethod.invoke(null, + getDiagnosticListenerForWriter(javapTaskInstance, log), log); + } + + /** + * Creates a new {@link com.sun.tools.javap.JavapTask} instance + */ + private static Object createJavapTaskObject() throws NoSuchMethodException, + InvocationTargetException, InstantiationException, IllegalAccessException { + return javapTaskCls.getConstructor().newInstance(); + } + + /** + * Generates a {@link DiagnosticListener} instance from a {@link com.sun.tools.javap.JavapTask} + * and a {@link PrintWriter} using + * {@link com.sun.tools.javap.JavapTask#getDiagnosticListenerForWriter(Writer)} + */ + @SuppressWarnings("unchecked") + private static DiagnosticListener getDiagnosticListenerForWriter( + Object javapTaskInstance, PrintWriter log) + throws InvocationTargetException, IllegalAccessException { + return (DiagnosticListener) javapTaskGetDiagnosticListenerForWriterMethod + .invoke(javapTaskInstance, log); // getDiagnosticListenerForWriter's signature: + // DiagnosticListener + // getDiagnosticListenerForWriter(Writer) + } +} diff --git a/inmemorycompiler/src/main/java/org/togetherjava/tjbot/javap/JavapOption.java b/inmemorycompiler/src/main/java/org/togetherjava/tjbot/javap/JavapOption.java new file mode 100644 index 0000000000..14f1f6e9a3 --- /dev/null +++ b/inmemorycompiler/src/main/java/org/togetherjava/tjbot/javap/JavapOption.java @@ -0,0 +1,31 @@ +package org.togetherjava.tjbot.javap; + + +/** + * Enum that represents every possible javap executable option that does not include an argument. + */ +public enum JavapOption { + VERBOSE("-verbose"), + LINE("-l"), + PUBLIC("-public"), + PROTECTED("-protected"), + PACKAGE("-package"), + PRIVATE("-private"), + DISASSEMBLE_CODE("-c"), + INTERNAL_TYPE_SIGNATURES("-s"), + SYSTEM_INFO("-sysinfo"), + CONSTANTS("-constants"); + + private final String option; + + JavapOption(String option) { + this.option = option; + } + + /** + * @return textual representation of the option + */ + public String getOption() { + return option; + } +} diff --git a/inmemorycompiler/src/main/java/org/togetherjava/tjbot/javap/ReflectionException.java b/inmemorycompiler/src/main/java/org/togetherjava/tjbot/javap/ReflectionException.java new file mode 100644 index 0000000000..34c13f5b07 --- /dev/null +++ b/inmemorycompiler/src/main/java/org/togetherjava/tjbot/javap/ReflectionException.java @@ -0,0 +1,11 @@ +package org.togetherjava.tjbot.javap; + +/** + * Thrown when an exception that is caused by things relating to reflection occurs. Typically, + * thrown by {@link Javap} (which uses A LOT of reflection). + */ +class ReflectionException extends RuntimeException { + public ReflectionException(String message, Exception cause) { + super(message, cause); + } +} diff --git a/inmemorycompiler/src/main/java/org/togetherjava/tjbot/javap/package-info.java b/inmemorycompiler/src/main/java/org/togetherjava/tjbot/javap/package-info.java new file mode 100644 index 0000000000..3589ed901a --- /dev/null +++ b/inmemorycompiler/src/main/java/org/togetherjava/tjbot/javap/package-info.java @@ -0,0 +1,7 @@ +@MethodsReturnNonnullByDefault +@ParametersAreNonnullByDefault +package org.togetherjava.tjbot.javap; + +import org.togetherjava.tjbot.annotations.MethodsReturnNonnullByDefault; + +import javax.annotation.ParametersAreNonnullByDefault; diff --git a/settings.gradle b/settings.gradle index 5c048b9ade..8b2af70409 100644 --- a/settings.gradle +++ b/settings.gradle @@ -3,6 +3,7 @@ rootProject.name = 'TJ-Bot' include 'application' include 'database' include 'formatter' +include 'inmemorycompiler' include 'utils' include 'website' diff --git a/utils/build.gradle b/utils/build.gradle index ae1923fecf..7a75b6ba8c 100644 --- a/utils/build.gradle +++ b/utils/build.gradle @@ -1,7 +1,7 @@ plugins { id 'java' } + dependencies { implementation 'com.google.code.findbugs:jsr305:3.0.2' } - From b3f8218607829e9a83b3b568b5cd90591a603d52 Mon Sep 17 00:00:00 2001 From: Zabuzard Date: Thu, 17 Nov 2022 10:49:12 +0100 Subject: [PATCH 2/4] undid reverted change --- .../java/org/togetherjava/tjbot/commands/MessageReceiver.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/application/src/main/java/org/togetherjava/tjbot/commands/MessageReceiver.java b/application/src/main/java/org/togetherjava/tjbot/commands/MessageReceiver.java index 87e0188c58..35843ead1c 100644 --- a/application/src/main/java/org/togetherjava/tjbot/commands/MessageReceiver.java +++ b/application/src/main/java/org/togetherjava/tjbot/commands/MessageReceiver.java @@ -7,7 +7,7 @@ import java.util.regex.Pattern; /** - * Receives incoming Discord guild messages from channels, which optionally match a given pattern. + * Receives incoming Discord guild messages from channels matching a given pattern. *

* All message receivers have to implement this interface. For convenience, there is a * {@link MessageReceiverAdapter} available that implemented most methods already. A new receiver From 545c1a76b6cc7b4c053618905c07009615814d17 Mon Sep 17 00:00:00 2001 From: Zabuzard Date: Thu, 17 Nov 2022 11:23:15 +0100 Subject: [PATCH 3/4] Adjustments for being a code-action --- .../togetherjava/tjbot/commands/Features.java | 3 - .../commands/bytecode/BytecodeCommand.java | 269 ------------------ .../tjbot/commands/bytecode/package-info.java | 10 - .../tjbot/commands/code/BytecodeAction.java | 78 +++++ .../commands/code/CodeMessageHandler.java | 2 +- ...CodeCommand.java => FormatCodeAction.java} | 2 +- 6 files changed, 80 insertions(+), 284 deletions(-) delete mode 100644 application/src/main/java/org/togetherjava/tjbot/commands/bytecode/BytecodeCommand.java delete mode 100644 application/src/main/java/org/togetherjava/tjbot/commands/bytecode/package-info.java create mode 100644 application/src/main/java/org/togetherjava/tjbot/commands/code/BytecodeAction.java rename application/src/main/java/org/togetherjava/tjbot/commands/code/{FormatCodeCommand.java => FormatCodeAction.java} (95%) diff --git a/application/src/main/java/org/togetherjava/tjbot/commands/Features.java b/application/src/main/java/org/togetherjava/tjbot/commands/Features.java index 8207cdb305..229e4b2811 100644 --- a/application/src/main/java/org/togetherjava/tjbot/commands/Features.java +++ b/application/src/main/java/org/togetherjava/tjbot/commands/Features.java @@ -6,7 +6,6 @@ import org.togetherjava.tjbot.commands.basic.RoleSelectCommand; import org.togetherjava.tjbot.commands.basic.SuggestionsUpDownVoter; import org.togetherjava.tjbot.commands.basic.VcActivityCommand; -import org.togetherjava.tjbot.commands.bytecode.BytecodeCommand; import org.togetherjava.tjbot.commands.code.CodeMessageAutoDetection; import org.togetherjava.tjbot.commands.code.CodeMessageHandler; import org.togetherjava.tjbot.commands.code.CodeMessageManualDetection; @@ -16,7 +15,6 @@ import org.togetherjava.tjbot.commands.mathcommands.wolframalpha.WolframAlphaCommand; import org.togetherjava.tjbot.commands.mediaonly.MediaOnlyChannelListener; import org.togetherjava.tjbot.commands.moderation.*; -import org.togetherjava.tjbot.commands.moderation.ReportCommand; import org.togetherjava.tjbot.commands.moderation.attachment.BlacklistedAttachmentListener; import org.togetherjava.tjbot.commands.moderation.modmail.ModMailCommand; import org.togetherjava.tjbot.commands.moderation.scam.ScamBlocker; @@ -143,7 +141,6 @@ public static Collection createFeatures(JDA jda, Database database, Con // Mixtures features.add(new HelpThreadOverviewUpdater(config, helpSystemHelper)); - features.add(new BytecodeCommand()); return features; } diff --git a/application/src/main/java/org/togetherjava/tjbot/commands/bytecode/BytecodeCommand.java b/application/src/main/java/org/togetherjava/tjbot/commands/bytecode/BytecodeCommand.java deleted file mode 100644 index 906536f8ce..0000000000 --- a/application/src/main/java/org/togetherjava/tjbot/commands/bytecode/BytecodeCommand.java +++ /dev/null @@ -1,269 +0,0 @@ -package org.togetherjava.tjbot.commands.bytecode; - -import net.dv8tion.jda.api.entities.Message; -import net.dv8tion.jda.api.entities.TextChannel; -import net.dv8tion.jda.api.events.interaction.command.MessageContextInteractionEvent; -import net.dv8tion.jda.api.events.message.MessageDeleteEvent; -import net.dv8tion.jda.api.events.message.MessageReceivedEvent; -import net.dv8tion.jda.api.events.message.MessageUpdateEvent; -import net.dv8tion.jda.api.interactions.InteractionHook; -import net.dv8tion.jda.api.interactions.commands.build.Commands; - -import org.togetherjava.tjbot.commands.BotCommandAdapter; -import org.togetherjava.tjbot.commands.CommandVisibility; -import org.togetherjava.tjbot.commands.MessageContextCommand; -import org.togetherjava.tjbot.commands.MessageReceiver; -import org.togetherjava.tjbot.imc.CompilationResult; -import org.togetherjava.tjbot.imc.CompileInfo; -import org.togetherjava.tjbot.imc.InMemoryCompiler; -import org.togetherjava.tjbot.imc.JavacOption; -import org.togetherjava.tjbot.javap.Javap; -import org.togetherjava.tjbot.javap.JavapOption; - -import javax.tools.Diagnostic; - -import java.util.*; -import java.util.regex.Matcher; -import java.util.regex.Pattern; -import java.util.stream.Collectors; - -/** - * Bytecode command that uses the message context commands Example usage: - *

- * - *

- * {@code
- *     ```java
- *     class Test {
- *         public void foo() {
- *             System.out.println("Hello World!");
- *         }
- *     }
- *     ```
- * }
- * 
- * - * then apply the application - */ -public final class BytecodeCommand extends BotCommandAdapter - implements MessageContextCommand, MessageReceiver { - private static final String CODE_BLOCK_OPENING = "```rust\n"; - private static final String CODE_BLOCK_CLOSING = "\n```"; - private static final Pattern ANY_CHANNEL_NAME = Pattern.compile(".*"); - - private final Pattern codeBlockExtractorPattern = - Pattern.compile("```(?:java)?\\s*([\\w\\W]+)```|``?([\\w\\W]+)``?"); - private final Map> userToBotMessages = new HashMap<>(); - - public BytecodeCommand() { - super(Commands.message("View bytecode"), CommandVisibility.GUILD); - } - - @Override - public Pattern getChannelNamePattern() { - return ANY_CHANNEL_NAME; - } - - @Override - public void onMessageContext(MessageContextInteractionEvent event) { - Message message = event.getTarget(); - String content = message.getContentRaw(); - - event.reply("Compiling...") - .mentionRepliedUser(false) - .flatMap(InteractionHook::retrieveOriginal) - .queue(compReply -> compile(message, compReply, parseCommandFromMessage(content))); - } - - @Override - public void onMessageDeleted(MessageDeleteEvent event) { - long mesageIdLong = event.getMessageIdLong(); - - if (userToBotMessages.containsKey(mesageIdLong)) { - deleteMyMessages(mesageIdLong, event.getTextChannel()); - } - } - - @Override - public void onMessageReceived(MessageReceivedEvent event) { - // Method isn't needed, context-commands are used for the initial message - } - - @Override - public void onMessageUpdated(MessageUpdateEvent event) { - Message message = event.getMessage(); - long messageIdLong = event.getMessageIdLong(); - - if (!userToBotMessages.containsKey(messageIdLong)) { - return; - } - - TextChannel textChannel = message.getTextChannel(); - List botMessages = userToBotMessages.get(messageIdLong); - - if (botMessages.isEmpty()) { - message.reply("An unknown error occurred").queue(); - - return; - } - - textChannel.retrieveMessageById(botMessages.get(0)).queue(botMessage -> { - textChannel.purgeMessagesById(botMessages.stream() - .skip(1) // skip the first bot message to edit it - .map(String::valueOf) - .toList()); - - botMessage.editMessage("Recompiling...").queue(); - - compile(message, botMessage, parseCommandFromMessage(message.getContentRaw())); - }); - } - - private void deleteMyMessages(Long msgId, TextChannel channel) { - if (!userToBotMessages.containsKey(msgId)) { - return; - } - - channel - .purgeMessagesById(userToBotMessages.get(msgId).stream().map(String::valueOf).toList()); - - userToBotMessages.remove(msgId); - } - - private void compile(Message userMessage, Message botMessage, String content) { - userToBotMessages.put(userMessage.getIdLong(), List.of(botMessage.getIdLong())); - - CompilationResult result; - - try { - result = InMemoryCompiler.compile(content, JavacOption.DEBUG_ALL); - } catch (RuntimeException e) { - botMessage - .editMessage("A fatal error has occurred during compilation. %s" - .formatted(e.getMessage())) - .mentionRepliedUser(false) - .queue(); - - return; - } - - if (!result.success()) { - botMessage - .editMessage("Compilation failed." + CODE_BLOCK_OPENING - + iterToCollection(result.compileInfos()).stream() - .map(CompileInfo::diagnostic) - .map(Diagnostic::toString) - .collect(Collectors.joining("\n")) - + CODE_BLOCK_CLOSING) - .mentionRepliedUser(false) - .queue(); - - return; - } - - botMessage.editMessage("Compilation was successfull! Disassembling...") - .mentionRepliedUser(false) - .queue(disReply -> { - String disassembled; - - try { - disassembled = Javap.disassemble(result.bytes(), JavapOption.VERBOSE); - } catch (RuntimeException e) { - botMessage - .editMessage("A fatal error has occurred during disassembly. %s" - .formatted(e.getMessage())) - .mentionRepliedUser(false) - .queue(); - - return; - } - - String msgResult = surroundInCodeBlock(disassembled); - - disReply.delete().queue(); - - if (msgResult.length() <= Message.MAX_CONTENT_LENGTH) { - userMessage.reply(msgResult) - .mentionRepliedUser(false) - .queue(msg -> userToBotMessages.put(userMessage.getIdLong(), - List.of(msg.getIdLong()))); - - return; - } - - List msgResults = explodeEvery(disassembled, - Message.MAX_CONTENT_LENGTH - surroundInCodeBlock("").length()); - Iterator iterator = msgResults.iterator(); - List messageIds = new ArrayList<>(msgResults.size()); - - if (iterator.hasNext()) { - userMessage.reply(surroundInCodeBlock(iterator.next())) - .mentionRepliedUser(false) - .queue(msg -> messageIds.add(msg.getIdLong())); - } - - while (iterator.hasNext()) { - disReply.getTextChannel() - .sendMessage(surroundInCodeBlock(iterator.next())) - .queue(msg -> messageIds.add(msg.getIdLong())); - } - - userToBotMessages.put(userMessage.getIdLong(), messageIds); - }); - } - - private String surroundInCodeBlock(String s) { - return CODE_BLOCK_OPENING + s + CODE_BLOCK_CLOSING; - } - - /** - * Example: - * - *
-     * {@code
-     * takeApart("Hello\nWorld!", 3) returns List("Hel", "lo", "Wor", "ld!")
-     * }
-     * 
- */ - private List explodeEvery(String message, int maxPartLength) { - List result = new ArrayList<>(); - String[] lines = message.split("\n"); - int currentLength = 0; - StringBuilder buffer = new StringBuilder(); - - for (String line : lines) { - if (currentLength + line.length() > maxPartLength) { - result.add(buffer.toString()); - buffer = new StringBuilder(); - currentLength = 0; - } - - buffer.append(line); - currentLength += line.length(); - } - - if (!buffer.isEmpty()) { - result.add(buffer.toString()); - } - - return result; - } - - private Collection iterToCollection(Iterable iter) { - Collection list = new ArrayList<>(); - - iter.forEach(list::add); - - return list; - } - - private String parseCommandFromMessage(String messageContent) { - Matcher codeBlockMatcher = codeBlockExtractorPattern.matcher(messageContent); - - if (codeBlockMatcher.find()) { - return codeBlockMatcher.group(1); - } - - return messageContent; - } -} diff --git a/application/src/main/java/org/togetherjava/tjbot/commands/bytecode/package-info.java b/application/src/main/java/org/togetherjava/tjbot/commands/bytecode/package-info.java deleted file mode 100644 index 729e166d73..0000000000 --- a/application/src/main/java/org/togetherjava/tjbot/commands/bytecode/package-info.java +++ /dev/null @@ -1,10 +0,0 @@ -/** - * This package offers the {@link org.togetherjava.tjbot.commands.bytecode.BytecodeCommand}. - */ -@MethodsReturnNonnullByDefault -@ParametersAreNonnullByDefault -package org.togetherjava.tjbot.commands.bytecode; - -import org.togetherjava.tjbot.annotations.MethodsReturnNonnullByDefault; - -import javax.annotation.ParametersAreNonnullByDefault; diff --git a/application/src/main/java/org/togetherjava/tjbot/commands/code/BytecodeAction.java b/application/src/main/java/org/togetherjava/tjbot/commands/code/BytecodeAction.java new file mode 100644 index 0000000000..a61b867bad --- /dev/null +++ b/application/src/main/java/org/togetherjava/tjbot/commands/code/BytecodeAction.java @@ -0,0 +1,78 @@ +package org.togetherjava.tjbot.commands.code; + +import net.dv8tion.jda.api.EmbedBuilder; +import net.dv8tion.jda.api.entities.MessageEmbed; + +import org.togetherjava.tjbot.commands.utils.CodeFence; +import org.togetherjava.tjbot.imc.CompilationResult; +import org.togetherjava.tjbot.imc.InMemoryCompiler; +import org.togetherjava.tjbot.imc.JavacOption; +import org.togetherjava.tjbot.javap.Javap; +import org.togetherjava.tjbot.javap.JavapOption; + +import javax.annotation.Nullable; + +import java.util.StringJoiner; + +// TODO Javadoc +final class BytecodeAction implements CodeAction { + @Override + public String getLabel() { + return "Bytecode"; + } + + @Override + public MessageEmbed apply(CodeFence codeFence) { + if (!isLanguageSupported(codeFence.language())) { + return createResponse("Sorry, only Java is supported."); + } + + String result = compile(codeFence.code()); + return createResponse(result); + } + + private static boolean isLanguageSupported(@Nullable String language) { + // Assume that absence indicates Java code + return language == null || "java".equals(language); + } + + private static MessageEmbed createResponse(String content) { + // Rust highlighting looks decent for bytecode + CodeFence resultCodeFence = new CodeFence("rust", content); + + return new EmbedBuilder().setTitle("Bytecode") + .setDescription(resultCodeFence.toMarkdown()) + .setColor(CodeMessageHandler.AMBIENT_COLOR) + .build(); + } + + private static String compile(String code) { + // Raw compilation + CompilationResult compilationResult; + try { + compilationResult = InMemoryCompiler.compile(code, JavacOption.DEBUG_ALL); + } catch (RuntimeException e) { + // TODO logging + return "A fatal error has occurred during compilation: " + e.getMessage(); + } + + if (!compilationResult.success()) { + StringJoiner failureMessage = new StringJoiner("\n", "Compilation failed.\n", ""); + compilationResult.compileInfos() + .forEach(info -> failureMessage.add(info.diagnostic().toString())); + return failureMessage.toString(); + } + + // Disassembling + String disassembledResult; + try { + disassembledResult = Javap.disassemble(compilationResult.bytes(), JavapOption.VERBOSE); + } catch (RuntimeException e) { + // TODO logging + return "A fatal error has occurred during disassembly: " + e.getMessage(); + } + + // TODO max length of embeds + return disassembledResult; + } +} diff --git a/application/src/main/java/org/togetherjava/tjbot/commands/code/CodeMessageHandler.java b/application/src/main/java/org/togetherjava/tjbot/commands/code/CodeMessageHandler.java index 341c8ad351..aa3c469bce 100644 --- a/application/src/main/java/org/togetherjava/tjbot/commands/code/CodeMessageHandler.java +++ b/application/src/main/java/org/togetherjava/tjbot/commands/code/CodeMessageHandler.java @@ -70,7 +70,7 @@ public CodeMessageHandler() { componentIdInteractor = new ComponentIdInteractor(getInteractionType(), getName()); - List codeActions = List.of(new FormatCodeCommand()); + List codeActions = List.of(new FormatCodeAction(), new BytecodeAction()); labelToCodeAction = codeActions.stream() .collect(Collectors.toMap(CodeAction::getLabel, Function.identity(), (x, y) -> y, diff --git a/application/src/main/java/org/togetherjava/tjbot/commands/code/FormatCodeCommand.java b/application/src/main/java/org/togetherjava/tjbot/commands/code/FormatCodeAction.java similarity index 95% rename from application/src/main/java/org/togetherjava/tjbot/commands/code/FormatCodeCommand.java rename to application/src/main/java/org/togetherjava/tjbot/commands/code/FormatCodeAction.java index 2a3b086cc4..a37d795bec 100644 --- a/application/src/main/java/org/togetherjava/tjbot/commands/code/FormatCodeCommand.java +++ b/application/src/main/java/org/togetherjava/tjbot/commands/code/FormatCodeAction.java @@ -11,7 +11,7 @@ *

* While it will attempt formatting for any language, best results are achieved for Java code. */ -final class FormatCodeCommand implements CodeAction { +final class FormatCodeAction implements CodeAction { private final Formatter formatter = new Formatter(); @Override From 6b7c8e7816de115b87bff3779e05a55f4052d7d5 Mon Sep 17 00:00:00 2001 From: Zabuzard Date: Thu, 17 Nov 2022 14:39:25 +0100 Subject: [PATCH 4/4] Improvements to javap --- application/build.gradle | 4 +- build.gradle | 5 - formatter/build.gradle | 1 - inmemorycompiler/build.gradle | 8 - .../togetherjava/tjbot/imc/package-info.java | 4 +- .../tjbot/javap/IMJavapFileManager.java | 40 ----- .../tjbot/javap/InMemoryJavaFileManager.java | 49 ++++++ .../org/togetherjava/tjbot/javap/Javap.java | 163 +++++++++--------- .../togetherjava/tjbot/javap/JavapOption.java | 48 +++++- .../tjbot/javap/ReflectionException.java | 11 -- .../tjbot/javap/package-info.java | 4 + 11 files changed, 185 insertions(+), 152 deletions(-) delete mode 100644 inmemorycompiler/src/main/java/org/togetherjava/tjbot/javap/IMJavapFileManager.java create mode 100644 inmemorycompiler/src/main/java/org/togetherjava/tjbot/javap/InMemoryJavaFileManager.java delete mode 100644 inmemorycompiler/src/main/java/org/togetherjava/tjbot/javap/ReflectionException.java diff --git a/application/build.gradle b/application/build.gradle index 0891de12b8..28b02e4768 100644 --- a/application/build.gradle +++ b/application/build.gradle @@ -1,3 +1,5 @@ +import java.time.Instant + buildscript { dependencies { classpath 'org.xerial:sqlite-jdbc:3.39.2.0' @@ -28,7 +30,7 @@ jib { } container { mainClass = 'org.togetherjava.tjbot.BootstrapLauncher' - setCreationTime(java.time.Instant.now().toString()) + setCreationTime(Instant.now().toString()) } } diff --git a/build.gradle b/build.gradle index 09d6f785df..d6bc81a0cf 100644 --- a/build.gradle +++ b/build.gradle @@ -56,11 +56,6 @@ subprojects { excludes { // Disables "Track uses of "TO-DO" tags" rule. message 'java:S1135' - - // Disables "Regular expressions should not overflow the stack" rule. - // https://sonarcloud.io/project/issues?id=Together-Java_TJ-Bot&issues=AXvleoajNC7zjjhmSufQ&open=AXvleoajNC7zjjhmSufQ - // https://sonarcloud.io/project/issues?id=Together-Java_TJ-Bot&issues=AXvleoX5NC7zjjhmSufP&open=AXvleoX5NC7zjjhmSufP - message 'java:S5998' } } diff --git a/formatter/build.gradle b/formatter/build.gradle index e05ddb18dd..9479725367 100644 --- a/formatter/build.gradle +++ b/formatter/build.gradle @@ -10,4 +10,3 @@ dependencies { testImplementation 'org.junit.jupiter:junit-jupiter-params:5.9.0' testRuntimeOnly 'org.junit.jupiter:junit-jupiter-engine:5.9.0' } - diff --git a/inmemorycompiler/build.gradle b/inmemorycompiler/build.gradle index 282261f5b1..8485f89868 100644 --- a/inmemorycompiler/build.gradle +++ b/inmemorycompiler/build.gradle @@ -3,15 +3,7 @@ plugins { } dependencies { - implementation 'org.jetbrains:annotations:23.0.0' implementation 'com.google.code.findbugs:jsr305:3.0.2' implementation project(':utils') - - testImplementation 'org.junit.jupiter:junit-jupiter-api:5.8.1' - testRuntimeOnly 'org.junit.jupiter:junit-jupiter-engine:5.8.1' -} - -test { - useJUnitPlatform() } diff --git a/inmemorycompiler/src/main/java/org/togetherjava/tjbot/imc/package-info.java b/inmemorycompiler/src/main/java/org/togetherjava/tjbot/imc/package-info.java index 87b4fbb59c..270f61760b 100644 --- a/inmemorycompiler/src/main/java/org/togetherjava/tjbot/imc/package-info.java +++ b/inmemorycompiler/src/main/java/org/togetherjava/tjbot/imc/package-info.java @@ -1,5 +1,7 @@ /** - * This package provides utility classes to compile Java code fully in memory. (IMC stands for + * This package provides utility classes to compile Java code fully in memory. + *

+ * See {@link org.togetherjava.tjbot.imc.InMemoryCompiler} as entry point. (IMC stands for * In-Memory-Compiler) */ @MethodsReturnNonnullByDefault diff --git a/inmemorycompiler/src/main/java/org/togetherjava/tjbot/javap/IMJavapFileManager.java b/inmemorycompiler/src/main/java/org/togetherjava/tjbot/javap/IMJavapFileManager.java deleted file mode 100644 index bb14be4412..0000000000 --- a/inmemorycompiler/src/main/java/org/togetherjava/tjbot/javap/IMJavapFileManager.java +++ /dev/null @@ -1,40 +0,0 @@ -package org.togetherjava.tjbot.javap; - -import org.jetbrains.annotations.Nullable; - -import javax.tools.ForwardingJavaFileManager; -import javax.tools.JavaFileManager; -import javax.tools.JavaFileObject; -import javax.tools.SimpleJavaFileObject; - -import java.io.ByteArrayInputStream; -import java.io.InputStream; -import java.net.URI; - -/** - * File manager that returns given bytes for requests to ANY java file input - * - * @see JavaFileManager - */ -class IMJavapFileManager extends ForwardingJavaFileManager { - private final byte[] bytes; - private final String fileName; - - protected IMJavapFileManager(JavaFileManager fileManager, byte[] bytes, String fileName) { - super(fileManager); - - this.bytes = bytes; - this.fileName = fileName; - } - - @Override - public JavaFileObject getJavaFileForInput(@Nullable Location location, - @Nullable String className, JavaFileObject.Kind kind) { - return new SimpleJavaFileObject(URI.create("file:///%s".formatted(fileName)), kind) { - @Override - public InputStream openInputStream() { - return new ByteArrayInputStream(bytes); - } - }; - } -} diff --git a/inmemorycompiler/src/main/java/org/togetherjava/tjbot/javap/InMemoryJavaFileManager.java b/inmemorycompiler/src/main/java/org/togetherjava/tjbot/javap/InMemoryJavaFileManager.java new file mode 100644 index 0000000000..18d04f99c1 --- /dev/null +++ b/inmemorycompiler/src/main/java/org/togetherjava/tjbot/javap/InMemoryJavaFileManager.java @@ -0,0 +1,49 @@ +package org.togetherjava.tjbot.javap; + +import javax.annotation.Nullable; +import javax.tools.ForwardingJavaFileManager; +import javax.tools.JavaFileManager; +import javax.tools.JavaFileObject; +import javax.tools.SimpleJavaFileObject; + +import java.io.ByteArrayInputStream; +import java.io.InputStream; +import java.net.URI; + +/** + * File manager that always returns given predefined data for any file request. + * + * @see JavaFileManager + */ +final class InMemoryJavaFileManager extends ForwardingJavaFileManager { + private final byte[] fileData; + private final String fileName; + + InMemoryJavaFileManager(JavaFileManager fileManager, byte[] fileData, String fileName) { + super(fileManager); + + this.fileData = fileData.clone(); + this.fileName = fileName; + } + + @Override + public JavaFileObject getJavaFileForInput(@Nullable Location location, + @Nullable String className, JavaFileObject.Kind kind) { + return new InMemoryJavaFile(kind, fileData, fileName); + } + + private static final class InMemoryJavaFile extends SimpleJavaFileObject { + private final byte[] fileData; + + private InMemoryJavaFile(Kind kind, byte[] fileData, String fileName) { + super(URI.create("file:///" + fileName), kind); + + this.fileData = fileData; + } + + @Override + public InputStream openInputStream() { + return new ByteArrayInputStream(fileData); + } + } +} diff --git a/inmemorycompiler/src/main/java/org/togetherjava/tjbot/javap/Javap.java b/inmemorycompiler/src/main/java/org/togetherjava/tjbot/javap/Javap.java index e4d5762cf8..8fd51c2b7e 100644 --- a/inmemorycompiler/src/main/java/org/togetherjava/tjbot/javap/Javap.java +++ b/inmemorycompiler/src/main/java/org/togetherjava/tjbot/javap/Javap.java @@ -16,125 +16,132 @@ import java.util.stream.Collectors; /** - * A javap-interface that uses reflection to access locked-down classes of the jdk.jdeps module and - * keep everything in-memory + * In-memory disassembler of raw Java bytecode (for example, as received by + * {@link org.togetherjava.tjbot.imc.InMemoryCompiler}, or by reading a {@code .class} file). */ -// Disables "Reflection should not be used to increase accessibility of classes, methods, or fields" -// rule (Reflection is required for the Javap class to work). -@SuppressWarnings({"java:S3011"}) +/* + * Sonar does not like the heavy use of reflection to access locked down internal JDK tools, but the + * class is designed based on this. + */ +@SuppressWarnings("java:S3011") public final class Javap { - // Hide constructor - private Javap() {} + // FIXME Make this a non-static class + private Javap() { + throw new UnsupportedOperationException("Utility class"); + } private static final String TEMP_FILE_NAME = "tmp"; + // FIXME Odd name private static final String ANNOYING_WARNING_MESSAGE = "Warning: File /%s does not contain class % javapFileManagerCls; - private static final Class javapTaskCls; + private static final Class javapFileManagerType; + private static final Class javapTaskType; - private static final Method javapFileManagerCreateMethod; - private static final Method javapTaskRunMethod; - private static final Method javapTaskGetDiagnosticListenerForWriterMethod; + private static final Method javapFileManagerCreate; + private static final Method javapTaskRun; + private static final Method javapTaskGetDiagnosticListenerForWriter; - private static final Field javapTaskDefaultFileManagerField; - private static final Field javapTaskLogField; + private static final Field javapTaskDefaultFileManager; + private static final Field javapTaskLog; static { try { - javapFileManagerCls = Class.forName("com.sun.tools.javap.JavapFileManager"); - javapFileManagerCreateMethod = javapFileManagerCls.getDeclaredMethod("create", + javapFileManagerType = Class.forName("com.sun.tools.javap.JavapFileManager"); + javapFileManagerCreate = javapFileManagerType.getDeclaredMethod("create", DiagnosticListener.class, PrintWriter.class); - javapTaskCls = Class.forName("com.sun.tools.javap.JavapTask"); - javapTaskDefaultFileManagerField = javapTaskCls.getDeclaredField("defaultFileManager"); - javapTaskLogField = javapTaskCls.getDeclaredField("log"); - javapTaskRunMethod = javapTaskCls.getDeclaredMethod("run", String[].class); - javapTaskGetDiagnosticListenerForWriterMethod = - javapTaskCls.getDeclaredMethod("getDiagnosticListenerForWriter", Writer.class); - - javapFileManagerCreateMethod.setAccessible(true); - javapTaskDefaultFileManagerField.setAccessible(true); - javapTaskLogField.setAccessible(true); - javapTaskRunMethod.setAccessible(true); - javapTaskGetDiagnosticListenerForWriterMethod.setAccessible(true); - } catch (ClassNotFoundException | NoSuchMethodException | NoSuchFieldException ex) { - throw new ReflectionException( - "A fatal exception has occurred while using reflection in the non-static initializer of org.togetherjava.tjbot.javap.Javap", - ex); + javapTaskType = Class.forName("com.sun.tools.javap.JavapTask"); + javapTaskDefaultFileManager = javapTaskType.getDeclaredField("defaultFileManager"); + javapTaskLog = javapTaskType.getDeclaredField("log"); + javapTaskRun = javapTaskType.getDeclaredMethod("run", String[].class); + javapTaskGetDiagnosticListenerForWriter = + javapTaskType.getDeclaredMethod("getDiagnosticListenerForWriter", Writer.class); + + javapFileManagerCreate.setAccessible(true); + javapTaskDefaultFileManager.setAccessible(true); + javapTaskLog.setAccessible(true); + javapTaskRun.setAccessible(true); + javapTaskGetDiagnosticListenerForWriter.setAccessible(true); + } catch (ClassNotFoundException | NoSuchMethodException | NoSuchFieldException e) { + throw new IllegalStateException( + "Error while attempting to access JDK internal Javap classes for the disassembler.", + e); } } /** - * Disassembles the given classfile bytecode with given program arguments + * Disassembles the given bytecode with given options. * - * @param bytes classfile bytecode - * @param options options to give to javap - * @return disassembled view - * @throws ReflectionException if an exception occurs while doing reflection black magic + * @param rawBytecode the raw bytecode to disassemble + * @param options selectable options + * @return disassembled bytecode + * @throws RuntimeException If the given bytecode could not be disassembled, for example, + * because it was invalid */ - public static String disassemble(byte[] bytes, JavapOption... options) - throws ReflectionException { - StringWriter stringWriter = new StringWriter(); - PrintWriter log = new PrintWriter(stringWriter); + public static String disassemble(byte[] rawBytecode, JavapOption... options) { + // FIXME Proper exception usage + StringWriter result = new StringWriter(); + PrintWriter resultWriter = new PrintWriter(result); try { - Object javapTaskInstance = createJavapTaskObject(); - - javapTaskDefaultFileManagerField.set(javapTaskInstance, new IMJavapFileManager( - getDefaultFileManager(javapTaskInstance, log), bytes, TEMP_FILE_NAME)); - - javapTaskLogField.set(javapTaskInstance, log); + Object javapTask = newJavapTask(); - List invokeOptions = Arrays.stream(options) - .map(JavapOption::getOption) - .collect(Collectors.toCollection(ArrayList::new)); + var fileManager = new InMemoryJavaFileManager( + getDefaultFileManager(javapTask, resultWriter), rawBytecode, TEMP_FILE_NAME); + javapTaskDefaultFileManager.set(javapTask, fileManager); - invokeOptions.add(TEMP_FILE_NAME); + javapTaskLog.set(javapTask, resultWriter); - javapTaskRunMethod.invoke(javapTaskInstance, - (Object) invokeOptions.toArray(String[]::new)); + javapTaskRun.invoke(javapTask, optionsToInvokeArgs(options)); } catch (InvocationTargetException | NoSuchMethodException | InstantiationException - | IllegalAccessException ex) { - throw new ReflectionException("A fatal exception has occurred while using reflection", - ex); + | IllegalAccessException e) { + throw new IllegalArgumentException("Failed to disassemble the given bytecode.", e); } - return stringWriter.toString() - .replace(ANNOYING_WARNING_MESSAGE.formatted(TEMP_FILE_NAME), ""); + return result.toString().replace(ANNOYING_WARNING_MESSAGE.formatted(TEMP_FILE_NAME), ""); } /** - * Gets the default file manager instance from a {@link com.sun.tools.javap.JavapTask} and a + * Gets the default file manager instance from a {@code com.sun.tools.javap.JavapTask} and a * {@link PrintWriter} using - * {@link com.sun.tools.javap.JavapFileManager#create(DiagnosticListener, PrintWriter)} + * {@code com.sun.tools.javap.JavapFileManager#create(DiagnosticListener, PrintWriter)} */ - private static JavaFileManager getDefaultFileManager(Object javapTaskInstance, PrintWriter log) + private static JavaFileManager getDefaultFileManager(Object javapTask, PrintWriter writer) throws InvocationTargetException, IllegalAccessException { - return (JavaFileManager) javapFileManagerCreateMethod.invoke(null, - getDiagnosticListenerForWriter(javapTaskInstance, log), log); - } - - /** - * Creates a new {@link com.sun.tools.javap.JavapTask} instance - */ - private static Object createJavapTaskObject() throws NoSuchMethodException, - InvocationTargetException, InstantiationException, IllegalAccessException { - return javapTaskCls.getConstructor().newInstance(); + DiagnosticListener diagnosticListener = + getDiagnosticListenerForWriter(javapTask, writer); + return (JavaFileManager) javapFileManagerCreate.invoke(null, diagnosticListener, writer); } /** - * Generates a {@link DiagnosticListener} instance from a {@link com.sun.tools.javap.JavapTask} + * Generates a {@link DiagnosticListener} instance from a {@code com.sun.tools.javap.JavapTask} * and a {@link PrintWriter} using - * {@link com.sun.tools.javap.JavapTask#getDiagnosticListenerForWriter(Writer)} + * {@code com.sun.tools.javap.JavapTask#getDiagnosticListenerForWriter(Writer)} */ @SuppressWarnings("unchecked") private static DiagnosticListener getDiagnosticListenerForWriter( - Object javapTaskInstance, PrintWriter log) + Object javapTask, PrintWriter writer) throws InvocationTargetException, IllegalAccessException { - return (DiagnosticListener) javapTaskGetDiagnosticListenerForWriterMethod - .invoke(javapTaskInstance, log); // getDiagnosticListenerForWriter's signature: - // DiagnosticListener - // getDiagnosticListenerForWriter(Writer) + return (DiagnosticListener) javapTaskGetDiagnosticListenerForWriter + .invoke(javapTask, writer); + } + + /** + * Creates a new {@code com.sun.tools.javap.JavapTask} instance + */ + private static Object newJavapTask() throws NoSuchMethodException, InvocationTargetException, + InstantiationException, IllegalAccessException { + return javapTaskType.getConstructor().newInstance(); + } + + private static Object[] optionsToInvokeArgs(JavapOption... options) { + List invokeArgs = Arrays.stream(options) + .map(JavapOption::getLabel) + .collect(Collectors.toCollection(ArrayList::new)); + + invokeArgs.add(TEMP_FILE_NAME); + + return invokeArgs.toArray(Object[]::new); } } diff --git a/inmemorycompiler/src/main/java/org/togetherjava/tjbot/javap/JavapOption.java b/inmemorycompiler/src/main/java/org/togetherjava/tjbot/javap/JavapOption.java index 14f1f6e9a3..bd7a91848a 100644 --- a/inmemorycompiler/src/main/java/org/togetherjava/tjbot/javap/JavapOption.java +++ b/inmemorycompiler/src/main/java/org/togetherjava/tjbot/javap/JavapOption.java @@ -1,31 +1,65 @@ package org.togetherjava.tjbot.javap; - /** - * Enum that represents every possible javap executable option that does not include an argument. + * Selectable options for {@link Javap}. See the official + * documentation + * for details. */ public enum JavapOption { + /** + * Shows additional information about the selected class. + */ VERBOSE("-verbose"), + /** + * Shows line and local variable tables. + */ LINE("-l"), + /** + * Shows only public classes and members. + */ PUBLIC("-public"), + /** + * Shows only protected and public classes and members. + */ PROTECTED("-protected"), + /** + * Shows package/protected/public classes and members (default). + */ PACKAGE("-package"), + /** + * Shows all classes and members. + */ PRIVATE("-private"), + /** + * Shows disassembled code, for example, the instructions that comprise the Java bytecodes, for + * each of the methods in the class. + */ DISASSEMBLE_CODE("-c"), + /** + * Shows internal type signatures. + */ INTERNAL_TYPE_SIGNATURES("-s"), + /** + * Shows system information (path, size, date, SHA-256 hash) of the class being processed. + */ SYSTEM_INFO("-sysinfo"), + /** + * Shows static final constants. + */ CONSTANTS("-constants"); - private final String option; + private final String label; - JavapOption(String option) { - this.option = option; + JavapOption(String label) { + this.label = label; } /** + * Gets the label of this option. + * * @return textual representation of the option */ - public String getOption() { - return option; + public String getLabel() { + return label; } } diff --git a/inmemorycompiler/src/main/java/org/togetherjava/tjbot/javap/ReflectionException.java b/inmemorycompiler/src/main/java/org/togetherjava/tjbot/javap/ReflectionException.java deleted file mode 100644 index 34c13f5b07..0000000000 --- a/inmemorycompiler/src/main/java/org/togetherjava/tjbot/javap/ReflectionException.java +++ /dev/null @@ -1,11 +0,0 @@ -package org.togetherjava.tjbot.javap; - -/** - * Thrown when an exception that is caused by things relating to reflection occurs. Typically, - * thrown by {@link Javap} (which uses A LOT of reflection). - */ -class ReflectionException extends RuntimeException { - public ReflectionException(String message, Exception cause) { - super(message, cause); - } -} diff --git a/inmemorycompiler/src/main/java/org/togetherjava/tjbot/javap/package-info.java b/inmemorycompiler/src/main/java/org/togetherjava/tjbot/javap/package-info.java index 3589ed901a..4b45453c81 100644 --- a/inmemorycompiler/src/main/java/org/togetherjava/tjbot/javap/package-info.java +++ b/inmemorycompiler/src/main/java/org/togetherjava/tjbot/javap/package-info.java @@ -1,3 +1,7 @@ +/** + * Provides a disassembler that can turn raw Java bytecode into a human-readable form. See + * {@link org.togetherjava.tjbot.javap.Javap} as entry point. + */ @MethodsReturnNonnullByDefault @ParametersAreNonnullByDefault package org.togetherjava.tjbot.javap;