repo
stringclasses
1k values
file_url
stringlengths
96
373
file_path
stringlengths
11
294
content
stringlengths
0
32.8k
language
stringclasses
1 value
license
stringclasses
6 values
commit_sha
stringclasses
1k values
retrieved_at
stringdate
2026-01-04 14:45:56
2026-01-04 18:30:23
truncated
bool
2 classes
alkarn/sslengine.example
https://github.com/alkarn/sslengine.example/blob/13a9e6cb04713213a8ac3fc7ced06e5ef8cdf720/src/main/java/alkarn/github/io/sslengine/example/NioSslServer.java
src/main/java/alkarn/github/io/sslengine/example/NioSslServer.java
package alkarn.github.io.sslengine.example; import java.io.IOException; import java.net.InetSocketAddress; import java.nio.ByteBuffer; import java.nio.channels.SelectionKey; import java.nio.channels.Selector; import java.nio.channels.ServerSocketChannel; import java.nio.channels.SocketChannel; import java.nio.channels.spi.SelectorProvider; import java.security.SecureRandom; import java.util.Iterator; import javax.net.ssl.SSLContext; import javax.net.ssl.SSLEngine; import javax.net.ssl.SSLEngineResult; import javax.net.ssl.SSLException; import javax.net.ssl.SSLSession; /** * An SSL/TLS server, that will listen to a specific address and port and serve SSL/TLS connections * compatible with the protocol it applies. * <p/> * After initialization {@link NioSslServer#start()} should be called so the server starts to listen to * new connection requests. At this point, start is blocking, so, in order to be able to gracefully stop * the server, a {@link Runnable} containing a server object should be created. This runnable should * start the server in its run method and also provide a stop method, which will call {@link NioSslServer#stop()}. * </p> * NioSslServer makes use of Java NIO, and specifically listens to new connection requests with a {@link ServerSocketChannel}, which will * create new {@link SocketChannel}s and a {@link Selector} which serves all the connections in one thread. * * @author <a href="mailto:alex.a.karnezis@gmail.com">Alex Karnezis</a> */ public class NioSslServer extends NioSslPeer { /** * Declares if the server is active to serve and create new connections. */ private boolean active; /** * The context will be initialized with a specific SSL/TLS protocol and will then be used * to create {@link SSLEngine} classes for each new connection that arrives to the server. */ private SSLContext context; /** * A part of Java NIO that will be used to serve all connections to the server in one thread. */ private Selector selector; /** * Server is designed to apply an SSL/TLS protocol and listen to an IP address and port. * * @param protocol - the SSL/TLS protocol that this server will be configured to apply. * @param hostAddress - the IP address this server will listen to. * @param port - the port this server will listen to. * @throws Exception */ public NioSslServer(String protocol, String hostAddress, int port) throws Exception { context = SSLContext.getInstance(protocol); context.init(createKeyManagers("./src/main/resources/server.jks", "storepass", "keypass"), createTrustManagers("./src/main/resources/trustedCerts.jks", "storepass"), new SecureRandom()); SSLSession dummySession = context.createSSLEngine().getSession(); myAppData = ByteBuffer.allocate(dummySession.getApplicationBufferSize()); myNetData = ByteBuffer.allocate(dummySession.getPacketBufferSize()); peerAppData = ByteBuffer.allocate(dummySession.getApplicationBufferSize()); peerNetData = ByteBuffer.allocate(dummySession.getPacketBufferSize()); dummySession.invalidate(); selector = SelectorProvider.provider().openSelector(); ServerSocketChannel serverSocketChannel = ServerSocketChannel.open(); serverSocketChannel.configureBlocking(false); serverSocketChannel.socket().bind(new InetSocketAddress(hostAddress, port)); serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT); active = true; } /** * Should be called in order the server to start listening to new connections. * This method will run in a loop as long as the server is active. In order to stop the server * you should use {@link NioSslServer#stop()} which will set it to inactive state * and also wake up the listener, which may be in blocking select() state. * * @throws Exception */ public void start() throws Exception { log.debug("Initialized and waiting for new connections..."); while (isActive()) { selector.select(); Iterator<SelectionKey> selectedKeys = selector.selectedKeys().iterator(); while (selectedKeys.hasNext()) { SelectionKey key = selectedKeys.next(); selectedKeys.remove(); if (!key.isValid()) { continue; } if (key.isAcceptable()) { accept(key); } else if (key.isReadable()) { read((SocketChannel) key.channel(), (SSLEngine) key.attachment()); } } } log.debug("Goodbye!"); } /** * Sets the server to an inactive state, in order to exit the reading loop in {@link NioSslServer#start()} * and also wakes up the selector, which may be in select() blocking state. */ public void stop() { log.debug("Will now close server..."); active = false; executor.shutdown(); selector.wakeup(); } /** * Will be called after a new connection request arrives to the server. Creates the {@link SocketChannel} that will * be used as the network layer link, and the {@link SSLEngine} that will encrypt and decrypt all the data * that will be exchanged during the session with this specific client. * * @param key - the key dedicated to the {@link ServerSocketChannel} used by the server to listen to new connection requests. * @throws Exception */ private void accept(SelectionKey key) throws Exception { log.debug("New connection request!"); SocketChannel socketChannel = ((ServerSocketChannel) key.channel()).accept(); socketChannel.configureBlocking(false); SSLEngine engine = context.createSSLEngine(); engine.setUseClientMode(false); engine.beginHandshake(); if (doHandshake(socketChannel, engine)) { socketChannel.register(selector, SelectionKey.OP_READ, engine); } else { socketChannel.close(); log.debug("Connection closed due to handshake failure."); } } /** * Will be called by the selector when the specific socket channel has data to be read. * As soon as the server reads these data, it will call {@link NioSslServer#write(SocketChannel, SSLEngine, String)} * to send back a trivial response. * * @param socketChannel - the transport link used between the two peers. * @param engine - the engine used for encryption/decryption of the data exchanged between the two peers. * @throws IOException if an I/O error occurs to the socket channel. */ @Override protected void read(SocketChannel socketChannel, SSLEngine engine) throws IOException { log.debug("About to read from a client..."); peerNetData.clear(); int bytesRead = socketChannel.read(peerNetData); if (bytesRead > 0) { peerNetData.flip(); while (peerNetData.hasRemaining()) { peerAppData.clear(); SSLEngineResult result = engine.unwrap(peerNetData, peerAppData); switch (result.getStatus()) { case OK: peerAppData.flip(); log.debug("Incoming message: " + new String(peerAppData.array())); break; case BUFFER_OVERFLOW: peerAppData = enlargeApplicationBuffer(engine, peerAppData); break; case BUFFER_UNDERFLOW: peerNetData = handleBufferUnderflow(engine, peerNetData); break; case CLOSED: log.debug("Client wants to close connection..."); closeConnection(socketChannel, engine); log.debug("Goodbye client!"); return; default: throw new IllegalStateException("Invalid SSL status: " + result.getStatus()); } } write(socketChannel, engine, "Hello! I am your server!"); } else if (bytesRead < 0) { log.error("Received end of stream. Will try to close connection with client..."); handleEndOfStream(socketChannel, engine); log.debug("Goodbye client!"); } } /** * Will send a message back to a client. * * @param key - the key dedicated to the socket channel that will be used to write to the client. * @param message - the message to be sent. * @throws IOException if an I/O error occurs to the socket channel. */ @Override protected void write(SocketChannel socketChannel, SSLEngine engine, String message) throws IOException { log.debug("About to write to a client..."); myAppData.clear(); myAppData.put(message.getBytes()); myAppData.flip(); while (myAppData.hasRemaining()) { // The loop has a meaning for (outgoing) messages larger than 16KB. // Every wrap call will remove 16KB from the original message and send it to the remote peer. myNetData.clear(); SSLEngineResult result = engine.wrap(myAppData, myNetData); switch (result.getStatus()) { case OK: myNetData.flip(); while (myNetData.hasRemaining()) { socketChannel.write(myNetData); } log.debug("Message sent to the client: " + message); break; case BUFFER_OVERFLOW: myNetData = enlargePacketBuffer(engine, myNetData); break; case BUFFER_UNDERFLOW: throw new SSLException("Buffer underflow occured after a wrap. I don't think we should ever get here."); case CLOSED: closeConnection(socketChannel, engine); return; default: throw new IllegalStateException("Invalid SSL status: " + result.getStatus()); } } } /** * Determines if the the server is active or not. * * @return if the server is active or not. */ private boolean isActive() { return active; } }
java
MIT
13a9e6cb04713213a8ac3fc7ced06e5ef8cdf720
2026-01-05T02:42:05.260857Z
false
alkarn/sslengine.example
https://github.com/alkarn/sslengine.example/blob/13a9e6cb04713213a8ac3fc7ced06e5ef8cdf720/src/main/java/alkarn/github/io/sslengine/example/NioSslPeer.java
src/main/java/alkarn/github/io/sslengine/example/NioSslPeer.java
package alkarn.github.io.sslengine.example; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.nio.BufferOverflowException; import java.nio.ByteBuffer; import java.nio.channels.SocketChannel; import java.security.KeyStore; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import javax.net.ssl.KeyManager; import javax.net.ssl.KeyManagerFactory; import javax.net.ssl.SSLContext; import javax.net.ssl.SSLEngine; import javax.net.ssl.SSLEngineResult; import javax.net.ssl.SSLEngineResult.HandshakeStatus; import javax.net.ssl.SSLException; import javax.net.ssl.SSLSession; import javax.net.ssl.TrustManager; import javax.net.ssl.TrustManagerFactory; import org.apache.log4j.Logger; /** * A class that represents an SSL/TLS peer, and can be extended to create a client or a server. * <p/> * It makes use of the JSSE framework, and specifically the {@link SSLEngine} logic, which * is described by Oracle as "an advanced API, not appropriate for casual use", since * it requires the user to implement much of the communication establishment procedure himself. * More information about it can be found here: http://docs.oracle.com/javase/8/docs/technotes/guides/security/jsse/JSSERefGuide.html#SSLEngine * <p/> * {@link NioSslPeer} implements the handshake protocol, required to establish a connection between two peers, * which is common for both client and server and provides the abstract {@link NioSslPeer#read(SocketChannel, SSLEngine)} and * {@link NioSslPeer#write(SocketChannel, SSLEngine, String)} methods, that need to be implemented by the specific SSL/TLS peer * that is going to extend this class. * * @author <a href="mailto:alex.a.karnezis@gmail.com">Alex Karnezis</a> */ public abstract class NioSslPeer { /** * Class' logger. */ protected final Logger log = Logger.getLogger(getClass()); /** * Will contain this peer's application data in plaintext, that will be later encrypted * using {@link SSLEngine#wrap(ByteBuffer, ByteBuffer)} and sent to the other peer. This buffer can typically * be of any size, as long as it is large enough to contain this peer's outgoing messages. * If this peer tries to send a message bigger than buffer's capacity a {@link BufferOverflowException} * will be thrown. */ protected ByteBuffer myAppData; /** * Will contain this peer's encrypted data, that will be generated after {@link SSLEngine#wrap(ByteBuffer, ByteBuffer)} * is applied on {@link NioSslPeer#myAppData}. It should be initialized using {@link SSLSession#getPacketBufferSize()}, * which returns the size up to which, SSL/TLS packets will be generated from the engine under a session. * All SSLEngine network buffers should be sized at least this large to avoid insufficient space problems when performing wrap and unwrap calls. */ protected ByteBuffer myNetData; /** * Will contain the other peer's (decrypted) application data. It must be large enough to hold the application data * from any peer. Can be initialized with {@link SSLSession#getApplicationBufferSize()} for an estimation * of the other peer's application data and should be enlarged if this size is not enough. */ protected ByteBuffer peerAppData; /** * Will contain the other peer's encrypted data. The SSL/TLS protocols specify that implementations should produce packets containing at most 16 KB of plaintext, * so a buffer sized to this value should normally cause no capacity problems. However, some implementations violate the specification and generate large records up to 32 KB. * If the {@link SSLEngine#unwrap(ByteBuffer, ByteBuffer)} detects large inbound packets, the buffer sizes returned by SSLSession will be updated dynamically, so the this peer * should check for overflow conditions and enlarge the buffer using the session's (updated) buffer size. */ protected ByteBuffer peerNetData; /** * Will be used to execute tasks that may emerge during handshake in parallel with the server's main thread. */ protected ExecutorService executor = Executors.newSingleThreadExecutor(); protected abstract void read(SocketChannel socketChannel, SSLEngine engine) throws Exception; protected abstract void write(SocketChannel socketChannel, SSLEngine engine, String message) throws Exception; /** * Implements the handshake protocol between two peers, required for the establishment of the SSL/TLS connection. * During the handshake, encryption configuration information - such as the list of available cipher suites - will be exchanged * and if the handshake is successful will lead to an established SSL/TLS session. * * <p/> * A typical handshake will usually contain the following steps: * * <ul> * <li>1. wrap: ClientHello</li> * <li>2. unwrap: ServerHello/Cert/ServerHelloDone</li> * <li>3. wrap: ClientKeyExchange</li> * <li>4. wrap: ChangeCipherSpec</li> * <li>5. wrap: Finished</li> * <li>6. unwrap: ChangeCipherSpec</li> * <li>7. unwrap: Finished</li> * </ul> * <p/> * Handshake is also used during the end of the session, in order to properly close the connection between the two peers. * A proper connection close will typically include the one peer sending a CLOSE message to another, and then wait for * the other's CLOSE message to close the transport link. The other peer from his perspective would read a CLOSE message * from his peer and then enter the handshake procedure to send his own CLOSE message as well. * * @param socketChannel - the socket channel that connects the two peers. * @param engine - the engine that will be used for encryption/decryption of the data exchanged with the other peer. * @return True if the connection handshake was successful or false if an error occurred. * @throws IOException - if an error occurs during read/write to the socket channel. */ protected boolean doHandshake(SocketChannel socketChannel, SSLEngine engine) throws IOException { log.debug("About to do handshake..."); SSLEngineResult result; HandshakeStatus handshakeStatus; // NioSslPeer's fields myAppData and peerAppData are supposed to be large enough to hold all message data the peer // will send and expects to receive from the other peer respectively. Since the messages to be exchanged will usually be less // than 16KB long the capacity of these fields should also be smaller. Here we initialize these two local buffers // to be used for the handshake, while keeping client's buffers at the same size. int appBufferSize = engine.getSession().getApplicationBufferSize(); ByteBuffer myAppData = ByteBuffer.allocate(appBufferSize); ByteBuffer peerAppData = ByteBuffer.allocate(appBufferSize); myNetData.clear(); peerNetData.clear(); handshakeStatus = engine.getHandshakeStatus(); while (handshakeStatus != SSLEngineResult.HandshakeStatus.FINISHED && handshakeStatus != SSLEngineResult.HandshakeStatus.NOT_HANDSHAKING) { switch (handshakeStatus) { case NEED_UNWRAP: if (socketChannel.read(peerNetData) < 0) { if (engine.isInboundDone() && engine.isOutboundDone()) { return false; } try { engine.closeInbound(); } catch (SSLException e) { log.error("This engine was forced to close inbound, without having received the proper SSL/TLS close notification message from the peer, due to end of stream."); } engine.closeOutbound(); // After closeOutbound the engine will be set to WRAP state, in order to try to send a close message to the client. handshakeStatus = engine.getHandshakeStatus(); break; } peerNetData.flip(); try { result = engine.unwrap(peerNetData, peerAppData); peerNetData.compact(); handshakeStatus = result.getHandshakeStatus(); } catch (SSLException sslException) { log.error("A problem was encountered while processing the data that caused the SSLEngine to abort. Will try to properly close connection..."); engine.closeOutbound(); handshakeStatus = engine.getHandshakeStatus(); break; } switch (result.getStatus()) { case OK: break; case BUFFER_OVERFLOW: // Will occur when peerAppData's capacity is smaller than the data derived from peerNetData's unwrap. peerAppData = enlargeApplicationBuffer(engine, peerAppData); break; case BUFFER_UNDERFLOW: // Will occur either when no data was read from the peer or when the peerNetData buffer was too small to hold all peer's data. peerNetData = handleBufferUnderflow(engine, peerNetData); break; case CLOSED: if (engine.isOutboundDone()) { return false; } else { engine.closeOutbound(); handshakeStatus = engine.getHandshakeStatus(); break; } default: throw new IllegalStateException("Invalid SSL status: " + result.getStatus()); } break; case NEED_WRAP: myNetData.clear(); try { result = engine.wrap(myAppData, myNetData); handshakeStatus = result.getHandshakeStatus(); } catch (SSLException sslException) { log.error("A problem was encountered while processing the data that caused the SSLEngine to abort. Will try to properly close connection..."); engine.closeOutbound(); handshakeStatus = engine.getHandshakeStatus(); break; } switch (result.getStatus()) { case OK : myNetData.flip(); while (myNetData.hasRemaining()) { socketChannel.write(myNetData); } break; case BUFFER_OVERFLOW: // Will occur if there is not enough space in myNetData buffer to write all the data that would be generated by the method wrap. // Since myNetData is set to session's packet size we should not get to this point because SSLEngine is supposed // to produce messages smaller or equal to that, but a general handling would be the following: myNetData = enlargePacketBuffer(engine, myNetData); break; case BUFFER_UNDERFLOW: throw new SSLException("Buffer underflow occured after a wrap. I don't think we should ever get here."); case CLOSED: try { myNetData.flip(); while (myNetData.hasRemaining()) { socketChannel.write(myNetData); } // At this point the handshake status will probably be NEED_UNWRAP so we make sure that peerNetData is clear to read. peerNetData.clear(); } catch (Exception e) { log.error("Failed to send server's CLOSE message due to socket channel's failure."); handshakeStatus = engine.getHandshakeStatus(); } break; default: throw new IllegalStateException("Invalid SSL status: " + result.getStatus()); } break; case NEED_TASK: Runnable task; while ((task = engine.getDelegatedTask()) != null) { executor.execute(task); } handshakeStatus = engine.getHandshakeStatus(); break; case FINISHED: break; case NOT_HANDSHAKING: break; default: throw new IllegalStateException("Invalid SSL status: " + handshakeStatus); } } return true; } protected ByteBuffer enlargePacketBuffer(SSLEngine engine, ByteBuffer buffer) { return enlargeBuffer(buffer, engine.getSession().getPacketBufferSize()); } protected ByteBuffer enlargeApplicationBuffer(SSLEngine engine, ByteBuffer buffer) { return enlargeBuffer(buffer, engine.getSession().getApplicationBufferSize()); } /** * Compares <code>sessionProposedCapacity<code> with buffer's capacity. If buffer's capacity is smaller, * returns a buffer with the proposed capacity. If it's equal or larger, returns a buffer * with capacity twice the size of the initial one. * * @param buffer - the buffer to be enlarged. * @param sessionProposedCapacity - the minimum size of the new buffer, proposed by {@link SSLSession}. * @return A new buffer with a larger capacity. */ protected ByteBuffer enlargeBuffer(ByteBuffer buffer, int sessionProposedCapacity) { if (sessionProposedCapacity > buffer.capacity()) { buffer = ByteBuffer.allocate(sessionProposedCapacity); } else { buffer = ByteBuffer.allocate(buffer.capacity() * 2); } return buffer; } /** * Handles {@link SSLEngineResult.Status#BUFFER_UNDERFLOW}. Will check if the buffer is already filled, and if there is no space problem * will return the same buffer, so the client tries to read again. If the buffer is already filled will try to enlarge the buffer either to * session's proposed size or to a larger capacity. A buffer underflow can happen only after an unwrap, so the buffer will always be a * peerNetData buffer. * * @param buffer - will always be peerNetData buffer. * @param engine - the engine used for encryption/decryption of the data exchanged between the two peers. * @return The same buffer if there is no space problem or a new buffer with the same data but more space. * @throws Exception */ protected ByteBuffer handleBufferUnderflow(SSLEngine engine, ByteBuffer buffer) { if (engine.getSession().getPacketBufferSize() < buffer.limit()) { return buffer; } else { ByteBuffer replaceBuffer = enlargePacketBuffer(engine, buffer); buffer.flip(); replaceBuffer.put(buffer); return replaceBuffer; } } /** * This method should be called when this peer wants to explicitly close the connection * or when a close message has arrived from the other peer, in order to provide an orderly shutdown. * <p/> * It first calls {@link SSLEngine#closeOutbound()} which prepares this peer to send its own close message and * sets {@link SSLEngine} to the <code>NEED_WRAP</code> state. Then, it delegates the exchange of close messages * to the handshake method and finally, it closes socket channel. * * @param socketChannel - the transport link used between the two peers. * @param engine - the engine used for encryption/decryption of the data exchanged between the two peers. * @throws IOException if an I/O error occurs to the socket channel. */ protected void closeConnection(SocketChannel socketChannel, SSLEngine engine) throws IOException { engine.closeOutbound(); doHandshake(socketChannel, engine); socketChannel.close(); } /** * In addition to orderly shutdowns, an unorderly shutdown may occur, when the transport link (socket channel) * is severed before close messages are exchanged. This may happen by getting an -1 or {@link IOException} * when trying to read from the socket channel, or an {@link IOException} when trying to write to it. * In both cases {@link SSLEngine#closeInbound()} should be called and then try to follow the standard procedure. * * @param socketChannel - the transport link used between the two peers. * @param engine - the engine used for encryption/decryption of the data exchanged between the two peers. * @throws IOException if an I/O error occurs to the socket channel. */ protected void handleEndOfStream(SocketChannel socketChannel, SSLEngine engine) throws IOException { try { engine.closeInbound(); } catch (Exception e) { log.error("This engine was forced to close inbound, without having received the proper SSL/TLS close notification message from the peer, due to end of stream."); } closeConnection(socketChannel, engine); } /** * Creates the key managers required to initiate the {@link SSLContext}, using a JKS keystore as an input. * * @param filepath - the path to the JKS keystore. * @param keystorePassword - the keystore's password. * @param keyPassword - the key's passsword. * @return {@link KeyManager} array that will be used to initiate the {@link SSLContext}. * @throws Exception */ protected KeyManager[] createKeyManagers(String filepath, String keystorePassword, String keyPassword) throws Exception { KeyStore keyStore = KeyStore.getInstance("JKS"); InputStream keyStoreIS = new FileInputStream(filepath); try { keyStore.load(keyStoreIS, keystorePassword.toCharArray()); } finally { if (keyStoreIS != null) { keyStoreIS.close(); } } KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm()); kmf.init(keyStore, keyPassword.toCharArray()); return kmf.getKeyManagers(); } /** * Creates the trust managers required to initiate the {@link SSLContext}, using a JKS keystore as an input. * * @param filepath - the path to the JKS keystore. * @param keystorePassword - the keystore's password. * @return {@link TrustManager} array, that will be used to initiate the {@link SSLContext}. * @throws Exception */ protected TrustManager[] createTrustManagers(String filepath, String keystorePassword) throws Exception { KeyStore trustStore = KeyStore.getInstance("JKS"); InputStream trustStoreIS = new FileInputStream(filepath); try { trustStore.load(trustStoreIS, keystorePassword.toCharArray()); } finally { if (trustStoreIS != null) { trustStoreIS.close(); } } TrustManagerFactory trustFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm()); trustFactory.init(trustStore); return trustFactory.getTrustManagers(); } }
java
MIT
13a9e6cb04713213a8ac3fc7ced06e5ef8cdf720
2026-01-05T02:42:05.260857Z
false
Despector/Despector
https://github.com/Despector/Despector/blob/e60cfaaf7a0688bc83f8b00c392521d0b162afba/src/test/java/org/spongepowered/test/util/AstAsserts.java
src/test/java/org/spongepowered/test/util/AstAsserts.java
/* * The MIT License (MIT) * * Copyright (c) Despector <https://despector.voxelgenesis.com> * Copyright (c) contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package org.spongepowered.test.util; import org.junit.Assert; import org.spongepowered.despector.ast.Annotation; import org.spongepowered.despector.ast.stmt.StatementBlock; import org.spongepowered.despector.ast.type.FieldEntry; import org.spongepowered.despector.ast.type.MethodEntry; import org.spongepowered.despector.ast.type.TypeEntry; import org.spongepowered.despector.ast.type.TypeEntry.InnerClassInfo; public class AstAsserts { public static void assertEquals(TypeEntry a, TypeEntry b) { Assert.assertEquals(a.getLanguage(), b.getLanguage()); Assert.assertEquals(a.getAccessModifier(), b.getAccessModifier()); Assert.assertEquals(a.isSynthetic(), b.isSynthetic()); Assert.assertEquals(a.isFinal(), b.isFinal()); Assert.assertEquals(a.isAbstract(), b.isAbstract()); Assert.assertEquals(a.isDeprecated(), b.isDeprecated()); Assert.assertEquals(a.getName(), b.getName()); Assert.assertEquals(a.getInterfaces().size(), b.getInterfaces().size()); for (String i : a.getInterfaces()) { if (!b.getInterfaces().contains(i)) { Assert.fail(); } } for (FieldEntry fld : a.getFields()) { FieldEntry other = b.getField(fld.getName()); if (other == null) { Assert.fail(); } assertEquals(fld, other); } for (FieldEntry fld : a.getStaticFields()) { FieldEntry other = b.getStaticField(fld.getName()); if (other == null) { Assert.fail(); } assertEquals(fld, other); } for (MethodEntry fld : a.getStaticMethods()) { MethodEntry other = b.getMethod(fld.getName()); if (other == null) { Assert.fail(); } assertEquals(fld, other); } for (MethodEntry fld : a.getMethods()) { MethodEntry other = b.getMethod(fld.getName()); if (other == null) { Assert.fail(); } assertEquals(fld, other); } Assert.assertEquals(a.getSignature(), b.getSignature()); for (Annotation anno : a.getAnnotations()) { Annotation other = b.getAnnotation(anno.getType()); if (other == null) { Assert.fail(); } assertEquals(anno, other); } for (InnerClassInfo inner : a.getInnerClasses()) { InnerClassInfo other = b.getInnerClassInfo(inner.getName()); if (other == null) { Assert.fail(); } Assert.assertEquals(inner, other); } } public static void assertEquals(FieldEntry a, FieldEntry b) { Assert.assertEquals(a.getAccessModifier(), b.getAccessModifier()); Assert.assertEquals(a.getOwnerName(), b.getOwnerName()); Assert.assertEquals(a.getType(), b.getType()); Assert.assertEquals(a.getName(), b.getName()); Assert.assertEquals(a.isFinal(), b.isFinal()); Assert.assertEquals(a.isStatic(), b.isStatic()); Assert.assertEquals(a.isSynthetic(), b.isSynthetic()); Assert.assertEquals(a.isVolatile(), b.isVolatile()); Assert.assertEquals(a.isTransient(), b.isTransient()); Assert.assertEquals(a.isDeprecated(), b.isDeprecated()); for (Annotation anno : a.getAnnotations()) { Annotation other = b.getAnnotation(anno.getType()); if (other == null) { Assert.fail(); } assertEquals(anno, other); } } public static void assertEquals(MethodEntry a, MethodEntry b) { Assert.assertEquals(a.getAccessModifier(), b.getAccessModifier()); Assert.assertEquals(a.getOwnerName(), b.getOwnerName()); Assert.assertEquals(a.getName(), b.getName()); Assert.assertEquals(a.getDescription(), b.getDescription()); Assert.assertEquals(a.isAbstract(), b.isAbstract()); Assert.assertEquals(a.isFinal(), b.isFinal()); Assert.assertEquals(a.isStatic(), b.isStatic()); Assert.assertEquals(a.isSynthetic(), b.isSynthetic()); Assert.assertEquals(a.isBridge(), b.isBridge()); Assert.assertEquals(a.isSynchronized(), b.isSynchronized()); Assert.assertEquals(a.isNative(), b.isNative()); Assert.assertEquals(a.isVarargs(), b.isVarargs()); Assert.assertEquals(a.isStrictFp(), b.isStrictFp()); Assert.assertEquals(a.isDeprecated(), b.isDeprecated()); Assert.assertEquals(a.getMethodSignature(), b.getMethodSignature()); Assert.assertEquals(a.getAnnotationValue(), b.getAnnotationValue()); assertEquals(a.getInstructions(), b.getInstructions()); for (Annotation anno : a.getAnnotations()) { Annotation other = b.getAnnotation(anno.getType()); if (other == null) { Assert.fail(); } assertEquals(anno, other); } } public static void assertEquals(Annotation a, Annotation b) { Assert.assertEquals(a.getType(), b.getType()); Assert.assertEquals(a.getValues(), b.getValues()); } public static void assertEquals(StatementBlock a, StatementBlock b) { if (a.getStatementCount() != b.getStatementCount()) { Assert.fail(); } for (int i = 0; i < a.getStatementCount(); i++) { Assert.assertEquals(a.getStatement(i), b.getStatement(i)); } } }
java
MIT
e60cfaaf7a0688bc83f8b00c392521d0b162afba
2026-01-05T02:42:07.381192Z
false
Despector/Despector
https://github.com/Despector/Despector/blob/e60cfaaf7a0688bc83f8b00c392521d0b162afba/src/test/java/org/spongepowered/test/util/TestHelper.java
src/test/java/org/spongepowered/test/util/TestHelper.java
/* * The MIT License (MIT) * * Copyright (c) Despector <https://despector.voxelgenesis.com> * Copyright (c) contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package org.spongepowered.test.util; import com.google.common.collect.Maps; import org.junit.Assert; import org.spongepowered.despector.ast.SourceSet; import org.spongepowered.despector.ast.type.MethodEntry; import org.spongepowered.despector.ast.type.TypeEntry; import org.spongepowered.despector.decompiler.Decompilers; import org.spongepowered.despector.emitter.Emitters; import org.spongepowered.despector.emitter.format.EmitterFormat; import org.spongepowered.despector.emitter.java.JavaEmitterContext; import java.io.ByteArrayInputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.io.StringWriter; import java.util.Map; public class TestHelper { public static final boolean IS_ECLIPSE = Boolean.valueOf(System.getProperty("despector.eclipse", "false")); private static final Map<Class<?>, TypeEntry> CACHED_TYPES = Maps.newHashMap(); private static final SourceSet DUMMY_SOURCE_SET = new SourceSet(); static { DUMMY_SOURCE_SET.setLoader(new TestLoader(TestHelper.class.getProtectionDomain().getCodeSource().getLocation().getPath())); } private static class TestLoader implements SourceSet.Loader { private final String path; public TestLoader(String path) { this.path = path; } @Override public InputStream find(String name) { File file = new File(this.path, name + ".class"); if (!file.exists()) { return null; } try { return new FileInputStream(file); } catch (FileNotFoundException e) { e.printStackTrace(); } return null; } } public static TypeEntry get(Class<?> cls) { TypeEntry type = CACHED_TYPES.get(cls); if (type != null) { return type; } String path = cls.getProtectionDomain().getCodeSource().getLocation().getPath(); File file = new File(path, cls.getName().replace('.', '/') + ".class"); try { type = Decompilers.WILD.decompile(file, DUMMY_SOURCE_SET); Decompilers.WILD.flushTasks(); } catch (IOException e) { e.printStackTrace(); } CACHED_TYPES.put(cls, type); return type; } public static String getAsString(byte[] data, String method_name) { TypeEntry type = null; try { type = Decompilers.WILD.decompile(new ByteArrayInputStream(data), DUMMY_SOURCE_SET); Decompilers.WILD.flushTasks(); } catch (IOException e) { e.printStackTrace(); } MethodEntry method = type.getStaticMethod(method_name); return getAsString(type, method); } public static String getAsString(TypeEntry type, MethodEntry method) { StringWriter writer = new StringWriter(); JavaEmitterContext emitter = new JavaEmitterContext(writer, EmitterFormat.defaults()); emitter.setEmitterSet(Emitters.JAVA_SET); emitter.setMethod(method); emitter.setType(type); emitter.emitBody(method.getInstructions()); emitter.flush(); return writer.toString(); } public static String getAsString(Class<?> cls, String method_name) { TypeEntry type = get(cls); MethodEntry method = type.getMethod(method_name); return getAsString(type, method); } public static void check(Class<?> cls, String method_name, String expected) { TypeEntry type = get(cls); MethodEntry method = type.getMethod(method_name); String actual = getAsString(type, method); if (!actual.equals(expected)) { System.err.println("Test " + method_name + " failed!"); System.err.println("Expected:"); System.err.println(expected); System.err.println("Found:"); System.err.println(actual); Assert.assertEquals(expected, actual); } } }
java
MIT
e60cfaaf7a0688bc83f8b00c392521d0b162afba
2026-01-05T02:42:07.381192Z
false
Despector/Despector
https://github.com/Despector/Despector/blob/e60cfaaf7a0688bc83f8b00c392521d0b162afba/src/test/java/org/spongepowered/test/util/TestMethodBuilder.java
src/test/java/org/spongepowered/test/util/TestMethodBuilder.java
/* * The MIT License (MIT) * * Copyright (c) Despector <https://despector.voxelgenesis.com> * Copyright (c) contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package org.spongepowered.test.util; import static org.objectweb.asm.Opcodes.*; import org.objectweb.asm.ClassWriter; import org.objectweb.asm.Label; import org.objectweb.asm.MethodVisitor; import org.objectweb.asm.Type; public class TestMethodBuilder { private Type type; private ClassWriter cw; private MethodVisitor generator; public TestMethodBuilder(String name, String sig) { this.cw = new ClassWriter(ClassWriter.COMPUTE_MAXS | ClassWriter.COMPUTE_FRAMES); this.cw.visit(V1_8, ACC_PUBLIC | ACC_SUPER, name + "_Class", null, "java/lang/Object", null); String desc = "L" + name + "_Class;"; this.type = Type.getType(desc); { MethodVisitor mv = this.cw.visitMethod(ACC_PUBLIC, "<init>", "()V", null, null); mv.visitCode(); Label l0 = new Label(); mv.visitLabel(l0); mv.visitVarInsn(ALOAD, 0); mv.visitMethodInsn(INVOKESPECIAL, "java/lang/Object", "<init>", "()V", false); mv.visitInsn(RETURN); Label l1 = new Label(); mv.visitLabel(l1); mv.visitLocalVariable("this", desc, null, l0, l1, 0); mv.visitMaxs(0, 0); mv.visitEnd(); } { MethodVisitor mv = this.cw.visitMethod(ACC_PUBLIC | ACC_STATIC, name, sig, null, null); mv.visitCode(); this.generator = mv; } } public Type getType() { return this.type; } public MethodVisitor getGenerator() { return this.generator; } public byte[] finish() { this.generator.visitMaxs(0, 0); this.generator.visitEnd(); this.cw.visitEnd(); return this.cw.toByteArray(); } }
java
MIT
e60cfaaf7a0688bc83f8b00c392521d0b162afba
2026-01-05T02:42:07.381192Z
false
Despector/Despector
https://github.com/Despector/Despector/blob/e60cfaaf7a0688bc83f8b00c392521d0b162afba/src/test/java/org/spongepowered/test/util/KotlinTestHelper.java
src/test/java/org/spongepowered/test/util/KotlinTestHelper.java
/* * The MIT License (MIT) * * Copyright (c) Despector <https://despector.voxelgenesis.com> * Copyright (c) contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package org.spongepowered.test.util; import org.spongepowered.despector.ast.SourceSet; import org.spongepowered.despector.ast.type.MethodEntry; import org.spongepowered.despector.ast.type.TypeEntry; import org.spongepowered.despector.config.LibraryConfiguration; import org.spongepowered.despector.decompiler.Decompilers; import org.spongepowered.despector.emitter.Emitters; import org.spongepowered.despector.emitter.format.EmitterFormat; import org.spongepowered.despector.emitter.java.JavaEmitterContext; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.StringWriter; public class KotlinTestHelper { private static final SourceSet DUMMY_SOURCE_SET = new SourceSet(); public static String getMethodAsString(byte[] data, String method_name) { LibraryConfiguration.quiet = false; LibraryConfiguration.parallel = false; LibraryConfiguration.force_lang = true; TypeEntry type = null; try { type = Decompilers.KOTLIN.decompile(new ByteArrayInputStream(data), DUMMY_SOURCE_SET); } catch (IOException e) { e.printStackTrace(); } MethodEntry method = type.getStaticMethod(method_name); return getMethodAsString(type, method); } public static String getMethodAsString(TypeEntry type, MethodEntry method) { StringWriter writer = new StringWriter(); JavaEmitterContext emitter = new JavaEmitterContext(writer, EmitterFormat.defaults()); Emitters.KOTLIN.setup(emitter); emitter.setType(type); emitter.emit(method); emitter.flush(); return writer.toString(); } }
java
MIT
e60cfaaf7a0688bc83f8b00c392521d0b162afba
2026-01-05T02:42:07.381192Z
false
Despector/Despector
https://github.com/Despector/Despector/blob/e60cfaaf7a0688bc83f8b00c392521d0b162afba/src/test/java/org/spongepowered/test/generate/TestGenerator.java
src/test/java/org/spongepowered/test/generate/TestGenerator.java
/* * The MIT License (MIT) * * Copyright (c) Despector <https://despector.voxelgenesis.com> * Copyright (c) contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package org.spongepowered.test.generate; import com.google.common.io.Files; import java.io.File; import java.io.IOException; public class TestGenerator { public static void main(String[] args) { File tests_dir = new File("src/test/java/org/spongepowered/test/generate"); if (!tests_dir.exists() || !tests_dir.isDirectory()) { System.err.println("Tests directory " + tests_dir.getAbsolutePath() + " does not exist or is not a directory."); return; } File tests_bin_dir = new File("build/classes/java/test/org/spongepowered/test/generate"); if (!tests_bin_dir.exists() || !tests_bin_dir.isDirectory()) { System.err.println("Tests directory " + tests_dir.getAbsolutePath() + " does not exist or is not a directory. (have you run `./gradlew build` yet?)"); return; } File tests_out_dir = new File("src/test/resources/javaclasses"); if (!tests_out_dir.exists()) { tests_out_dir.mkdirs(); } for (File f : tests_dir.listFiles()) { if (f.getName().equals("TestGenerator.java")) { continue; } if (!f.getName().endsWith(".java")) { continue; } String name = f.getName().substring(0, f.getName().length() - 5); File compiled = new File(tests_bin_dir, name + ".class"); if (!compiled.exists()) { System.err.println("Test file " + name + " does not exist in the compiled output. (have you run `./gradlew build` yet?)"); continue; } System.out.println("Adding test for " + name); try { Files.copy(f, new File(tests_out_dir, name + ".java.test")); Files.copy(compiled, new File(tests_out_dir, name + ".class.test")); f.delete(); } catch (IOException e) { e.printStackTrace(); } } } }
java
MIT
e60cfaaf7a0688bc83f8b00c392521d0b162afba
2026-01-05T02:42:07.381192Z
false
Despector/Despector
https://github.com/Despector/Despector/blob/e60cfaaf7a0688bc83f8b00c392521d0b162afba/src/test/java/org/spongepowered/test/builder/BuilderTest.java
src/test/java/org/spongepowered/test/builder/BuilderTest.java
/* * The MIT License (MIT) * * Copyright (c) Despector <https://despector.voxelgenesis.com> * Copyright (c) contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package org.spongepowered.test.builder; import static org.spongepowered.despector.transform.builder.Builders.createClass; import static org.spongepowered.despector.transform.builder.Builders.integer; import static org.spongepowered.despector.transform.builder.Builders.localAssign; import static org.spongepowered.despector.transform.builder.Builders.returnVoid; import org.junit.Test; import org.spongepowered.despector.ast.AccessModifier; import org.spongepowered.despector.ast.Locals.LocalInstance; import org.spongepowered.despector.ast.SourceSet; import org.spongepowered.despector.ast.generic.ClassTypeSignature; import org.spongepowered.despector.ast.type.ClassEntry; import org.spongepowered.despector.emitter.Emitters; import org.spongepowered.despector.emitter.bytecode.BytecodeEmitterContext; import org.spongepowered.despector.transform.builder.ClassTypeBuilder; import org.spongepowered.despector.transform.builder.MethodBuilder; import org.spongepowered.test.util.TestHelper; import java.io.ByteArrayOutputStream; public class BuilderTest { @Test public void testSimple() { SourceSet set = new SourceSet(); ClassTypeBuilder builder = createClass("test/TestType").access(AccessModifier.PUBLIC); MethodBuilder mth = builder.method().name("test_mth").desc("()V").setStatic(true); LocalInstance i = mth.createLocal("i", ClassTypeSignature.INT); mth.statement(localAssign(i, integer(65))) .statement(returnVoid()) .build(set); ClassEntry entry = builder.build(set); ByteArrayOutputStream out = new ByteArrayOutputStream(); BytecodeEmitterContext ctx = new BytecodeEmitterContext(out); Emitters.BYTECODE.emit(ctx, entry); String actual = TestHelper.getAsString(out.toByteArray(), "test_mth"); System.out.print(actual); } }
java
MIT
e60cfaaf7a0688bc83f8b00c392521d0b162afba
2026-01-05T02:42:07.381192Z
false
Despector/Despector
https://github.com/Despector/Despector/blob/e60cfaaf7a0688bc83f8b00c392521d0b162afba/src/test/java/org/spongepowered/test/kotlin/StringTests.java
src/test/java/org/spongepowered/test/kotlin/StringTests.java
/* * The MIT License (MIT) * * Copyright (c) Despector <https://despector.voxelgenesis.com> * Copyright (c) contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package org.spongepowered.test.kotlin; import static org.objectweb.asm.Opcodes.*; import org.junit.Assert; import org.junit.Test; import org.objectweb.asm.Label; import org.objectweb.asm.MethodVisitor; import org.spongepowered.test.util.KotlinTestHelper; import org.spongepowered.test.util.TestMethodBuilder; public class StringTests { @Test public void testSimpleStringTemplate() { TestMethodBuilder builder = new TestMethodBuilder("main", "()V"); MethodVisitor mv = builder.getGenerator(); Label start = new Label(); mv.visitLabel(start); Label end = new Label(); mv.visitInsn(ICONST_5); mv.visitVarInsn(ISTORE, 1); mv.visitTypeInsn(NEW, "java/lang/StringBuilder"); mv.visitInsn(DUP); mv.visitMethodInsn(INVOKESPECIAL, "java/lang/StringBuilder", "<init>", "()V", false); mv.visitLdcInsn("a is "); mv.visitMethodInsn(INVOKEVIRTUAL, "java/lang/StringBuilder", "append", "(Ljava/lang/String;)Ljava/lang/StringBuilder;", false); mv.visitVarInsn(ILOAD, 1); mv.visitMethodInsn(INVOKEVIRTUAL, "java/lang/StringBuilder", "append", "(I)Ljava/lang/StringBuilder;", false); mv.visitMethodInsn(INVOKEVIRTUAL, "java/lang/StringBuilder", "toString", "()Ljava/lang/String;", false); mv.visitVarInsn(ASTORE, 2); mv.visitLabel(end); mv.visitInsn(RETURN); mv.visitLocalVariable("a", "I", null, start, end, 1); mv.visitLocalVariable("s", "Ljava/lang/String;", null, start, end, 2); String insn = KotlinTestHelper.getMethodAsString(builder.finish(), "main"); String good = "fun main() {\n" + " val a: Int = 5\n" + " val s: String = \"a is $a\"\n" + "}"; Assert.assertEquals(good, insn); } }
java
MIT
e60cfaaf7a0688bc83f8b00c392521d0b162afba
2026-01-05T02:42:07.381192Z
false
Despector/Despector
https://github.com/Despector/Despector/blob/e60cfaaf7a0688bc83f8b00c392521d0b162afba/src/test/java/org/spongepowered/test/kotlin/TernaryTests.java
src/test/java/org/spongepowered/test/kotlin/TernaryTests.java
/* * The MIT License (MIT) * * Copyright (c) Despector <https://despector.voxelgenesis.com> * Copyright (c) contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package org.spongepowered.test.kotlin; import static org.objectweb.asm.Opcodes.GOTO; import static org.objectweb.asm.Opcodes.IF_ICMPLE; import static org.objectweb.asm.Opcodes.ILOAD; import static org.objectweb.asm.Opcodes.IRETURN; import org.junit.Assert; import org.junit.Test; import org.objectweb.asm.Label; import org.objectweb.asm.MethodVisitor; import org.spongepowered.test.util.KotlinTestHelper; import org.spongepowered.test.util.TestMethodBuilder; public class TernaryTests { @Test public void testSimpleTernary() { TestMethodBuilder builder = new TestMethodBuilder("maxOf", "(II)I"); MethodVisitor mv = builder.getGenerator(); Label start = new Label(); Label l1 = new Label(); mv.visitLabel(start); Label end = new Label(); mv.visitVarInsn(ILOAD, 0); mv.visitVarInsn(ILOAD, 1); mv.visitJumpInsn(IF_ICMPLE, l1); mv.visitVarInsn(ILOAD, 0); mv.visitJumpInsn(GOTO, end); mv.visitLabel(l1); mv.visitVarInsn(ILOAD, 1); mv.visitLabel(end); mv.visitInsn(IRETURN); mv.visitLocalVariable("a", "I", null, start, end, 0); mv.visitLocalVariable("b", "I", null, start, end, 1); String insn = KotlinTestHelper.getMethodAsString(builder.finish(), "maxOf"); String good = "fun maxOf(a: Int, b: Int) = if (a > b) a else b"; Assert.assertEquals(good, insn); } }
java
MIT
e60cfaaf7a0688bc83f8b00c392521d0b162afba
2026-01-05T02:42:07.381192Z
false
Despector/Despector
https://github.com/Despector/Despector/blob/e60cfaaf7a0688bc83f8b00c392521d0b162afba/src/test/java/org/spongepowered/test/kotlin/RangeTests.java
src/test/java/org/spongepowered/test/kotlin/RangeTests.java
/* * The MIT License (MIT) * * Copyright (c) Despector <https://despector.voxelgenesis.com> * Copyright (c) contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package org.spongepowered.test.kotlin; import static org.objectweb.asm.Opcodes.*; import org.junit.Assert; import org.junit.Test; import org.objectweb.asm.Label; import org.objectweb.asm.MethodVisitor; import org.spongepowered.test.util.KotlinTestHelper; import org.spongepowered.test.util.TestMethodBuilder; public class RangeTests { //@Test public void testIfRange() { TestMethodBuilder builder = new TestMethodBuilder("decimalDigitValue", "(C)I"); MethodVisitor mv = builder.getGenerator(); Label start = new Label(); Label l1 = new Label(); Label l2 = new Label(); Label l3 = new Label(); mv.visitLabel(start); Label end = new Label(); mv.visitIntInsn(BIPUSH, 48); mv.visitVarInsn(ILOAD, 0); mv.visitVarInsn(ISTORE, 1); mv.visitVarInsn(ILOAD, 1); mv.visitJumpInsn(IF_ICMPGT, l1); mv.visitVarInsn(ILOAD, 1); mv.visitIntInsn(BIPUSH, 57); mv.visitJumpInsn(IF_ICMPGT, l1); mv.visitInsn(ICONST_0); mv.visitJumpInsn(GOTO, l2); mv.visitLabel(l1); mv.visitInsn(ICONST_1); mv.visitLabel(l2); mv.visitJumpInsn(IFEQ, l3); mv.visitTypeInsn(NEW, "java/lang/IllegalArgumentException"); mv.visitInsn(DUP); mv.visitLdcInsn("Out of range"); mv.visitMethodInsn(INVOKESPECIAL, "java/lang/IllegalArgumentException", "<init>", "(Ljava/lang/String;)V", false); mv.visitTypeInsn(CHECKCAST, "java/lang/Throwable"); mv.visitInsn(ATHROW); mv.visitLabel(l3); mv.visitVarInsn(ILOAD, 0); mv.visitIntInsn(BIPUSH, 48); mv.visitInsn(ISUB); mv.visitLabel(end); mv.visitInsn(IRETURN); mv.visitLocalVariable("c", "C", null, start, end, 0); String insn = KotlinTestHelper.getMethodAsString(builder.finish(), "decimalDigitValue"); String good = "fun decimalDigitValue(c: Char): Int {\n" + " if (param1 !in '0'..'9') {\n" + " throw IllegalArgumentException(\"Out of range\")\n" + " }\n\n" + " return c - 48\n" + "}"; Assert.assertEquals(good, insn); } }
java
MIT
e60cfaaf7a0688bc83f8b00c392521d0b162afba
2026-01-05T02:42:07.381192Z
false
Despector/Despector
https://github.com/Despector/Despector/blob/e60cfaaf7a0688bc83f8b00c392521d0b162afba/src/test/java/org/spongepowered/test/kotlin/BasicTests.java
src/test/java/org/spongepowered/test/kotlin/BasicTests.java
/* * The MIT License (MIT) * * Copyright (c) Despector <https://despector.voxelgenesis.com> * Copyright (c) contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package org.spongepowered.test.kotlin; import static org.objectweb.asm.Opcodes.*; import org.junit.Assert; import org.junit.Test; import org.objectweb.asm.Label; import org.objectweb.asm.MethodVisitor; import org.spongepowered.test.util.KotlinTestHelper; import org.spongepowered.test.util.TestMethodBuilder; public class BasicTests { @Test public void testSimple() { TestMethodBuilder builder = new TestMethodBuilder("sum", "(II)I"); MethodVisitor mv = builder.getGenerator(); Label start = new Label(); mv.visitLabel(start); Label end = new Label(); mv.visitVarInsn(ILOAD, 0); mv.visitVarInsn(ILOAD, 1); mv.visitInsn(IADD); mv.visitLabel(end); mv.visitInsn(IRETURN); mv.visitLocalVariable("a", "I", null, start, end, 0); mv.visitLocalVariable("b", "I", null, start, end, 1); String insn = KotlinTestHelper.getMethodAsString(builder.finish(), "sum"); String good = "fun sum(a: Int, b: Int) = a + b"; Assert.assertEquals(good, insn); } @Test public void testNoVoidReturnDeclared() { TestMethodBuilder builder = new TestMethodBuilder("main", "()V"); MethodVisitor mv = builder.getGenerator(); Label start = new Label(); mv.visitLabel(start); Label end = new Label(); mv.visitLdcInsn("Hello"); mv.visitVarInsn(ASTORE, 1); mv.visitFieldInsn(GETSTATIC, "java/lang/System", "out", "Ljava/io/PrintStream;"); mv.visitVarInsn(ALOAD, 1); mv.visitMethodInsn(INVOKEVIRTUAL, "java/io/PrintStream", "println", "(Ljava/lang/String;)V", true); mv.visitLabel(end); mv.visitInsn(RETURN); String insn = KotlinTestHelper.getMethodAsString(builder.finish(), "main"); String good = "fun main() {\n" + " val param1: String = \"Hello\"\n" + " println(param1)\n" + "}"; Assert.assertEquals(good, insn); } @Test public void testLocals() { TestMethodBuilder builder = new TestMethodBuilder("main", "()V"); MethodVisitor mv = builder.getGenerator(); Label start = new Label(); mv.visitLabel(start); Label end = new Label(); mv.visitLdcInsn("Hello"); mv.visitVarInsn(ASTORE, 0); Label start2 = new Label(); mv.visitLabel(start2); mv.visitInsn(ICONST_2); mv.visitVarInsn(ISTORE, 1); mv.visitIincInsn(1, 5); mv.visitFieldInsn(GETSTATIC, "java/lang/System", "out", "Ljava/io/PrintStream;"); mv.visitVarInsn(ALOAD, 0); mv.visitMethodInsn(INVOKEVIRTUAL, "java/io/PrintStream", "println", "(Ljava/lang/String;)V", true); mv.visitLabel(end); mv.visitInsn(RETURN); mv.visitLocalVariable("s", "Ljava/lang/String;", null, start, end, 0); mv.visitLocalVariable("a", "I", null, start2, end, 1); String insn = KotlinTestHelper.getMethodAsString(builder.finish(), "main"); String good = "fun main() {\n" + " val s: String = \"Hello\"\n" + " var a: Int = 2\n" + " a += 5\n" + " println(s)\n" + "}"; Assert.assertEquals(good, insn); } }
java
MIT
e60cfaaf7a0688bc83f8b00c392521d0b162afba
2026-01-05T02:42:07.381192Z
false
Despector/Despector
https://github.com/Despector/Despector/blob/e60cfaaf7a0688bc83f8b00c392521d0b162afba/src/test/java/org/spongepowered/test/kotlin/OperatorTests.java
src/test/java/org/spongepowered/test/kotlin/OperatorTests.java
/* * The MIT License (MIT) * * Copyright (c) Despector <https://despector.voxelgenesis.com> * Copyright (c) contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package org.spongepowered.test.kotlin; import static org.objectweb.asm.Opcodes.*; import org.junit.Assert; import org.junit.Test; import org.objectweb.asm.Label; import org.objectweb.asm.MethodVisitor; import org.spongepowered.test.util.KotlinTestHelper; import org.spongepowered.test.util.TestMethodBuilder; public class OperatorTests { @Test public void testIntConstant() { TestMethodBuilder builder = new TestMethodBuilder("test_mth", "(I)V"); MethodVisitor mv = builder.getGenerator(); Label start = new Label(); mv.visitLabel(start); Label end = new Label(); mv.visitIntInsn(BIPUSH, 65); mv.visitIntInsn(ISTORE, 0); mv.visitLabel(end); mv.visitInsn(RETURN); mv.visitLocalVariable("i", "I", null, start, end, 0); String insn = KotlinTestHelper.getMethodAsString(builder.finish(), "test_mth"); String good = "fun test_mth(i: Int) {\n" + " i = 65\n" + "}"; Assert.assertEquals(good, insn); } @Test public void testNegative() { TestMethodBuilder builder = new TestMethodBuilder("test_mth", "(II)V"); MethodVisitor mv = builder.getGenerator(); Label start = new Label(); mv.visitLabel(start); Label end = new Label(); mv.visitIntInsn(ILOAD, 1); mv.visitInsn(INEG); mv.visitIntInsn(ISTORE, 0); mv.visitLabel(end); mv.visitInsn(RETURN); mv.visitLocalVariable("i", "I", null, start, end, 0); mv.visitLocalVariable("a", "I", null, start, end, 1); String insn = KotlinTestHelper.getMethodAsString(builder.finish(), "test_mth"); String good = "fun test_mth(i: Int, a: Int) {\n" + " i = -a\n" + "}"; Assert.assertEquals(good, insn); } @Test public void testAdd() { TestMethodBuilder builder = new TestMethodBuilder("test_mth", "(III)V"); MethodVisitor mv = builder.getGenerator(); Label start = new Label(); mv.visitLabel(start); Label end = new Label(); mv.visitIntInsn(ILOAD, 1); mv.visitIntInsn(ILOAD, 2); mv.visitInsn(IADD); mv.visitIntInsn(ISTORE, 0); mv.visitLabel(end); mv.visitInsn(RETURN); mv.visitLocalVariable("i", "I", null, start, end, 0); mv.visitLocalVariable("a", "I", null, start, end, 1); mv.visitLocalVariable("b", "I", null, start, end, 2); String insn = KotlinTestHelper.getMethodAsString(builder.finish(), "test_mth"); String good = "fun test_mth(i: Int, a: Int, b: Int) {\n" + " i = a + b\n" + "}"; Assert.assertEquals(good, insn); } @Test public void testSub() { TestMethodBuilder builder = new TestMethodBuilder("test_mth", "(III)V"); MethodVisitor mv = builder.getGenerator(); Label start = new Label(); mv.visitLabel(start); Label end = new Label(); mv.visitIntInsn(ILOAD, 1); mv.visitIntInsn(ILOAD, 2); mv.visitInsn(ISUB); mv.visitIntInsn(ISTORE, 0); mv.visitLabel(end); mv.visitInsn(RETURN); mv.visitLocalVariable("i", "I", null, start, end, 0); mv.visitLocalVariable("a", "I", null, start, end, 1); mv.visitLocalVariable("b", "I", null, start, end, 2); String insn = KotlinTestHelper.getMethodAsString(builder.finish(), "test_mth"); String good = "fun test_mth(i: Int, a: Int, b: Int) {\n" + " i = a - b\n" + "}"; Assert.assertEquals(good, insn); } @Test public void testMultiply() { TestMethodBuilder builder = new TestMethodBuilder("test_mth", "(III)V"); MethodVisitor mv = builder.getGenerator(); Label start = new Label(); mv.visitLabel(start); Label end = new Label(); mv.visitIntInsn(ILOAD, 1); mv.visitIntInsn(ILOAD, 2); mv.visitInsn(IMUL); mv.visitIntInsn(ISTORE, 0); mv.visitLabel(end); mv.visitInsn(RETURN); mv.visitLocalVariable("i", "I", null, start, end, 0); mv.visitLocalVariable("a", "I", null, start, end, 1); mv.visitLocalVariable("b", "I", null, start, end, 2); String insn = KotlinTestHelper.getMethodAsString(builder.finish(), "test_mth"); String good = "fun test_mth(i: Int, a: Int, b: Int) {\n" + " i = a * b\n" + "}"; Assert.assertEquals(good, insn); } @Test public void testDiv() { TestMethodBuilder builder = new TestMethodBuilder("test_mth", "(III)V"); MethodVisitor mv = builder.getGenerator(); Label start = new Label(); mv.visitLabel(start); Label end = new Label(); mv.visitIntInsn(ILOAD, 1); mv.visitIntInsn(ILOAD, 2); mv.visitInsn(IDIV); mv.visitIntInsn(ISTORE, 0); mv.visitLabel(end); mv.visitInsn(RETURN); mv.visitLocalVariable("i", "I", null, start, end, 0); mv.visitLocalVariable("a", "I", null, start, end, 1); mv.visitLocalVariable("b", "I", null, start, end, 2); String insn = KotlinTestHelper.getMethodAsString(builder.finish(), "test_mth"); String good = "fun test_mth(i: Int, a: Int, b: Int) {\n" + " i = a / b\n" + "}"; Assert.assertEquals(good, insn); } @Test public void testRem() { TestMethodBuilder builder = new TestMethodBuilder("test_mth", "(III)V"); MethodVisitor mv = builder.getGenerator(); Label start = new Label(); mv.visitLabel(start); Label end = new Label(); mv.visitIntInsn(ILOAD, 1); mv.visitIntInsn(ILOAD, 2); mv.visitInsn(IREM); mv.visitIntInsn(ISTORE, 0); mv.visitLabel(end); mv.visitInsn(RETURN); mv.visitLocalVariable("i", "I", null, start, end, 0); mv.visitLocalVariable("a", "I", null, start, end, 1); mv.visitLocalVariable("b", "I", null, start, end, 2); String insn = KotlinTestHelper.getMethodAsString(builder.finish(), "test_mth"); String good = "fun test_mth(i: Int, a: Int, b: Int) {\n" + " i = a % b\n" + "}"; Assert.assertEquals(good, insn); } @Test public void testShr() { TestMethodBuilder builder = new TestMethodBuilder("test_mth", "(III)V"); MethodVisitor mv = builder.getGenerator(); Label start = new Label(); mv.visitLabel(start); Label end = new Label(); mv.visitIntInsn(ILOAD, 1); mv.visitIntInsn(ILOAD, 2); mv.visitInsn(ISHR); mv.visitIntInsn(ISTORE, 0); mv.visitLabel(end); mv.visitInsn(RETURN); mv.visitLocalVariable("i", "I", null, start, end, 0); mv.visitLocalVariable("a", "I", null, start, end, 1); mv.visitLocalVariable("b", "I", null, start, end, 2); String insn = KotlinTestHelper.getMethodAsString(builder.finish(), "test_mth"); String good = "fun test_mth(i: Int, a: Int, b: Int) {\n" + " i = a shr b\n" + "}"; Assert.assertEquals(good, insn); } @Test public void testUshr() { TestMethodBuilder builder = new TestMethodBuilder("test_mth", "(III)V"); MethodVisitor mv = builder.getGenerator(); Label start = new Label(); mv.visitLabel(start); Label end = new Label(); mv.visitIntInsn(ILOAD, 1); mv.visitIntInsn(ILOAD, 2); mv.visitInsn(IUSHR); mv.visitIntInsn(ISTORE, 0); mv.visitLabel(end); mv.visitInsn(RETURN); mv.visitLocalVariable("i", "I", null, start, end, 0); mv.visitLocalVariable("a", "I", null, start, end, 1); mv.visitLocalVariable("b", "I", null, start, end, 2); String insn = KotlinTestHelper.getMethodAsString(builder.finish(), "test_mth"); String good = "fun test_mth(i: Int, a: Int, b: Int) {\n" + " i = a ushr b\n" + "}"; Assert.assertEquals(good, insn); } @Test public void testShl() { TestMethodBuilder builder = new TestMethodBuilder("test_mth", "(III)V"); MethodVisitor mv = builder.getGenerator(); Label start = new Label(); mv.visitLabel(start); Label end = new Label(); mv.visitIntInsn(ILOAD, 1); mv.visitIntInsn(ILOAD, 2); mv.visitInsn(ISHL); mv.visitIntInsn(ISTORE, 0); mv.visitLabel(end); mv.visitInsn(RETURN); mv.visitLocalVariable("i", "I", null, start, end, 0); mv.visitLocalVariable("a", "I", null, start, end, 1); mv.visitLocalVariable("b", "I", null, start, end, 2); String insn = KotlinTestHelper.getMethodAsString(builder.finish(), "test_mth"); String good = "fun test_mth(i: Int, a: Int, b: Int) {\n" + " i = a shl b\n" + "}"; Assert.assertEquals(good, insn); } @Test public void testFloatCompare() { TestMethodBuilder builder = new TestMethodBuilder("test_mth", "(ZFF)V"); MethodVisitor mv = builder.getGenerator(); Label start = new Label(); mv.visitLabel(start); Label end = new Label(); Label l1 = new Label(); Label l2 = new Label(); mv.visitIntInsn(FLOAD, 1); mv.visitIntInsn(FLOAD, 2); mv.visitInsn(FCMPG); mv.visitJumpInsn(IFGT, l1); mv.visitInsn(ICONST_1); mv.visitJumpInsn(GOTO, l2); mv.visitLabel(l1); mv.visitInsn(ICONST_0); mv.visitLabel(l2); mv.visitIntInsn(ISTORE, 0); mv.visitLabel(end); mv.visitInsn(RETURN); mv.visitLocalVariable("i", "Z", null, start, end, 0); mv.visitLocalVariable("a", "F", null, start, end, 1); mv.visitLocalVariable("b", "F", null, start, end, 2); String insn = KotlinTestHelper.getMethodAsString(builder.finish(), "test_mth"); String good = "fun test_mth(i: Boolean, a: Float, b: Float) {\n" + " i = a <= b\n" + "}"; Assert.assertEquals(good, insn); } }
java
MIT
e60cfaaf7a0688bc83f8b00c392521d0b162afba
2026-01-05T02:42:07.381192Z
false
Despector/Despector
https://github.com/Despector/Despector/blob/e60cfaaf7a0688bc83f8b00c392521d0b162afba/src/test/java/org/spongepowered/test/kotlin/IfTests.java
src/test/java/org/spongepowered/test/kotlin/IfTests.java
/* * The MIT License (MIT) * * Copyright (c) Despector <https://despector.voxelgenesis.com> * Copyright (c) contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package org.spongepowered.test.kotlin; import static org.objectweb.asm.Opcodes.IF_ICMPLE; import static org.objectweb.asm.Opcodes.ILOAD; import static org.objectweb.asm.Opcodes.IRETURN; import org.junit.Assert; import org.junit.Test; import org.objectweb.asm.Label; import org.objectweb.asm.MethodVisitor; import org.spongepowered.test.util.KotlinTestHelper; import org.spongepowered.test.util.TestMethodBuilder; public class IfTests { @Test public void testSimpleIf() { TestMethodBuilder builder = new TestMethodBuilder("maxOf", "(II)I"); MethodVisitor mv = builder.getGenerator(); Label start = new Label(); Label l1 = new Label(); mv.visitLabel(start); Label end = new Label(); mv.visitVarInsn(ILOAD, 0); mv.visitVarInsn(ILOAD, 1); mv.visitJumpInsn(IF_ICMPLE, l1); mv.visitVarInsn(ILOAD, 0); mv.visitInsn(IRETURN); mv.visitLabel(l1); mv.visitVarInsn(ILOAD, 1); mv.visitLabel(end); mv.visitInsn(IRETURN); mv.visitLocalVariable("a", "I", null, start, end, 0); mv.visitLocalVariable("b", "I", null, start, end, 1); String insn = KotlinTestHelper.getMethodAsString(builder.finish(), "maxOf"); String good = "fun maxOf(a: Int, b: Int): Int {\n" + " if (a > b) {\n" + " return a\n" + " }\n\n" + " return b\n" + "}"; Assert.assertEquals(good, insn); } }
java
MIT
e60cfaaf7a0688bc83f8b00c392521d0b162afba
2026-01-05T02:42:07.381192Z
false
Despector/Despector
https://github.com/Despector/Despector/blob/e60cfaaf7a0688bc83f8b00c392521d0b162afba/src/test/java/org/spongepowered/test/decompile/TernaryTests.java
src/test/java/org/spongepowered/test/decompile/TernaryTests.java
/* * The MIT License (MIT) * * Copyright (c) Despector <https://despector.voxelgenesis.com> * Copyright (c) contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package org.spongepowered.test.decompile; import static org.objectweb.asm.Opcodes.*; import org.junit.Assert; import org.junit.BeforeClass; import org.junit.Test; import org.objectweb.asm.Label; import org.objectweb.asm.MethodVisitor; import org.objectweb.asm.Type; import org.spongepowered.despector.config.LibraryConfiguration; import org.spongepowered.test.util.TestHelper; import org.spongepowered.test.util.TestMethodBuilder; public class TernaryTests { @BeforeClass public static void setup() { LibraryConfiguration.quiet = false; LibraryConfiguration.parallel = false; } private static final Type THIS_TYPE = Type.getType(TernaryTests.class); @Test public void testSimple() { TestMethodBuilder builder = new TestMethodBuilder("test_mth", "(ZI)V"); MethodVisitor mv = builder.getGenerator(); Label start = new Label(); mv.visitLabel(start); Label end = new Label(); Label l1 = new Label(); Label l2 = new Label(); mv.visitIntInsn(ILOAD, 0); mv.visitJumpInsn(IFEQ, l1); mv.visitIntInsn(BIPUSH, 6); mv.visitJumpInsn(GOTO, l2); mv.visitLabel(l1); mv.visitInsn(ICONST_3); mv.visitLabel(l2); mv.visitIntInsn(ISTORE, 1); mv.visitLabel(end); mv.visitInsn(RETURN); mv.visitLocalVariable("a", "Z", null, start, end, 0); mv.visitLocalVariable("i", "I", null, start, end, 1); String insn = TestHelper.getAsString(builder.finish(), "test_mth"); String good = "i = a ? 6 : 3;"; Assert.assertEquals(good, insn); } @Test public void testToField() { TestMethodBuilder builder = new TestMethodBuilder("test_mth", "(ZI)V"); MethodVisitor mv = builder.getGenerator(); Label start = new Label(); mv.visitLabel(start); Label end = new Label(); Label l1 = new Label(); Label l2 = new Label(); mv.visitIntInsn(ILOAD, 0); mv.visitJumpInsn(IFEQ, l1); mv.visitIntInsn(BIPUSH, 6); mv.visitJumpInsn(GOTO, l2); mv.visitLabel(l1); mv.visitInsn(ICONST_3); mv.visitLabel(l2); mv.visitFieldInsn(PUTSTATIC, THIS_TYPE.getInternalName(), "afield", "I"); mv.visitLabel(end); mv.visitInsn(RETURN); mv.visitLocalVariable("a", "Z", null, start, end, 0); mv.visitLocalVariable("i", "I", null, start, end, 1); String insn = TestHelper.getAsString(builder.finish(), "test_mth"); String good = "org.spongepowered.test.decompile.TernaryTests.afield = a ? 6 : 3;"; Assert.assertEquals(good, insn); } @Test public void testNested() { TestMethodBuilder builder = new TestMethodBuilder("test_mth", "(ZIZ)V"); MethodVisitor mv = builder.getGenerator(); Label start = new Label(); mv.visitLabel(start); Label end = new Label(); Label l1 = new Label(); Label l2 = new Label(); Label l3 = new Label(); mv.visitIntInsn(ILOAD, 0); mv.visitJumpInsn(IFEQ, l1); mv.visitIntInsn(ILOAD, 2); mv.visitJumpInsn(IFEQ, l3); mv.visitInsn(ICONST_4); mv.visitJumpInsn(GOTO, l2); mv.visitLabel(l3); mv.visitInsn(ICONST_5); mv.visitJumpInsn(GOTO, l2); mv.visitLabel(l1); mv.visitInsn(ICONST_3); mv.visitLabel(l2); mv.visitIntInsn(ISTORE, 1); mv.visitLabel(end); mv.visitInsn(RETURN); mv.visitLocalVariable("a", "Z", null, start, end, 0); mv.visitLocalVariable("i", "I", null, start, end, 1); mv.visitLocalVariable("b", "Z", null, start, end, 2); String insn = TestHelper.getAsString(builder.finish(), "test_mth"); String good = "i = a ? b ? 4 : 5 : 3;"; Assert.assertEquals(good, insn); } @Test public void testNested2() { TestMethodBuilder builder = new TestMethodBuilder("test_mth", "(ZIZ)V"); MethodVisitor mv = builder.getGenerator(); Label start = new Label(); mv.visitLabel(start); Label end = new Label(); Label l1 = new Label(); Label l2 = new Label(); Label l3 = new Label(); mv.visitIntInsn(ILOAD, 0); mv.visitJumpInsn(IFEQ, l1); mv.visitInsn(ICONST_3); mv.visitJumpInsn(GOTO, l2); mv.visitLabel(l1); mv.visitIntInsn(ILOAD, 2); mv.visitJumpInsn(IFEQ, l3); mv.visitInsn(ICONST_4); mv.visitJumpInsn(GOTO, l2); mv.visitLabel(l3); mv.visitInsn(ICONST_5); mv.visitLabel(l2); mv.visitIntInsn(ISTORE, 1); mv.visitLabel(end); mv.visitInsn(RETURN); mv.visitLocalVariable("a", "Z", null, start, end, 0); mv.visitLocalVariable("i", "I", null, start, end, 1); mv.visitLocalVariable("b", "Z", null, start, end, 2); String insn = TestHelper.getAsString(builder.finish(), "test_mth"); String good = "i = a ? 3 : b ? 4 : 5;"; Assert.assertEquals(good, insn); } @Test public void testReturned() { TestMethodBuilder builder = new TestMethodBuilder("test_mth", "(ZI)I"); MethodVisitor mv = builder.getGenerator(); Label start = new Label(); mv.visitLabel(start); Label end = new Label(); Label l1 = new Label(); mv.visitIntInsn(ILOAD, 0); mv.visitJumpInsn(IFEQ, l1); mv.visitIntInsn(BIPUSH, 6); mv.visitJumpInsn(GOTO, end); mv.visitLabel(l1); mv.visitInsn(ICONST_3); mv.visitLabel(end); mv.visitInsn(IRETURN); mv.visitLocalVariable("a", "Z", null, start, end, 0); mv.visitLocalVariable("i", "I", null, start, end, 1); String insn = TestHelper.getAsString(builder.finish(), "test_mth"); String good = "return a ? 6 : 3;"; Assert.assertEquals(good, insn); } }
java
MIT
e60cfaaf7a0688bc83f8b00c392521d0b162afba
2026-01-05T02:42:07.381192Z
false
Despector/Despector
https://github.com/Despector/Despector/blob/e60cfaaf7a0688bc83f8b00c392521d0b162afba/src/test/java/org/spongepowered/test/decompile/DoWhileTests.java
src/test/java/org/spongepowered/test/decompile/DoWhileTests.java
/* * The MIT License (MIT) * * Copyright (c) Despector <https://despector.voxelgenesis.com> * Copyright (c) contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package org.spongepowered.test.decompile; import static org.objectweb.asm.Opcodes.*; import org.junit.Assert; import org.junit.BeforeClass; import org.junit.Test; import org.objectweb.asm.Label; import org.objectweb.asm.MethodVisitor; import org.objectweb.asm.Type; import org.spongepowered.despector.config.LibraryConfiguration; import org.spongepowered.test.util.TestHelper; import org.spongepowered.test.util.TestMethodBuilder; public class DoWhileTests { @BeforeClass public static void setup() { LibraryConfiguration.quiet = false; LibraryConfiguration.parallel = false; } private static final Type THIS_TYPE = Type.getType(DoWhileTests.class); public static void body() { } @Test public void testDoWhile() { TestMethodBuilder builder = new TestMethodBuilder("test_mth", "(I)V"); MethodVisitor mv = builder.getGenerator(); Label start = new Label(); mv.visitLabel(start); Label end = new Label(); Label l1 = new Label(); mv.visitLabel(l1); mv.visitMethodInsn(INVOKESTATIC, THIS_TYPE.getInternalName(), "body", "()V", false); mv.visitVarInsn(ILOAD, 0); mv.visitInsn(ICONST_5); mv.visitJumpInsn(IF_ICMPLT, l1); mv.visitLabel(end); mv.visitInsn(RETURN); mv.visitLocalVariable("i", "I", null, start, end, 0); String insn = TestHelper.getAsString(builder.finish(), "test_mth"); String good = "do {\n" + " org.spongepowered.test.decompile.DoWhileTests.body();\n" + "} while (i < 5);"; Assert.assertEquals(good, insn); } @Test public void testDoWhileAnd() { TestMethodBuilder builder = new TestMethodBuilder("test_mth", "(ZZ)V"); MethodVisitor mv = builder.getGenerator(); Label start = new Label(); mv.visitLabel(start); Label end = new Label(); Label l1 = new Label(); mv.visitLabel(l1); mv.visitMethodInsn(INVOKESTATIC, THIS_TYPE.getInternalName(), "body", "()V", false); mv.visitVarInsn(ILOAD, 0); mv.visitJumpInsn(IFEQ, end); mv.visitVarInsn(ILOAD, 1); mv.visitJumpInsn(IFNE, l1); mv.visitLabel(end); mv.visitInsn(RETURN); mv.visitLocalVariable("a", "Z", null, start, end, 0); mv.visitLocalVariable("b", "Z", null, start, end, 1); String insn = TestHelper.getAsString(builder.finish(), "test_mth"); String good = "do {\n" + " org.spongepowered.test.decompile.DoWhileTests.body();\n" + "} while (a && b);"; Assert.assertEquals(good, insn); } @Test public void testDoWhileOr() { TestMethodBuilder builder = new TestMethodBuilder("test_mth", "(ZZ)V"); MethodVisitor mv = builder.getGenerator(); Label start = new Label(); mv.visitLabel(start); Label end = new Label(); Label l1 = new Label(); mv.visitLabel(l1); mv.visitMethodInsn(INVOKESTATIC, THIS_TYPE.getInternalName(), "body", "()V", false); mv.visitVarInsn(ILOAD, 0); mv.visitJumpInsn(IFNE, l1); mv.visitVarInsn(ILOAD, 1); mv.visitJumpInsn(IFNE, l1); mv.visitLabel(end); mv.visitInsn(RETURN); mv.visitLocalVariable("a", "Z", null, start, end, 0); mv.visitLocalVariable("b", "Z", null, start, end, 1); String insn = TestHelper.getAsString(builder.finish(), "test_mth"); String good = "do {\n" + " org.spongepowered.test.decompile.DoWhileTests.body();\n" + "} while (a || b);"; Assert.assertEquals(good, insn); } @Test public void testDoWhileBreak() { TestMethodBuilder builder = new TestMethodBuilder("test_mth", "(IZ)V"); MethodVisitor mv = builder.getGenerator(); Label start = new Label(); mv.visitLabel(start); Label end = new Label(); Label l1 = new Label(); Label l2 = new Label(); mv.visitLabel(l1); mv.visitMethodInsn(INVOKESTATIC, THIS_TYPE.getInternalName(), "body", "()V", false); mv.visitVarInsn(ILOAD, 1); mv.visitJumpInsn(IFEQ, l2); mv.visitJumpInsn(GOTO, end); mv.visitLabel(l2); mv.visitVarInsn(ILOAD, 0); mv.visitInsn(ICONST_5); mv.visitJumpInsn(IF_ICMPLT, l1); mv.visitLabel(end); mv.visitInsn(RETURN); mv.visitLocalVariable("i", "I", null, start, end, 0); mv.visitLocalVariable("a", "Z", null, start, end, 1); String insn = TestHelper.getAsString(builder.finish(), "test_mth"); String good = "do {\n" + " org.spongepowered.test.decompile.DoWhileTests.body();\n" + " if (a) {\n" + " break;\n" + " }\n" + "} while (i < 5);"; Assert.assertEquals(good, insn); } //@Test public void testDoWhileContinue() { TestMethodBuilder builder = new TestMethodBuilder("test_mth", "(IZ)V"); MethodVisitor mv = builder.getGenerator(); Label start = new Label(); mv.visitLabel(start); Label end = new Label(); Label l1 = new Label(); Label l2 = new Label(); mv.visitLabel(l1); mv.visitMethodInsn(INVOKESTATIC, THIS_TYPE.getInternalName(), "body", "()V", false); mv.visitVarInsn(ILOAD, 1); mv.visitJumpInsn(IFEQ, l2); mv.visitJumpInsn(GOTO, l1); mv.visitLabel(l2); mv.visitMethodInsn(INVOKESTATIC, THIS_TYPE.getInternalName(), "body", "()V", false); mv.visitVarInsn(ILOAD, 0); mv.visitInsn(ICONST_5); mv.visitJumpInsn(IF_ICMPLT, l1); mv.visitLabel(end); mv.visitInsn(RETURN); mv.visitLocalVariable("i", "I", null, start, end, 0); mv.visitLocalVariable("a", "Z", null, start, end, 1); String insn = TestHelper.getAsString(builder.finish(), "test_mth"); String good = "do {\n" + " DoWhileTests.body();\n" + " if (a) {\n" + " continue;\n" + " }\n" + " DoWhileTests.body();\n" + "} while (i < 5);"; Assert.assertEquals(good, insn); } }
java
MIT
e60cfaaf7a0688bc83f8b00c392521d0b162afba
2026-01-05T02:42:07.381192Z
false
Despector/Despector
https://github.com/Despector/Despector/blob/e60cfaaf7a0688bc83f8b00c392521d0b162afba/src/test/java/org/spongepowered/test/decompile/MethodTests.java
src/test/java/org/spongepowered/test/decompile/MethodTests.java
/* * The MIT License (MIT) * * Copyright (c) Despector <https://despector.voxelgenesis.com> * Copyright (c) contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package org.spongepowered.test.decompile; import static org.objectweb.asm.Opcodes.*; import org.junit.Assert; import org.junit.BeforeClass; import org.junit.Test; import org.objectweb.asm.Label; import org.objectweb.asm.MethodVisitor; import org.spongepowered.despector.config.LibraryConfiguration; import org.spongepowered.test.util.TestHelper; import org.spongepowered.test.util.TestMethodBuilder; public class MethodTests { @BeforeClass public static void setup() { LibraryConfiguration.quiet = false; LibraryConfiguration.parallel = false; } @Test public void testStaticInvoke() { TestMethodBuilder builder = new TestMethodBuilder("test_mth", "()V"); MethodVisitor mv = builder.getGenerator(); Label start = new Label(); Label end = new Label(); mv.visitLabel(start); mv.visitFieldInsn(GETSTATIC, "java/lang/System", "out", "Ljava/io/PrintStream;"); mv.visitLdcInsn("Hello World!"); mv.visitMethodInsn(INVOKEVIRTUAL, "java/io/PrintStream", "println", "(Ljava/lang/String;)V", false); mv.visitLabel(end); mv.visitInsn(RETURN); String insn = TestHelper.getAsString(builder.finish(), "test_mth"); String good = "System.out.println(\"Hello World!\");"; Assert.assertEquals(good, insn); } @Test public void testInstanceInvoke() { TestMethodBuilder builder = new TestMethodBuilder("test_mth", "()V"); MethodVisitor mv = builder.getGenerator(); Label start = new Label(); Label end = new Label(); mv.visitLabel(start); mv.visitLdcInsn("Hello World!"); mv.visitMethodInsn(INVOKEVIRTUAL, "java/lang/String", "length", "()I", false); mv.visitInsn(POP); mv.visitLabel(end); mv.visitInsn(RETURN); String insn = TestHelper.getAsString(builder.finish(), "test_mth"); String good = "\"Hello World!\".length();"; Assert.assertEquals(good, insn); } @Test public void testNew() { TestMethodBuilder builder = new TestMethodBuilder("test_mth", "()V"); MethodVisitor mv = builder.getGenerator(); Label start = new Label(); Label l1 = new Label(); Label end = new Label(); mv.visitLabel(start); mv.visitTypeInsn(NEW, "java/lang/String"); mv.visitInsn(DUP); mv.visitLdcInsn("Hello World"); mv.visitMethodInsn(INVOKESPECIAL, "java/lang/String", "<init>", "(Ljava/lang/String;)V", false); mv.visitVarInsn(ASTORE, 0); mv.visitLabel(l1); mv.visitInsn(RETURN); mv.visitLabel(end); mv.visitLocalVariable("a", "Ljava/lang/String;", null, l1, end, 0); String insn = TestHelper.getAsString(builder.finish(), "test_mth"); String good = "String a = new String(\"Hello World\");"; Assert.assertEquals(good, insn); } @Test public void testNewArray() { TestMethodBuilder builder = new TestMethodBuilder("test_mth", "()V"); MethodVisitor mv = builder.getGenerator(); Label start = new Label(); Label l1 = new Label(); Label end = new Label(); mv.visitLabel(start); mv.visitInsn(ICONST_5); mv.visitIntInsn(NEWARRAY, T_INT); mv.visitVarInsn(ASTORE, 0); mv.visitLabel(l1); mv.visitInsn(RETURN); mv.visitLabel(end); mv.visitLocalVariable("a", "[I", null, l1, end, 0); String insn = TestHelper.getAsString(builder.finish(), "test_mth"); String good = "int[] a = new int[5];"; Assert.assertEquals(good, insn); } @Test public void testMultiNewArray() { TestMethodBuilder builder = new TestMethodBuilder("test_mth", "()V"); MethodVisitor mv = builder.getGenerator(); Label start = new Label(); Label l1 = new Label(); Label end = new Label(); mv.visitLabel(start); mv.visitInsn(ICONST_5); mv.visitIntInsn(BIPUSH, 6); mv.visitMultiANewArrayInsn("[[I", 2); mv.visitVarInsn(ASTORE, 0); mv.visitLabel(l1); mv.visitInsn(RETURN); mv.visitLabel(end); mv.visitLocalVariable("a", "[[I", null, l1, end, 0); String insn = TestHelper.getAsString(builder.finish(), "test_mth"); String good = "int[][] a = new int[5][6];"; Assert.assertEquals(good, insn); } }
java
MIT
e60cfaaf7a0688bc83f8b00c392521d0b162afba
2026-01-05T02:42:07.381192Z
false
Despector/Despector
https://github.com/Despector/Despector/blob/e60cfaaf7a0688bc83f8b00c392521d0b162afba/src/test/java/org/spongepowered/test/decompile/OperatorTests.java
src/test/java/org/spongepowered/test/decompile/OperatorTests.java
/* * The MIT License (MIT) * * Copyright (c) Despector <https://despector.voxelgenesis.com> * Copyright (c) contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package org.spongepowered.test.decompile; import static org.objectweb.asm.Opcodes.*; import org.junit.Assert; import org.junit.BeforeClass; import org.junit.Test; import org.objectweb.asm.Label; import org.objectweb.asm.MethodVisitor; import org.objectweb.asm.Type; import org.spongepowered.despector.config.LibraryConfiguration; import org.spongepowered.test.util.TestHelper; import org.spongepowered.test.util.TestMethodBuilder; public class OperatorTests { @BeforeClass public static void setup() { LibraryConfiguration.quiet = false; LibraryConfiguration.parallel = false; } @Test public void testIntConstant() { TestMethodBuilder builder = new TestMethodBuilder("test_mth", "(I)V"); MethodVisitor mv = builder.getGenerator(); Label start = new Label(); mv.visitLabel(start); Label end = new Label(); mv.visitIntInsn(BIPUSH, 65); mv.visitIntInsn(ISTORE, 0); mv.visitLabel(end); mv.visitInsn(RETURN); mv.visitLocalVariable("i", "I", null, start, end, 0); String insn = TestHelper.getAsString(builder.finish(), "test_mth"); String good = "i = 65;"; Assert.assertEquals(good, insn); } @Test public void testTypeConstant() { TestMethodBuilder builder = new TestMethodBuilder("test_mth", "(I)V"); MethodVisitor mv = builder.getGenerator(); Label start = new Label(); mv.visitLabel(start); Label end = new Label(); mv.visitLdcInsn(Type.getType("Ljava/lang/String;")); mv.visitIntInsn(ASTORE, 0); mv.visitLabel(end); mv.visitInsn(RETURN); mv.visitLocalVariable("i", "Ljava/lang/Class;", null, start, end, 0); String insn = TestHelper.getAsString(builder.finish(), "test_mth"); String good = "i = String.class;"; Assert.assertEquals(good, insn); } @Test public void testNegative() { TestMethodBuilder builder = new TestMethodBuilder("test_mth", "(II)V"); MethodVisitor mv = builder.getGenerator(); Label start = new Label(); mv.visitLabel(start); Label end = new Label(); mv.visitIntInsn(ILOAD, 1); mv.visitInsn(INEG); mv.visitIntInsn(ISTORE, 0); mv.visitLabel(end); mv.visitInsn(RETURN); mv.visitLocalVariable("i", "I", null, start, end, 0); mv.visitLocalVariable("a", "I", null, start, end, 1); String insn = TestHelper.getAsString(builder.finish(), "test_mth"); String good = "i = -a;"; Assert.assertEquals(good, insn); } @Test public void testAdd() { TestMethodBuilder builder = new TestMethodBuilder("test_mth", "(III)V"); MethodVisitor mv = builder.getGenerator(); Label start = new Label(); mv.visitLabel(start); Label end = new Label(); mv.visitIntInsn(ILOAD, 1); mv.visitIntInsn(ILOAD, 2); mv.visitInsn(IADD); mv.visitIntInsn(ISTORE, 0); mv.visitLabel(end); mv.visitInsn(RETURN); mv.visitLocalVariable("i", "I", null, start, end, 0); mv.visitLocalVariable("a", "I", null, start, end, 1); mv.visitLocalVariable("b", "I", null, start, end, 2); String insn = TestHelper.getAsString(builder.finish(), "test_mth"); String good = "i = a + b;"; Assert.assertEquals(good, insn); } @Test public void testSub() { TestMethodBuilder builder = new TestMethodBuilder("test_mth", "(III)V"); MethodVisitor mv = builder.getGenerator(); Label start = new Label(); mv.visitLabel(start); Label end = new Label(); mv.visitIntInsn(ILOAD, 1); mv.visitIntInsn(ILOAD, 2); mv.visitInsn(ISUB); mv.visitIntInsn(ISTORE, 0); mv.visitLabel(end); mv.visitInsn(RETURN); mv.visitLocalVariable("i", "I", null, start, end, 0); mv.visitLocalVariable("a", "I", null, start, end, 1); mv.visitLocalVariable("b", "I", null, start, end, 2); String insn = TestHelper.getAsString(builder.finish(), "test_mth"); String good = "i = a - b;"; Assert.assertEquals(good, insn); } @Test public void testMultiply() { TestMethodBuilder builder = new TestMethodBuilder("test_mth", "(III)V"); MethodVisitor mv = builder.getGenerator(); Label start = new Label(); mv.visitLabel(start); Label end = new Label(); mv.visitIntInsn(ILOAD, 1); mv.visitIntInsn(ILOAD, 2); mv.visitInsn(IMUL); mv.visitIntInsn(ISTORE, 0); mv.visitLabel(end); mv.visitInsn(RETURN); mv.visitLocalVariable("i", "I", null, start, end, 0); mv.visitLocalVariable("a", "I", null, start, end, 1); mv.visitLocalVariable("b", "I", null, start, end, 2); String insn = TestHelper.getAsString(builder.finish(), "test_mth"); String good = "i = a * b;"; Assert.assertEquals(good, insn); } @Test public void testDiv() { TestMethodBuilder builder = new TestMethodBuilder("test_mth", "(III)V"); MethodVisitor mv = builder.getGenerator(); Label start = new Label(); mv.visitLabel(start); Label end = new Label(); mv.visitIntInsn(ILOAD, 1); mv.visitIntInsn(ILOAD, 2); mv.visitInsn(IDIV); mv.visitIntInsn(ISTORE, 0); mv.visitLabel(end); mv.visitInsn(RETURN); mv.visitLocalVariable("i", "I", null, start, end, 0); mv.visitLocalVariable("a", "I", null, start, end, 1); mv.visitLocalVariable("b", "I", null, start, end, 2); String insn = TestHelper.getAsString(builder.finish(), "test_mth"); String good = "i = a / b;"; Assert.assertEquals(good, insn); } @Test public void testRem() { TestMethodBuilder builder = new TestMethodBuilder("test_mth", "(III)V"); MethodVisitor mv = builder.getGenerator(); Label start = new Label(); mv.visitLabel(start); Label end = new Label(); mv.visitIntInsn(ILOAD, 1); mv.visitIntInsn(ILOAD, 2); mv.visitInsn(IREM); mv.visitIntInsn(ISTORE, 0); mv.visitLabel(end); mv.visitInsn(RETURN); mv.visitLocalVariable("i", "I", null, start, end, 0); mv.visitLocalVariable("a", "I", null, start, end, 1); mv.visitLocalVariable("b", "I", null, start, end, 2); String insn = TestHelper.getAsString(builder.finish(), "test_mth"); String good = "i = a % b;"; Assert.assertEquals(good, insn); } @Test public void testShr() { TestMethodBuilder builder = new TestMethodBuilder("test_mth", "(III)V"); MethodVisitor mv = builder.getGenerator(); Label start = new Label(); mv.visitLabel(start); Label end = new Label(); mv.visitIntInsn(ILOAD, 1); mv.visitIntInsn(ILOAD, 2); mv.visitInsn(ISHR); mv.visitIntInsn(ISTORE, 0); mv.visitLabel(end); mv.visitInsn(RETURN); mv.visitLocalVariable("i", "I", null, start, end, 0); mv.visitLocalVariable("a", "I", null, start, end, 1); mv.visitLocalVariable("b", "I", null, start, end, 2); String insn = TestHelper.getAsString(builder.finish(), "test_mth"); String good = "i = a >> b;"; Assert.assertEquals(good, insn); } @Test public void testUshr() { TestMethodBuilder builder = new TestMethodBuilder("test_mth", "(III)V"); MethodVisitor mv = builder.getGenerator(); Label start = new Label(); mv.visitLabel(start); Label end = new Label(); mv.visitIntInsn(ILOAD, 1); mv.visitIntInsn(ILOAD, 2); mv.visitInsn(IUSHR); mv.visitIntInsn(ISTORE, 0); mv.visitLabel(end); mv.visitInsn(RETURN); mv.visitLocalVariable("i", "I", null, start, end, 0); mv.visitLocalVariable("a", "I", null, start, end, 1); mv.visitLocalVariable("b", "I", null, start, end, 2); String insn = TestHelper.getAsString(builder.finish(), "test_mth"); String good = "i = a >>> b;"; Assert.assertEquals(good, insn); } @Test public void testShl() { TestMethodBuilder builder = new TestMethodBuilder("test_mth", "(III)V"); MethodVisitor mv = builder.getGenerator(); Label start = new Label(); mv.visitLabel(start); Label end = new Label(); mv.visitIntInsn(ILOAD, 1); mv.visitIntInsn(ILOAD, 2); mv.visitInsn(ISHL); mv.visitIntInsn(ISTORE, 0); mv.visitLabel(end); mv.visitInsn(RETURN); mv.visitLocalVariable("i", "I", null, start, end, 0); mv.visitLocalVariable("a", "I", null, start, end, 1); mv.visitLocalVariable("b", "I", null, start, end, 2); String insn = TestHelper.getAsString(builder.finish(), "test_mth"); String good = "i = a << b;"; Assert.assertEquals(good, insn); } @Test public void testFloatCompare() { TestMethodBuilder builder = new TestMethodBuilder("test_mth", "(ZFF)V"); MethodVisitor mv = builder.getGenerator(); Label start = new Label(); mv.visitLabel(start); Label end = new Label(); Label l1 = new Label(); Label l2 = new Label(); mv.visitIntInsn(FLOAD, 1); mv.visitIntInsn(FLOAD, 2); mv.visitInsn(FCMPG); mv.visitJumpInsn(IFGT, l1); mv.visitInsn(ICONST_1); mv.visitJumpInsn(GOTO, l2); mv.visitLabel(l1); mv.visitInsn(ICONST_0); mv.visitLabel(l2); mv.visitIntInsn(ISTORE, 0); mv.visitLabel(end); mv.visitInsn(RETURN); mv.visitLocalVariable("i", "Z", null, start, end, 0); mv.visitLocalVariable("a", "F", null, start, end, 1); mv.visitLocalVariable("b", "F", null, start, end, 2); String insn = TestHelper.getAsString(builder.finish(), "test_mth"); String good = "i = a <= b;"; Assert.assertEquals(good, insn); } }
java
MIT
e60cfaaf7a0688bc83f8b00c392521d0b162afba
2026-01-05T02:42:07.381192Z
false
Despector/Despector
https://github.com/Despector/Despector/blob/e60cfaaf7a0688bc83f8b00c392521d0b162afba/src/test/java/org/spongepowered/test/decompile/TryCatchTests.java
src/test/java/org/spongepowered/test/decompile/TryCatchTests.java
/* * The MIT License (MIT) * * Copyright (c) Despector <https://despector.voxelgenesis.com> * Copyright (c) contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package org.spongepowered.test.decompile; import static org.objectweb.asm.Opcodes.*; import org.junit.Assert; import org.junit.BeforeClass; import org.junit.Test; import org.objectweb.asm.Label; import org.objectweb.asm.MethodVisitor; import org.objectweb.asm.Type; import org.spongepowered.despector.config.LibraryConfiguration; import org.spongepowered.test.util.TestHelper; import org.spongepowered.test.util.TestMethodBuilder; public class TryCatchTests { @BeforeClass public static void setup() { LibraryConfiguration.quiet = false; LibraryConfiguration.parallel = false; } private static final Type THIS_TYPE = Type.getType(TryCatchTests.class); @Test public void testTryCatch() { TestMethodBuilder builder = new TestMethodBuilder("test_mth", "()V"); MethodVisitor mv = builder.getGenerator(); Label l0 = new Label(); Label l1 = new Label(); Label l2 = new Label(); Label l4 = new Label(); mv.visitTryCatchBlock(l0, l1, l2, "java/lang/NullPointerException"); mv.visitLabel(l0); mv.visitMethodInsn(INVOKESTATIC, THIS_TYPE.getInternalName(), "body", "()V", false); mv.visitLabel(l1); mv.visitJumpInsn(GOTO, l4); mv.visitLabel(l2); mv.visitVarInsn(ASTORE, 2); mv.visitVarInsn(ALOAD, 2); mv.visitMethodInsn(INVOKEVIRTUAL, "java/lang/NullPointerException", "printStackTrace", "()V", false); mv.visitLabel(l4); mv.visitInsn(RETURN); Label l5 = new Label(); mv.visitLabel(l5); mv.visitLocalVariable("e", "Ljava/lang/NullPointerException;", null, l2, l5, 2); String insn = TestHelper.getAsString(builder.finish(), "test_mth"); String good = "try {\n" + " org.spongepowered.test.decompile.TryCatchTests.body();\n" + "} catch (NullPointerException e) {\n" + " e.printStackTrace();\n" + "}"; Assert.assertEquals(good, insn); } @Test public void testTryMultiCatch() { TestMethodBuilder builder = new TestMethodBuilder("test_mth", "()V"); MethodVisitor mv = builder.getGenerator(); Label l0 = new Label(); Label l1 = new Label(); Label l2 = new Label(); Label l3 = new Label(); Label l4 = new Label(); mv.visitTryCatchBlock(l0, l1, l2, "java/lang/NullPointerException"); mv.visitTryCatchBlock(l0, l1, l3, "java/lang/OutOfMemoryError"); mv.visitLabel(l0); mv.visitMethodInsn(INVOKESTATIC, THIS_TYPE.getInternalName(), "body", "()V", false); mv.visitLabel(l1); mv.visitJumpInsn(GOTO, l4); mv.visitLabel(l2); mv.visitVarInsn(ASTORE, 2); mv.visitVarInsn(ALOAD, 2); mv.visitMethodInsn(INVOKEVIRTUAL, "java/lang/NullPointerException", "printStackTrace", "()V", false); mv.visitJumpInsn(GOTO, l4); mv.visitLabel(l3); mv.visitVarInsn(ASTORE, 2); mv.visitVarInsn(ALOAD, 2); mv.visitMethodInsn(INVOKEVIRTUAL, "java/lang/OutOfMemoryError", "printStackTrace", "()V", false); mv.visitLabel(l4); mv.visitInsn(RETURN); Label l5 = new Label(); mv.visitLabel(l5); mv.visitLocalVariable("e", "Ljava/lang/NullPointerException;", null, l2, l3, 2); mv.visitLocalVariable("e", "Ljava/lang/OutOfMemoryError;", null, l3, l4, 2); String insn = TestHelper.getAsString(builder.finish(), "test_mth"); String good = "try {\n" + " org.spongepowered.test.decompile.TryCatchTests.body();\n" + "} catch (NullPointerException e) {\n" + " e.printStackTrace();\n" + "} catch (OutOfMemoryError e) {\n" + " e.printStackTrace();\n" + "}"; Assert.assertEquals(good, insn); } @Test public void testTryPipeCatch() { TestMethodBuilder builder = new TestMethodBuilder("test_mth", "()V"); MethodVisitor mv = builder.getGenerator(); Label l0 = new Label(); Label l1 = new Label(); Label l2 = new Label(); Label l4 = new Label(); mv.visitTryCatchBlock(l0, l1, l2, "java/lang/NullPointerException"); mv.visitTryCatchBlock(l0, l1, l2, "java/lang/OutOfMemoryError"); mv.visitLabel(l0); mv.visitMethodInsn(INVOKESTATIC, THIS_TYPE.getInternalName(), "body", "()V", false); mv.visitLabel(l1); mv.visitJumpInsn(GOTO, l4); mv.visitLabel(l2); mv.visitVarInsn(ASTORE, 2); mv.visitVarInsn(ALOAD, 2); mv.visitMethodInsn(INVOKEVIRTUAL, "java/lang/NullPointerException", "printStackTrace", "()V", false); mv.visitLabel(l4); mv.visitInsn(RETURN); Label l5 = new Label(); mv.visitLabel(l5); mv.visitLocalVariable("e", "Ljava/lang/NullPointerException;", null, l2, l4, 2); String insn = TestHelper.getAsString(builder.finish(), "test_mth"); String good = "try {\n" + " org.spongepowered.test.decompile.TryCatchTests.body();\n" + "} catch (NullPointerException | OutOfMemoryError e) {\n" + " e.printStackTrace();\n" + "}"; Assert.assertEquals(good, insn); } @Test public void testTryCatchNested() { TestMethodBuilder builder = new TestMethodBuilder("test_mth", "()V"); MethodVisitor mv = builder.getGenerator(); Label l0 = new Label(); Label l1 = new Label(); Label l2 = new Label(); Label l3 = new Label(); Label l4 = new Label(); mv.visitTryCatchBlock(l0, l1, l2, "java/lang/Exception"); mv.visitTryCatchBlock(l0, l3, l4, "java/lang/NullPointerException"); mv.visitLabel(l0); mv.visitMethodInsn(INVOKESTATIC, THIS_TYPE.getInternalName(), "body", "()V", false); mv.visitLabel(l1); Label l5 = new Label(); mv.visitJumpInsn(GOTO, l5); mv.visitLabel(l2); mv.visitVarInsn(ASTORE, 3); Label l6 = new Label(); mv.visitLabel(l6); mv.visitVarInsn(ALOAD, 3); mv.visitMethodInsn(INVOKEVIRTUAL, "java/lang/Exception", "printStackTrace", "()V", false); mv.visitLabel(l3); mv.visitJumpInsn(GOTO, l5); mv.visitLabel(l4); mv.visitVarInsn(ASTORE, 3); Label l7 = new Label(); mv.visitLabel(l7); mv.visitVarInsn(ALOAD, 3); mv.visitMethodInsn(INVOKEVIRTUAL, "java/lang/NullPointerException", "printStackTrace", "()V", false); mv.visitLabel(l5); mv.visitInsn(RETURN); Label l8 = new Label(); mv.visitLabel(l8); mv.visitLocalVariable("e", "Ljava/lang/Exception;", null, l6, l3, 3); mv.visitLocalVariable("e", "Ljava/lang/NullPointerException;", null, l7, l5, 3); String insn = TestHelper.getAsString(builder.finish(), "test_mth"); String good = "try {\n" + " try {\n" + " org.spongepowered.test.decompile.TryCatchTests.body();\n" + " } catch (Exception e) {\n" + " e.printStackTrace();\n" + " }\n" + "} catch (NullPointerException e) {\n" + " e.printStackTrace();\n" + "}"; Assert.assertEquals(good, insn); } @Test public void testTryCatchWithControlFlow() { TestMethodBuilder builder = new TestMethodBuilder("test_mth", "()V"); MethodVisitor mv = builder.getGenerator(); Label l0 = new Label(); Label l1 = new Label(); Label l2 = new Label(); Label l4 = new Label(); mv.visitTryCatchBlock(l0, l1, l2, "java/lang/NullPointerException"); mv.visitLabel(l0); mv.visitMethodInsn(INVOKESTATIC, THIS_TYPE.getInternalName(), "body", "()V", false); mv.visitLabel(l1); mv.visitJumpInsn(GOTO, l4); mv.visitLabel(l2); mv.visitVarInsn(ASTORE, 2); mv.visitVarInsn(ALOAD, 2); mv.visitJumpInsn(IFNULL, l4); mv.visitVarInsn(ALOAD, 2); mv.visitMethodInsn(INVOKEVIRTUAL, "java/lang/NullPointerException", "printStackTrace", "()V", false); mv.visitLabel(l4); mv.visitInsn(RETURN); Label l5 = new Label(); mv.visitLabel(l5); mv.visitLocalVariable("e", "Ljava/lang/NullPointerException;", null, l2, l5, 2); String insn = TestHelper.getAsString(builder.finish(), "test_mth"); String good = "try {\n" + " org.spongepowered.test.decompile.TryCatchTests.body();\n" + "} catch (NullPointerException e) {\n" + " if (e != null) {\n" + " e.printStackTrace();\n" + " }\n" + "}"; Assert.assertEquals(good, insn); } @Test public void testTryCatchReturnedTernary() { TestMethodBuilder builder = new TestMethodBuilder("test_mth", "(Z)I"); MethodVisitor mv = builder.getGenerator(); Label l0 = new Label(); Label l1 = new Label(); Label l2 = new Label(); mv.visitTryCatchBlock(l0, l1, l2, "java/lang/Exception"); mv.visitLabel(l0); mv.visitVarInsn(ILOAD, 1); Label l3 = new Label(); mv.visitJumpInsn(IFEQ, l3); mv.visitIntInsn(BIPUSH, 6); mv.visitJumpInsn(GOTO, l1); mv.visitLabel(l3); mv.visitInsn(ICONST_3); mv.visitLabel(l1); mv.visitInsn(IRETURN); mv.visitLabel(l2); mv.visitVarInsn(ASTORE, 2); Label l4 = new Label(); mv.visitLabel(l4); mv.visitInsn(ICONST_0); mv.visitInsn(IRETURN); Label l5 = new Label(); mv.visitLabel(l5); mv.visitLocalVariable("a", "Z", null, l0, l5, 1); mv.visitLocalVariable("e", "Ljava/lang/Exception;", null, l4, l5, 2); String insn = TestHelper.getAsString(builder.finish(), "test_mth"); String good = "try {\n" + " return a ? 6 : 3;\n" + "} catch (Exception e) {\n" + " return 0;\n" + "}"; Assert.assertEquals(good, insn); } }
java
MIT
e60cfaaf7a0688bc83f8b00c392521d0b162afba
2026-01-05T02:42:07.381192Z
false
Despector/Despector
https://github.com/Despector/Despector/blob/e60cfaaf7a0688bc83f8b00c392521d0b162afba/src/test/java/org/spongepowered/test/decompile/SwitchTests.java
src/test/java/org/spongepowered/test/decompile/SwitchTests.java
/* * The MIT License (MIT) * * Copyright (c) Despector <https://despector.voxelgenesis.com> * Copyright (c) contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package org.spongepowered.test.decompile; import static org.objectweb.asm.Opcodes.*; import org.junit.Assert; import org.junit.BeforeClass; import org.junit.Test; import org.objectweb.asm.ClassWriter; import org.objectweb.asm.FieldVisitor; import org.objectweb.asm.Label; import org.objectweb.asm.MethodVisitor; import org.objectweb.asm.Opcodes; import org.objectweb.asm.Type; import org.objectweb.asm.commons.GeneratorAdapter; import org.objectweb.asm.commons.Method; import org.spongepowered.despector.config.LibraryConfiguration; import org.spongepowered.test.util.TestHelper; public class SwitchTests { @BeforeClass public static void setup() { LibraryConfiguration.quiet = false; LibraryConfiguration.parallel = false; } private static enum TestEnum { ONE, TWO, THREE, FOUR, FIVE, SIX, SEVEN, EIGHT, NINE, TEN, } private static final Type TEST_ENUM_TYPE = Type.getType(TestEnum.class); private static final Type THIS_TYPE = Type.getType(SwitchTests.class); public static void body() { } @Test public void testTableSwitchEclipse() { ClassWriter cw = new ClassWriter(ClassWriter.COMPUTE_MAXS | ClassWriter.COMPUTE_FRAMES); cw.visit(V1_8, ACC_PUBLIC | ACC_SUPER, "SwitchTests_Class", null, "java/lang/Object", null); FieldVisitor fv = cw.visitField(ACC_PRIVATE + ACC_STATIC + ACC_SYNTHETIC, "$SWITCH_TABLE$org$spongepowered$test$decompile$SwitchTests$TestEnum", "[I", null, null); fv.visitEnd(); { Method m = Method.getMethod("void <init> ()"); GeneratorAdapter mg = new GeneratorAdapter(ACC_PUBLIC, m, null, null, cw); mg.loadThis(); mg.invokeConstructor(Type.getType(Object.class), m); mg.returnValue(); mg.endMethod(); } { Method m = Method.getMethod("void test_mth (" + TEST_ENUM_TYPE.getClassName() + ")"); GeneratorAdapter mv = new GeneratorAdapter(ACC_PUBLIC + ACC_STATIC, m, null, null, cw); Label start = mv.newLabel(); mv.visitLabel(start); Label l1 = mv.newLabel(); Label l2 = mv.newLabel(); Label def = mv.newLabel(); Label end = mv.newLabel(); mv.invokeStatic(THIS_TYPE, Method.getMethod("int[] $SWITCH_TABLE$org$spongepowered$test$decompile$SwitchTests$TestEnum ()")); mv.loadArg(0); mv.invokeVirtual(TEST_ENUM_TYPE, Method.getMethod("int ordinal ()")); mv.arrayLoad(Type.INT_TYPE); mv.visitTableSwitchInsn(1, 2, def, l1, l2); mv.visitLabel(l1); mv.invokeStatic(THIS_TYPE, Method.getMethod("void body ()")); mv.goTo(end); mv.visitLabel(l2); mv.invokeStatic(THIS_TYPE, Method.getMethod("void body ()")); mv.goTo(end); mv.visitLabel(def); mv.invokeStatic(THIS_TYPE, Method.getMethod("void body ()")); mv.visitLabel(end); mv.visitInsn(RETURN); mv.visitLocalVariable("ie", TEST_ENUM_TYPE.getDescriptor(), null, start, end, 0); mv.endMethod(); } generateSwitchSyntheticEclipse(cw); cw.visitEnd(); String insn = TestHelper.getAsString(cw.toByteArray(), "test_mth"); String good = "switch (ie) {\n" + "case ONE:\n" + " org.spongepowered.test.decompile.SwitchTests.body();\n" + " break;\n" + "case TWO:\n" + " org.spongepowered.test.decompile.SwitchTests.body();\n" + " break;\n" + "default:\n" + " org.spongepowered.test.decompile.SwitchTests.body();\n" + "}"; Assert.assertEquals(good, insn); } @Test public void testLookupSwitchEclipse() { ClassWriter cw = new ClassWriter(ClassWriter.COMPUTE_MAXS | ClassWriter.COMPUTE_FRAMES); cw.visit(V1_8, ACC_PUBLIC | ACC_SUPER, "SwitchTests_Class", null, "java/lang/Object", null); FieldVisitor fv = cw.visitField(ACC_PRIVATE + ACC_STATIC + ACC_SYNTHETIC, "$SWITCH_TABLE$org$spongepowered$test$decompile$SwitchTests$TestEnum", "[I", null, null); fv.visitEnd(); { Method m = Method.getMethod("void <init> ()"); GeneratorAdapter mg = new GeneratorAdapter(ACC_PUBLIC, m, null, null, cw); mg.loadThis(); mg.invokeConstructor(Type.getType(Object.class), m); mg.returnValue(); mg.endMethod(); } { Method m = Method.getMethod("void test_mth (" + TEST_ENUM_TYPE.getClassName() + ")"); GeneratorAdapter mv = new GeneratorAdapter(ACC_PUBLIC + ACC_STATIC, m, null, null, cw); Label start = mv.newLabel(); mv.visitLabel(start); Label l1 = mv.newLabel(); Label l2 = mv.newLabel(); Label def = mv.newLabel(); Label end = mv.newLabel(); mv.invokeStatic(THIS_TYPE, Method.getMethod("int[] $SWITCH_TABLE$org$spongepowered$test$decompile$SwitchTests$TestEnum ()")); mv.loadArg(0); mv.invokeVirtual(TEST_ENUM_TYPE, Method.getMethod("int ordinal ()")); mv.arrayLoad(Type.INT_TYPE); mv.visitLookupSwitchInsn(def, new int[] {1, 8}, new Label[] {l1, l2}); mv.visitLabel(l1); mv.invokeStatic(THIS_TYPE, Method.getMethod("void body ()")); mv.goTo(end); mv.visitLabel(l2); mv.invokeStatic(THIS_TYPE, Method.getMethod("void body ()")); mv.goTo(end); mv.visitLabel(def); mv.invokeStatic(THIS_TYPE, Method.getMethod("void body ()")); mv.visitLabel(end); mv.visitInsn(RETURN); mv.visitLocalVariable("ie", TEST_ENUM_TYPE.getDescriptor(), null, start, end, 0); mv.endMethod(); } generateSwitchSyntheticEclipse(cw); cw.visitEnd(); String insn = TestHelper.getAsString(cw.toByteArray(), "test_mth"); String good = "switch (ie) {\n" + "case ONE:\n" + " org.spongepowered.test.decompile.SwitchTests.body();\n" + " break;\n" + "case EIGHT:\n" + " org.spongepowered.test.decompile.SwitchTests.body();\n" + " break;\n" + "default:\n" + " org.spongepowered.test.decompile.SwitchTests.body();\n" + "}"; Assert.assertEquals(good, insn); } @Test public void testReturnSwitchEclipse() { ClassWriter cw = new ClassWriter(ClassWriter.COMPUTE_MAXS | ClassWriter.COMPUTE_FRAMES); cw.visit(V1_8, ACC_PUBLIC | ACC_SUPER, "SwitchTests_Class", null, "java/lang/Object", null); FieldVisitor fv = cw.visitField(ACC_PRIVATE + ACC_STATIC + ACC_SYNTHETIC, "$SWITCH_TABLE$org$spongepowered$test$decompile$SwitchTests$TestEnum", "[I", null, null); fv.visitEnd(); { Method m = Method.getMethod("void <init> ()"); GeneratorAdapter mg = new GeneratorAdapter(ACC_PUBLIC, m, null, null, cw); mg.loadThis(); mg.invokeConstructor(Type.getType(Object.class), m); mg.returnValue(); mg.endMethod(); } { Method m = Method.getMethod("void test_mth (" + TEST_ENUM_TYPE.getClassName() + ")"); GeneratorAdapter mv = new GeneratorAdapter(ACC_PUBLIC + ACC_STATIC, m, null, null, cw); Label start = mv.newLabel(); mv.visitLabel(start); Label l1 = mv.newLabel(); Label l2 = mv.newLabel(); Label def = mv.newLabel(); Label end = mv.newLabel(); mv.invokeStatic(THIS_TYPE, Method.getMethod("int[] $SWITCH_TABLE$org$spongepowered$test$decompile$SwitchTests$TestEnum ()")); mv.loadArg(0); mv.invokeVirtual(TEST_ENUM_TYPE, Method.getMethod("int ordinal ()")); mv.arrayLoad(Type.INT_TYPE); mv.visitLookupSwitchInsn(def, new int[] {1, 8}, new Label[] {l1, l2}); mv.visitLabel(l1); mv.invokeStatic(THIS_TYPE, Method.getMethod("void body ()")); mv.visitInsn(RETURN); mv.visitLabel(l2); mv.invokeStatic(THIS_TYPE, Method.getMethod("void body ()")); mv.visitInsn(RETURN); mv.visitLabel(def); mv.invokeStatic(THIS_TYPE, Method.getMethod("void body ()")); mv.visitLabel(end); mv.visitInsn(RETURN); mv.visitLocalVariable("ie", TEST_ENUM_TYPE.getDescriptor(), null, start, end, 0); mv.endMethod(); } generateSwitchSyntheticEclipse(cw); cw.visitEnd(); String insn = TestHelper.getAsString(cw.toByteArray(), "test_mth"); String good = "switch (ie) {\n" + "case ONE:\n" + " org.spongepowered.test.decompile.SwitchTests.body();\n" + " return;\n" + "case EIGHT:\n" + " org.spongepowered.test.decompile.SwitchTests.body();\n" + " return;\n" + "}\n" + "\n" + "org.spongepowered.test.decompile.SwitchTests.body();"; Assert.assertEquals(good, insn); } private static void generateSwitchSyntheticEclipse(ClassWriter cw) { MethodVisitor mv = cw.visitMethod(ACC_STATIC + ACC_SYNTHETIC, "$SWITCH_TABLE$org$spongepowered$test$decompile$SwitchTests$TestEnum", "()[I", null, null); mv.visitCode(); Label l0 = new Label(); Label l1 = new Label(); Label l2 = new Label(); mv.visitTryCatchBlock(l0, l1, l2, "java/lang/NoSuchFieldError"); Label l3 = new Label(); Label l4 = new Label(); Label l5 = new Label(); mv.visitTryCatchBlock(l3, l4, l5, "java/lang/NoSuchFieldError"); Label l6 = new Label(); Label l7 = new Label(); Label l8 = new Label(); mv.visitTryCatchBlock(l6, l7, l8, "java/lang/NoSuchFieldError"); Label l9 = new Label(); Label l10 = new Label(); Label l11 = new Label(); mv.visitTryCatchBlock(l9, l10, l11, "java/lang/NoSuchFieldError"); Label l12 = new Label(); Label l13 = new Label(); Label l14 = new Label(); mv.visitTryCatchBlock(l12, l13, l14, "java/lang/NoSuchFieldError"); Label l15 = new Label(); Label l16 = new Label(); Label l17 = new Label(); mv.visitTryCatchBlock(l15, l16, l17, "java/lang/NoSuchFieldError"); Label l18 = new Label(); Label l19 = new Label(); Label l20 = new Label(); mv.visitTryCatchBlock(l18, l19, l20, "java/lang/NoSuchFieldError"); Label l21 = new Label(); Label l22 = new Label(); Label l23 = new Label(); mv.visitTryCatchBlock(l21, l22, l23, "java/lang/NoSuchFieldError"); Label l24 = new Label(); Label l25 = new Label(); Label l26 = new Label(); mv.visitTryCatchBlock(l24, l25, l26, "java/lang/NoSuchFieldError"); Label l27 = new Label(); Label l28 = new Label(); Label l29 = new Label(); mv.visitTryCatchBlock(l27, l28, l29, "java/lang/NoSuchFieldError"); Label l30 = new Label(); mv.visitLabel(l30); mv.visitLineNumber(28, l30); mv.visitFieldInsn(GETSTATIC, "org/spongepowered/test/decompile/SwitchTests", "$SWITCH_TABLE$org$spongepowered$test$decompile$SwitchTests$TestEnum", "[I"); Label l31 = new Label(); mv.visitJumpInsn(IFNULL, l31); mv.visitFieldInsn(GETSTATIC, "org/spongepowered/test/decompile/SwitchTests", "$SWITCH_TABLE$org$spongepowered$test$decompile$SwitchTests$TestEnum", "[I"); mv.visitInsn(ARETURN); mv.visitLabel(l31); mv.visitMethodInsn(INVOKESTATIC, "org/spongepowered/test/decompile/SwitchTests$TestEnum", "values", "()[Lorg/spongepowered/test/decompile/SwitchTests$TestEnum;", false); mv.visitInsn(ARRAYLENGTH); mv.visitIntInsn(NEWARRAY, T_INT); mv.visitVarInsn(ASTORE, 0); mv.visitLabel(l0); mv.visitVarInsn(ALOAD, 0); mv.visitFieldInsn(GETSTATIC, "org/spongepowered/test/decompile/SwitchTests$TestEnum", "EIGHT", "Lorg/spongepowered/test/decompile/SwitchTests$TestEnum;"); mv.visitMethodInsn(INVOKEVIRTUAL, "org/spongepowered/test/decompile/SwitchTests$TestEnum", "ordinal", "()I", false); mv.visitIntInsn(BIPUSH, 8); mv.visitInsn(IASTORE); mv.visitLabel(l1); mv.visitJumpInsn(GOTO, l3); mv.visitLabel(l2); mv.visitInsn(POP); mv.visitLabel(l3); mv.visitVarInsn(ALOAD, 0); mv.visitFieldInsn(GETSTATIC, "org/spongepowered/test/decompile/SwitchTests$TestEnum", "FIVE", "Lorg/spongepowered/test/decompile/SwitchTests$TestEnum;"); mv.visitMethodInsn(INVOKEVIRTUAL, "org/spongepowered/test/decompile/SwitchTests$TestEnum", "ordinal", "()I", false); mv.visitInsn(ICONST_5); mv.visitInsn(IASTORE); mv.visitLabel(l4); mv.visitJumpInsn(GOTO, l6); mv.visitLabel(l5); mv.visitInsn(POP); mv.visitLabel(l6); mv.visitVarInsn(ALOAD, 0); mv.visitFieldInsn(GETSTATIC, "org/spongepowered/test/decompile/SwitchTests$TestEnum", "FOUR", "Lorg/spongepowered/test/decompile/SwitchTests$TestEnum;"); mv.visitMethodInsn(INVOKEVIRTUAL, "org/spongepowered/test/decompile/SwitchTests$TestEnum", "ordinal", "()I", false); mv.visitInsn(ICONST_4); mv.visitInsn(IASTORE); mv.visitLabel(l7); mv.visitJumpInsn(GOTO, l9); mv.visitLabel(l8); mv.visitInsn(POP); mv.visitLabel(l9); mv.visitVarInsn(ALOAD, 0); mv.visitFieldInsn(GETSTATIC, "org/spongepowered/test/decompile/SwitchTests$TestEnum", "NINE", "Lorg/spongepowered/test/decompile/SwitchTests$TestEnum;"); mv.visitMethodInsn(INVOKEVIRTUAL, "org/spongepowered/test/decompile/SwitchTests$TestEnum", "ordinal", "()I", false); mv.visitIntInsn(BIPUSH, 9); mv.visitInsn(IASTORE); mv.visitLabel(l10); mv.visitJumpInsn(GOTO, l12); mv.visitLabel(l11); mv.visitInsn(POP); mv.visitLabel(l12); mv.visitVarInsn(ALOAD, 0); mv.visitFieldInsn(GETSTATIC, "org/spongepowered/test/decompile/SwitchTests$TestEnum", "ONE", "Lorg/spongepowered/test/decompile/SwitchTests$TestEnum;"); mv.visitMethodInsn(INVOKEVIRTUAL, "org/spongepowered/test/decompile/SwitchTests$TestEnum", "ordinal", "()I", false); mv.visitInsn(ICONST_1); mv.visitInsn(IASTORE); mv.visitLabel(l13); mv.visitJumpInsn(GOTO, l15); mv.visitLabel(l14); mv.visitFrame(Opcodes.F_SAME1, 0, null, 1, new Object[] {"java/lang/NoSuchFieldError"}); mv.visitInsn(POP); mv.visitLabel(l15); mv.visitFrame(Opcodes.F_SAME, 0, null, 0, null); mv.visitVarInsn(ALOAD, 0); mv.visitFieldInsn(GETSTATIC, "org/spongepowered/test/decompile/SwitchTests$TestEnum", "SEVEN", "Lorg/spongepowered/test/decompile/SwitchTests$TestEnum;"); mv.visitMethodInsn(INVOKEVIRTUAL, "org/spongepowered/test/decompile/SwitchTests$TestEnum", "ordinal", "()I", false); mv.visitIntInsn(BIPUSH, 7); mv.visitInsn(IASTORE); mv.visitLabel(l16); mv.visitJumpInsn(GOTO, l18); mv.visitLabel(l17); mv.visitInsn(POP); mv.visitLabel(l18); mv.visitVarInsn(ALOAD, 0); mv.visitFieldInsn(GETSTATIC, "org/spongepowered/test/decompile/SwitchTests$TestEnum", "SIX", "Lorg/spongepowered/test/decompile/SwitchTests$TestEnum;"); mv.visitMethodInsn(INVOKEVIRTUAL, "org/spongepowered/test/decompile/SwitchTests$TestEnum", "ordinal", "()I", false); mv.visitIntInsn(BIPUSH, 6); mv.visitInsn(IASTORE); mv.visitLabel(l19); mv.visitJumpInsn(GOTO, l21); mv.visitLabel(l20); mv.visitInsn(POP); mv.visitLabel(l21); mv.visitVarInsn(ALOAD, 0); mv.visitFieldInsn(GETSTATIC, "org/spongepowered/test/decompile/SwitchTests$TestEnum", "TEN", "Lorg/spongepowered/test/decompile/SwitchTests$TestEnum;"); mv.visitMethodInsn(INVOKEVIRTUAL, "org/spongepowered/test/decompile/SwitchTests$TestEnum", "ordinal", "()I", false); mv.visitIntInsn(BIPUSH, 10); mv.visitInsn(IASTORE); mv.visitLabel(l22); mv.visitJumpInsn(GOTO, l24); mv.visitLabel(l23); mv.visitInsn(POP); mv.visitLabel(l24); mv.visitVarInsn(ALOAD, 0); mv.visitFieldInsn(GETSTATIC, "org/spongepowered/test/decompile/SwitchTests$TestEnum", "THREE", "Lorg/spongepowered/test/decompile/SwitchTests$TestEnum;"); mv.visitMethodInsn(INVOKEVIRTUAL, "org/spongepowered/test/decompile/SwitchTests$TestEnum", "ordinal", "()I", false); mv.visitInsn(ICONST_3); mv.visitInsn(IASTORE); mv.visitLabel(l25); mv.visitJumpInsn(GOTO, l27); mv.visitLabel(l26); mv.visitInsn(POP); mv.visitLabel(l27); mv.visitVarInsn(ALOAD, 0); mv.visitFieldInsn(GETSTATIC, "org/spongepowered/test/decompile/SwitchTests$TestEnum", "TWO", "Lorg/spongepowered/test/decompile/SwitchTests$TestEnum;"); mv.visitMethodInsn(INVOKEVIRTUAL, "org/spongepowered/test/decompile/SwitchTests$TestEnum", "ordinal", "()I", false); mv.visitInsn(ICONST_2); mv.visitInsn(IASTORE); mv.visitLabel(l28); Label l32 = new Label(); mv.visitJumpInsn(GOTO, l32); mv.visitLabel(l29); mv.visitInsn(POP); mv.visitLabel(l32); mv.visitVarInsn(ALOAD, 0); mv.visitInsn(DUP); mv.visitFieldInsn(PUTSTATIC, "org/spongepowered/test/decompile/SwitchTests", "$SWITCH_TABLE$org$spongepowered$test$decompile$SwitchTests$TestEnum", "[I"); mv.visitInsn(ARETURN); mv.visitMaxs(0, 0); mv.visitEnd(); } }
java
MIT
e60cfaaf7a0688bc83f8b00c392521d0b162afba
2026-01-05T02:42:07.381192Z
false
Despector/Despector
https://github.com/Despector/Despector/blob/e60cfaaf7a0688bc83f8b00c392521d0b162afba/src/test/java/org/spongepowered/test/decompile/IfTests.java
src/test/java/org/spongepowered/test/decompile/IfTests.java
/* * The MIT License (MIT) * * Copyright (c) Despector <https://despector.voxelgenesis.com> * Copyright (c) contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package org.spongepowered.test.decompile; import static org.objectweb.asm.Opcodes.*; import org.junit.Assert; import org.junit.BeforeClass; import org.junit.Test; import org.objectweb.asm.Label; import org.objectweb.asm.MethodVisitor; import org.objectweb.asm.Type; import org.spongepowered.despector.config.LibraryConfiguration; import org.spongepowered.test.util.TestHelper; import org.spongepowered.test.util.TestMethodBuilder; public class IfTests { @BeforeClass public static void setup() { LibraryConfiguration.quiet = false; LibraryConfiguration.parallel = false; } private static final Type THIS_TYPE = Type.getType(IfTests.class); @Test public void testSimple() { TestMethodBuilder builder = new TestMethodBuilder("test_mth", "(Z)V"); MethodVisitor mv = builder.getGenerator(); Label start = new Label(); mv.visitLabel(start); Label end = new Label(); mv.visitVarInsn(ILOAD, 0); mv.visitJumpInsn(IFEQ, end); mv.visitMethodInsn(INVOKESTATIC, THIS_TYPE.getInternalName(), "body", "()V", false); mv.visitLabel(end); mv.visitInsn(RETURN); mv.visitLocalVariable("a", "Z", null, start, end, 0); String insn = TestHelper.getAsString(builder.finish(), "test_mth"); String good = "if (a) {\n" + " org.spongepowered.test.decompile.IfTests.body();\n" + "}"; Assert.assertEquals(good, insn); } @Test public void testComparisonAndNull() { TestMethodBuilder builder = new TestMethodBuilder("test_mth", "(ILjava/lang/Object;)V"); MethodVisitor mv = builder.getGenerator(); Label start = new Label(); mv.visitLabel(start); Label ret = new Label(); Label body = new Label(); mv.visitVarInsn(ILOAD, 0); mv.visitInsn(ICONST_3); mv.visitJumpInsn(IF_ICMPLT, body); mv.visitVarInsn(ILOAD, 1); mv.visitJumpInsn(IFNULL, ret); mv.visitLabel(body); mv.visitMethodInsn(INVOKESTATIC, THIS_TYPE.getInternalName(), "body", "()V", false); mv.visitLabel(ret); mv.visitInsn(RETURN); mv.visitLocalVariable("a", "I", null, start, ret, 0); mv.visitLocalVariable("b", "Ljava/lang/Object;", null, start, ret, 1); String insn = TestHelper.getAsString(builder.finish(), "test_mth"); String good = "if (a < 3 || b != null) {\n" + " org.spongepowered.test.decompile.IfTests.body();\n" + "}"; Assert.assertEquals(good, insn); } @Test public void testOr() { TestMethodBuilder builder = new TestMethodBuilder("test_mth", "(ZZ)V"); MethodVisitor mv = builder.getGenerator(); Label start = new Label(); mv.visitLabel(start); Label ret = new Label(); Label body = new Label(); mv.visitVarInsn(ILOAD, 0); mv.visitJumpInsn(IFNE, body); mv.visitVarInsn(ILOAD, 1); mv.visitJumpInsn(IFEQ, ret); mv.visitLabel(body); mv.visitMethodInsn(INVOKESTATIC, THIS_TYPE.getInternalName(), "body", "()V", false); mv.visitLabel(ret); mv.visitInsn(RETURN); mv.visitLocalVariable("a", "Z", null, start, ret, 0); mv.visitLocalVariable("b", "Z", null, start, ret, 1); String insn = TestHelper.getAsString(builder.finish(), "test_mth"); String good = "if (a || b) {\n" + " org.spongepowered.test.decompile.IfTests.body();\n" + "}"; Assert.assertEquals(good, insn); } @Test public void testAnd() { TestMethodBuilder builder = new TestMethodBuilder("test_mth", "(ZZ)V"); MethodVisitor mv = builder.getGenerator(); Label start = new Label(); mv.visitLabel(start); Label ret = new Label(); Label body = new Label(); mv.visitVarInsn(ILOAD, 0); mv.visitJumpInsn(IFEQ, ret); mv.visitVarInsn(ILOAD, 1); mv.visitJumpInsn(IFEQ, ret); mv.visitLabel(body); mv.visitMethodInsn(INVOKESTATIC, THIS_TYPE.getInternalName(), "body", "()V", false); mv.visitLabel(ret); mv.visitInsn(RETURN); mv.visitLocalVariable("a", "Z", null, start, ret, 0); mv.visitLocalVariable("b", "Z", null, start, ret, 1); String insn = TestHelper.getAsString(builder.finish(), "test_mth"); String good = "if (a && b) {\n" + " org.spongepowered.test.decompile.IfTests.body();\n" + "}"; Assert.assertEquals(good, insn); } @Test public void testMultipleAnd() { TestMethodBuilder builder = new TestMethodBuilder("test_mth", "(ZZZ)V"); MethodVisitor mv = builder.getGenerator(); Label start = new Label(); mv.visitLabel(start); Label ret = new Label(); Label body = new Label(); mv.visitVarInsn(ILOAD, 0); mv.visitJumpInsn(IFEQ, ret); mv.visitVarInsn(ILOAD, 1); mv.visitJumpInsn(IFEQ, ret); mv.visitVarInsn(ILOAD, 2); mv.visitJumpInsn(IFEQ, ret); mv.visitLabel(body); mv.visitMethodInsn(INVOKESTATIC, THIS_TYPE.getInternalName(), "body", "()V", false); mv.visitLabel(ret); mv.visitInsn(RETURN); mv.visitLocalVariable("a", "Z", null, start, ret, 0); mv.visitLocalVariable("b", "Z", null, start, ret, 1); mv.visitLocalVariable("c", "Z", null, start, ret, 2); String insn = TestHelper.getAsString(builder.finish(), "test_mth"); String good = "if (a && b && c) {\n" + " org.spongepowered.test.decompile.IfTests.body();\n" + "}"; Assert.assertEquals(good, insn); } @Test public void testMultipleOr() { TestMethodBuilder builder = new TestMethodBuilder("test_mth", "(ZZZ)V"); MethodVisitor mv = builder.getGenerator(); Label start = new Label(); mv.visitLabel(start); Label ret = new Label(); Label body = new Label(); mv.visitVarInsn(ILOAD, 0); mv.visitJumpInsn(IFNE, body); mv.visitVarInsn(ILOAD, 1); mv.visitJumpInsn(IFNE, body); mv.visitVarInsn(ILOAD, 2); mv.visitJumpInsn(IFEQ, ret); mv.visitLabel(body); mv.visitMethodInsn(INVOKESTATIC, THIS_TYPE.getInternalName(), "body", "()V", false); mv.visitLabel(ret); mv.visitInsn(RETURN); mv.visitLocalVariable("a", "Z", null, start, ret, 0); mv.visitLocalVariable("b", "Z", null, start, ret, 1); mv.visitLocalVariable("c", "Z", null, start, ret, 2); String insn = TestHelper.getAsString(builder.finish(), "test_mth"); String good = "if (a || b || c) {\n" + " org.spongepowered.test.decompile.IfTests.body();\n" + "}"; Assert.assertEquals(good, insn); } @Test public void testOrAnd() { TestMethodBuilder builder = new TestMethodBuilder("test_mth", "(ZZZ)V"); MethodVisitor mv = builder.getGenerator(); Label start = new Label(); mv.visitLabel(start); Label ret = new Label(); Label body = new Label(); mv.visitVarInsn(ILOAD, 0); mv.visitJumpInsn(IFNE, body); mv.visitVarInsn(ILOAD, 1); mv.visitJumpInsn(IFEQ, ret); mv.visitVarInsn(ILOAD, 2); mv.visitJumpInsn(IFEQ, ret); mv.visitLabel(body); mv.visitMethodInsn(INVOKESTATIC, THIS_TYPE.getInternalName(), "body", "()V", false); mv.visitLabel(ret); mv.visitInsn(RETURN); mv.visitLocalVariable("a", "Z", null, start, ret, 0); mv.visitLocalVariable("b", "Z", null, start, ret, 1); mv.visitLocalVariable("c", "Z", null, start, ret, 2); String insn = TestHelper.getAsString(builder.finish(), "test_mth"); String good = "if (a || b && c) {\n" + " org.spongepowered.test.decompile.IfTests.body();\n" + "}"; Assert.assertEquals(good, insn); } @Test public void testAndOr() { TestMethodBuilder builder = new TestMethodBuilder("test_mth", "(ZZZ)V"); MethodVisitor mv = builder.getGenerator(); Label start = new Label(); mv.visitLabel(start); Label ret = new Label(); Label body = new Label(); Label l1 = new Label(); mv.visitVarInsn(ILOAD, 0); mv.visitJumpInsn(IFEQ, l1); mv.visitVarInsn(ILOAD, 1); mv.visitJumpInsn(IFNE, body); mv.visitLabel(l1); mv.visitVarInsn(ILOAD, 2); mv.visitJumpInsn(IFEQ, ret); mv.visitLabel(body); mv.visitMethodInsn(INVOKESTATIC, THIS_TYPE.getInternalName(), "body", "()V", false); mv.visitLabel(ret); mv.visitInsn(RETURN); mv.visitLocalVariable("a", "Z", null, start, ret, 0); mv.visitLocalVariable("b", "Z", null, start, ret, 1); mv.visitLocalVariable("c", "Z", null, start, ret, 2); String insn = TestHelper.getAsString(builder.finish(), "test_mth"); String good = "if (a && b || c) {\n" + " org.spongepowered.test.decompile.IfTests.body();\n" + "}"; Assert.assertEquals(good, insn); } @Test public void testPOS() { TestMethodBuilder builder = new TestMethodBuilder("test_mth", "(ZZZZ)V"); MethodVisitor mv = builder.getGenerator(); Label start = new Label(); mv.visitLabel(start); Label ret = new Label(); Label body = new Label(); Label l1 = new Label(); mv.visitVarInsn(ILOAD, 0); mv.visitJumpInsn(IFNE, l1); mv.visitVarInsn(ILOAD, 1); mv.visitJumpInsn(IFEQ, ret); mv.visitLabel(l1); mv.visitVarInsn(ILOAD, 2); mv.visitJumpInsn(IFNE, body); mv.visitVarInsn(ILOAD, 3); mv.visitJumpInsn(IFEQ, ret); mv.visitLabel(body); mv.visitMethodInsn(INVOKESTATIC, THIS_TYPE.getInternalName(), "body", "()V", false); mv.visitLabel(ret); mv.visitInsn(RETURN); mv.visitLocalVariable("a", "Z", null, start, ret, 0); mv.visitLocalVariable("b", "Z", null, start, ret, 1); mv.visitLocalVariable("c", "Z", null, start, ret, 2); mv.visitLocalVariable("d", "Z", null, start, ret, 3); String insn = TestHelper.getAsString(builder.finish(), "test_mth"); String good = "if ((a || b) && (c || d)) {\n" + " org.spongepowered.test.decompile.IfTests.body();\n" + "}"; Assert.assertEquals(good, insn); } @Test public void testSOP() { TestMethodBuilder builder = new TestMethodBuilder("test_mth", "(ZZZZ)V"); MethodVisitor mv = builder.getGenerator(); Label start = new Label(); mv.visitLabel(start); Label ret = new Label(); Label body = new Label(); Label l1 = new Label(); mv.visitVarInsn(ILOAD, 0); mv.visitJumpInsn(IFEQ, l1); mv.visitVarInsn(ILOAD, 1); mv.visitJumpInsn(IFNE, body); mv.visitLabel(l1); mv.visitVarInsn(ILOAD, 2); mv.visitJumpInsn(IFEQ, ret); mv.visitVarInsn(ILOAD, 3); mv.visitJumpInsn(IFEQ, ret); mv.visitLabel(body); mv.visitMethodInsn(INVOKESTATIC, THIS_TYPE.getInternalName(), "body", "()V", false); mv.visitLabel(ret); mv.visitInsn(RETURN); mv.visitLocalVariable("a", "Z", null, start, ret, 0); mv.visitLocalVariable("b", "Z", null, start, ret, 1); mv.visitLocalVariable("c", "Z", null, start, ret, 2); mv.visitLocalVariable("d", "Z", null, start, ret, 3); String insn = TestHelper.getAsString(builder.finish(), "test_mth"); String good = "if (a && b || c && d) {\n" + " org.spongepowered.test.decompile.IfTests.body();\n" + "}"; Assert.assertEquals(good, insn); } @Test public void testCommonFactor() { TestMethodBuilder builder = new TestMethodBuilder("test_mth", "(ZZZZZ)V"); MethodVisitor mv = builder.getGenerator(); Label start = new Label(); mv.visitLabel(start); Label ret = new Label(); Label body = new Label(); Label l1 = new Label(); Label l2 = new Label(); mv.visitVarInsn(ILOAD, 0); mv.visitJumpInsn(IFNE, l1); mv.visitVarInsn(ILOAD, 1); mv.visitJumpInsn(IFEQ, l2); mv.visitLabel(l1); mv.visitVarInsn(ILOAD, 2); mv.visitJumpInsn(IFNE, body); mv.visitLabel(l2); mv.visitVarInsn(ILOAD, 3); mv.visitJumpInsn(IFEQ, ret); mv.visitVarInsn(ILOAD, 4); mv.visitJumpInsn(IFEQ, ret); mv.visitLabel(body); mv.visitMethodInsn(INVOKESTATIC, THIS_TYPE.getInternalName(), "body", "()V", false); mv.visitLabel(ret); mv.visitInsn(RETURN); mv.visitLocalVariable("a", "Z", null, start, ret, 0); mv.visitLocalVariable("b", "Z", null, start, ret, 1); mv.visitLocalVariable("c", "Z", null, start, ret, 2); mv.visitLocalVariable("d", "Z", null, start, ret, 3); mv.visitLocalVariable("e", "Z", null, start, ret, 4); String insn = TestHelper.getAsString(builder.finish(), "test_mth"); String good = "if ((a || b) && c || d && e) {\n" + " org.spongepowered.test.decompile.IfTests.body();\n" + "}"; Assert.assertEquals(good, insn); } @Test public void testElse() { TestMethodBuilder builder = new TestMethodBuilder("test_mth", "(Z)V"); MethodVisitor mv = builder.getGenerator(); Label start = new Label(); mv.visitLabel(start); Label end = new Label(); Label else_ = new Label(); mv.visitVarInsn(ILOAD, 0); mv.visitJumpInsn(IFEQ, else_); mv.visitMethodInsn(INVOKESTATIC, THIS_TYPE.getInternalName(), "body", "()V", false); mv.visitJumpInsn(GOTO, end); mv.visitLabel(else_); mv.visitMethodInsn(INVOKESTATIC, THIS_TYPE.getInternalName(), "body", "()V", false); mv.visitLabel(end); mv.visitInsn(RETURN); mv.visitLocalVariable("a", "Z", null, start, end, 0); String insn = TestHelper.getAsString(builder.finish(), "test_mth"); String good = "if (a) {\n" + " org.spongepowered.test.decompile.IfTests.body();\n" + "} else {\n" + " org.spongepowered.test.decompile.IfTests.body();\n" + "}"; Assert.assertEquals(good, insn); } @Test public void testNestedIf() { TestMethodBuilder builder = new TestMethodBuilder("test_mth", "(ZZ)V"); MethodVisitor mv = builder.getGenerator(); Label start = new Label(); mv.visitLabel(start); Label end = new Label(); Label else_ = new Label(); Label inner_else = new Label(); Label inner_end = new Label(); mv.visitVarInsn(ILOAD, 0); mv.visitJumpInsn(IFEQ, else_); mv.visitVarInsn(ILOAD, 1); mv.visitJumpInsn(IFEQ, inner_else); mv.visitMethodInsn(INVOKESTATIC, THIS_TYPE.getInternalName(), "body", "()V", false); mv.visitJumpInsn(GOTO, inner_end); mv.visitLabel(inner_else); mv.visitMethodInsn(INVOKESTATIC, THIS_TYPE.getInternalName(), "body", "()V", false); mv.visitLabel(inner_end); mv.visitMethodInsn(INVOKESTATIC, THIS_TYPE.getInternalName(), "body", "()V", false); mv.visitJumpInsn(GOTO, end); mv.visitLabel(else_); mv.visitMethodInsn(INVOKESTATIC, THIS_TYPE.getInternalName(), "body", "()V", false); mv.visitLabel(end); mv.visitInsn(RETURN); mv.visitLocalVariable("a", "Z", null, start, end, 0); mv.visitLocalVariable("b", "Z", null, start, end, 1); String insn = TestHelper.getAsString(builder.finish(), "test_mth"); String good = "if (a) {\n" + " if (b) {\n" + " org.spongepowered.test.decompile.IfTests.body();\n" + " } else {\n" + " org.spongepowered.test.decompile.IfTests.body();\n" + " }\n\n" + " org.spongepowered.test.decompile.IfTests.body();\n" + "} else {\n" + " org.spongepowered.test.decompile.IfTests.body();\n" + "}"; Assert.assertEquals(good, insn); } @Test public void testNestedIf2() { TestMethodBuilder builder = new TestMethodBuilder("test_mth", "(ZZ)V"); MethodVisitor mv = builder.getGenerator(); Label start = new Label(); mv.visitLabel(start); Label end = new Label(); Label else_ = new Label(); Label inner_else = new Label(); mv.visitVarInsn(ILOAD, 0); mv.visitJumpInsn(IFEQ, else_); mv.visitVarInsn(ILOAD, 1); mv.visitJumpInsn(IFEQ, inner_else); mv.visitMethodInsn(INVOKESTATIC, THIS_TYPE.getInternalName(), "body", "()V", false); mv.visitLabel(inner_else); mv.visitJumpInsn(GOTO, end); mv.visitLabel(else_); mv.visitMethodInsn(INVOKESTATIC, THIS_TYPE.getInternalName(), "body", "()V", false); mv.visitLabel(end); mv.visitInsn(RETURN); mv.visitLocalVariable("a", "Z", null, start, end, 0); mv.visitLocalVariable("b", "Z", null, start, end, 1); String insn = TestHelper.getAsString(builder.finish(), "test_mth"); String good = "if (a) {\n" + " if (b) {\n" + " org.spongepowered.test.decompile.IfTests.body();\n" + " }\n" + "} else {\n" + " org.spongepowered.test.decompile.IfTests.body();\n" + "}"; Assert.assertEquals(good, insn); } @Test public void testNestedIf2Optimized() { TestMethodBuilder builder = new TestMethodBuilder("test_mth", "(ZZ)V"); MethodVisitor mv = builder.getGenerator(); Label start = new Label(); mv.visitLabel(start); Label end = new Label(); Label else_ = new Label(); mv.visitVarInsn(ILOAD, 0); mv.visitJumpInsn(IFEQ, else_); mv.visitVarInsn(ILOAD, 1); mv.visitJumpInsn(IFEQ, end); mv.visitMethodInsn(INVOKESTATIC, THIS_TYPE.getInternalName(), "body", "()V", false); mv.visitJumpInsn(GOTO, end); mv.visitLabel(else_); mv.visitMethodInsn(INVOKESTATIC, THIS_TYPE.getInternalName(), "body", "()V", false); mv.visitLabel(end); mv.visitInsn(RETURN); mv.visitLocalVariable("a", "Z", null, start, end, 0); mv.visitLocalVariable("b", "Z", null, start, end, 1); String insn = TestHelper.getAsString(builder.finish(), "test_mth"); String good = "if (a) {\n" + " if (b) {\n" + " org.spongepowered.test.decompile.IfTests.body();\n" + " }\n" + "} else {\n" + " org.spongepowered.test.decompile.IfTests.body();\n" + "}"; Assert.assertEquals(good, insn); } @Test public void testNestedIf3() { TestMethodBuilder builder = new TestMethodBuilder("test_mth", "(ZZZ)V"); MethodVisitor mv = builder.getGenerator(); Label start = new Label(); mv.visitLabel(start); Label end = new Label(); Label l1 = new Label(); Label l2 = new Label(); Label l3 = new Label(); mv.visitVarInsn(ILOAD, 0); mv.visitJumpInsn(IFEQ, end); mv.visitVarInsn(ILOAD, 1); mv.visitJumpInsn(IFEQ, l1); mv.visitVarInsn(ILOAD, 2); mv.visitJumpInsn(IFEQ, l2); mv.visitMethodInsn(INVOKESTATIC, THIS_TYPE.getInternalName(), "body", "()V", false); mv.visitJumpInsn(GOTO, l3); mv.visitLabel(l2); mv.visitMethodInsn(INVOKESTATIC, THIS_TYPE.getInternalName(), "body", "()V", false); mv.visitLabel(l3); mv.visitLabel(l1); mv.visitMethodInsn(INVOKESTATIC, THIS_TYPE.getInternalName(), "body", "()V", false); mv.visitLabel(end); mv.visitInsn(RETURN); mv.visitLocalVariable("a", "Z", null, start, end, 0); mv.visitLocalVariable("b", "Z", null, start, end, 1); mv.visitLocalVariable("c", "Z", null, start, end, 2); String insn = TestHelper.getAsString(builder.finish(), "test_mth"); String good = "if (a) {\n" + " if (b) {\n" + " if (c) {\n" + " org.spongepowered.test.decompile.IfTests.body();\n" + " } else {\n" + " org.spongepowered.test.decompile.IfTests.body();\n" + " }\n" + " }\n\n" + " org.spongepowered.test.decompile.IfTests.body();\n" + "}"; Assert.assertEquals(good, insn); } @Test public void testNestedIf3Optimized() { TestMethodBuilder builder = new TestMethodBuilder("test_mth", "(ZZZ)V"); MethodVisitor mv = builder.getGenerator(); Label start = new Label(); mv.visitLabel(start); Label end = new Label(); Label l1 = new Label(); Label l2 = new Label(); mv.visitVarInsn(ILOAD, 0); mv.visitJumpInsn(IFEQ, end); mv.visitVarInsn(ILOAD, 1); mv.visitJumpInsn(IFEQ, l1); mv.visitVarInsn(ILOAD, 2); mv.visitJumpInsn(IFEQ, l2); mv.visitMethodInsn(INVOKESTATIC, THIS_TYPE.getInternalName(), "body", "()V", false); mv.visitJumpInsn(GOTO, l1); mv.visitLabel(l2); mv.visitMethodInsn(INVOKESTATIC, THIS_TYPE.getInternalName(), "body", "()V", false); mv.visitLabel(l1); mv.visitMethodInsn(INVOKESTATIC, THIS_TYPE.getInternalName(), "body", "()V", false); mv.visitLabel(end); mv.visitInsn(RETURN); mv.visitLocalVariable("a", "Z", null, start, end, 0); mv.visitLocalVariable("b", "Z", null, start, end, 1); mv.visitLocalVariable("c", "Z", null, start, end, 2); String insn = TestHelper.getAsString(builder.finish(), "test_mth"); String good = "if (a) {\n" + " if (b) {\n" + " if (c) {\n" + " org.spongepowered.test.decompile.IfTests.body();\n" + " } else {\n" + " org.spongepowered.test.decompile.IfTests.body();\n" + " }\n" + " }\n\n" + " org.spongepowered.test.decompile.IfTests.body();\n" + "}"; Assert.assertEquals(good, insn); } @Test public void testElif() { TestMethodBuilder builder = new TestMethodBuilder("test_mth", "(ZZ)V"); MethodVisitor mv = builder.getGenerator(); Label start = new Label(); mv.visitLabel(start); Label end = new Label(); Label else_ = new Label(); Label else2 = new Label(); mv.visitVarInsn(ILOAD, 0); mv.visitJumpInsn(IFEQ, else_); mv.visitMethodInsn(INVOKESTATIC, THIS_TYPE.getInternalName(), "body", "()V", false); mv.visitJumpInsn(GOTO, end); mv.visitLabel(else_); mv.visitVarInsn(ILOAD, 1); mv.visitJumpInsn(IFEQ, else2); mv.visitMethodInsn(INVOKESTATIC, THIS_TYPE.getInternalName(), "body", "()V", false); mv.visitJumpInsn(GOTO, end); mv.visitLabel(else2); mv.visitMethodInsn(INVOKESTATIC, THIS_TYPE.getInternalName(), "body", "()V", false); mv.visitLabel(end); mv.visitInsn(RETURN); mv.visitLocalVariable("a", "Z", null, start, end, 0); mv.visitLocalVariable("b", "Z", null, start, end, 1); String insn = TestHelper.getAsString(builder.finish(), "test_mth"); String good = "if (a) {\n" + " org.spongepowered.test.decompile.IfTests.body();\n" + "} else if (b) {\n" + " org.spongepowered.test.decompile.IfTests.body();\n" + "} else {\n" + " org.spongepowered.test.decompile.IfTests.body();\n" + "}"; Assert.assertEquals(good, insn); } @Test public void testNestedInstanceOf() { TestMethodBuilder builder = new TestMethodBuilder("test_mth", "(ZLjava/lang/Object;)V"); MethodVisitor mv = builder.getGenerator(); Label start = new Label(); mv.visitLabel(start); Label end = new Label(); Label l1 = new Label(); mv.visitVarInsn(ILOAD, 0); mv.visitJumpInsn(IFEQ, end); mv.visitMethodInsn(INVOKESTATIC, THIS_TYPE.getInternalName(), "body", "()V", false); mv.visitVarInsn(ILOAD, 1); mv.visitTypeInsn(INSTANCEOF, THIS_TYPE.getInternalName()); mv.visitJumpInsn(IFEQ, l1); mv.visitMethodInsn(INVOKESTATIC, THIS_TYPE.getInternalName(), "body", "()V", false); mv.visitLabel(l1); mv.visitLabel(end); mv.visitInsn(RETURN); mv.visitLocalVariable("a", "Z", null, start, end, 0); mv.visitLocalVariable("b", "Ljava/lang/Object;", null, start, end, 1); String insn = TestHelper.getAsString(builder.finish(), "test_mth"); String good = "if (a) {\n" + " org.spongepowered.test.decompile.IfTests.body();\n" + " if (b instanceof org.spongepowered.test.decompile.IfTests) {\n" + " org.spongepowered.test.decompile.IfTests.body();\n" + " }\n" + "}"; Assert.assertEquals(good, insn); } @Test public void testNestedInstanceOfOptimized() { TestMethodBuilder builder = new TestMethodBuilder("test_mth", "(ZLjava/lang/Object;)V"); MethodVisitor mv = builder.getGenerator(); Label start = new Label(); mv.visitLabel(start); Label end = new Label(); mv.visitVarInsn(ILOAD, 0); mv.visitJumpInsn(IFEQ, end); mv.visitMethodInsn(INVOKESTATIC, THIS_TYPE.getInternalName(), "body", "()V", false); mv.visitVarInsn(ILOAD, 1); mv.visitTypeInsn(INSTANCEOF, THIS_TYPE.getInternalName()); mv.visitJumpInsn(IFEQ, end); mv.visitMethodInsn(INVOKESTATIC, THIS_TYPE.getInternalName(), "body", "()V", false); mv.visitLabel(end); mv.visitInsn(RETURN); mv.visitLocalVariable("a", "Z", null, start, end, 0); mv.visitLocalVariable("b", "Ljava/lang/Object;", null, start, end, 1); String insn = TestHelper.getAsString(builder.finish(), "test_mth"); String good = "if (a) {\n" + " org.spongepowered.test.decompile.IfTests.body();\n" + " if (b instanceof org.spongepowered.test.decompile.IfTests) {\n" + " org.spongepowered.test.decompile.IfTests.body();\n" + " }\n" + "}"; Assert.assertEquals(good, insn); } @Test public void testIfReturns() { TestMethodBuilder builder = new TestMethodBuilder("test_mth", "(ZZ)V"); MethodVisitor mv = builder.getGenerator(); Label start = new Label(); mv.visitLabel(start); Label end = new Label(); Label l1 = new Label(); mv.visitVarInsn(ILOAD, 0); mv.visitJumpInsn(IFEQ, l1); mv.visitMethodInsn(INVOKESTATIC, THIS_TYPE.getInternalName(), "body", "()V", false); mv.visitInsn(RETURN); mv.visitLabel(l1); mv.visitVarInsn(ILOAD, 1); mv.visitJumpInsn(IFEQ, end); mv.visitMethodInsn(INVOKESTATIC, THIS_TYPE.getInternalName(), "body", "()V", false); mv.visitInsn(RETURN); mv.visitLabel(end); mv.visitMethodInsn(INVOKESTATIC, THIS_TYPE.getInternalName(), "body", "()V", false); mv.visitInsn(RETURN); mv.visitLocalVariable("a", "Z", null, start, end, 0); mv.visitLocalVariable("b", "Z", null, start, end, 1); String insn = TestHelper.getAsString(builder.finish(), "test_mth"); String good = "if (a) {\n" + " org.spongepowered.test.decompile.IfTests.body();\n" + " return;\n" + "}\n\n" + "if (b) {\n" + " org.spongepowered.test.decompile.IfTests.body();\n" + " return;\n" + "}\n\n" + "org.spongepowered.test.decompile.IfTests.body();"; Assert.assertEquals(good, insn); } @Test public void testIfElseReturns() { TestMethodBuilder builder = new TestMethodBuilder("test_mth", "(ZZ)V"); MethodVisitor mv = builder.getGenerator(); Label start = new Label(); mv.visitLabel(start); Label end = new Label(); Label l1 = new Label(); Label l2 = new Label(); mv.visitVarInsn(ILOAD, 0); mv.visitJumpInsn(IFEQ, l1); mv.visitMethodInsn(INVOKESTATIC, THIS_TYPE.getInternalName(), "body", "()V", false); mv.visitVarInsn(ILOAD, 1); mv.visitJumpInsn(IFEQ, l2); mv.visitInsn(RETURN); mv.visitLabel(l1); mv.visitMethodInsn(INVOKESTATIC, THIS_TYPE.getInternalName(), "body", "()V", false); mv.visitLabel(l2); mv.visitInsn(RETURN); mv.visitLocalVariable("a", "Z", null, start, end, 0); mv.visitLocalVariable("b", "Z", null, start, end, 1); String insn = TestHelper.getAsString(builder.finish(), "test_mth"); String good = "if (a) {\n" + " org.spongepowered.test.decompile.IfTests.body();\n" + " if (b) {\n" + " return;\n" + " }\n" + "} else {\n" + " org.spongepowered.test.decompile.IfTests.body();\n" + "}"; Assert.assertEquals(good, insn); } }
java
MIT
e60cfaaf7a0688bc83f8b00c392521d0b162afba
2026-01-05T02:42:07.381192Z
false
Despector/Despector
https://github.com/Despector/Despector/blob/e60cfaaf7a0688bc83f8b00c392521d0b162afba/src/test/java/org/spongepowered/test/decompile/WhileTests.java
src/test/java/org/spongepowered/test/decompile/WhileTests.java
/* * The MIT License (MIT) * * Copyright (c) Despector <https://despector.voxelgenesis.com> * Copyright (c) contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package org.spongepowered.test.decompile; import static org.objectweb.asm.Opcodes.*; import org.junit.Assert; import org.junit.BeforeClass; import org.junit.Test; import org.objectweb.asm.Label; import org.objectweb.asm.MethodVisitor; import org.objectweb.asm.Type; import org.spongepowered.despector.config.LibraryConfiguration; import org.spongepowered.test.util.TestHelper; import org.spongepowered.test.util.TestMethodBuilder; public class WhileTests { @BeforeClass public static void setup() { LibraryConfiguration.quiet = false; LibraryConfiguration.parallel = false; } private static final Type THIS_TYPE = Type.getType(WhileTests.class); public static void body() { } @Test public void testWhile() { TestMethodBuilder builder = new TestMethodBuilder("test_mth", "(I)V"); MethodVisitor mv = builder.getGenerator(); Label start = new Label(); mv.visitLabel(start); Label end = new Label(); Label l1 = new Label(); mv.visitLabel(l1); mv.visitVarInsn(ILOAD, 0); mv.visitInsn(ICONST_5); mv.visitJumpInsn(IF_ICMPGE, end); mv.visitMethodInsn(INVOKESTATIC, THIS_TYPE.getInternalName(), "body", "()V", false); mv.visitJumpInsn(GOTO, l1); mv.visitLabel(end); mv.visitInsn(RETURN); mv.visitLocalVariable("i", "I", null, start, end, 0); String insn = TestHelper.getAsString(builder.finish(), "test_mth"); String good = "while (i < 5) {\n" + " org.spongepowered.test.decompile.WhileTests.body();\n" + "}"; Assert.assertEquals(good, insn); } @Test public void testWhileInverse() { TestMethodBuilder builder = new TestMethodBuilder("test_mth", "(I)V"); MethodVisitor mv = builder.getGenerator(); Label start = new Label(); mv.visitLabel(start); Label end = new Label(); Label l1 = new Label(); Label l2 = new Label(); mv.visitJumpInsn(GOTO, l2); mv.visitLabel(l1); mv.visitMethodInsn(INVOKESTATIC, THIS_TYPE.getInternalName(), "body", "()V", false); mv.visitLabel(l2); mv.visitVarInsn(ILOAD, 0); mv.visitInsn(ICONST_5); mv.visitJumpInsn(IF_ICMPLT, l1); mv.visitLabel(end); mv.visitInsn(RETURN); mv.visitLocalVariable("i", "I", null, start, end, 0); String insn = TestHelper.getAsString(builder.finish(), "test_mth"); String good = "while (i < 5) {\n" + " org.spongepowered.test.decompile.WhileTests.body();\n" + "}"; Assert.assertEquals(good, insn); } @Test public void testFor() { TestMethodBuilder builder = new TestMethodBuilder("test_mth", "(I)V"); MethodVisitor mv = builder.getGenerator(); Label start = new Label(); mv.visitLabel(start); Label end = new Label(); Label l1 = new Label(); mv.visitInsn(ICONST_0); mv.visitVarInsn(ISTORE, 0); mv.visitLabel(l1); mv.visitVarInsn(ILOAD, 0); mv.visitInsn(ICONST_5); mv.visitJumpInsn(IF_ICMPGE, end); mv.visitMethodInsn(INVOKESTATIC, THIS_TYPE.getInternalName(), "body", "()V", false); mv.visitIincInsn(0, 1); mv.visitJumpInsn(GOTO, l1); mv.visitLabel(end); mv.visitInsn(RETURN); mv.visitLocalVariable("i", "I", null, start, end, 0); String insn = TestHelper.getAsString(builder.finish(), "test_mth"); String good = "for (i = 0; i < 5; i++) {\n" + " org.spongepowered.test.decompile.WhileTests.body();\n" + "}"; Assert.assertEquals(good, insn); } @Test public void testForInverse() { TestMethodBuilder builder = new TestMethodBuilder("test_mth", "(I)V"); MethodVisitor mv = builder.getGenerator(); Label start = new Label(); mv.visitLabel(start); Label end = new Label(); Label l1 = new Label(); Label l2 = new Label(); mv.visitInsn(ICONST_0); mv.visitVarInsn(ISTORE, 0); mv.visitJumpInsn(GOTO, l2); mv.visitLabel(l1); mv.visitMethodInsn(INVOKESTATIC, THIS_TYPE.getInternalName(), "body", "()V", false); mv.visitIincInsn(0, 1); mv.visitLabel(l2); mv.visitVarInsn(ILOAD, 0); mv.visitInsn(ICONST_5); mv.visitJumpInsn(IF_ICMPLT, l1); mv.visitLabel(end); mv.visitInsn(RETURN); mv.visitLocalVariable("i", "I", null, start, end, 0); String insn = TestHelper.getAsString(builder.finish(), "test_mth"); String good = "for (i = 0; i < 5; i++) {\n" + " org.spongepowered.test.decompile.WhileTests.body();\n" + "}"; Assert.assertEquals(good, insn); } @Test public void testWhileAnd() { TestMethodBuilder builder = new TestMethodBuilder("test_mth", "(ZZ)V"); MethodVisitor mv = builder.getGenerator(); Label start = new Label(); mv.visitLabel(start); Label end = new Label(); Label l1 = new Label(); mv.visitLabel(l1); mv.visitVarInsn(ILOAD, 0); mv.visitJumpInsn(IFEQ, end); mv.visitVarInsn(ILOAD, 1); mv.visitJumpInsn(IFEQ, end); mv.visitMethodInsn(INVOKESTATIC, THIS_TYPE.getInternalName(), "body", "()V", false); mv.visitJumpInsn(GOTO, l1); mv.visitLabel(end); mv.visitInsn(RETURN); mv.visitLocalVariable("a", "Z", null, start, end, 0); mv.visitLocalVariable("b", "Z", null, start, end, 1); String insn = TestHelper.getAsString(builder.finish(), "test_mth"); String good = "while (a && b) {\n" + " org.spongepowered.test.decompile.WhileTests.body();\n" + "}"; Assert.assertEquals(good, insn); } @Test public void testWhileAndInverse() { TestMethodBuilder builder = new TestMethodBuilder("test_mth", "(ZZ)V"); MethodVisitor mv = builder.getGenerator(); Label start = new Label(); mv.visitLabel(start); Label end = new Label(); Label l1 = new Label(); Label l2 = new Label(); mv.visitJumpInsn(GOTO, l2); mv.visitLabel(l1); mv.visitMethodInsn(INVOKESTATIC, THIS_TYPE.getInternalName(), "body", "()V", false); mv.visitLabel(l2); mv.visitVarInsn(ILOAD, 0); mv.visitJumpInsn(IFEQ, end); mv.visitVarInsn(ILOAD, 1); mv.visitJumpInsn(IFNE, l1); mv.visitLabel(end); mv.visitInsn(RETURN); mv.visitLocalVariable("a", "Z", null, start, end, 0); mv.visitLocalVariable("b", "Z", null, start, end, 1); String insn = TestHelper.getAsString(builder.finish(), "test_mth"); String good = "while (a && b) {\n" + " org.spongepowered.test.decompile.WhileTests.body();\n" + "}"; Assert.assertEquals(good, insn); } @Test public void testWhileNestedIf() { TestMethodBuilder builder = new TestMethodBuilder("test_mth", "(ZZ)V"); MethodVisitor mv = builder.getGenerator(); Label start = new Label(); mv.visitLabel(start); Label end = new Label(); Label l1 = new Label(); Label l2 = new Label(); mv.visitLabel(l1); mv.visitVarInsn(ILOAD, 0); mv.visitJumpInsn(IFEQ, end); mv.visitVarInsn(ILOAD, 1); mv.visitJumpInsn(IFEQ, l2); mv.visitMethodInsn(INVOKESTATIC, THIS_TYPE.getInternalName(), "body", "()V", false); mv.visitLabel(l2); mv.visitMethodInsn(INVOKESTATIC, THIS_TYPE.getInternalName(), "body", "()V", false); mv.visitJumpInsn(GOTO, l1); mv.visitLabel(end); mv.visitInsn(RETURN); mv.visitLocalVariable("a", "Z", null, start, end, 0); mv.visitLocalVariable("b", "Z", null, start, end, 1); String insn = TestHelper.getAsString(builder.finish(), "test_mth"); String good = "while (a) {\n" + " if (b) {\n" + " org.spongepowered.test.decompile.WhileTests.body();\n" + " }\n\n" + " org.spongepowered.test.decompile.WhileTests.body();\n" + "}"; Assert.assertEquals(good, insn); } @Test public void testWhileNestedIfInverse() { TestMethodBuilder builder = new TestMethodBuilder("test_mth", "(ZZ)V"); MethodVisitor mv = builder.getGenerator(); Label start = new Label(); mv.visitLabel(start); Label end = new Label(); Label l1 = new Label(); Label l2 = new Label(); Label l3 = new Label(); mv.visitJumpInsn(GOTO, l3); mv.visitLabel(l1); mv.visitVarInsn(ILOAD, 1); mv.visitJumpInsn(IFEQ, l2); mv.visitMethodInsn(INVOKESTATIC, THIS_TYPE.getInternalName(), "body", "()V", false); mv.visitLabel(l2); mv.visitMethodInsn(INVOKESTATIC, THIS_TYPE.getInternalName(), "body", "()V", false); mv.visitLabel(l3); mv.visitVarInsn(ILOAD, 0); mv.visitJumpInsn(IFNE, l1); mv.visitLabel(end); mv.visitInsn(RETURN); mv.visitLocalVariable("a", "Z", null, start, end, 0); mv.visitLocalVariable("b", "Z", null, start, end, 1); String insn = TestHelper.getAsString(builder.finish(), "test_mth"); String good = "while (a) {\n" + " if (b) {\n" + " org.spongepowered.test.decompile.WhileTests.body();\n" + " }\n\n" + " org.spongepowered.test.decompile.WhileTests.body();\n" + "}"; Assert.assertEquals(good, insn); } @Test public void testWhileBreak() { TestMethodBuilder builder = new TestMethodBuilder("test_mth", "(IZ)V"); MethodVisitor mv = builder.getGenerator(); Label start = new Label(); mv.visitLabel(start); Label end = new Label(); Label l1 = new Label(); Label l2 = new Label(); mv.visitLabel(l1); mv.visitVarInsn(ILOAD, 0); mv.visitInsn(ICONST_5); mv.visitJumpInsn(IF_ICMPGE, end); mv.visitMethodInsn(INVOKESTATIC, THIS_TYPE.getInternalName(), "body", "()V", false); mv.visitVarInsn(ILOAD, 1); mv.visitJumpInsn(IFEQ, l2); mv.visitJumpInsn(GOTO, end); mv.visitLabel(l2); mv.visitJumpInsn(GOTO, l1); mv.visitLabel(end); mv.visitInsn(RETURN); mv.visitLocalVariable("i", "I", null, start, end, 0); mv.visitLocalVariable("a", "Z", null, start, end, 1); String insn = TestHelper.getAsString(builder.finish(), "test_mth"); String good = "while (i < 5) {\n" + " org.spongepowered.test.decompile.WhileTests.body();\n" + " if (a) {\n" + " break;\n" + " }\n" + "}"; Assert.assertEquals(good, insn); } @Test public void testWhileBreakInverse() { TestMethodBuilder builder = new TestMethodBuilder("test_mth", "(IZ)V"); MethodVisitor mv = builder.getGenerator(); Label start = new Label(); mv.visitLabel(start); Label end = new Label(); Label l1 = new Label(); Label l2 = new Label(); mv.visitJumpInsn(GOTO, l2); mv.visitLabel(l1); mv.visitMethodInsn(INVOKESTATIC, THIS_TYPE.getInternalName(), "body", "()V", false); mv.visitVarInsn(ILOAD, 1); mv.visitJumpInsn(IFEQ, l2); mv.visitJumpInsn(GOTO, end); mv.visitLabel(l2); mv.visitVarInsn(ILOAD, 0); mv.visitInsn(ICONST_5); mv.visitJumpInsn(IF_ICMPLT, l1); mv.visitLabel(end); mv.visitInsn(RETURN); mv.visitLocalVariable("i", "I", null, start, end, 0); mv.visitLocalVariable("a", "Z", null, start, end, 1); String insn = TestHelper.getAsString(builder.finish(), "test_mth"); String good = "while (i < 5) {\n" + " org.spongepowered.test.decompile.WhileTests.body();\n" + " if (a) {\n" + " break;\n" + " }\n" + "}"; Assert.assertEquals(good, insn); } @Test public void testWhileContinue() { TestMethodBuilder builder = new TestMethodBuilder("test_mth", "(IZ)V"); MethodVisitor mv = builder.getGenerator(); Label start = new Label(); mv.visitLabel(start); Label end = new Label(); Label l1 = new Label(); Label l2 = new Label(); mv.visitLabel(l1); mv.visitVarInsn(ILOAD, 0); mv.visitInsn(ICONST_5); mv.visitJumpInsn(IF_ICMPGE, end); mv.visitMethodInsn(INVOKESTATIC, THIS_TYPE.getInternalName(), "body", "()V", false); mv.visitVarInsn(ILOAD, 1); mv.visitJumpInsn(IFEQ, l2); mv.visitJumpInsn(GOTO, l1); mv.visitLabel(l2); mv.visitJumpInsn(GOTO, l1); mv.visitLabel(end); mv.visitInsn(RETURN); mv.visitLocalVariable("i", "I", null, start, end, 0); mv.visitLocalVariable("a", "Z", null, start, end, 1); String insn = TestHelper.getAsString(builder.finish(), "test_mth"); String good = "while (i < 5) {\n" + " org.spongepowered.test.decompile.WhileTests.body();\n" + " if (a) {\n" + " continue;\n" + " }\n" + "}"; Assert.assertEquals(good, insn); } @Test public void testWhileContinueInverse() { TestMethodBuilder builder = new TestMethodBuilder("test_mth", "(IZ)V"); MethodVisitor mv = builder.getGenerator(); Label start = new Label(); mv.visitLabel(start); Label end = new Label(); Label l1 = new Label(); Label l2 = new Label(); Label l3 = new Label(); mv.visitJumpInsn(GOTO, l3); mv.visitLabel(l1); mv.visitMethodInsn(INVOKESTATIC, THIS_TYPE.getInternalName(), "body", "()V", false); mv.visitVarInsn(ILOAD, 1); mv.visitJumpInsn(IFEQ, l2); mv.visitJumpInsn(GOTO, l3); mv.visitLabel(l2); mv.visitMethodInsn(INVOKESTATIC, THIS_TYPE.getInternalName(), "body", "()V", false); mv.visitLabel(l3); mv.visitVarInsn(ILOAD, 0); mv.visitInsn(ICONST_5); mv.visitJumpInsn(IF_ICMPLT, l1); mv.visitLabel(end); mv.visitInsn(RETURN); mv.visitLocalVariable("i", "I", null, start, end, 0); mv.visitLocalVariable("a", "Z", null, start, end, 1); String insn = TestHelper.getAsString(builder.finish(), "test_mth"); String good = "while (i < 5) {\n" + " org.spongepowered.test.decompile.WhileTests.body();\n" + " if (a) {\n" + " continue;\n" + " }\n\n" + " org.spongepowered.test.decompile.WhileTests.body();\n" + "}"; Assert.assertEquals(good, insn); } @Test public void testIfThenWhileInverse() { // the target of an if preceeding a while which has been made in the // inverse manner will be optimized to point to the condition of the // while loop rather than the start of the while loop TestMethodBuilder builder = new TestMethodBuilder("test_mth", "(IZ)V"); MethodVisitor mv = builder.getGenerator(); Label start = new Label(); mv.visitLabel(start); Label end = new Label(); Label l1 = new Label(); Label l2 = new Label(); mv.visitVarInsn(ILOAD, 1); mv.visitJumpInsn(IFEQ, l2); mv.visitInsn(RETURN); mv.visitLabel(l1); mv.visitMethodInsn(INVOKESTATIC, THIS_TYPE.getInternalName(), "body", "()V", false); mv.visitLabel(l2); mv.visitVarInsn(ILOAD, 0); mv.visitInsn(ICONST_5); mv.visitJumpInsn(IF_ICMPLT, l1); mv.visitLabel(end); mv.visitInsn(RETURN); mv.visitLocalVariable("i", "I", null, start, end, 0); mv.visitLocalVariable("a", "Z", null, start, end, 1); String insn = TestHelper.getAsString(builder.finish(), "test_mth"); String good = "if (a) {\n" + " return;\n" + "}\n\n" + "while (i < 5) {\n" + " org.spongepowered.test.decompile.WhileTests.body();\n" + "}"; Assert.assertEquals(good, insn); } @Test public void testWhileDirectBreak() { // if the break is the only thing in a condition it will sometimes be // optimized so that the inverse of the condition targets the outside of // the loop rather than having a goto inside the condition TestMethodBuilder builder = new TestMethodBuilder("test_mth", "(IZ)V"); MethodVisitor mv = builder.getGenerator(); Label start = new Label(); mv.visitLabel(start); Label end = new Label(); Label l1 = new Label(); mv.visitLabel(l1); mv.visitVarInsn(ILOAD, 0); mv.visitInsn(ICONST_5); mv.visitJumpInsn(IF_ICMPGE, end); mv.visitMethodInsn(INVOKESTATIC, THIS_TYPE.getInternalName(), "body", "()V", false); mv.visitVarInsn(ILOAD, 1); mv.visitJumpInsn(IFNE, end); mv.visitJumpInsn(GOTO, l1); mv.visitLabel(end); mv.visitInsn(RETURN); mv.visitLocalVariable("i", "I", null, start, end, 0); mv.visitLocalVariable("a", "Z", null, start, end, 1); String insn = TestHelper.getAsString(builder.finish(), "test_mth"); String good = "while (i < 5) {\n" + " org.spongepowered.test.decompile.WhileTests.body();\n" + " if (a) {\n" + " break;\n" + " }\n" + "}"; Assert.assertEquals(good, insn); } }
java
MIT
e60cfaaf7a0688bc83f8b00c392521d0b162afba
2026-01-05T02:42:07.381192Z
false
Despector/Despector
https://github.com/Despector/Despector/blob/e60cfaaf7a0688bc83f8b00c392521d0b162afba/src/test/java/org/spongepowered/test/formatting/FormattingTest.java
src/test/java/org/spongepowered/test/formatting/FormattingTest.java
/* * The MIT License (MIT) * * Copyright (c) Despector <https://despector.voxelgenesis.com> * Copyright (c) contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package org.spongepowered.test.formatting; import org.spongepowered.despector.ast.type.TypeEntry; import org.spongepowered.despector.emitter.Emitters; import org.spongepowered.despector.emitter.format.EmitterFormat; import org.spongepowered.despector.emitter.java.JavaEmitterContext; import org.spongepowered.test.util.TestHelper; import java.io.StringWriter; /** * Writing unit tests for all cases of formatting would be exhausting so this is * a simple test rig for playing with formatting easily and checking the * results. */ public class FormattingTest { public static void main(String[] args) { TypeEntry type = TestHelper.get(FormattingTestClass.class); EmitterFormat format = new EmitterFormat(); // Configure format for testing here StringWriter writer = new StringWriter(); JavaEmitterContext emitter = new JavaEmitterContext(writer, format); emitter.setEmitterSet(Emitters.JAVA_SET); emitter.emitOuterType(type); emitter.flush(); System.out.println(writer.toString()); } }
java
MIT
e60cfaaf7a0688bc83f8b00c392521d0b162afba
2026-01-05T02:42:07.381192Z
false
Despector/Despector
https://github.com/Despector/Despector/blob/e60cfaaf7a0688bc83f8b00c392521d0b162afba/src/test/java/org/spongepowered/test/formatting/FormattingTestClass.java
src/test/java/org/spongepowered/test/formatting/FormattingTestClass.java
/* * The MIT License (MIT) * * Copyright (c) Despector <https://despector.voxelgenesis.com> * Copyright (c) contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package org.spongepowered.test.formatting; public class FormattingTestClass { public int afield = 5; public String anotherfield = ""; public int foo() throws RuntimeException { return 0; } public void bar(String... args) { } public static void main(String[] args) { FormattingTestClass insn = new FormattingTestClass(); if (insn != null) { insn.foo(); } insn.bar("This is a very long line", "with a lot of args that should form breakpoints and test line", "wrapping foo bar bazz wheee alright this is over 150 characters"); } public static class AnotherClass extends Foo implements Baz { } public static class Bar implements Baz { } public static interface Baz { } public static enum Noo { ONE(1, 4), TWO(5, 2), THREE(4, 5); Noo(int a, int b) { } } public static class Foo { } }
java
MIT
e60cfaaf7a0688bc83f8b00c392521d0b162afba
2026-01-05T02:42:07.381192Z
false
Despector/Despector
https://github.com/Despector/Despector/blob/e60cfaaf7a0688bc83f8b00c392521d0b162afba/src/test/java/org/spongepowered/test/ast/SignatureParserTest.java
src/test/java/org/spongepowered/test/ast/SignatureParserTest.java
/* * The MIT License (MIT) * * Copyright (c) Despector <https://despector.voxelgenesis.com> * Copyright (c) contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package org.spongepowered.test.ast; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; import org.junit.Test; import org.spongepowered.despector.ast.generic.ClassSignature; import org.spongepowered.despector.ast.generic.ClassTypeSignature; import org.spongepowered.despector.ast.generic.GenericClassTypeSignature; import org.spongepowered.despector.ast.generic.MethodSignature; import org.spongepowered.despector.ast.generic.TypeArgument; import org.spongepowered.despector.ast.generic.TypeParameter; import org.spongepowered.despector.ast.generic.TypeSignature; import org.spongepowered.despector.ast.generic.TypeVariableSignature; import org.spongepowered.despector.ast.generic.WildcardType; import org.spongepowered.despector.util.SignatureParser; public class SignatureParserTest { @Test public void testBasic() { String sig = "Ljava/lang/Object;"; ClassSignature cls = SignatureParser.parse(sig); assertEquals(0, cls.getParameters().size()); assertEquals("Ljava/lang/Object;", cls.getSuperclassSignature().getType()); assertEquals(0, cls.getInterfaceSignatures().size()); } @Test public void testUtf() { String sig = "Ljava/lang/λ;"; ClassSignature cls = SignatureParser.parse(sig); assertEquals(0, cls.getParameters().size()); assertEquals("Ljava/lang/λ;", cls.getSuperclassSignature().getType()); assertEquals(0, cls.getInterfaceSignatures().size()); } @Test public void testBasic2() { String sig = "Ljava/lang/Object<TT;>;"; ClassSignature cls = SignatureParser.parse(sig); assertEquals(0, cls.getParameters().size()); assertEquals("Ljava/lang/Object;", cls.getSuperclassSignature().getType()); assertEquals(1, cls.getSuperclassSignature().getArguments().size()); assertEquals(TypeVariableSignature.class, cls.getSuperclassSignature().getArguments().get(0).getSignature().getClass()); TypeVariableSignature param = (TypeVariableSignature) cls.getSuperclassSignature().getArguments().get(0).getSignature(); assertEquals("TT;", param.getIdentifier()); assertEquals(0, cls.getInterfaceSignatures().size()); } @Test public void testBasic3() { String sig = "<T:Ljava/lang/Object;E:Ljava/lang/Number;>Ljava/lang/Object;Ljava/util/Comparator<TE;>;"; ClassSignature cls = SignatureParser.parse(sig); assertEquals(2, cls.getParameters().size()); TypeParameter param1 = cls.getParameters().get(0); assertEquals("T", param1.getIdentifier()); assertTrue(param1.getClassBound() instanceof GenericClassTypeSignature); GenericClassTypeSignature param1_classbound = (GenericClassTypeSignature) param1.getClassBound(); assertEquals("Ljava/lang/Object;", param1_classbound.getType()); } @Test public void testBasic4() { String sig = "Ljava/util/List<[I>;"; TypeSignature cls = SignatureParser.parseFieldTypeSignature(sig); assertEquals(GenericClassTypeSignature.class, cls.getClass()); GenericClassTypeSignature g = (GenericClassTypeSignature) cls; assertEquals("Ljava/util/List;", g.getDescriptor()); assertEquals(1, g.getArguments().size()); TypeArgument p = g.getArguments().get(0); assertEquals(WildcardType.NONE, p.getWildcard()); TypeSignature ps = p.getSignature(); assertEquals(ClassTypeSignature.class, ps.getClass()); assertEquals("[I", ps.getDescriptor()); } @Test public void testChildClass() { String sig = "(Lio/github/katrix/katlib/shade/scala/Function1<Lio/github/katrix/katlib/shade/scala/runtime/Nothing$;Ljava/lang/Object;>;)" + "Lio/github/katrix/katlib/shade/scala/Option<Lio/github/katrix/katlib/shade/scala/runtime/Nothing$;>.WithFilter;"; MethodSignature mth = SignatureParser.parseMethod(sig); assertEquals(1, mth.getParameters().size()); TypeSignature param = mth.getParameters().get(0); assertTrue(param instanceof GenericClassTypeSignature); GenericClassTypeSignature paramGeneric = (GenericClassTypeSignature) param; assertEquals(2, paramGeneric.getArguments().size()); TypeArgument arg1 = paramGeneric.getArguments().get(0); assertEquals("Lio/github/katrix/katlib/shade/scala/runtime/Nothing$;", arg1.getSignature().getDescriptor()); assertEquals(WildcardType.NONE, arg1.getWildcard()); TypeArgument arg2 = paramGeneric.getArguments().get(1); assertEquals("Ljava/lang/Object;", arg2.getSignature().getDescriptor()); assertEquals(WildcardType.NONE, arg2.getWildcard()); assertTrue(mth.getReturnType() instanceof GenericClassTypeSignature); GenericClassTypeSignature ret = (GenericClassTypeSignature) mth.getReturnType(); assertNotNull(ret.getParent()); assertEquals("LWithFilter;", ret.getDescriptor()); GenericClassTypeSignature parent = ret.getParent(); assertEquals(1, parent.getArguments().size()); assertEquals("Lio/github/katrix/katlib/shade/scala/runtime/Nothing$;", parent.getArguments().get(0).getSignature().getDescriptor()); assertEquals("Lio/github/katrix/katlib/shade/scala/Option;", parent.getDescriptor()); } }
java
MIT
e60cfaaf7a0688bc83f8b00c392521d0b162afba
2026-01-05T02:42:07.381192Z
false
Despector/Despector
https://github.com/Despector/Despector/blob/e60cfaaf7a0688bc83f8b00c392521d0b162afba/src/test/java/org/spongepowered/test/ast/LambdaTest.java
src/test/java/org/spongepowered/test/ast/LambdaTest.java
/* * The MIT License (MIT) * * Copyright (c) Despector <https://despector.voxelgenesis.com> * Copyright (c) contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package org.spongepowered.test.ast; import static org.objectweb.asm.Opcodes.*; import org.junit.Assert; import org.junit.BeforeClass; import org.junit.Test; import org.objectweb.asm.Handle; import org.objectweb.asm.Label; import org.objectweb.asm.MethodVisitor; import org.objectweb.asm.Type; import org.spongepowered.despector.config.LibraryConfiguration; import org.spongepowered.test.util.TestHelper; import org.spongepowered.test.util.TestMethodBuilder; import java.util.concurrent.Callable; import java.util.function.Consumer; public class LambdaTest { @BeforeClass public static void setup() { LibraryConfiguration.quiet = false; LibraryConfiguration.parallel = false; } public void test_lambda() { Runnable r = () -> System.out.println("Hello World"); r.run(); } @Test public void testLambda() { TestMethodBuilder builder = new TestMethodBuilder("test_mth", "()V"); MethodVisitor mv = builder.getGenerator(); Label start = new Label(); mv.visitLabel(start); if (TestHelper.IS_ECLIPSE) { mv.visitInvokeDynamicInsn("run", "()Ljava/lang/Runnable;", new Handle(H_INVOKESTATIC, "java/lang/invoke/LambdaMetafactory", "metafactory", "(Ljava/lang/invoke/MethodHandles$Lookup;Ljava/lang/String;Ljava/lang/invoke/MethodType;Ljava/lang/invoke/MethodType;Ljava/lang/invoke/MethodHandle;Ljava/lang/invoke/MethodType;)Ljava/lang/invoke/CallSite;"), new Object[] {Type.getType("()V"), new Handle(H_INVOKESTATIC, "org/spongepowered/test/ast/LambdaTest", "lambda$0", "()V"), Type.getType("()V")}); } else { // javac adds an extra decoration to the lambda method name with the // name of the calling method mv.visitInvokeDynamicInsn("run", "()Ljava/lang/Runnable;", new Handle(H_INVOKESTATIC, "java/lang/invoke/LambdaMetafactory", "metafactory", "(Ljava/lang/invoke/MethodHandles$Lookup;Ljava/lang/String;Ljava/lang/invoke/MethodType;Ljava/lang/invoke/MethodType;Ljava/lang/invoke/MethodHandle;Ljava/lang/invoke/MethodType;)Ljava/lang/invoke/CallSite;"), new Object[] {Type.getType("()V"), new Handle(H_INVOKESTATIC, "org/spongepowered/test/ast/LambdaTest", "lambda$test_lambda$0", "()V"), Type.getType("()V")}); } mv.visitVarInsn(ASTORE, 1); Label l1 = new Label(); mv.visitLabel(l1); mv.visitVarInsn(ALOAD, 1); mv.visitMethodInsn(INVOKEINTERFACE, "java/lang/Runnable", "run", "()V", true); mv.visitInsn(RETURN); Label end = new Label(); mv.visitLabel(end); mv.visitLocalVariable("this", "Lorg/spongepowered/test/ast/LambdaTest;", null, start, end, 0); mv.visitLocalVariable("r", "Ljava/lang/Runnable;", null, l1, end, 1); String insn = TestHelper.getAsString(builder.finish(), "test_mth"); String good = "Runnable r = () -> System.out.println(\"Hello World\");\n" + "r.run();"; Assert.assertEquals(good, insn); } public void test_consumer() { Consumer<Object> r = (obj) -> System.out.println("Hello World"); r.accept(null); } @Test public void testConsumer() { TestMethodBuilder builder = new TestMethodBuilder("test_mth", "()V"); MethodVisitor mv = builder.getGenerator(); Label start = new Label(); mv.visitLabel(start); if (TestHelper.IS_ECLIPSE) { mv.visitInvokeDynamicInsn("accept", "()Ljava/util/function/Consumer;", new Handle(H_INVOKESTATIC, "java/lang/invoke/LambdaMetafactory", "metafactory", "(Ljava/lang/invoke/MethodHandles$Lookup;Ljava/lang/String;Ljava/lang/invoke/MethodType;Ljava/lang/invoke/MethodType;Ljava/lang/invoke/MethodHandle;Ljava/lang/invoke/MethodType;)Ljava/lang/invoke/CallSite;"), new Object[] {Type.getType("(Ljava/lang/Object;)V"), new Handle(H_INVOKESTATIC, "org/spongepowered/test/ast/LambdaTest", "lambda$1", "(Ljava/lang/Object;)V"), Type.getType("(Ljava/lang/Object;)V")}); } else { // javac adds an extra decoration to the lambda method name with the // name of the calling method mv.visitInvokeDynamicInsn("accept", "()Ljava/util/function/Consumer;", new Handle(H_INVOKESTATIC, "java/lang/invoke/LambdaMetafactory", "metafactory", "(Ljava/lang/invoke/MethodHandles$Lookup;Ljava/lang/String;Ljava/lang/invoke/MethodType;Ljava/lang/invoke/MethodType;Ljava/lang/invoke/MethodHandle;Ljava/lang/invoke/MethodType;)Ljava/lang/invoke/CallSite;"), new Object[] {Type.getType("(Ljava/lang/Object;)V"), new Handle(H_INVOKESTATIC, "org/spongepowered/test/ast/LambdaTest", "lambda$test_consumer$1", "(Ljava/lang/Object;)V"), Type.getType("(Ljava/lang/Object;)V")}); } mv.visitVarInsn(ASTORE, 1); Label l1 = new Label(); mv.visitLabel(l1); mv.visitVarInsn(ALOAD, 1); mv.visitInsn(ACONST_NULL); mv.visitMethodInsn(INVOKEINTERFACE, "java/util/function/Consumer", "accept", "(Ljava/lang/Object;)V", true); mv.visitInsn(RETURN); Label end = new Label(); mv.visitLabel(end); mv.visitLocalVariable("this", "Lorg/spongepowered/test/ast/LambdaTest;", null, start, end, 0); mv.visitLocalVariable("r", "Ljava/util/function/Consumer;", "Ljava/util/function/Consumer<Ljava/lang/Object;>;", l1, end, 1); String insn = TestHelper.getAsString(builder.finish(), "test_mth"); String good = "java.util.function.Consumer<Object> r = (obj) -> System.out.println(\"Hello World\");\n" + "r.accept(null);"; Assert.assertEquals(good, insn); } public void test_producer() throws Exception { Callable<Object> r = () -> null; r.call(); } @Test public void testProducer() { TestMethodBuilder builder = new TestMethodBuilder("test_mth", "()V"); MethodVisitor mv = builder.getGenerator(); Label start = new Label(); mv.visitLabel(start); if (TestHelper.IS_ECLIPSE) { mv.visitInvokeDynamicInsn("call", "()Ljava/util/concurrent/Callable;", new Handle(H_INVOKESTATIC, "java/lang/invoke/LambdaMetafactory", "metafactory", "(Ljava/lang/invoke/MethodHandles$Lookup;Ljava/lang/String;Ljava/lang/invoke/MethodType;Ljava/lang/invoke/MethodType;Ljava/lang/invoke/MethodHandle;Ljava/lang/invoke/MethodType;)Ljava/lang/invoke/CallSite;"), new Object[] {Type.getType("()Ljava/lang/Object;"), new Handle(H_INVOKESTATIC, "org/spongepowered/test/ast/LambdaTest", "lambda$2", "()Ljava/lang/Object;"), Type.getType("()Ljava/lang/Object;")}); } else { // javac adds an extra decoration to the lambda method name with the // name of the calling method mv.visitInvokeDynamicInsn("call", "()Ljava/util/concurrent/Callable;", new Handle(H_INVOKESTATIC, "java/lang/invoke/LambdaMetafactory", "metafactory", "(Ljava/lang/invoke/MethodHandles$Lookup;Ljava/lang/String;Ljava/lang/invoke/MethodType;Ljava/lang/invoke/MethodType;Ljava/lang/invoke/MethodHandle;Ljava/lang/invoke/MethodType;)Ljava/lang/invoke/CallSite;"), new Object[] {Type.getType("()Ljava/lang/Object;"), new Handle(H_INVOKESTATIC, "org/spongepowered/test/ast/LambdaTest", "lambda$test_producer$2", "()Ljava/lang/Object;"), Type.getType("()Ljava/lang/Object;")}); } mv.visitVarInsn(ASTORE, 1); Label l1 = new Label(); mv.visitLabel(l1); mv.visitVarInsn(ALOAD, 1); mv.visitMethodInsn(INVOKEINTERFACE, "java/util/concurrent/Callable", "call", "()Ljava/lang/Object;", true); mv.visitInsn(POP); mv.visitInsn(RETURN); Label end = new Label(); mv.visitLabel(end); mv.visitLocalVariable("this", "Lorg/spongepowered/test/ast/LambdaTest;", null, start, end, 0); mv.visitLocalVariable("r", "Ljava/util/concurrent/Callable;", "Ljava/util/concurrent/Callable<Ljava/lang/Object;>;", l1, end, 1); String insn = TestHelper.getAsString(builder.finish(), "test_mth"); String good = "java.util.concurrent.Callable<Object> r = () -> null;\n" + "r.call();"; Assert.assertEquals(good, insn); } public void test_method_ref(Runnable r, String s) { Runnable a = () -> System.out.println(r + s); a.run(); } @Test public void testMethodRef() { TestMethodBuilder builder = new TestMethodBuilder("test_mth", "(Ljava/lang/Runnable;)V"); MethodVisitor mv = builder.getGenerator(); Label start = new Label(); mv.visitLabel(start); mv.visitVarInsn(ALOAD, 1); mv.visitInvokeDynamicInsn("run", "(Ljava/lang/Runnable;)Ljava/lang/Runnable;", new Handle(H_INVOKESTATIC, "java/lang/invoke/LambdaMetafactory", "metafactory", "(Ljava/lang/invoke/MethodHandles$Lookup;Ljava/lang/String;Ljava/lang/invoke/MethodType;Ljava/lang/invoke/MethodType;Ljava/lang/invoke/MethodHandle;Ljava/lang/invoke/MethodType;)Ljava/lang/invoke/CallSite;"), new Object[] {Type.getType("()V"), new Handle(H_INVOKEINTERFACE, "java/lang/Runnable", "run", "()V"), Type.getType("()V")}); mv.visitVarInsn(ASTORE, 2); Label l1 = new Label(); mv.visitLabel(l1); mv.visitVarInsn(ALOAD, 2); mv.visitMethodInsn(INVOKEINTERFACE, "java/lang/Runnable", "run", "()V", true); mv.visitInsn(RETURN); Label end = new Label(); mv.visitLabel(end); mv.visitLocalVariable("this", "Lorg/spongepowered/test/ast/LambdaTest;", null, start, end, 0); mv.visitLocalVariable("r", "Ljava/lang/Runnable;", null, start, end, 1); mv.visitLocalVariable("a", "Ljava/lang/Runnable;", null, l1, end, 2); String insn = TestHelper.getAsString(builder.finish(), "test_mth"); String good = "Runnable a = r::run;\n" + "a.run();"; Assert.assertEquals(good, insn); } @Test public void testMethodRefJavac() { // apparently javac chooses it add a call to r.getClass() before the // method ref TestMethodBuilder builder = new TestMethodBuilder("test_mth", "(Ljava/lang/Runnable;)V"); MethodVisitor mv = builder.getGenerator(); Label start = new Label(); mv.visitLabel(start); mv.visitVarInsn(ALOAD, 1); mv.visitInsn(DUP); mv.visitMethodInsn(INVOKEVIRTUAL, "java/lang/Object", "getClass", "()Ljava/lang/Class;", false); mv.visitInsn(POP); mv.visitInvokeDynamicInsn("run", "(Ljava/lang/Runnable;)Ljava/lang/Runnable;", new Handle(H_INVOKESTATIC, "java/lang/invoke/LambdaMetafactory", "metafactory", "(Ljava/lang/invoke/MethodHandles$Lookup;Ljava/lang/String;Ljava/lang/invoke/MethodType;Ljava/lang/invoke/MethodType;Ljava/lang/invoke/MethodHandle;Ljava/lang/invoke/MethodType;)Ljava/lang/invoke/CallSite;"), new Object[] {Type.getType("()V"), new Handle(H_INVOKEINTERFACE, "java/lang/Runnable", "run", "()V"), Type.getType("()V")}); mv.visitVarInsn(ASTORE, 2); Label l1 = new Label(); mv.visitLabel(l1); mv.visitVarInsn(ALOAD, 2); mv.visitMethodInsn(INVOKEINTERFACE, "java/lang/Runnable", "run", "()V", true); mv.visitInsn(RETURN); Label end = new Label(); mv.visitLabel(end); mv.visitLocalVariable("this", "Lorg/spongepowered/test/ast/LambdaTest;", null, start, end, 0); mv.visitLocalVariable("r", "Ljava/lang/Runnable;", null, start, end, 1); mv.visitLocalVariable("a", "Ljava/lang/Runnable;", null, l1, end, 2); String insn = TestHelper.getAsString(builder.finish(), "test_mth"); String good = "r.getClass();\n" + "Runnable a = r::run;\n" + "a.run();"; Assert.assertEquals(good, insn); } }
java
MIT
e60cfaaf7a0688bc83f8b00c392521d0b162afba
2026-01-05T02:42:07.381192Z
false
Despector/Despector
https://github.com/Despector/Despector/blob/e60cfaaf7a0688bc83f8b00c392521d0b162afba/src/test/java/org/spongepowered/test/ast/ConditionSimplificationTest.java
src/test/java/org/spongepowered/test/ast/ConditionSimplificationTest.java
/* * The MIT License (MIT) * * Copyright (c) Despector <https://despector.voxelgenesis.com> * Copyright (c) contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package org.spongepowered.test.ast; import static org.junit.Assert.assertEquals; import org.junit.Test; import org.spongepowered.despector.ast.AstVisitor; import org.spongepowered.despector.ast.generic.ClassTypeSignature; import org.spongepowered.despector.ast.generic.TypeSignature; import org.spongepowered.despector.ast.insn.Instruction; import org.spongepowered.despector.ast.insn.condition.AndCondition; import org.spongepowered.despector.ast.insn.condition.BooleanCondition; import org.spongepowered.despector.ast.insn.condition.Condition; import org.spongepowered.despector.ast.insn.condition.OrCondition; import org.spongepowered.despector.util.ConditionUtil; import org.spongepowered.despector.util.serialization.MessagePacker; import java.io.IOException; public class ConditionSimplificationTest { private static final BooleanCondition a = new BooleanCondition(new MockInsn('a'), false); private static final BooleanCondition anot = new BooleanCondition(a.getConditionValue(), true); private static final BooleanCondition b = new BooleanCondition(new MockInsn('b'), false); private static final BooleanCondition bnot = new BooleanCondition(b.getConditionValue(), true); private static final BooleanCondition c = new BooleanCondition(new MockInsn('c'), false); private static final BooleanCondition d = new BooleanCondition(new MockInsn('d'), false); private static final BooleanCondition e = new BooleanCondition(new MockInsn('e'), false); private static OrCondition or(Condition... c) { return new OrCondition(c); } private static AndCondition and(Condition... c) { return new AndCondition(c); } @Test public void testTrivial() { Condition complex = a; Condition simple = a; Condition simplified = ConditionUtil.simplifyCondition(complex); assertEquals(simple, simplified); } @Test public void testTrivial2() { Condition complex = or(a, a); Condition simple = a; Condition simplified = ConditionUtil.simplifyCondition(complex); assertEquals(simple, simplified); } @Test public void testTrivial3() { Condition complex = or(a, and(a, b)); Condition simple = a; Condition simplified = ConditionUtil.simplifyCondition(complex); assertEquals(simple, simplified); } @Test public void testTrivial4() { Condition complex = or(a, and(anot, b)); Condition simple = or(a, b); Condition simplified = ConditionUtil.simplifyCondition(complex); assertEquals(simple, simplified); } @Test public void testTrivial5() { Condition complex = or(a, and(anot, b), and(b, c)); Condition simple = or(a, b); Condition simplified = ConditionUtil.simplifyCondition(complex); assertEquals(simple, simplified); } @Test public void testTrivial6() { Condition complex = or(and(a, b), and(a, bnot, c)); Condition simple = and(a, or(b, c)); Condition simplified = ConditionUtil.simplifyCondition(complex); assertEquals(simple, simplified); } @Test public void testTrivial7() { Condition complex = or(and(a, b), and(a, bnot)); Condition simple = a; Condition simplified = ConditionUtil.simplifyCondition(complex); assertEquals(simple, simplified); } @Test public void testTrivial8() { Condition complex = or(and(a, b), and(a, c), and(d, b), and(d, c)); Condition simple = and(or(a, d), or(b, c)); Condition simplified = ConditionUtil.simplifyCondition(complex); assertEquals(simple, simplified); } @Test public void testTrivial9() { Condition complex = or(and(a, b), and(a, c), and(d, a), and(d, c)); Condition simple = or(and(a, or(b, c, d)), and(d, c)); Condition simplified = ConditionUtil.simplifyCondition(complex); assertEquals(simple, simplified); } @Test public void testTrivial10() { Condition complex = or(and(a, b), and(a, c), and(d, c), and(d, e)); Condition simple = or(and(a, or(b, c)), and(d, or(c, e))); Condition simplified = ConditionUtil.simplifyCondition(complex); assertEquals(simple, simplified); } @Test public void testTrivial11() { Condition complex = or(and(a, d), and(e, d), and(b, c)); Condition simple = or(and(or(a, e), d), and(b, c)); Condition simplified = ConditionUtil.simplifyCondition(complex); assertEquals(simple, simplified); } @Test public void testTrivial12() { Condition complex = or(a, and(b, b)); Condition simple = or(a, b); Condition simplified = ConditionUtil.simplifyCondition(complex); assertEquals(simple, simplified); } private static class MockInsn implements Instruction { private char c; public MockInsn(char c) { this.c = c; } @Override public TypeSignature inferType() { return ClassTypeSignature.INT; } @Override public void accept(AstVisitor visitor) { } @Override public String toString() { return this.c + ""; } @Override public void writeTo(MessagePacker pack) throws IOException { } } }
java
MIT
e60cfaaf7a0688bc83f8b00c392521d0b162afba
2026-01-05T02:42:07.381192Z
false
Despector/Despector
https://github.com/Despector/Despector/blob/e60cfaaf7a0688bc83f8b00c392521d0b162afba/src/test/java/org/spongepowered/test/ast/FullClassTests.java
src/test/java/org/spongepowered/test/ast/FullClassTests.java
/* * The MIT License (MIT) * * Copyright (c) Despector <https://despector.voxelgenesis.com> * Copyright (c) contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package org.spongepowered.test.ast; import org.junit.Assert; import org.junit.BeforeClass; import org.junit.Test; import org.spongepowered.despector.Language; import org.spongepowered.despector.ast.SourceSet; import org.spongepowered.despector.ast.type.TypeEntry; import org.spongepowered.despector.config.LibraryConfiguration; import org.spongepowered.despector.decompiler.BaseDecompiler; import org.spongepowered.despector.decompiler.Decompiler; import org.spongepowered.despector.decompiler.Decompilers; import org.spongepowered.despector.emitter.Emitters; import org.spongepowered.despector.emitter.format.EmitterFormat; import org.spongepowered.despector.emitter.java.JavaEmitterContext; import java.io.IOException; import java.io.InputStream; import java.io.StringWriter; import java.net.URISyntaxException; import java.net.URL; import java.nio.file.Files; import java.nio.file.Paths; public class FullClassTests { @BeforeClass public static void setup() { LibraryConfiguration.quiet = false; LibraryConfiguration.parallel = false; } // TODO: auto-detect all test cases and generate a junit test per file @Test public void testBasic() throws Exception { compare("javaclasses/BasicClass", Language.JAVA); } @Test public void testGenerics() throws Exception { compare("javaclasses/GenericsTestClass", Language.JAVA); } public static void compare(String classname, Language lang) throws IOException, URISyntaxException { URL source = Thread.currentThread().getContextClassLoader().getResource(classname + ".java.test"); InputStream compiled = Thread.currentThread().getContextClassLoader().getResourceAsStream(classname + ".class.test"); if (source == null) { Assert.fail("Resource not found " + classname + ".java.test"); } if (compiled == null) { Assert.fail("Resource not found " + classname + ".class.test"); } SourceSet src = new SourceSet(); Decompiler decomp = Decompilers.get(lang); TypeEntry type = decomp.decompile(compiled, src); ((BaseDecompiler) decomp).flushTasks(); StringWriter writer = new StringWriter(); JavaEmitterContext ctx = new JavaEmitterContext(writer, EmitterFormat.defaults()); Emitters.get(lang).emit(ctx, type); String source_str = new String(Files.readAllBytes(Paths.get(source.toURI()))).replaceAll("\r\n", "\n"); Assert.assertEquals(source_str, writer.toString()); } }
java
MIT
e60cfaaf7a0688bc83f8b00c392521d0b162afba
2026-01-05T02:42:07.381192Z
false
Despector/Despector
https://github.com/Despector/Despector/blob/e60cfaaf7a0688bc83f8b00c392521d0b162afba/src/test/java/org/spongepowered/test/serialization/MessagePackTest.java
src/test/java/org/spongepowered/test/serialization/MessagePackTest.java
/* * The MIT License (MIT) * * Copyright (c) Despector <https://despector.voxelgenesis.com> * Copyright (c) contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package org.spongepowered.test.serialization; import static org.junit.Assert.assertEquals; import org.junit.Test; import org.spongepowered.despector.util.serialization.MessagePacker; import org.spongepowered.despector.util.serialization.MessageUnpacker; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; public class MessagePackTest { @Test public void testNil() throws IOException { ByteArrayOutputStream out = new ByteArrayOutputStream(); try (MessagePacker msg = new MessagePacker(out)) { msg.startMap(2); msg.writeString("val1").writeNil(); } ByteArrayInputStream in = new ByteArrayInputStream(out.toByteArray()); try (MessageUnpacker unpack = new MessageUnpacker(in)) { int len = unpack.readMap(); assertEquals(2, len); assertEquals("val1", unpack.readString()); unpack.readNil(); } } @Test public void testBool() throws IOException { ByteArrayOutputStream out = new ByteArrayOutputStream(); try (MessagePacker msg = new MessagePacker(out)) { msg.startMap(2); msg.writeString("val1").writeBool(true); msg.writeString("val2").writeBool(false); } ByteArrayInputStream in = new ByteArrayInputStream(out.toByteArray()); try (MessageUnpacker unpack = new MessageUnpacker(in)) { int len = unpack.readMap(); assertEquals(2, len); assertEquals("val1", unpack.readString()); assertEquals(true, unpack.readBool()); assertEquals("val2", unpack.readString()); assertEquals(false, unpack.readBool()); } } @Test public void testInt() throws IOException { ByteArrayOutputStream out = new ByteArrayOutputStream(); try (MessagePacker msg = new MessagePacker(out)) { msg.startMap(6); msg.writeString("val1").writeInt(5); msg.writeString("val2").writeInt(-5); msg.writeString("val3").writeInt(86); msg.writeString("val4").writeInt(500); msg.writeString("val5").writeInt(150000); msg.writeString("val6").writeInt(5000000000L); } ByteArrayInputStream in = new ByteArrayInputStream(out.toByteArray()); try (MessageUnpacker unpack = new MessageUnpacker(in)) { int len = unpack.readMap(); assertEquals(6, len); assertEquals("val1", unpack.readString()); assertEquals(5, unpack.readInt()); assertEquals("val2", unpack.readString()); assertEquals(-5, unpack.readInt()); assertEquals("val3", unpack.readString()); assertEquals(86, unpack.readInt()); assertEquals("val4", unpack.readString()); assertEquals(500, unpack.readInt()); assertEquals("val5", unpack.readString()); assertEquals(150000, unpack.readInt()); assertEquals("val6", unpack.readString()); assertEquals(5000000000L, unpack.readLong()); } } @Test public void testFloat() throws IOException { ByteArrayOutputStream out = new ByteArrayOutputStream(); try (MessagePacker msg = new MessagePacker(out)) { msg.startMap(2); msg.writeString("val1").writeFloat(0.5f); msg.writeString("val2").writeDouble(0.5); } ByteArrayInputStream in = new ByteArrayInputStream(out.toByteArray()); try (MessageUnpacker unpack = new MessageUnpacker(in)) { int len = unpack.readMap(); assertEquals(2, len); assertEquals("val1", unpack.readString()); assertEquals(0.5f, unpack.readFloat(), 0.001f); assertEquals("val2", unpack.readString()); assertEquals(0.5, unpack.readDouble(), 0.001); } } @Test public void testString() throws IOException { ByteArrayOutputStream out = new ByteArrayOutputStream(); try (MessagePacker msg = new MessagePacker(out)) { msg.startMap(2); msg.writeString("val1").writeString("Hello"); msg.writeString("val2").writeString("This string is longer than 31 bytes and therefore will be encoded as a TYTE_STR8"); } ByteArrayInputStream in = new ByteArrayInputStream(out.toByteArray()); try (MessageUnpacker unpack = new MessageUnpacker(in)) { int len = unpack.readMap(); assertEquals(2, len); assertEquals("val1", unpack.readString()); assertEquals("Hello", unpack.readString()); assertEquals("val2", unpack.readString()); assertEquals("This string is longer than 31 bytes and therefore will be encoded as a TYTE_STR8", unpack.readString()); } } }
java
MIT
e60cfaaf7a0688bc83f8b00c392521d0b162afba
2026-01-05T02:42:07.381192Z
false
Despector/Despector
https://github.com/Despector/Despector/blob/e60cfaaf7a0688bc83f8b00c392521d0b162afba/src/test/java/org/spongepowered/test/serialization/SignatureSerializationTest.java
src/test/java/org/spongepowered/test/serialization/SignatureSerializationTest.java
/* * The MIT License (MIT) * * Copyright (c) Despector <https://despector.voxelgenesis.com> * Copyright (c) contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package org.spongepowered.test.serialization; import org.junit.Assert; import org.junit.Test; import org.spongepowered.despector.ast.generic.ClassTypeSignature; import org.spongepowered.despector.ast.generic.GenericClassTypeSignature; import org.spongepowered.despector.ast.generic.TypeArgument; import org.spongepowered.despector.ast.generic.TypeSignature; import org.spongepowered.despector.ast.generic.TypeVariableSignature; import org.spongepowered.despector.ast.generic.VoidTypeSignature; import org.spongepowered.despector.ast.generic.WildcardType; import org.spongepowered.despector.util.serialization.AstLoader; import org.spongepowered.despector.util.serialization.MessagePacker; import org.spongepowered.despector.util.serialization.MessageUnpacker; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; public class SignatureSerializationTest { @Test public void testVoid() throws IOException { TypeSignature sig = VoidTypeSignature.VOID; ByteArrayOutputStream out = new ByteArrayOutputStream(); MessagePacker pack = new MessagePacker(out); sig.writeTo(pack); MessageUnpacker unpack = new MessageUnpacker(new ByteArrayInputStream(out.toByteArray())); TypeSignature loaded = AstLoader.loadTypeSignature(unpack); Assert.assertEquals(sig, loaded); } @Test public void testClass() throws IOException { TypeSignature sig = ClassTypeSignature.of("Ljava/lang/String;"); ByteArrayOutputStream out = new ByteArrayOutputStream(); MessagePacker pack = new MessagePacker(out); sig.writeTo(pack); MessageUnpacker unpack = new MessageUnpacker(new ByteArrayInputStream(out.toByteArray())); TypeSignature loaded = AstLoader.loadTypeSignature(unpack); Assert.assertEquals(sig, loaded); } @Test public void testPrimative() throws IOException { TypeSignature sig = ClassTypeSignature.INT; ByteArrayOutputStream out = new ByteArrayOutputStream(); MessagePacker pack = new MessagePacker(out); sig.writeTo(pack); MessageUnpacker unpack = new MessageUnpacker(new ByteArrayInputStream(out.toByteArray())); TypeSignature loaded = AstLoader.loadTypeSignature(unpack); Assert.assertEquals(sig, loaded); } @Test public void testGeneric() throws IOException { GenericClassTypeSignature sig = new GenericClassTypeSignature("Ljava/util/List;"); sig.getArguments().add(new TypeArgument(WildcardType.NONE, ClassTypeSignature.INTEGER_OBJECT)); ByteArrayOutputStream out = new ByteArrayOutputStream(); MessagePacker pack = new MessagePacker(out); sig.writeTo(pack); MessageUnpacker unpack = new MessageUnpacker(new ByteArrayInputStream(out.toByteArray())); TypeSignature loaded = AstLoader.loadTypeSignature(unpack); Assert.assertEquals(sig, loaded); } @Test public void testVar() throws IOException { TypeSignature sig = new TypeVariableSignature("T"); ByteArrayOutputStream out = new ByteArrayOutputStream(); MessagePacker pack = new MessagePacker(out); sig.writeTo(pack); MessageUnpacker unpack = new MessageUnpacker(new ByteArrayInputStream(out.toByteArray())); TypeSignature loaded = AstLoader.loadTypeSignature(unpack); Assert.assertEquals(sig, loaded); } }
java
MIT
e60cfaaf7a0688bc83f8b00c392521d0b162afba
2026-01-05T02:42:07.381192Z
false
Despector/Despector
https://github.com/Despector/Despector/blob/e60cfaaf7a0688bc83f8b00c392521d0b162afba/src/test/java/org/spongepowered/test/serialization/AstSerializationTest.java
src/test/java/org/spongepowered/test/serialization/AstSerializationTest.java
/* * The MIT License (MIT) * * Copyright (c) Despector <https://despector.voxelgenesis.com> * Copyright (c) contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package org.spongepowered.test.serialization; import org.junit.Assert; import org.junit.Test; import org.spongepowered.despector.ast.Locals; import org.spongepowered.despector.ast.Locals.Local; import org.spongepowered.despector.ast.Locals.LocalInstance; import org.spongepowered.despector.ast.SourceSet; import org.spongepowered.despector.ast.generic.ClassTypeSignature; import org.spongepowered.despector.ast.type.MethodEntry; import org.spongepowered.despector.util.serialization.AstLoader; import org.spongepowered.despector.util.serialization.MessagePacker; import org.spongepowered.despector.util.serialization.MessageUnpacker; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; public class AstSerializationTest { @Test public void testLocals() throws IOException { MethodEntry method = new MethodEntry(new SourceSet()); method.setStatic(false); Locals locals = new Locals(method); Local l = locals.getLocal(0); LocalInstance a = new LocalInstance(l, "this", null, -1, -1); l.addInstance(a); l = locals.getLocal(1); LocalInstance b = new LocalInstance(l, "i", ClassTypeSignature.INT, -1, -1); l.addInstance(b); ByteArrayOutputStream out = new ByteArrayOutputStream(); MessagePacker pack = new MessagePacker(out); locals.writeTo(pack); MessageUnpacker unpack = new MessageUnpacker(new ByteArrayInputStream(out.toByteArray())); Locals loaded = AstLoader.loadLocals(unpack, method, new SourceSet()); l = loaded.getLocal(0); Assert.assertEquals(a, l.getParameterInstance()); l = loaded.getLocal(1); Assert.assertEquals(b, l.getParameterInstance()); } }
java
MIT
e60cfaaf7a0688bc83f8b00c392521d0b162afba
2026-01-05T02:42:07.381192Z
false
Despector/Despector
https://github.com/Despector/Despector/blob/e60cfaaf7a0688bc83f8b00c392521d0b162afba/src/main/java/org/spongepowered/despector/package-info.java
src/main/java/org/spongepowered/despector/package-info.java
/* * The MIT License (MIT) * * Copyright (c) Despector <https://despector.voxelgenesis.com> * Copyright (c) contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ @org.spongepowered.despector.util.NonnullByDefault package org.spongepowered.despector;
java
MIT
e60cfaaf7a0688bc83f8b00c392521d0b162afba
2026-01-05T02:42:07.381192Z
false
Despector/Despector
https://github.com/Despector/Despector/blob/e60cfaaf7a0688bc83f8b00c392521d0b162afba/src/main/java/org/spongepowered/despector/Despector.java
src/main/java/org/spongepowered/despector/Despector.java
/* * The MIT License (MIT) * * Copyright (c) Despector <https://despector.voxelgenesis.com> * Copyright (c) contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package org.spongepowered.despector; import org.spongepowered.despector.ast.SourceSet; import org.spongepowered.despector.ast.type.TypeEntry; import org.spongepowered.despector.config.ConfigBase.CleanupConfigSection; import org.spongepowered.despector.config.ConfigManager; import org.spongepowered.despector.config.LibraryConfiguration; import org.spongepowered.despector.decompiler.BaseDecompiler; import org.spongepowered.despector.decompiler.Decompiler; import org.spongepowered.despector.decompiler.Decompilers; import org.spongepowered.despector.decompiler.DirectoryWalker; import org.spongepowered.despector.decompiler.JarWalker; import org.spongepowered.despector.emitter.Emitter; import org.spongepowered.despector.emitter.Emitters; import org.spongepowered.despector.emitter.format.EmitterFormat; import org.spongepowered.despector.emitter.format.FormatLoader; import org.spongepowered.despector.emitter.java.JavaEmitterContext; import org.spongepowered.despector.parallel.Timing; import org.spongepowered.despector.transform.TypeTransformer; import org.spongepowered.despector.transform.cleanup.CleanupOperations; import java.io.FileWriter; import java.io.IOException; import java.io.InputStream; import java.io.StringWriter; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.function.Consumer; /** * Despector. */ public final class Despector { private static final Map<String, Consumer<String>> flags = new HashMap<>(); public static Language LANGUAGE = Language.ANY; static { flags.put("--config=", (arg) -> { String config = arg.substring(9); Path config_path = Paths.get(".").resolve(config); ConfigManager.load(config_path); }); flags.put("--lang=", (arg) -> { String lang = arg.substring(7); if ("kotlin".equalsIgnoreCase(lang)) { LANGUAGE = Language.KOTLIN; } else if ("java".equalsIgnoreCase(lang)) { LANGUAGE = Language.JAVA; } else if ("any".equalsIgnoreCase(lang)) { LANGUAGE = Language.ANY; } else { System.err.println("Unknown language: " + lang); System.err.println("Options are: java, kotlin, any"); System.exit(0); } }); } /** * Decompiles the given {@link InputStream}. */ public static TypeEntry decompile(InputStream input) throws IOException { SourceSet source = new SourceSet(); return decompile(input, source, Language.ANY); } /** * Decompiles the given {@link InputStream} as the given language. */ public static TypeEntry decompile(InputStream input, Language lang) throws IOException { return decompile(input, new SourceSet(), lang); } /** * Decompiles the given {@link InputStream} with the given loader for * additional types. */ public static TypeEntry decompile(InputStream input, SourceSet.Loader loader) throws IOException { SourceSet source = new SourceSet(); source.setLoader(loader); return decompile(input, source); } /** * Decompiles the given {@link InputStream} with the given language and * loader for additional types. */ public static TypeEntry decompile(InputStream input, Language lang, SourceSet.Loader loader) throws IOException { SourceSet source = new SourceSet(); source.setLoader(loader); return decompile(input, source, lang); } /** * Decompiles the given {@link InputStream} into the given source set. */ public static TypeEntry decompile(InputStream input, SourceSet source) throws IOException { return decompile(input, source, Language.ANY); } /** * Decompiles the given {@link InputStream} with the given language into the * given source set. */ public static TypeEntry decompile(InputStream input, SourceSet source, Language lang) throws IOException { TypeEntry type = Decompilers.get(lang).decompile(input, source); return type; } /** * Emits the given type entry to a string. */ public static String emitToString(TypeEntry type) { StringWriter writer = new StringWriter(); JavaEmitterContext ctx = new JavaEmitterContext(writer, EmitterFormat.defaults()); Emitters.get(type.getLanguage()).emit(ctx, type); return writer.toString(); } /** * The main entrance point. */ public static void main(String[] args) throws IOException { if (args.length < 2) { System.out.println("Usage: java -jar Despector.jar [sources...] [destination]"); return; } List<String> sources = new ArrayList<>(); outer: for (int i = 0; i < args.length - 1; i++) { if (args[i].startsWith("-")) { for (String flag : flags.keySet()) { if (args[i].startsWith(flag)) { flags.get(flag).accept(args[i]); continue outer; } } System.err.println("Unknown flag: " + args[i]); } else { sources.add(args[i]); } } String destination = args[args.length - 1]; Path output = Paths.get(destination).toAbsolutePath(); if (!Files.exists(output)) { Files.createDirectories(output); } EmitterFormat formatter = EmitterFormat.defaults(); formatter.loadFrom(ConfigManager.getConfig().formatter); Path formatter_path = Paths.get(".").resolve(ConfigManager.getConfig().emitter.formatting_path); Path importorder_path = Paths.get(".").resolve(ConfigManager.getConfig().emitter.imports_path); if (Files.exists(formatter_path) && Files.exists(importorder_path)) { FormatLoader formatter_loader = FormatLoader.getLoader(ConfigManager.getConfig().emitter.formatting_type); formatter_loader.load(formatter, formatter_path, importorder_path); } Decompiler decompiler = Decompilers.get(LANGUAGE); if (LibraryConfiguration.parallel) { System.out.println("Running parallel decompile with " + Runtime.getRuntime().availableProcessors() + " workers"); } SourceSet source = new SourceSet(); for (String s : sources) { Path path = Paths.get(s); if (!Files.exists(path)) { System.err.println("Unknown source: " + path.toAbsolutePath().toString()); } else if (s.endsWith(".jar")) { JarWalker walker = new JarWalker(path); walker.walk(source, decompiler); } else if (Files.isDirectory(path)) { DirectoryWalker walker = new DirectoryWalker(path); try { walker.walk(source, decompiler); } catch (IOException e) { System.err.println("Error while walking directory: " + path.toAbsolutePath().toString()); e.printStackTrace(); } } else if (s.endsWith(".class")) { decompiler.decompile(path, source); } else { System.err.println("Unknown source type: " + path.toAbsolutePath().toString() + " must be jar or directory"); } } if (LibraryConfiguration.parallel && decompiler instanceof BaseDecompiler) { ((BaseDecompiler) decompiler).flushTasks(); } if (source.getAllClasses().isEmpty()) { System.err.println("No sources found."); return; } List<TypeTransformer> transformers = new ArrayList<>(); for (String operation : ConfigManager.getConfig().cleanup.operations) { TypeTransformer transformer = CleanupOperations.getOperation(operation); if (transformer == null) { System.err.println("Unknown cleanup operation: " + operation); } else { transformers.add(transformer); } } Map<String, Set<TypeTransformer>> targeted_transformers = new HashMap<>(); for (CleanupConfigSection section : ConfigManager.getConfig().cleanup_sections) { List<TypeTransformer> trans = new ArrayList<>(); for (String operation : section.operations) { TypeTransformer transformer = CleanupOperations.getOperation(operation); if (transformer == null) { System.err.println("Unknown cleanup operation: " + operation); } else { trans.add(transformer); } } for (String target : section.targets) { Set<TypeTransformer> target_trans = targeted_transformers.get(target); if (target_trans == null) { target_trans = new HashSet<>(); targeted_transformers.put(target, target_trans); } target_trans.addAll(trans); } } if (!transformers.isEmpty() || !targeted_transformers.isEmpty()) { for (TypeEntry type : source.getAllClasses()) { for (TypeTransformer transformer : transformers) { transformer.transform(type); } Set<TypeTransformer> targetted = targeted_transformers.get(type.getName()); if (targetted != null) { for (TypeTransformer transformer : targetted) { transformer.transform(type); } } } } Emitter<JavaEmitterContext> emitter = Emitters.get(LANGUAGE); for (TypeEntry type : source.getAllClasses()) { if (type.isInnerClass() || type.isAnonType()) { continue; } Path out = output.resolve(type.getName() + LANGUAGE.getExtension(type)); if (!Files.exists(out.getParent())) { Files.createDirectories(out.getParent()); } try (FileWriter writer = new FileWriter(out.toFile())) { JavaEmitterContext ctx = new JavaEmitterContext(writer, formatter); emitter.emit(ctx, type); } } if (LibraryConfiguration.print_times) { System.out.println("Time spend decompiling: " + (Timing.time_decompiling / 1000000) + "ms"); System.out.println("Time spend decompiling methods: " + (Timing.time_decompiling_methods / 1000000) + "ms"); System.out.println("Time spend loading classes: " + (Timing.time_loading_classes / 1000000) + "ms"); System.out.println("Time spend emitting: " + (Timing.time_emitting / 1000000) + "ms"); } } private Despector() { } }
java
MIT
e60cfaaf7a0688bc83f8b00c392521d0b162afba
2026-01-05T02:42:07.381192Z
false
Despector/Despector
https://github.com/Despector/Despector/blob/e60cfaaf7a0688bc83f8b00c392521d0b162afba/src/main/java/org/spongepowered/despector/Language.java
src/main/java/org/spongepowered/despector/Language.java
/* * The MIT License (MIT) * * Copyright (c) Despector <https://despector.voxelgenesis.com> * Copyright (c) contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package org.spongepowered.despector; import org.spongepowered.despector.ast.type.TypeEntry; /** * Represents a source language. */ public enum Language { JAVA(".java"), KOTLIN(".kt"), ANY(null); private final String ext; Language(String ext) { this.ext = ext; } /** * Gets the type extension for this language. */ public String getExtension(TypeEntry type) { if (this.ext != null) { return this.ext; } return type.getLanguage().getExtension(type); } }
java
MIT
e60cfaaf7a0688bc83f8b00c392521d0b162afba
2026-01-05T02:42:07.381192Z
false
Despector/Despector
https://github.com/Despector/Despector/blob/e60cfaaf7a0688bc83f8b00c392521d0b162afba/src/main/java/org/spongepowered/despector/util/NonnullByDefault.java
src/main/java/org/spongepowered/despector/util/NonnullByDefault.java
/* * The MIT License (MIT) * * Copyright (c) Despector <https://despector.voxelgenesis.com> * Copyright (c) contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package org.spongepowered.despector.util; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import javax.annotation.Nonnull; import javax.annotation.meta.TypeQualifierDefault; /** * An annotation marking that all elements are non-null by default. */ @Nonnull @TypeQualifierDefault({ ElementType.FIELD, ElementType.METHOD, ElementType.PARAMETER }) @Retention(RetentionPolicy.RUNTIME) public @interface NonnullByDefault { }
java
MIT
e60cfaaf7a0688bc83f8b00c392521d0b162afba
2026-01-05T02:42:07.381192Z
false
Despector/Despector
https://github.com/Despector/Despector/blob/e60cfaaf7a0688bc83f8b00c392521d0b162afba/src/main/java/org/spongepowered/despector/util/package-info.java
src/main/java/org/spongepowered/despector/util/package-info.java
/* * The MIT License (MIT) * * Copyright (c) Despector <https://despector.voxelgenesis.com> * Copyright (c) contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ @org.spongepowered.despector.util.NonnullByDefault package org.spongepowered.despector.util;
java
MIT
e60cfaaf7a0688bc83f8b00c392521d0b162afba
2026-01-05T02:42:07.381192Z
false
Despector/Despector
https://github.com/Despector/Despector/blob/e60cfaaf7a0688bc83f8b00c392521d0b162afba/src/main/java/org/spongepowered/despector/util/DebugUtil.java
src/main/java/org/spongepowered/despector/util/DebugUtil.java
/* * The MIT License (MIT) * * Copyright (c) Despector <https://despector.voxelgenesis.com> * Copyright (c) contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package org.spongepowered.despector.util; import org.spongepowered.despector.decompiler.ir.Insn; public class DebugUtil { private static final String[] opcodes = new String[256]; static { opcodes[Insn.NOOP] = "NOOP"; opcodes[Insn.PUSH] = "PUSH"; opcodes[Insn.ICONST] = "ICONST"; opcodes[Insn.LCONST] = "LCONST"; opcodes[Insn.FCONST] = "FCONST"; opcodes[Insn.DCONST] = "DCONST"; opcodes[Insn.LOCAL_LOAD] = "LOCAL_LOAD"; opcodes[Insn.LOCAL_STORE] = "LOCAL_STORE"; opcodes[Insn.ARRAY_LOAD] = "ARRAY_LOAD"; opcodes[Insn.ARRAY_STORE] = "ARRAY_STORE"; opcodes[Insn.GETFIELD] = "GETFIELD"; opcodes[Insn.PUTFIELD] = "PUTFIELD"; opcodes[Insn.GETSTATIC] = "GETSTATIC"; opcodes[Insn.PUTSTATIC] = "PUTSTATIC"; opcodes[Insn.INVOKE] = "INVOKE"; opcodes[Insn.INVOKESTATIC] = "INVOKESTATIC"; opcodes[Insn.NEW] = "NEW"; opcodes[Insn.NEWARRAY] = "NEWARRAY"; opcodes[Insn.THROW] = "THROW"; opcodes[Insn.RETURN] = "RETURN"; opcodes[Insn.ARETURN] = "ARETURN"; opcodes[Insn.POP] = "POP"; opcodes[Insn.DUP] = "DUP"; opcodes[Insn.DUP_X1] = "DUP_X1"; opcodes[Insn.DUP_X2] = "DUP_X2"; opcodes[Insn.DUP2] = "DUP2"; opcodes[Insn.DUP2_X1] = "DUP2_X1"; opcodes[Insn.DUP2_X2] = "DUP2_X2"; opcodes[Insn.SWAP] = "SWAP"; opcodes[Insn.ADD] = "ADD"; opcodes[Insn.SUB] = "SUB"; opcodes[Insn.MUL] = "MUL"; opcodes[Insn.DIV] = "DIV"; opcodes[Insn.REM] = "REM"; opcodes[Insn.NEG] = "NEG"; opcodes[Insn.SHL] = "SHL"; opcodes[Insn.SHR] = "SHR"; opcodes[Insn.USHR] = "USHR"; opcodes[Insn.AND] = "AND"; opcodes[Insn.OR] = "OR"; opcodes[Insn.XOR] = "XOR"; opcodes[Insn.IINC] = "IINC"; opcodes[Insn.CMP] = "CMP"; opcodes[Insn.IFEQ] = "IFEQ"; opcodes[Insn.IFNE] = "IFNE"; opcodes[Insn.IF_CMPLT] = "IF_CMPLT"; opcodes[Insn.IF_CMPLE] = "IF_CMPLE"; opcodes[Insn.IF_CMPGE] = "IF_CMPGE"; opcodes[Insn.IF_CMPGT] = "IF_CMPGT"; opcodes[Insn.IF_CMPEQ] = "IF_CMPEQ"; opcodes[Insn.IF_CMPNE] = "IF_CMPNE"; opcodes[Insn.GOTO] = "GOTO"; opcodes[Insn.SWITCH] = "SWITCH"; } public static String opcodeToString(int opcode) { return opcodes[opcode]; } private DebugUtil() { } }
java
MIT
e60cfaaf7a0688bc83f8b00c392521d0b162afba
2026-01-05T02:42:07.381192Z
false
Despector/Despector
https://github.com/Despector/Despector/blob/e60cfaaf7a0688bc83f8b00c392521d0b162afba/src/main/java/org/spongepowered/despector/util/TypeHelper.java
src/main/java/org/spongepowered/despector/util/TypeHelper.java
/* * The MIT License (MIT) * * Copyright (c) Despector <https://despector.voxelgenesis.com> * Copyright (c) contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package org.spongepowered.despector.util; import com.google.common.base.Throwables; import com.google.common.collect.Lists; import java.util.BitSet; import java.util.List; import java.util.regex.Matcher; import java.util.regex.Pattern; /** * Various utility methods for working with types. */ public final class TypeHelper { private static final Pattern ANON_CLASS = Pattern.compile(".*\\$[0-9]+"); public static boolean isAnonClass(String name) { return ANON_CLASS.matcher(name).matches(); } public static String descToTypeName(String desc) { return descToType(desc).replace('/', '.'); } /** * Converts a description to a type name. */ public static String descToType(String desc) { if (desc.startsWith("[")) { return descToType(desc.substring(1)) + "[]"; } if (desc.startsWith("L") && desc.endsWith(";")) { return desc.substring(1, desc.length() - 1); } if (desc.startsWith("T")) { // TODO parse the bounds of the generic return "java/lang/Object"; } if (desc.equals("I")) { return "int"; } if (desc.equals("S")) { return "short"; } if (desc.equals("B")) { return "byte"; } if (desc.equals("Z")) { return "boolean"; } if (desc.equals("F")) { return "float"; } if (desc.equals("D")) { return "double"; } if (desc.equals("J")) { return "long"; } if (desc.equals("C")) { return "char"; } if (desc.equals("V")) { return "void"; } return desc; } /** * Resolves the given type name to the actual class. */ public static Class<?> classForTypeName(String obf) { Class<?> actual_class = null; if ("void".equals(obf)) { actual_class = void.class; } else if ("char".equals(obf)) { actual_class = char.class; } else if ("boolean".equals(obf)) { actual_class = boolean.class; } else if ("byte".equals(obf)) { actual_class = byte.class; } else if ("short".equals(obf)) { actual_class = short.class; } else if ("int".equals(obf)) { actual_class = int.class; } else if ("long".equals(obf)) { actual_class = long.class; } else if ("float".equals(obf)) { actual_class = float.class; } else if ("double".equals(obf)) { actual_class = double.class; } else { try { actual_class = Class.forName(obf.replace('/', '.')); } catch (ClassNotFoundException e) { System.err.println("Failed to find class " + obf + " on classpath"); Throwables.propagate(e); } } return actual_class; } /** * Counts the number of parameters in the given method signature. */ public static int paramCount(String sig) { if (sig == null) { return 0; } int depth = 0; int count = 0; for (int i = sig.indexOf('(') + 1; i < sig.length(); i++) { char next = sig.charAt(i); if (depth > 0) { if (next == '>') { depth--; } else if (next == '<') { depth++; } continue; } if (next == ')') { break; } if (next == '[') { continue; } if (next == '<') { depth++; } if (next == 'L' || next == 'T') { // Generics may be arbitrarily nested so we need to ensure we // parse until the ';' at the same level that we started. int generic_depth = 0; while (next != ';' || generic_depth > 0) { if (next == '<') { generic_depth++; next = sig.charAt(++i); continue; } if (generic_depth > 0) { if (next == '>') { generic_depth--; } else if (next == '<') { generic_depth++; } } next = sig.charAt(++i); } } count++; } return count; } /** * Gets the parameter types out of the given method signature. */ public static List<String> splitSig(String sig) { if (sig == null) { return null; } List<String> params = Lists.newArrayList(); String accu = ""; boolean is_array = false; int depth = 0; for (int i = sig.indexOf('(') + 1; i < sig.length(); i++) { char next = sig.charAt(i); if (depth > 0) { if (next == '>') { depth--; } else if (next == '<') { depth++; } continue; } if (next == ')') { break; } if (next == '[') { is_array = true; continue; } if (next == '<') { depth++; } if (next == 'L' || next == 'T') { int generics_depth = 0; while (next != ';' || generics_depth > 0) { if (next == '<') { generics_depth++; next = sig.charAt(++i); continue; } if (generics_depth > 0) { if (next == '>') { generics_depth--; } else if (next == '<') { generics_depth++; } } else { accu += next; } next = sig.charAt(++i); } accu += next; } else { accu += next; } if (is_array) { accu = "[" + accu; } params.add(accu); accu = ""; is_array = false; } return params; } private static final Pattern DESC = Pattern.compile("\\([^\\)]*\\)(.*)"); /** * Gets the return value from the given method signature. */ public static String getRet(String signature) { Matcher matcher = DESC.matcher(signature); if (matcher.find()) { return matcher.group(1); } throw new IllegalStateException("Expected return type, but '" + signature + "' is not a valid method signature"); } /** * Gets if the given name is a primative type. */ public static boolean isPrimative(String type) { if ("void".equals(type) || "boolean".equals(type) || "byte".equals(type) || "short".equals(type) || "int".equals(type) || "long".equals(type) || "float".equals(type) || "double".equals(type) || "char".equals(type)) { return true; } return false; } private static final BitSet DESCRIPTOR_CHARS = new BitSet(); public static boolean isDescriptor(String type) { return DESCRIPTOR_CHARS.get(type.charAt(0)); } static { DESCRIPTOR_CHARS.set('['); DESCRIPTOR_CHARS.set('L'); DESCRIPTOR_CHARS.set('B'); DESCRIPTOR_CHARS.set('C'); DESCRIPTOR_CHARS.set('S'); DESCRIPTOR_CHARS.set('I'); DESCRIPTOR_CHARS.set('J'); DESCRIPTOR_CHARS.set('F'); DESCRIPTOR_CHARS.set('D'); DESCRIPTOR_CHARS.set('Z'); DESCRIPTOR_CHARS.set('V'); } private TypeHelper() { } }
java
MIT
e60cfaaf7a0688bc83f8b00c392521d0b162afba
2026-01-05T02:42:07.381192Z
false
Despector/Despector
https://github.com/Despector/Despector/blob/e60cfaaf7a0688bc83f8b00c392521d0b162afba/src/main/java/org/spongepowered/despector/util/ConditionUtil.java
src/main/java/org/spongepowered/despector/util/ConditionUtil.java
/* * The MIT License (MIT) * * Copyright (c) Despector <https://despector.voxelgenesis.com> * Copyright (c) contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package org.spongepowered.despector.util; import org.spongepowered.despector.ast.insn.condition.AndCondition; import org.spongepowered.despector.ast.insn.condition.BooleanCondition; import org.spongepowered.despector.ast.insn.condition.CompareCondition; import org.spongepowered.despector.ast.insn.condition.Condition; import org.spongepowered.despector.ast.insn.condition.InverseCondition; import org.spongepowered.despector.ast.insn.condition.OrCondition; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; /** * A utility for operations on conditions. */ public final class ConditionUtil { /** * Creates the inverse of the given condition. Where it can this is * performed without resorting to wrapping in a {@link InverseCondition}. */ public static Condition inverse(Condition condition) { if (condition instanceof BooleanCondition) { BooleanCondition b = (BooleanCondition) condition; return new BooleanCondition(b.getConditionValue(), !b.isInverse()); } else if (condition instanceof AndCondition) { AndCondition and = (AndCondition) condition; List<Condition> args = new ArrayList<>(); for (Condition arg : and.getOperands()) { args.add(inverse(arg)); } return new OrCondition(args); } else if (condition instanceof OrCondition) { OrCondition and = (OrCondition) condition; List<Condition> args = new ArrayList<>(); for (Condition arg : and.getOperands()) { args.add(inverse(arg)); } return new AndCondition(args); } else if (condition instanceof CompareCondition) { CompareCondition cmp = (CompareCondition) condition; return new CompareCondition(cmp.getLeft(), cmp.getRight(), cmp.getOperator().inverse()); } return new InverseCondition(condition); } /** * Gets if two conditions are inverses of each other. */ public static boolean isInverse(Condition a, Condition other) { if (other instanceof BooleanCondition && a instanceof BooleanCondition) { BooleanCondition ab = (BooleanCondition) a; BooleanCondition ob = (BooleanCondition) other; return ab.getConditionValue().equals(ob.getConditionValue()) && ab.isInverse() != ob.isInverse(); } if (other instanceof CompareCondition && a instanceof CompareCondition) { CompareCondition ab = (CompareCondition) a; CompareCondition ob = (CompareCondition) other; return ab.getLeft().equals(ob.getLeft()) && ab.getRight().equals(ob.getRight()) && ab.getOperator() == ob.getOperator().inverse(); } return false; } private static int getMapping(Map<Condition, Integer> mapping, Condition condition) { if (mapping.containsKey(condition)) { return mapping.get(condition); } int highest = 1; for (Condition key : mapping.keySet()) { int kvalue = mapping.get(key); if (isInverse(condition, key)) { mapping.put(condition, -kvalue); return -kvalue; } if (condition.equals(key)) { mapping.put(condition, kvalue); return kvalue; } if (kvalue >= highest) { highest = kvalue + 1; } } mapping.put(condition, highest); return highest; } private static int[] encode(AndCondition and, Map<Condition, Integer> mapping) { int[] encoding = new int[and.getOperands().size()]; int i = 0; Set<Integer> seen = new HashSet<>(); for (Condition c : and.getOperands()) { int m = getMapping(mapping, c); if (seen.contains(m)) { continue; } seen.add(m); encoding[i++] = m; } if (i < encoding.length) { return Arrays.copyOf(encoding, i); } return encoding; } /** * Gets is the first param contains the inverse of the second param. */ private static boolean containsInverse(int[] a, int[] b) { outer: for (int i = 0; i < b.length; i++) { int next = b[i]; for (int o = 0; o < a.length; o++) { if (a[o] == -next) { continue outer; } } return false; } return true; } private static boolean isInverse(int[] a, int[] b) { if (a.length != b.length) { return false; } outer: for (int i = 0; i < b.length; i++) { int next = b[i]; for (int o = 0; o < a.length; o++) { if (a[o] == -next) { continue outer; } } return false; } return true; } /** * Gets is the first param contains the second param. */ private static boolean contains(int[] a, int[] b) { outer: for (int i = 0; i < b.length; i++) { int next = b[i]; for (int o = 0; o < a.length; o++) { if (a[o] == next) { continue outer; } } return false; } return true; } private static boolean contains(int[] a, int b) { for (int o = 0; o < a.length; o++) { if (a[o] == b) { return true; } } return false; } /** * Removes a sub part from a larger term. Be sure to check that the term * contains the subpart <strong>before</strong> calling this. */ private static int[] remove(int[] next, int[] common) { int[] remaining = new int[next.length - common.length]; int remaining_index = 0; int common_index = 0; for (int o = 0; o < next.length; o++) { if (common_index < common.length && next[o] == common[common_index]) { common_index++; } else { remaining[remaining_index++] = next[o]; } } if (common_index != common.length) { return null; } return remaining; } private static int[] findCommonSubpart(int[] a, int[] b) { int[] common = new int[Math.max(a.length, b.length)]; int common_length = 0; for (int i = 0; i < a.length; i++) { for (int j = 0; j < b.length; j++) { if (a[i] == b[j]) { common[common_length++] = a[i]; break; } } } if (common_length == 0) { return null; } return Arrays.copyOf(common, common_length); } private static Pair<int[], int[]> simplifyCommonSubparts(int[] a, int[] b, List<int[]> encodings) { if (a.length < b.length) { return null; } int[] common = findCommonSubpart(a, b); if (common == null) { return null; } int common_length = common.length; int[] remaining_a = remove(a, common); int[] remaining_b = remove(b, common); if (isInverse(remaining_a, remaining_b)) { return new Pair<>(common, null); } else if (remaining_b.length == 1 && containsInverse(remaining_a, remaining_b)) { int[] new_m = new int[a.length - remaining_b.length]; int d = 0; outer: for (int j = 0; j < a.length; j++) { for (int v = 0; v < remaining_b.length; v++) { if (a[j] == -remaining_b[v]) { continue outer; } } new_m[d++] = a[j]; } return new Pair<>(new_m, null); } else if (remaining_a.length == remaining_b.length && remaining_a.length == 1) { int[] new_m = new int[common_length]; for (int i = 0; i < common_length; i++) { new_m[i] = common[i]; } int[] dm = new int[] {-remaining_a[0], -remaining_b[0]}; for (int i = 0; i < encodings.size(); i++) { int[] n = encodings.get(i); if (n == a || n == b) { continue; } if (n.length == 2 && contains(n, dm)) { return new Pair<>(null, new_m); } } } return null; } private static Condition reverse(Map<Condition, Integer> mapping, int val) { for (Map.Entry<Condition, Integer> e : mapping.entrySet()) { if (e.getValue() == val) { return e.getKey(); } } return null; } private static Condition decode(int[] next, Map<Condition, Integer> mapping) { List<Condition> partial = new ArrayList<>(); for (int o = 0; o < next.length; o++) { int val = next[o]; Condition p = reverse(mapping, val); if (p == null) { p = inverse(reverse(mapping, -val)); if (p == null) { throw new IllegalStateException(); } } partial.add(p); } if (partial.size() == 1) { return partial.get(0); } return new AndCondition(partial); } private static List<Condition> decode(List<int[]> encodings, Map<Condition, Integer> mapping) { List<Condition> reverse = new ArrayList<>(); for (int i = 0; i < encodings.size(); i++) { int[] next = encodings.get(i); reverse.add(decode(next, mapping)); } return reverse; } private static int countOccurances(List<int[]> encodings, int value) { int count = 0; for (int[] next : encodings) { if (contains(next, value)) { count++; } } return count; } private static BisectionResult findBiscection(List<int[]> encodings) { // This attempts to find a bisection of the terms. A bisection here // being a pair of values such that every term in the encoding contains // exactly one of the values. In other words the terms can be split into // two groups such that all members of one group contain the first value // and all members of the second group contain the second term. // this can probably be extended to find the n-section of the set but I // think this is sufficient for now. if (encodings.size() < 4) { if (encodings.size() >= 2) { int[] c = findCommonSubpart(encodings.get(0), encodings.get(1)); int[] p = c; if (c != null && encodings.size() == 3) { c = findCommonSubpart(c, encodings.get(2)); } if (c == null) { if (p != null) { List<int[]> r = new ArrayList<>(); int[] r2 = null; for (int[] e : encodings) { if (contains(e, p)) { r.add(remove(e, p)); } else { r2 = e; } } return new BisectionResult(p, r2, r, null); } return null; } List<int[]> r = new ArrayList<>(); for (int[] e : encodings) { if (contains(e, c)) { r.add(remove(e, c)); } } return new BisectionResult(c, null, r, null); } return null; } // if there is a bisection then there must be at least one common value // in the first three terms int[] a = findCommonSubpart(encodings.get(0), encodings.get(1)); if (a == null) { a = findCommonSubpart(encodings.get(0), encodings.get(2)); if (a == null) { return null; } } // We now want to find which value of the term is the most common if // there are more than one to give us the largest initial section. This // is not 100% reliable but we just have to take those punches or redo // the entire subsequent calculation attempting to find a bisection for // each possible term. Possible, but perhaps an exercise for later. int max = 0; int[] min_a = new int[1]; if (a.length > 1) { for (int j = 0; j < a.length; j++) { int c = countOccurances(encodings, a[j]); if (c > max) { max = c; min_a[0] = a[j]; } } } else { min_a[0] = a[0]; } List<int[]> remaining = new ArrayList<>(); for (int j = 0; j < encodings.size(); j++) { int[] next = encodings.get(j); int[] r = null; if (contains(next, min_a)) { r = remove(next, min_a); } remaining.add(r); } outer: for (int k = 1; k < a.length; k++) { int[] t = new int[] {a[k]}; for (int j = 0; j < encodings.size(); j++) { int[] next = remaining.get(j); if (next == null || !contains(next, t)) { continue outer; } } min_a = Arrays.copyOf(min_a, min_a.length + 1); min_a[min_a.length - 1] = a[k]; } List<int[]> untouched = new ArrayList<>(); for (int i = 0; i < encodings.size(); i++) { if (remaining.get(i) == null) { untouched.add(encodings.get(i)); } } List<int[]> group1 = new ArrayList<>(); for (int i = 0; i < remaining.size(); i++) { int[] n = remaining.get(i); if (n != null) { group1.add(n); } } if (untouched.size() == 0) { return new BisectionResult(min_a, null, group1, null); } else if (untouched.size() == 1) { return new BisectionResult(min_a, untouched.get(0), group1, null); } int[] b = findCommonSubpart(untouched.get(0), untouched.get(1)); for (int i = 2; i < untouched.size(); i++) { if (b == null) { break; } b = findCommonSubpart(b, encodings.get(i)); } if (b == null) { return new BisectionResult(min_a, null, group1, untouched); } List<int[]> remaining2 = new ArrayList<>(); for (int j = 0; j < untouched.size(); j++) { int[] next = untouched.get(j); int[] r = null; if (contains(next, b)) { r = remove(next, b); } remaining2.add(r); } return new BisectionResult(min_a, b, group1, remaining2); } private static Condition postsimplify(List<int[]> encodings, Map<Condition, Integer> mapping) { BisectionResult bisection = findBiscection(encodings); if (bisection != null) { if (bisection.second == null) { Condition common_condition = decode(bisection.first, mapping); List<Condition> operands = decode(bisection.first_remaining, mapping); if (bisection.second_remaining != null) { List<Condition> operands2 = decode(bisection.second_remaining, mapping); return new OrCondition(new AndCondition(common_condition, new OrCondition(operands)), new OrCondition(operands2)); } return new AndCondition(common_condition, new OrCondition(operands)); } List<int[]> a = bisection.first_remaining; List<int[]> b = bisection.second_remaining; Condition first = decode(bisection.first, mapping); Condition second = decode(bisection.second, mapping); if (b == null) { List<Condition> operands = decode(a, mapping); int[] t = null; for (int i = 0; i < encodings.size(); i++) { t = encodings.get(i); if (contains(t, bisection.first)) { break; } t = null; } if (t != null) { int i = 0; for (; i < t.length; i++) { if (t[i] == bisection.first[0]) { break; } } if (i < t.length / 2) { return new OrCondition(new AndCondition(first, new OrCondition(operands)), second); } return new OrCondition(new AndCondition(new OrCondition(operands), first), second); } return new OrCondition(new AndCondition(first, new OrCondition(operands)), second); } if (a.size() == b.size()) { boolean equal = true; // check if our groups are equal to each other, if they are then // we can make things even simpler outer: for (int i = 0; i < a.size(); i++) { int[] next = a.get(i); for (int j = 0; j < b.size(); j++) { int[] n = b.get(j); if (Arrays.equals(next, n)) { continue outer; } } equal = false; break; } if (equal) { // we have a proper bisection where both groups are also the // same and thus we have an equation of the form // (a + b)(c + d + ... + e) List<Condition> group = decode(a, mapping); return new AndCondition(new OrCondition(first, second), new OrCondition(group)); } } List<Condition> group = decode(bisection.first_remaining, mapping); List<Condition> group2 = decode(bisection.second_remaining, mapping); return new OrCondition(new AndCondition(first, new OrCondition(group)), new AndCondition(second, new OrCondition(group2))); } return null; } private static final boolean DEBUG_SIMPLIFICATION = Boolean.getBoolean("despect.debug.simplification"); /** * Attempts to simplify the given condition. */ public static Condition simplifyCondition(Condition condition) { // A brute force simplification of sum-of-products expressions if (condition instanceof OrCondition) { OrCondition or = (OrCondition) condition; List<int[]> encodings = new ArrayList<>(or.getOperands().size()); Map<Condition, Integer> mapping = new HashMap<>(); // Each of the conditions is encoded into an integer array, every // condition is inserted into a map to track an integer value for // each condition. Conditions that are equivalent are given the same // number and conditions that are inverses of each other are given // numbers which are the negative of each other. // This encoding allows very quick and easy comparisons of // whether conditions are equal or inverses of each other. // This simplification method is a massive fucking hack in an // attempt to more easily handle more than a small number of // conditions. The problem of minimizing boolean functions is // NP-hard and traditional solutions such as the Quine–McCluskey // algorithm start to require a prohibative amount of memory and // time with even a seemingly small number of conditions. // TODO: The Espresso heuristic logic minimizer may be worth looking // into for (int i = 0; i < or.getOperands().size(); i++) { Condition c = or.getOperands().get(i); if (c instanceof AndCondition) { encodings.add(encode((AndCondition) c, mapping)); } else { encodings.add(new int[] {getMapping(mapping, c)}); } } if (DEBUG_SIMPLIFICATION) { for (Map.Entry<Condition, Integer> e : mapping.entrySet()) { System.out.println(e.getKey() + " : " + e.getValue()); } System.out.print("Exp: "); for (int[] e : encodings) { for (int i = 0; i < e.length; i++) { System.out.print(e[i]); } System.out.print(" | "); } System.out.println(); } for (int j = 0; j < encodings.size(); j++) { for (int k = 0; k < encodings.size(); k++) { int[] n = encodings.get(k); for (Iterator<int[]> it = encodings.iterator(); it.hasNext();) { int[] m = it.next(); if (m == n || m.length < n.length) { continue; } // if m contains n either in whole or part then it can // be removed as any time n is true, m will also be true if (contains(m, n)) { it.remove(); if (DEBUG_SIMPLIFICATION) { System.out.println("Removed expression containing other expression"); System.out.print("Exp: "); for (int[] e : encodings) { for (int i = 0; i < e.length; i++) { System.out.print(e[i]); } System.out.print(" | "); } System.out.println(); } } } for (int l = 0; l < encodings.size(); l++) { if (l == k) { continue; } int[] m = encodings.get(l); // if m contains the inverse of n then those parts // corresponding to n can be removed from m if (n.length == 1 && containsInverse(m, n)) { int[] new_m = new int[m.length - n.length]; int d = 0; outer: for (int u = 0; u < m.length; u++) { for (int v = 0; v < n.length; v++) { if (m[u] == -n[v]) { continue outer; } } new_m[d++] = m[u]; } encodings.set(l, new_m); if (DEBUG_SIMPLIFICATION) { System.out.println("Removed inverse of other expression from expression"); System.out.print("Exp: "); for (int[] e : encodings) { for (int i = 0; i < e.length; i++) { System.out.print(e[i]); } System.out.print(" | "); } System.out.println(); } } else { // this extracts common subparts from m and n and // then performs a few simplifications ont he // remaining pieces. Pair<int[], int[]> s = simplifyCommonSubparts(m, n, encodings); if (s != null) { if (s.getFirst() != null) { encodings.set(l, s.getFirst()); if (DEBUG_SIMPLIFICATION) { System.out.println("Applied inverse removal to common sub part"); System.out.print("Exp: "); for (int[] e : encodings) { for (int i = 0; i < e.length; i++) { System.out.print(e[i]); } System.out.print(" | "); } System.out.println(); } } else { encodings.set(k, s.getSecond()); encodings.remove(l); if (DEBUG_SIMPLIFICATION) { System.out.println("Applied De Morgans law to common sub part"); System.out.print("Exp: "); for (int[] e : encodings) { for (int i = 0; i < e.length; i++) { System.out.print(e[i]); } System.out.print(" | "); } System.out.println(); } break; } } } } } } // postsimplify looks for common patterns and breaks them out Condition ps = postsimplify(encodings, mapping); if (ps != null) { return ps; } List<Condition> reverse = decode(encodings, mapping); if (encodings.size() == 1) { return reverse.get(0); } return new OrCondition(reverse); } return condition; } /** * A result of an attempted bisection of two conditions for a common sub * part. */ private static class BisectionResult { public int[] first; public int[] second; public List<int[]> first_remaining; public List<int[]> second_remaining; public BisectionResult(int[] f, int[] s, List<int[]> fr, List<int[]> sr) { this.first = f; this.second = s; this.first_remaining = fr; this.second_remaining = sr; } } private ConditionUtil() { } }
java
MIT
e60cfaaf7a0688bc83f8b00c392521d0b162afba
2026-01-05T02:42:07.381192Z
false
Despector/Despector
https://github.com/Despector/Despector/blob/e60cfaaf7a0688bc83f8b00c392521d0b162afba/src/main/java/org/spongepowered/despector/util/AstUtil.java
src/main/java/org/spongepowered/despector/util/AstUtil.java
/* * The MIT License (MIT) * * Copyright (c) Despector <https://despector.voxelgenesis.com> * Copyright (c) contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package org.spongepowered.despector.util; import org.spongepowered.despector.ast.Locals.LocalInstance; import org.spongepowered.despector.ast.insn.Instruction; import org.spongepowered.despector.ast.insn.InstructionVisitor; import org.spongepowered.despector.ast.insn.condition.Condition; import org.spongepowered.despector.ast.insn.cst.DoubleConstant; import org.spongepowered.despector.ast.insn.cst.FloatConstant; import org.spongepowered.despector.ast.insn.cst.IntConstant; import org.spongepowered.despector.ast.insn.cst.LongConstant; import org.spongepowered.despector.ast.insn.cst.NullConstant; import org.spongepowered.despector.ast.insn.cst.StringConstant; import org.spongepowered.despector.ast.insn.cst.TypeConstant; import org.spongepowered.despector.ast.insn.misc.Cast; import org.spongepowered.despector.ast.insn.misc.InstanceOf; import org.spongepowered.despector.ast.insn.misc.MultiNewArray; import org.spongepowered.despector.ast.insn.misc.NewArray; import org.spongepowered.despector.ast.insn.misc.NumberCompare; import org.spongepowered.despector.ast.insn.misc.Ternary; import org.spongepowered.despector.ast.insn.op.NegativeOperator; import org.spongepowered.despector.ast.insn.op.Operator; import org.spongepowered.despector.ast.insn.var.ArrayAccess; import org.spongepowered.despector.ast.insn.var.InstanceFieldAccess; import org.spongepowered.despector.ast.insn.var.LocalAccess; import org.spongepowered.despector.ast.insn.var.StaticFieldAccess; import org.spongepowered.despector.ast.stmt.Statement; import org.spongepowered.despector.ast.stmt.invoke.Lambda; import org.spongepowered.despector.ast.stmt.invoke.MethodReference; import org.spongepowered.despector.ast.stmt.invoke.InstanceMethodInvoke; import org.spongepowered.despector.ast.stmt.invoke.New; import org.spongepowered.despector.ast.stmt.invoke.StaticMethodInvoke; import org.spongepowered.despector.decompiler.ir.Insn; import org.spongepowered.despector.decompiler.ir.InvokeInsn; import org.spongepowered.despector.decompiler.ir.TypeIntInsn; import java.util.List; /** * Various utilities for working with AST elements. */ public final class AstUtil { /** * Gets the count of values consumed from the stack by the given opcode. */ public static int getStackRequirementsSize(Insn next) { if (next == null) { return 0; } switch (next.getOpcode()) { case -1: return 0; case Insn.ARRAY_STORE: return 3; case Insn.DUP2: case Insn.DUP2_X1: case Insn.DUP2_X2: case Insn.ARRAY_LOAD: case Insn.ADD: case Insn.SUB: case Insn.MUL: case Insn.DIV: case Insn.REM: case Insn.SHL: case Insn.SHR: case Insn.USHR: case Insn.AND: case Insn.OR: case Insn.XOR: case Insn.CMP: case Insn.IF_CMPEQ: case Insn.IF_CMPNE: case Insn.IF_CMPLT: case Insn.IF_CMPGE: case Insn.IF_CMPGT: case Insn.IF_CMPLE: case Insn.PUTFIELD: return 2; case Insn.DUP: case Insn.DUP_X1: case Insn.DUP_X2: case Insn.SWAP: case Insn.NEG: case Insn.GETFIELD: case Insn.NEWARRAY: case Insn.CAST: case Insn.INSTANCEOF: case Insn.LOCAL_STORE: case Insn.POP: case Insn.IFEQ: case Insn.IFNE: case Insn.ARETURN: case Insn.PUTSTATIC: case Insn.THROW: case Insn.SWITCH: return 1; case Insn.PUSH: case Insn.ICONST: case Insn.LCONST: case Insn.FCONST: case Insn.DCONST: case Insn.LOCAL_LOAD: case Insn.GETSTATIC: case Insn.NEW: case Insn.NOOP: case Insn.IINC: case Insn.GOTO: case Insn.RETURN: case Insn.INVOKEDYNAMIC: return 0; case Insn.INVOKE: { InvokeInsn method = (InvokeInsn) next; int count = TypeHelper.paramCount(method.getDescription()); // the object ref count++; return count; } case Insn.INVOKESTATIC: { InvokeInsn method = (InvokeInsn) next; int count = TypeHelper.paramCount(method.getDescription()); return count; } case Insn.MULTINEWARRAY: { TypeIntInsn array = (TypeIntInsn) next; return array.getValue(); } default: System.err.println("Unsupported opcode: " + next.getOpcode()); throw new IllegalStateException(); } } /** * Gets the count of values pushed to the stack by the given opcode. */ public static int getStackResultSize(Insn next) { if (next == null) { return 0; } switch (next.getOpcode()) { case -1: return 0; case Insn.DUP2: case Insn.DUP2_X1: case Insn.DUP2_X2: return 3; case Insn.DUP: case Insn.DUP_X1: case Insn.DUP_X2: return 2; case Insn.PUSH: case Insn.ICONST: case Insn.LCONST: case Insn.FCONST: case Insn.DCONST: case Insn.LOCAL_LOAD: case Insn.GETSTATIC: case Insn.NEW: case Insn.SWAP: case Insn.NEG: case Insn.GETFIELD: case Insn.NEWARRAY: case Insn.CAST: case Insn.INSTANCEOF: case Insn.ARRAY_LOAD: case Insn.ADD: case Insn.SUB: case Insn.MUL: case Insn.DIV: case Insn.REM: case Insn.SHL: case Insn.SHR: case Insn.USHR: case Insn.AND: case Insn.OR: case Insn.XOR: case Insn.CMP: case Insn.INVOKEDYNAMIC: case Insn.MULTINEWARRAY: return 1; case Insn.NOOP: case Insn.IINC: case Insn.GOTO: case Insn.RETURN: case Insn.LOCAL_STORE: case Insn.POP: case Insn.IFEQ: case Insn.IFNE: case Insn.ARETURN: case Insn.PUTSTATIC: case Insn.THROW: case Insn.SWITCH: case Insn.IF_CMPEQ: case Insn.IF_CMPNE: case Insn.IF_CMPLT: case Insn.IF_CMPGE: case Insn.IF_CMPGT: case Insn.IF_CMPLE: case Insn.PUTFIELD: case Insn.ARRAY_STORE: return 0; case Insn.INVOKE: case Insn.INVOKESTATIC: { InvokeInsn method = (InvokeInsn) next; if (!TypeHelper.getRet(method.getDescription()).equals("V")) { return 1; } return 0; } default: System.err.println("Unsupported opcode: " + next.getOpcode()); throw new IllegalStateException(); } } /** * Gets the change in stack size from the given opcode. */ public static int getStackDelta(Insn next) { return getStackResultSize(next) - getStackRequirementsSize(next); } /** * Gets if the given list of opcodes requires values on the stack from * before it starts. */ public static boolean hasStartingRequirement(List<Insn> opcodes) { int size = 0; for (int i = 0; i < opcodes.size(); i++) { Insn next = opcodes.get(i); size += getStackDelta(next); if (size < 0) { return true; } } return false; } /** * Returns the index of the opcode that is the start of the last statement * in the given list of opcodes. */ public static int findStartLastStatement(List<Insn> opcodes) { int required_stack = getStackDelta(opcodes.get(opcodes.size() - 1)); for (int index = opcodes.size() - 2; index >= 0; index--) { if (required_stack == 0) { return index + 1; } Insn next = opcodes.get(index); required_stack += getStackDelta(next); } return 0; } /** * Gets if the given statement references the given local. */ public static boolean references(Statement insn, LocalInstance local) { LocalFinder visitor = new LocalFinder(local); insn.accept(visitor); return visitor.isFound(); } /** * Gets if the given instruction references the given local. */ public static boolean references(Instruction insn, LocalInstance local) { LocalFinder visitor = new LocalFinder(local); insn.accept(visitor); return visitor.isFound(); } /** * Gets if the given condition references the given local. */ public static boolean references(Condition condition, LocalInstance local) { LocalFinder visitor = new LocalFinder(local); condition.accept(visitor); return visitor.isFound(); } /** * A visitor that looks for references to a given local. */ private static class LocalFinder implements InstructionVisitor { private final LocalInstance local; private boolean found = false; public LocalFinder(LocalInstance l) { this.local = l; } public boolean isFound() { return this.found; } @Override public void visitLocalInstance(LocalInstance local) { if (this.local == local || (this.local == null && local.getIndex() > 0)) { this.found = true; } } @Override public void visitArrayAccess(ArrayAccess insn) { } @Override public void visitCast(Cast insn) { } @Override public void visitDoubleConstant(DoubleConstant insn) { } @Override public void visitDynamicInvoke(Lambda insn) { } @Override public void visitFloatConstant(FloatConstant insn) { } @Override public void visitInstanceFieldAccess(InstanceFieldAccess insn) { } @Override public void visitInstanceMethodInvoke(InstanceMethodInvoke insn) { } @Override public void visitInstanceOf(InstanceOf insn) { } @Override public void visitIntConstant(IntConstant insn) { } @Override public void visitLocalAccess(LocalAccess insn) { } @Override public void visitLongConstant(LongConstant insn) { } @Override public void visitNegativeOperator(NegativeOperator insn) { } @Override public void visitNew(New insn) { } @Override public void visitNewArray(NewArray insn) { } @Override public void visitNullConstant(NullConstant insn) { } @Override public void visitNumberCompare(NumberCompare insn) { } @Override public void visitOperator(Operator insn) { } @Override public void visitStaticFieldAccess(StaticFieldAccess insn) { } @Override public void visitStaticMethodInvoke(StaticMethodInvoke insn) { } @Override public void visitStringConstant(StringConstant insn) { } @Override public void visitTernary(Ternary insn) { } @Override public void visitTypeConstant(TypeConstant insn) { } @Override public void visitMultiNewArray(MultiNewArray insn) { } @Override public void visitMethodReference(MethodReference methodReference) { } } private AstUtil() { } }
java
MIT
e60cfaaf7a0688bc83f8b00c392521d0b162afba
2026-01-05T02:42:07.381192Z
false
Despector/Despector
https://github.com/Despector/Despector/blob/e60cfaaf7a0688bc83f8b00c392521d0b162afba/src/main/java/org/spongepowered/despector/util/Pair.java
src/main/java/org/spongepowered/despector/util/Pair.java
/* * The MIT License (MIT) * * Copyright (c) Despector <https://despector.voxelgenesis.com> * Copyright (c) contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package org.spongepowered.despector.util; /** * A utility class for a pair of related objects. */ public class Pair<A, B> { private final A a; private final B b; public Pair(A a, B b) { this.a = a; this.b = b; } public A getFirst() { return this.a; } public B getSecond() { return this.b; } @Override public String toString() { return "Pair[" + this.a + ", " + this.b + "]"; } @Override public boolean equals(Object o) { if (o == this) { return true; } if (!(o instanceof Pair)) { return false; } Pair<?, ?> p = (Pair<?, ?>) o; if (this.a == null) { return p.a == null; } if (this.b == null) { return p.b == null; } return this.a.equals(p.a) && this.b.equals(p.b); } @Override public int hashCode() { int h = 1; h = h * 31 + (this.a == null ? 0 : this.a.hashCode()); h = h * 31 + (this.b == null ? 0 : this.b.hashCode()); return h; } }
java
MIT
e60cfaaf7a0688bc83f8b00c392521d0b162afba
2026-01-05T02:42:07.381192Z
false
Despector/Despector
https://github.com/Despector/Despector/blob/e60cfaaf7a0688bc83f8b00c392521d0b162afba/src/main/java/org/spongepowered/despector/util/SignatureParser.java
src/main/java/org/spongepowered/despector/util/SignatureParser.java
/* * The MIT License (MIT) * * Copyright (c) Despector <https://despector.voxelgenesis.com> * Copyright (c) contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package org.spongepowered.despector.util; import static com.google.common.base.Preconditions.checkState; import org.spongepowered.despector.ast.generic.ClassSignature; import org.spongepowered.despector.ast.generic.ClassTypeSignature; import org.spongepowered.despector.ast.generic.GenericClassTypeSignature; import org.spongepowered.despector.ast.generic.MethodSignature; import org.spongepowered.despector.ast.generic.TypeArgument; import org.spongepowered.despector.ast.generic.TypeParameter; import org.spongepowered.despector.ast.generic.TypeSignature; import org.spongepowered.despector.ast.generic.TypeVariableSignature; import org.spongepowered.despector.ast.generic.VoidTypeSignature; import org.spongepowered.despector.ast.generic.WildcardType; import java.util.List; /** * A parser for various generic signatures. */ public final class SignatureParser { private static final String VALID_PRIM = "BSIJFDCZ"; /** * Parses the given class signature. */ public static ClassSignature parse(String signature) { Parser parser = new Parser(signature); ClassSignature struct = new ClassSignature(); if (signature.startsWith("<")) { parser.skip(1); parseFormalTypeParameters(parser, struct.getParameters()); } GenericClassTypeSignature superclass = parseClassTypeSignature(parser, ""); struct.setSuperclassSignature(superclass); while (parser.hasNext()) { GenericClassTypeSignature sig = parseClassTypeSignature(parser, ""); struct.getInterfaceSignatures().add(sig); } return struct; } /** * Parses the given method signature. */ public static MethodSignature parseMethod(String signature) { Parser parser = new Parser(signature); MethodSignature sig = new MethodSignature(); if (parser.check('<')) { parseFormalTypeParameters(parser, sig.getTypeParameters()); } parser.expect('('); while (!parser.check(')')) { sig.getParameters().add(parseTypeSignature(parser)); } if (parser.check('V')) { sig.setReturnType(VoidTypeSignature.VOID); } else { sig.setReturnType(parseTypeSignature(parser)); } // TODO throws signature return sig; } private static void parseFormalTypeParameters(Parser parser, List<TypeParameter> type_params) { while (parser.peek() != '>') { String identifier = parser.nextIdentifier(); parser.expect(':'); TypeSignature class_bound = null; if (parser.peek() != ':') { class_bound = parseFieldTypeSignature(parser); } TypeParameter param = new TypeParameter(identifier, class_bound); type_params.add(param); while (parser.peek() == ':') { parser.skip(1); param.getInterfaceBounds().add(parseFieldTypeSignature(parser)); } } parser.skip(1); } public static TypeSignature parseFieldTypeSignature(String sig) { Parser parser = new Parser(sig); return parseFieldTypeSignature(parser); } private static TypeSignature parseTypeSignature(Parser parser) { char next = parser.peek(); if (VALID_PRIM.indexOf(next) != -1) { parser.skip(1); return ClassTypeSignature.of(String.valueOf(next)); } return parseFieldTypeSignature(parser); } private static TypeSignature parseFieldTypeSignature(Parser parser) { StringBuilder ident = new StringBuilder(); while (parser.check('[')) { ident.append('['); } char next = parser.peek(); if (ident.length() > 0) { if (VALID_PRIM.indexOf(next) != -1) { ident.append(next); parser.skip(1); return ClassTypeSignature.of(ident.toString()); } } if (next == 'T') { parser.skip(1); ident.append('T'); ident.append(parser.nextIdentifier()); ident.append(';'); TypeVariableSignature sig = new TypeVariableSignature(ident.toString()); parser.expect(';'); return sig; } checkState(next == 'L'); return parseClassTypeSignature(parser, ident.toString()); } public static GenericClassTypeSignature parseClassTypeSignature(String sig) { Parser parser = new Parser(sig); return parseClassTypeSignature(parser, ""); } private static GenericClassTypeSignature parseClassTypeSignature(Parser parser, String prefix) { StringBuilder ident = new StringBuilder(prefix); parser.expect('L'); ident.append("L"); ident.append(parser.nextIdentifier()); while (parser.check('/')) { ident.append('/'); ident.append(parser.nextIdentifier()); } ident.append(";"); GenericClassTypeSignature sig = new GenericClassTypeSignature(ident.toString()); if (parser.check('<')) { while (!parser.check('>')) { char wild = parser.peek(); WildcardType wildcard = null; if (wild == '*') { sig.getArguments().add(new TypeArgument(WildcardType.STAR, null)); parser.skip(1); continue; } else if (wild == '+') { parser.skip(1); wildcard = WildcardType.EXTENDS; } else if (wild == '-') { parser.skip(1); wildcard = WildcardType.SUPER; } else { wildcard = WildcardType.NONE; } sig.getArguments().add(new TypeArgument(wildcard, parseFieldTypeSignature(parser))); } } while (parser.peek() == '.') { parser.pop(); StringBuilder child = new StringBuilder(); child.append("L"); child.append(parser.nextIdentifier()); while (parser.check('/')) { child.append('/'); child.append(parser.nextIdentifier()); } child.append(";"); sig = new GenericClassTypeSignature(sig, child.toString()); if (parser.check('<')) { while (!parser.check('>')) { char wild = parser.peek(); WildcardType wildcard = null; if (wild == '*') { sig.getArguments().add(new TypeArgument(WildcardType.STAR, null)); parser.skip(1); continue; } else if (wild == '+') { parser.skip(1); wildcard = WildcardType.EXTENDS; } else if (wild == '-') { parser.skip(1); wildcard = WildcardType.SUPER; } else { wildcard = WildcardType.NONE; } sig.getArguments().add(new TypeArgument(wildcard, parseFieldTypeSignature(parser))); } } } parser.expect(';'); return sig; } /** * A helper for parsing. */ private static class Parser { private int index; private String buffer; public Parser(String data) { this.buffer = data; this.index = 0; } public boolean hasNext() { return this.index < this.buffer.length(); } public void skip(int n) { this.index += n; } public char peek() { return this.buffer.charAt(this.index); } public char pop() { return this.buffer.charAt(this.index++); } public boolean check(char n) { if (peek() == n) { this.index++; return true; } return false; } public void expect(char n) { if (peek() != n) { throw new IllegalStateException("Expected '" + n + "' at char " + this.index + " in \"" + this.buffer + "\""); } this.index++; } public String nextIdentifier() { StringBuilder ident = new StringBuilder(); int start = this.index; for (; this.index < this.buffer.length(); this.index++) { char next = this.buffer.charAt(this.index); if (Character.isAlphabetic(next) || next == '_' || next == '$' || (this.index > start && next >= '0' && next <= '9')) { ident.append(next); } else { break; } } if (ident.length() == 0) { throw new IllegalStateException("Expected identifier at char " + this.index + " in \"" + this.buffer + "\""); } return ident.toString(); } } private SignatureParser() { } }
java
MIT
e60cfaaf7a0688bc83f8b00c392521d0b162afba
2026-01-05T02:42:07.381192Z
false
Despector/Despector
https://github.com/Despector/Despector/blob/e60cfaaf7a0688bc83f8b00c392521d0b162afba/src/main/java/org/spongepowered/despector/util/Tristate.java
src/main/java/org/spongepowered/despector/util/Tristate.java
/* * The MIT License (MIT) * * Copyright (c) Despector <https://despector.voxelgenesis.com> * Copyright (c) contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package org.spongepowered.despector.util; /** * A tristate value that may be true, false, or undefined. */ public enum Tristate { TRUE(true), FALSE(false), UNDEFINED(false); private final boolean bool; Tristate(boolean b) { this.bool = b; } public boolean asBoolean() { return this.bool; } }
java
MIT
e60cfaaf7a0688bc83f8b00c392521d0b162afba
2026-01-05T02:42:07.381192Z
false
Despector/Despector
https://github.com/Despector/Despector/blob/e60cfaaf7a0688bc83f8b00c392521d0b162afba/src/main/java/org/spongepowered/despector/util/viewer/TabData.java
src/main/java/org/spongepowered/despector/util/viewer/TabData.java
package org.spongepowered.despector.util.viewer; import javax.swing.JTextArea; public class TabData { public final TabType type; public String data = ""; public JTextArea left = new JTextArea(); public JTextArea right = new JTextArea(); public TabData(TabType type) { this.type = type; } void update(String dat) { this.data = dat; this.left.setText(dat); this.right.setText(dat); } }
java
MIT
e60cfaaf7a0688bc83f8b00c392521d0b162afba
2026-01-05T02:42:07.381192Z
false
Despector/Despector
https://github.com/Despector/Despector/blob/e60cfaaf7a0688bc83f8b00c392521d0b162afba/src/main/java/org/spongepowered/despector/util/viewer/TabType.java
src/main/java/org/spongepowered/despector/util/viewer/TabType.java
package org.spongepowered.despector.util.viewer; public enum TabType { SOURCE, BYTECODE, DECOMPILED, GRAPH_0, GRAPH_1, GRAPH_2, }
java
MIT
e60cfaaf7a0688bc83f8b00c392521d0b162afba
2026-01-05T02:42:07.381192Z
false
Despector/Despector
https://github.com/Despector/Despector/blob/e60cfaaf7a0688bc83f8b00c392521d0b162afba/src/main/java/org/spongepowered/despector/util/viewer/Viewer.java
src/main/java/org/spongepowered/despector/util/viewer/Viewer.java
package org.spongepowered.despector.util.viewer; import com.google.common.base.Charsets; import org.spongepowered.despector.Despector; import org.spongepowered.despector.ast.type.MethodEntry; import org.spongepowered.despector.ast.type.TypeEntry; import org.spongepowered.despector.config.LibraryConfiguration; import org.spongepowered.despector.emitter.Emitters; import org.spongepowered.despector.emitter.format.EmitterFormat; import org.spongepowered.despector.emitter.java.JavaEmitterContext; import java.awt.BorderLayout; import java.awt.event.ActionEvent; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.PrintWriter; import java.io.StringWriter; import java.nio.file.Files; import java.util.EnumMap; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JSplitPane; import javax.swing.JTabbedPane; import javax.swing.JTextField; import javax.swing.border.EmptyBorder; public class Viewer { public static EnumMap<TabType, TabData> tabs = new EnumMap<>(TabType.class); private static JTextField file_name_field; public static void onLoad(ActionEvent evt) { String fn = file_name_field.getText(); System.out.println("Loading file: " + fn); String sourceFile = String.format("fern-decompiled/%s.java", fn.replace('.', '/')); File source = new File(sourceFile); if (source.exists() && source.isFile()) { try { tabs.get(TabType.SOURCE).update(new String(Files.readAllBytes(source.toPath()), Charsets.UTF_8)); } catch (IOException e) { e.printStackTrace(); tabs.get(TabType.SOURCE).update("Source: " + sourceFile + " could not be loaded."); } } else { tabs.get(TabType.SOURCE).update("Source: " + sourceFile + " not found."); } String compFile = String.format("source/%s.class", fn.replace('.', '/')); File comp = new File(compFile); if (comp.exists() && comp.isFile()) { try { TypeEntry ast = Despector.decompile(new FileInputStream(comp)); String str = Despector.emitToString(ast); tabs.get(TabType.DECOMPILED).update(str); StringWriter ir_writer = new StringWriter(); JavaEmitterContext ctx = new JavaEmitterContext(ir_writer, EmitterFormat.defaults()); Emitters.IR.emit(ctx, ast); tabs.get(TabType.BYTECODE).update(ir_writer.toString()); { StringWriter graph_writer = new StringWriter(); emitGraph(graph_writer, ast, 0); tabs.get(TabType.GRAPH_0).update(graph_writer.toString()); } { StringWriter graph_writer = new StringWriter(); emitGraph(graph_writer, ast, 1); tabs.get(TabType.GRAPH_1).update(graph_writer.toString()); } { StringWriter graph_writer = new StringWriter(); emitGraph(graph_writer, ast, 2); tabs.get(TabType.GRAPH_2).update(graph_writer.toString()); } } catch (IOException e) { e.printStackTrace(); tabs.get(TabType.DECOMPILED).update("Source: " + compFile + " could not be loaded."); tabs.get(TabType.BYTECODE).update("Source: " + compFile + " could not be loaded."); tabs.get(TabType.GRAPH_0).update("Source: " + compFile + " could not be loaded."); tabs.get(TabType.GRAPH_1).update("Source: " + compFile + " could not be loaded."); tabs.get(TabType.GRAPH_2).update("Source: " + compFile + " could not be loaded."); } } else { tabs.get(TabType.DECOMPILED).update("Source: " + compFile + " not found."); tabs.get(TabType.BYTECODE).update("Source: " + compFile + " not found."); tabs.get(TabType.GRAPH_0).update("Source: " + compFile + " not found."); tabs.get(TabType.GRAPH_1).update("Source: " + compFile + " not found."); tabs.get(TabType.GRAPH_2).update("Source: " + compFile + " not found."); } } public static void main(String[] args) { LibraryConfiguration.parallel = false; LibraryConfiguration.quiet = false; LibraryConfiguration.emit_block_debug = true; tabs.put(TabType.SOURCE, new TabData(TabType.SOURCE)); tabs.put(TabType.BYTECODE, new TabData(TabType.BYTECODE)); tabs.put(TabType.DECOMPILED, new TabData(TabType.DECOMPILED)); tabs.put(TabType.GRAPH_0, new TabData(TabType.GRAPH_0)); tabs.put(TabType.GRAPH_1, new TabData(TabType.GRAPH_1)); tabs.put(TabType.GRAPH_2, new TabData(TabType.GRAPH_2)); JFrame frame = new JFrame("Despector"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setBounds(50, 50, 1600, 900); JPanel contentPane = new JPanel(); contentPane.setBorder(new EmptyBorder(5, 5, 5, 5)); contentPane.setLayout(new BorderLayout(0, 0)); frame.setContentPane(contentPane); JPanel panel = new JPanel(); contentPane.add(panel, BorderLayout.NORTH); file_name_field = new JTextField(); panel.add(file_name_field); file_name_field.setColumns(100); file_name_field.setText("net.minecraft."); JButton loadBtn = new JButton("Load"); panel.add(loadBtn); loadBtn.addActionListener(Viewer::onLoad); JSplitPane splitPane = new JSplitPane(); splitPane.setDividerLocation(800); contentPane.add(splitPane, BorderLayout.CENTER); JTabbedPane leftPane = new JTabbedPane(JTabbedPane.TOP); splitPane.setLeftComponent(leftPane); leftPane.addTab("Source", null, new JScrollPane(tabs.get(TabType.SOURCE).left), null); leftPane.addTab("Bytecode", null, new JScrollPane(tabs.get(TabType.BYTECODE).left), null); leftPane.addTab("Decompiled", null, new JScrollPane(tabs.get(TabType.DECOMPILED).left), null); leftPane.addTab("Graph 0", null, new JScrollPane(tabs.get(TabType.GRAPH_0).left), null); leftPane.addTab("Graph 1", null, new JScrollPane(tabs.get(TabType.GRAPH_1).left), null); leftPane.addTab("Graph 2", null, new JScrollPane(tabs.get(TabType.GRAPH_2).left), null); JTabbedPane rightPane = new JTabbedPane(JTabbedPane.TOP); splitPane.setRightComponent(rightPane); rightPane.addTab("Source", null, new JScrollPane(tabs.get(TabType.SOURCE).right), null); rightPane.addTab("Bytecode", null, new JScrollPane(tabs.get(TabType.BYTECODE).right), null); rightPane.addTab("Decompiled", null, new JScrollPane(tabs.get(TabType.DECOMPILED).right), null); rightPane.addTab("Graph 0", null, new JScrollPane(tabs.get(TabType.GRAPH_0).right), null); rightPane.addTab("Graph 1", null, new JScrollPane(tabs.get(TabType.GRAPH_1).right), null); rightPane.addTab("Graph 2", null, new JScrollPane(tabs.get(TabType.GRAPH_2).right), null); frame.setVisible(true); } public static void emitGraph(StringWriter w, TypeEntry e, int i) { PrintWriter p = new PrintWriter(w); p.printf("class %s {\n\n", e.getName()); for (MethodEntry m : e.getStaticMethods()) { p.printf("static %s%s {\n", m.getName(), m.getDescription()); p.println(m.block_debug[i].replace("\n", "\n ")); p.printf("}\n\n"); } for (MethodEntry m : e.getMethods()) { p.printf("%s%s {\n", m.getName(), m.getDescription()); String g = m.block_debug[i]; if(g == null) { g = "An error occured before this graph could be compiled.\n"; } p.println(g.replace("\n", "\n ")); p.printf("}\n\n"); } p.printf("}\n"); } }
java
MIT
e60cfaaf7a0688bc83f8b00c392521d0b162afba
2026-01-05T02:42:07.381192Z
false
Despector/Despector
https://github.com/Despector/Despector/blob/e60cfaaf7a0688bc83f8b00c392521d0b162afba/src/main/java/org/spongepowered/despector/util/serialization/MessageUnpacker.java
src/main/java/org/spongepowered/despector/util/serialization/MessageUnpacker.java
/* * The MIT License (MIT) * * Copyright (c) Despector <https://despector.voxelgenesis.com> * Copyright (c) contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package org.spongepowered.despector.util.serialization; import static com.google.common.base.Preconditions.checkState; import static org.spongepowered.despector.util.serialization.MessageType.*; import com.google.common.base.Charsets; import java.io.DataInputStream; import java.io.IOException; import java.io.InputStream; /** * A deserializer for data using the messagepack format. */ public class MessageUnpacker implements AutoCloseable { private static final int FIXINT_TYPE_MASK = 0x80; private static final int FIXINT_MASK = 0x7F; private static final int NEGATIVE_FIXINT_MASK = 0xFFFFFF00; private static final int SHORTSTRING_TYPE_MASK = 0xE0; private static final int SHORTSTRING_MASK = 0x1F; private static final int SHORTARRAY_MASK = 0xF0; private static final int NIBBLE_MASK = 0xF; private final DataInputStream stream; public MessageUnpacker(InputStream str) { if (str instanceof DataInputStream) { this.stream = (DataInputStream) str; } else { this.stream = new DataInputStream(str); } checkState(this.stream.markSupported()); } @Override public void close() throws IOException { this.stream.close(); } /** * Peeks at the next type in the input. */ public MessageType peekType() throws IOException { this.stream.mark(1); int next = this.stream.readUnsignedByte(); this.stream.reset(); return MessageType.of(next); } private void expectType(MessageType type) throws IOException { MessageType actual = peekType(); if (actual != type && !(type == MessageType.UINT && actual == MessageType.INT)) { throw new IllegalStateException("Unexpected type " + actual.name() + " but expected " + type.name()); } } /** * Reads a nil value from the input. */ public void readNil() throws IOException { expectType(MessageType.NIL); this.stream.skipBytes(1); } /** * Reads a boolean value from the input. */ public boolean readBool() throws IOException { int next = this.stream.readUnsignedByte(); if (next == TYPE_BOOL_TRUE) { return true; } else if (next == TYPE_BOOL_FALSE) { return false; } throw new IllegalStateException("Unexpected type " + MessageType.of(next).name() + " but expected BOOL"); } /** * Reads a byte value from the input. */ public byte readByte() throws IOException { expectType(MessageType.INT); int next = this.stream.readUnsignedByte(); if ((next & FIXINT_TYPE_MASK) == 0) { return (byte) (next & FIXINT_MASK); } else if ((next & TYPE_NEGINT_MASK) == TYPE_NEGINT_MASK) { return (byte) (NEGATIVE_FIXINT_MASK | next); } else if (next == TYPE_INT8) { return this.stream.readByte(); } throw new IllegalStateException("Unexpected type " + MessageType.of(next).name() + " but expected INT"); } /** * Reads a short value from the input. */ public short readShort() throws IOException { expectType(MessageType.INT); int next = this.stream.readUnsignedByte(); if ((next & FIXINT_TYPE_MASK) == 0) { return (byte) (next & FIXINT_MASK); } else if ((next & TYPE_NEGINT_MASK) == TYPE_NEGINT_MASK) { return (byte) (NEGATIVE_FIXINT_MASK | next); } else if (next == TYPE_INT8) { return this.stream.readByte(); } else if (next == TYPE_INT16) { return this.stream.readShort(); } throw new IllegalStateException("Unexpected type " + MessageType.of(next).name() + " but expected INT"); } /** * Reads an integer value from the input. */ public int readInt() throws IOException { expectType(MessageType.INT); int next = this.stream.readUnsignedByte(); if ((next & FIXINT_TYPE_MASK) == 0) { return (byte) (next & FIXINT_MASK); } else if ((next & TYPE_NEGINT_MASK) == TYPE_NEGINT_MASK) { return (byte) (NEGATIVE_FIXINT_MASK | next); } else if (next == TYPE_INT8) { return this.stream.readByte(); } else if (next == TYPE_INT16) { return this.stream.readShort(); } else if (next == TYPE_INT32) { return this.stream.readInt(); } throw new IllegalStateException("Unexpected type " + MessageType.of(next).name() + " but expected INT"); } /** * Reads a long value from the input. */ public long readLong() throws IOException { expectType(MessageType.INT); int next = this.stream.readUnsignedByte(); if ((next & FIXINT_TYPE_MASK) == 0) { return (byte) (next & FIXINT_MASK); } else if ((next & TYPE_NEGINT_MASK) == TYPE_NEGINT_MASK) { return (byte) (NEGATIVE_FIXINT_MASK | next); } else if (next == TYPE_INT8) { return this.stream.readByte(); } else if (next == TYPE_INT16) { return this.stream.readShort(); } else if (next == TYPE_INT32) { return this.stream.readInt(); } else if (next == TYPE_INT64) { return this.stream.readLong(); } throw new IllegalStateException("Unexpected type " + MessageType.of(next).name() + " but expected INT"); } /** * Reads an unsigned byte value from the input. */ public int readUnsignedByte() throws IOException { expectType(MessageType.UINT); int next = this.stream.readUnsignedByte(); if ((next & FIXINT_TYPE_MASK) == 0) { return (next & FIXINT_MASK); } else if (next == TYPE_UINT8) { return this.stream.readByte(); } throw new IllegalStateException("Unexpected type " + MessageType.of(next).name() + " but expected UINT"); } /** * Reads an unsigned short value from the input. */ public int readUnsignedShort() throws IOException { expectType(MessageType.UINT); int next = this.stream.readUnsignedByte(); if ((next & FIXINT_TYPE_MASK) == 0) { return (byte) (next & FIXINT_MASK); } else if (next == TYPE_UINT8) { return this.stream.readByte(); } else if (next == TYPE_UINT16) { return this.stream.readShort(); } throw new IllegalStateException("Unexpected type " + MessageType.of(next).name() + " but expected UINT"); } /** * Reads an unsigned integer value from the input. */ public long readUnsignedInt() throws IOException { expectType(MessageType.UINT); int next = this.stream.readUnsignedByte(); if ((next & FIXINT_TYPE_MASK) == 0) { return (byte) (next & FIXINT_MASK); } else if (next == TYPE_UINT8) { return this.stream.readByte(); } else if (next == TYPE_UINT16) { return this.stream.readShort(); } else if (next == TYPE_UINT32) { return this.stream.readInt(); } throw new IllegalStateException("Unexpected type " + MessageType.of(next).name() + " but expected UINT"); } /** * Reads an unsigned long value from the input. */ public long readUnsignedLong() throws IOException { expectType(MessageType.UINT); int next = this.stream.readUnsignedByte(); if ((next & FIXINT_TYPE_MASK) == 0) { return (byte) (next & FIXINT_MASK); } else if (next == TYPE_UINT8) { return this.stream.readByte(); } else if (next == TYPE_UINT16) { return this.stream.readShort(); } else if (next == TYPE_UINT32) { return this.stream.readInt(); } else if (next == TYPE_UINT64) { return this.stream.readLong(); } throw new IllegalStateException("Unexpected type " + MessageType.of(next).name() + " but expected UINT"); } /** * Reads a 32-bit floating point value from the input. */ public float readFloat() throws IOException { expectType(MessageType.FLOAT); this.stream.skipBytes(1); return this.stream.readFloat(); } /** * Reads a 64-bit floating point value from the input. */ public double readDouble() throws IOException { expectType(MessageType.DOUBLE); this.stream.skipBytes(1); return this.stream.readDouble(); } /** * Reads a string value from the input. */ public String readString() throws IOException { expectType(MessageType.STRING); int next = this.stream.readUnsignedByte(); int len = -1; if ((next & SHORTSTRING_TYPE_MASK) == TYPE_STR5_MASK) { len = next & SHORTSTRING_MASK; } else if (next == TYPE_STR8) { len = this.stream.readUnsignedByte(); } else if (next == TYPE_STR16) { len = this.stream.readUnsignedShort(); } else if (next == TYPE_STR32) { len = this.stream.readInt(); } byte[] data = new byte[len]; this.stream.read(data); return new String(data, Charsets.UTF_8); } /** * Reads a binary value from the input. */ public byte[] readBinary() throws IOException { expectType(MessageType.BIN); int next = this.stream.readUnsignedByte(); int len = -1; if (next == TYPE_BIN8) { len = this.stream.readUnsignedByte(); } else if (next == TYPE_BIN16) { len = this.stream.readUnsignedShort(); } else if (next == TYPE_BIN32) { len = this.stream.readInt(); } byte[] data = new byte[len]; this.stream.read(data); return data; } /** * Reads an array value from the input and returns the number of items in * the array. */ public int readArray() throws IOException { expectType(MessageType.ARRAY); int next = this.stream.readUnsignedByte(); int len = -1; if ((next & SHORTARRAY_MASK) == TYPE_ARRAY8_MASK) { len = next & NIBBLE_MASK; } else if (next == TYPE_ARRAY16) { len = this.stream.readUnsignedShort(); } else if (next == TYPE_ARRAY32) { len = this.stream.readInt(); } return len; } /** * Reads a map value from the input and returns the number of key value * pairs in the map. */ public int readMap() throws IOException { expectType(MessageType.MAP); int next = this.stream.readUnsignedByte(); int len = -1; if ((next & SHORTARRAY_MASK) == TYPE_MAP8_MASK) { len = next & NIBBLE_MASK; } else if (next == TYPE_MAP16) { len = this.stream.readUnsignedShort(); } else if (next == TYPE_MAP32) { len = this.stream.readInt(); } return len; } }
java
MIT
e60cfaaf7a0688bc83f8b00c392521d0b162afba
2026-01-05T02:42:07.381192Z
false
Despector/Despector
https://github.com/Despector/Despector/blob/e60cfaaf7a0688bc83f8b00c392521d0b162afba/src/main/java/org/spongepowered/despector/util/serialization/MessagePacker.java
src/main/java/org/spongepowered/despector/util/serialization/MessagePacker.java
/* * The MIT License (MIT) * * Copyright (c) Despector <https://despector.voxelgenesis.com> * Copyright (c) contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package org.spongepowered.despector.util.serialization; import static org.spongepowered.despector.util.serialization.MessageType.*; import com.google.common.base.Charsets; import java.io.DataOutputStream; import java.io.IOException; import java.io.OutputStream; import java.util.ArrayDeque; import java.util.Deque; /** * A serializer for writing files using the messagepack format. */ public class MessagePacker implements AutoCloseable { private static final int MAX_POSITIVE_FIXINT = 0x7F; private static final int MIN_NEGATUVE_FIXINT = -32; private static final int NIBBLE_MASK = 0xF; private static final int BYTE_MASK = 0xFF; private static final int SHORT_MASK = 0xFFFF; private static final int MAX_FIXSTRING_LENGTH = 31; private final DataOutputStream stream; private final Deque<Frame> frames = new ArrayDeque<>(); public MessagePacker(OutputStream str) { if (str instanceof DataOutputStream) { this.stream = (DataOutputStream) str; } else { this.stream = new DataOutputStream(str); } this.frames.push(new Frame(FrameType.MAP, 1)); } @Override public void close() throws IOException { this.stream.close(); } /** * Writes a nil value. */ public MessagePacker writeNil() throws IOException { decreaseFrame(); this.stream.writeByte(TYPE_NIL); return this; } /** * Writes a boolean value. */ public MessagePacker writeBool(boolean val) throws IOException { decreaseFrame(); this.stream.writeByte(val ? TYPE_BOOL_TRUE : TYPE_BOOL_FALSE); return this; } /** * Writes an integer value. */ public MessagePacker writeInt(long val) throws IOException { decreaseFrame(); if (val >= 0 && val <= MAX_POSITIVE_FIXINT) { this.stream.writeByte((int) (val & MAX_POSITIVE_FIXINT)); } else if (val < 0 && val >= MIN_NEGATUVE_FIXINT) { this.stream.writeByte((int) val); } else if (val <= Byte.MAX_VALUE && val >= Byte.MIN_VALUE) { this.stream.writeByte(TYPE_INT8); this.stream.writeByte((int) (val & BYTE_MASK)); } else if (val <= Short.MAX_VALUE && val >= Short.MIN_VALUE) { this.stream.writeByte(TYPE_INT16); this.stream.writeShort((int) (val & SHORT_MASK)); } else if (val <= Integer.MAX_VALUE && val >= Integer.MIN_VALUE) { this.stream.writeByte(TYPE_INT32); this.stream.writeInt((int) val); } else { this.stream.writeByte(TYPE_INT64); this.stream.writeLong(val); } return this; } /** * Writes an unsigned integer value. */ public MessagePacker writeUnsignedInt(long val) throws IOException { decreaseFrame(); if (val <= MAX_POSITIVE_FIXINT) { this.stream.writeByte((int) (val & MAX_POSITIVE_FIXINT)); } else if (val <= BYTE_MASK) { this.stream.writeByte(TYPE_UINT8); this.stream.writeByte((int) (val & BYTE_MASK)); } else if (val <= SHORT_MASK) { this.stream.writeByte(TYPE_UINT16); this.stream.writeShort((int) (val & SHORT_MASK)); } else if (val <= 0xFFFFFFFF) { this.stream.writeByte(TYPE_UINT32); this.stream.writeInt((int) (val & 0xFFFFFFFF)); } else { this.stream.writeByte(TYPE_UINT64); this.stream.writeLong(val); } return this; } /** * Writes a 32-bit floating point value. */ public MessagePacker writeFloat(float val) throws IOException { decreaseFrame(); this.stream.writeByte(TYPE_FLOAT); this.stream.writeFloat(val); return this; } /** * Writes a 64-bit floating point value. */ public MessagePacker writeDouble(double val) throws IOException { decreaseFrame(); this.stream.writeByte(TYPE_DOUBLE); this.stream.writeDouble(val); return this; } /** * Writes a string value. */ public MessagePacker writeString(String val) throws IOException { decreaseStringFrame(); byte[] chars = val.getBytes(Charsets.UTF_8); int len = chars.length; if (len <= MAX_FIXSTRING_LENGTH) { this.stream.writeByte(TYPE_STR5_MASK | len); } else if (len < BYTE_MASK) { this.stream.writeByte(TYPE_STR8); this.stream.writeByte(len); } else if (len < SHORT_MASK) { this.stream.writeByte(TYPE_STR16); this.stream.writeShort(len); } else { this.stream.writeByte(TYPE_STR32); this.stream.writeInt(len); } this.stream.write(chars); return this; } /** * Writes a binary value. */ public MessagePacker writeBin(byte[] data) throws IOException { decreaseFrame(); if (data.length < BYTE_MASK) { this.stream.writeByte(TYPE_BIN8); this.stream.writeByte(data.length); } else if (data.length < SHORT_MASK) { this.stream.writeByte(TYPE_BIN16); this.stream.writeShort(data.length); } else { this.stream.writeByte(TYPE_BIN32); this.stream.writeInt(data.length); } this.stream.write(data); return this; } /** * Starts an array of values. */ public MessagePacker startArray(int len) throws IOException { decreaseFrame(); if (len < NIBBLE_MASK) { this.stream.writeByte(TYPE_ARRAY8_MASK | len); } else if (len < SHORT_MASK) { this.stream.writeByte(TYPE_ARRAY16); this.stream.writeShort(len); } else { this.stream.writeByte(TYPE_ARRAY32); this.stream.writeInt(len); } this.frames.push(new Frame(FrameType.ARRAY, len)); return this; } public MessagePacker endArray() { Frame f = this.frames.pop(); if (f.type != FrameType.ARRAY) { throw new IllegalStateException("Attempted to end map frame as array"); } if (f.remaining != 0) { throw new IllegalStateException("Frame underflow"); } return this; } /** * Starts a map of key value pairs. */ public MessagePacker startMap(int len) throws IOException { decreaseFrame(); if (len < NIBBLE_MASK) { this.stream.writeByte(TYPE_MAP8_MASK | len); } else if (len < SHORT_MASK) { this.stream.writeByte(TYPE_MAP16); this.stream.writeShort(len); } else { this.stream.writeByte(TYPE_MAP32); this.stream.writeInt(len); } this.frames.push(new Frame(FrameType.MAP, len * 2)); return this; } public MessagePacker endMap() { Frame f = this.frames.pop(); if (f.type != FrameType.MAP) { throw new IllegalStateException("Attempted to end array frame as map"); } if (f.remaining != 0) { throw new IllegalStateException("Frame underflow"); } return this; } private void decreaseFrame() { Frame f = this.frames.peek(); if (f.type == FrameType.MAP && f.remaining % 2 == 0) { throw new IllegalStateException("Expected map key"); } f.remaining--; if (f.remaining < 0) { throw new IllegalStateException("Frame " + f.type.name() + " overflowed"); } } private void decreaseStringFrame() { Frame f = this.frames.peek(); f.remaining--; if (f.remaining < 0) { throw new IllegalStateException("Frame " + f.type.name() + " overflowed"); } } // TODO support EXT private static class Frame { public FrameType type; public int remaining; public Frame(FrameType type, int len) { this.type = type; this.remaining = len; } } private static enum FrameType { ARRAY, MAP, } }
java
MIT
e60cfaaf7a0688bc83f8b00c392521d0b162afba
2026-01-05T02:42:07.381192Z
false
Despector/Despector
https://github.com/Despector/Despector/blob/e60cfaaf7a0688bc83f8b00c392521d0b162afba/src/main/java/org/spongepowered/despector/util/serialization/MessageType.java
src/main/java/org/spongepowered/despector/util/serialization/MessageType.java
/* * The MIT License (MIT) * * Copyright (c) Despector <https://despector.voxelgenesis.com> * Copyright (c) contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package org.spongepowered.despector.util.serialization; /** * An enumeration of messagepack data types. */ public enum MessageType { NIL, BOOL, INT, UINT, LONG, ULONG, FLOAT, DOUBLE, STRING, BIN, ARRAY, MAP; private static final int FIXINT_MASK = 0x80; private static final int SHORTSTRING_MASK = 0xE0; private static final int SHORTARRAY_MASK = 0xF0; public static final int TYPE_NIL = 0xC0; public static final int TYPE_BOOL_FALSE = 0xC2; public static final int TYPE_BOOL_TRUE = 0xC3; public static final int TYPE_NEGINT_MASK = 0xE0; public static final int TYPE_UINT8 = 0xCC; public static final int TYPE_UINT16 = 0xCD; public static final int TYPE_UINT32 = 0xCE; public static final int TYPE_UINT64 = 0xCF; public static final int TYPE_INT8 = 0xD0; public static final int TYPE_INT16 = 0xD1; public static final int TYPE_INT32 = 0xD2; public static final int TYPE_INT64 = 0xD3; public static final int TYPE_FLOAT = 0xCA; public static final int TYPE_DOUBLE = 0xCB; public static final int TYPE_STR5_MASK = 0xA0; public static final int TYPE_STR8 = 0xD9; public static final int TYPE_STR16 = 0xDA; public static final int TYPE_STR32 = 0xDB; public static final int TYPE_BIN8 = 0xC4; public static final int TYPE_BIN16 = 0xC5; public static final int TYPE_BIN32 = 0xC6; public static final int TYPE_ARRAY8_MASK = 0x90; public static final int TYPE_ARRAY16 = 0xDC; public static final int TYPE_ARRAY32 = 0xDD; public static final int TYPE_MAP8_MASK = 0x80; public static final int TYPE_MAP16 = 0xDE; public static final int TYPE_MAP32 = 0xDF; public static final int TYPE_FIXEXT1 = 0xD4; public static final int TYPE_FIXEXT2 = 0xD5; public static final int TYPE_FIXEXT4 = 0xD6; public static final int TYPE_FIXEXT8 = 0xD7; public static final int TYPE_FIXEXT16 = 0xD8; public static final int TYPE_EXT8 = 0xC7; public static final int TYPE_EXT16 = 0xC8; public static final int TYPE_EXT32 = 0xC9; /** * Gets the {@link MessageType} of the next value. */ public static MessageType of(int next) { if (next == TYPE_BOOL_FALSE || next == TYPE_BOOL_TRUE) { return BOOL; } else if ((next & FIXINT_MASK) == 0 || (next & TYPE_NEGINT_MASK) == TYPE_NEGINT_MASK || next == TYPE_INT8 || next == TYPE_INT16 || next == TYPE_INT32 || next == TYPE_INT64) { return INT; } else if (next == TYPE_UINT8 || next == TYPE_UINT16 || next == TYPE_UINT32 || next == TYPE_UINT64) { return UINT; } else if (next == TYPE_FLOAT) { return FLOAT; } else if (next == TYPE_DOUBLE) { return DOUBLE; } else if ((next & SHORTSTRING_MASK) == TYPE_STR5_MASK || next == TYPE_STR8 || next == TYPE_STR16 || next == TYPE_STR32) { return STRING; } else if (next == TYPE_BIN8 || next == TYPE_BIN16 || next == TYPE_BIN32) { return BIN; } else if ((next & SHORTARRAY_MASK) == TYPE_ARRAY8_MASK || next == TYPE_ARRAY16 || next == TYPE_ARRAY32) { return ARRAY; } else if ((next & SHORTARRAY_MASK) == TYPE_MAP8_MASK || next == TYPE_MAP16 || next == TYPE_MAP32) { return MAP; } else if (next == TYPE_NIL) { return NIL; } throw new IllegalArgumentException("Unsupported messagepack type: 0x" + Integer.toHexString(next)); } }
java
MIT
e60cfaaf7a0688bc83f8b00c392521d0b162afba
2026-01-05T02:42:07.381192Z
false
Despector/Despector
https://github.com/Despector/Despector/blob/e60cfaaf7a0688bc83f8b00c392521d0b162afba/src/main/java/org/spongepowered/despector/util/serialization/AstLoader.java
src/main/java/org/spongepowered/despector/util/serialization/AstLoader.java
/* * The MIT License (MIT) * * Copyright (c) Despector <https://despector.voxelgenesis.com> * Copyright (c) contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package org.spongepowered.despector.util.serialization; import com.google.common.base.Throwables; import org.spongepowered.despector.Language; import org.spongepowered.despector.ast.AccessModifier; import org.spongepowered.despector.ast.Annotation; import org.spongepowered.despector.ast.Annotation.EnumConstant; import org.spongepowered.despector.ast.AnnotationType; import org.spongepowered.despector.ast.Locals; import org.spongepowered.despector.ast.Locals.Local; import org.spongepowered.despector.ast.Locals.LocalInstance; import org.spongepowered.despector.ast.SourceSet; import org.spongepowered.despector.ast.generic.ClassSignature; import org.spongepowered.despector.ast.generic.ClassTypeSignature; import org.spongepowered.despector.ast.generic.GenericClassTypeSignature; import org.spongepowered.despector.ast.generic.MethodSignature; import org.spongepowered.despector.ast.generic.TypeArgument; import org.spongepowered.despector.ast.generic.TypeParameter; import org.spongepowered.despector.ast.generic.TypeSignature; import org.spongepowered.despector.ast.generic.TypeVariableSignature; import org.spongepowered.despector.ast.generic.VoidTypeSignature; import org.spongepowered.despector.ast.generic.WildcardType; import org.spongepowered.despector.ast.insn.Instruction; import org.spongepowered.despector.ast.insn.condition.AndCondition; import org.spongepowered.despector.ast.insn.condition.BooleanCondition; import org.spongepowered.despector.ast.insn.condition.CompareCondition; import org.spongepowered.despector.ast.insn.condition.CompareCondition.CompareOperator; import org.spongepowered.despector.ast.insn.condition.Condition; import org.spongepowered.despector.ast.insn.condition.InverseCondition; import org.spongepowered.despector.ast.insn.condition.OrCondition; import org.spongepowered.despector.ast.insn.cst.DoubleConstant; import org.spongepowered.despector.ast.insn.cst.FloatConstant; import org.spongepowered.despector.ast.insn.cst.IntConstant; import org.spongepowered.despector.ast.insn.cst.LongConstant; import org.spongepowered.despector.ast.insn.cst.NullConstant; import org.spongepowered.despector.ast.insn.cst.StringConstant; import org.spongepowered.despector.ast.insn.cst.TypeConstant; import org.spongepowered.despector.ast.insn.misc.Cast; import org.spongepowered.despector.ast.insn.misc.InstanceOf; import org.spongepowered.despector.ast.insn.misc.MultiNewArray; import org.spongepowered.despector.ast.insn.misc.NewArray; import org.spongepowered.despector.ast.insn.misc.NumberCompare; import org.spongepowered.despector.ast.insn.misc.Ternary; import org.spongepowered.despector.ast.insn.op.NegativeOperator; import org.spongepowered.despector.ast.insn.op.Operator; import org.spongepowered.despector.ast.insn.op.OperatorType; import org.spongepowered.despector.ast.insn.var.ArrayAccess; import org.spongepowered.despector.ast.insn.var.InstanceFieldAccess; import org.spongepowered.despector.ast.insn.var.LocalAccess; import org.spongepowered.despector.ast.insn.var.StaticFieldAccess; import org.spongepowered.despector.ast.stmt.Statement; import org.spongepowered.despector.ast.stmt.StatementBlock; import org.spongepowered.despector.ast.stmt.assign.ArrayAssignment; import org.spongepowered.despector.ast.stmt.assign.InstanceFieldAssignment; import org.spongepowered.despector.ast.stmt.assign.LocalAssignment; import org.spongepowered.despector.ast.stmt.assign.StaticFieldAssignment; import org.spongepowered.despector.ast.stmt.branch.Break; import org.spongepowered.despector.ast.stmt.branch.Break.Breakable; import org.spongepowered.despector.ast.stmt.branch.DoWhile; import org.spongepowered.despector.ast.stmt.branch.For; import org.spongepowered.despector.ast.stmt.branch.ForEach; import org.spongepowered.despector.ast.stmt.branch.If; import org.spongepowered.despector.ast.stmt.branch.Switch; import org.spongepowered.despector.ast.stmt.branch.TryCatch; import org.spongepowered.despector.ast.stmt.branch.While; import org.spongepowered.despector.ast.stmt.invoke.InstanceMethodInvoke; import org.spongepowered.despector.ast.stmt.invoke.InvokeStatement; import org.spongepowered.despector.ast.stmt.invoke.Lambda; import org.spongepowered.despector.ast.stmt.invoke.MethodReference; import org.spongepowered.despector.ast.stmt.invoke.New; import org.spongepowered.despector.ast.stmt.invoke.StaticMethodInvoke; import org.spongepowered.despector.ast.stmt.misc.Comment; import org.spongepowered.despector.ast.stmt.misc.Increment; import org.spongepowered.despector.ast.stmt.misc.Return; import org.spongepowered.despector.ast.stmt.misc.Throw; import org.spongepowered.despector.ast.type.AnnotationEntry; import org.spongepowered.despector.ast.type.ClassEntry; import org.spongepowered.despector.ast.type.EnumEntry; import org.spongepowered.despector.ast.type.FieldEntry; import org.spongepowered.despector.ast.type.InterfaceEntry; import org.spongepowered.despector.ast.type.MethodEntry; import org.spongepowered.despector.ast.type.TypeEntry; import org.spongepowered.despector.decompiler.BaseDecompiler; import java.io.IOException; import java.io.InputStream; import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.function.Function; public class AstLoader { private static void expectKey(MessageUnpacker unpack, String key) throws IOException { String actual = unpack.readString(); if (!actual.equals(key)) { throw new IllegalStateException("Expected key " + key + " but was " + actual); } } private static void startMap(MessageUnpacker unpack, int size) throws IOException { int actual = unpack.readMap(); if (actual != size) { throw new IllegalStateException("Expected map size " + size + " but was " + actual); } } public static void loadSources(SourceSet set, InputStream stream) throws IOException { MessageUnpacker unpack = new MessageUnpacker(stream); startMap(unpack, 2); expectKey(unpack, "version"); int version = unpack.readInt(); if (version != AstSerializer.VERSION) { throw new IllegalStateException("Unsupported ast version " + version); } expectKey(unpack, "classes"); int classes = unpack.readArray(); for (int i = 0; i < classes; i++) { set.add(loadType(unpack, set)); } } public static TypeEntry loadType(MessageUnpacker unpack, SourceSet set) throws IOException { TypeEntry entry = null; unpack.readMap(); expectKey(unpack, "id"); int id = unpack.readInt(); expectKey(unpack, "language"); Language lang = Language.values()[unpack.readInt()]; expectKey(unpack, "name"); String name = unpack.readString(); if (id == AstSerializer.ENTRY_ID_CLASS) { entry = new ClassEntry(set, lang, name); } else if (id == AstSerializer.ENTRY_ID_ENUM) { entry = new EnumEntry(set, lang, name); } else if (id == AstSerializer.ENTRY_ID_INTERFACE) { entry = new InterfaceEntry(set, lang, name); } else if (id == AstSerializer.ENTRY_ID_ANNOTATIONTYPE) { entry = new AnnotationEntry(set, lang, name); } expectKey(unpack, "access"); entry.setAccessModifier(AccessModifier.values()[unpack.readInt()]); expectKey(unpack, "synthetic"); entry.setSynthetic(unpack.readBool()); expectKey(unpack, "final"); entry.setFinal(unpack.readBool()); expectKey(unpack, "interfaces"); int interfaces = unpack.readArray(); for (int i = 0; i < interfaces; i++) { entry.getInterfaces().add(unpack.readString()); } expectKey(unpack, "staticfields"); int staticfields = unpack.readArray(); for (int i = 0; i < staticfields; i++) { entry.addField(loadField(unpack, set)); } expectKey(unpack, "fields"); int fields = unpack.readArray(); for (int i = 0; i < fields; i++) { entry.addField(loadField(unpack, set)); } expectKey(unpack, "staticmethods"); int staticmethods = unpack.readArray(); for (int i = 0; i < staticmethods; i++) { entry.addMethod(loadMethod(unpack, set)); } expectKey(unpack, "methods"); int methods = unpack.readArray(); for (int i = 0; i < methods; i++) { entry.addMethod(loadMethod(unpack, set)); } String key = unpack.readString(); if ("signature".equals(key)) { ClassSignature sig = loadClassSignature(unpack); if (sig != null) { entry.setSignature(sig); } expectKey(unpack, "annotations"); } else if (!"annotations".equals(key)) { throw new IllegalStateException("Expected key annotations but was " + key); } int annotations = unpack.readArray(); for (int i = 0; i < annotations; i++) { entry.addAnnotation(loadAnnotation(unpack, set)); } expectKey(unpack, "inner_classes"); int innerclasses = unpack.readArray(); for (int i = 0; i < innerclasses; i++) { startMap(unpack, 8); expectKey(unpack, "name"); String innername = unpack.readString(); expectKey(unpack, "simple_name"); String simple_name = null; if (unpack.peekType() == MessageType.NIL) { unpack.readNil(); } else { simple_name = unpack.readString(); } expectKey(unpack, "outer_name"); String outer_name = null; if (unpack.peekType() == MessageType.NIL) { unpack.readNil(); } else { outer_name = unpack.readString(); } int acc = 0; expectKey(unpack, "static"); if (unpack.readBool()) { acc |= BaseDecompiler.ACC_STATIC; } expectKey(unpack, "final"); if (unpack.readBool()) { acc |= BaseDecompiler.ACC_FINAL; } expectKey(unpack, "abstract"); if (unpack.readBool()) { acc |= BaseDecompiler.ACC_ABSTRACT; } expectKey(unpack, "synthetic"); if (unpack.readBool()) { acc |= BaseDecompiler.ACC_SYNTHETIC; } expectKey(unpack, "access"); AccessModifier mod = AccessModifier.values()[unpack.readInt()]; switch (mod) { case PRIVATE: acc |= BaseDecompiler.ACC_PRIVATE; break; case PUBLIC: acc |= BaseDecompiler.ACC_PUBLIC; break; case PROTECTED: acc |= BaseDecompiler.ACC_PROTECTED; break; case PACKAGE_PRIVATE: default: break; } entry.addInnerClass(innername, simple_name, outer_name, acc); } if (id == AstSerializer.ENTRY_ID_CLASS) { expectKey(unpack, "supername"); ((ClassEntry) entry).setSuperclass(unpack.readString()); } else if (id == AstSerializer.ENTRY_ID_ENUM) { expectKey(unpack, "enumconstants"); int csts = unpack.readArray(); EnumEntry e = (EnumEntry) entry; for (int i = 0; i < csts; i++) { e.addEnumConstant(unpack.readString()); } } if (entry.getSignature() == null) { ClassSignature sig = new ClassSignature(); if (entry instanceof ClassEntry) { sig.setSuperclassSignature(new GenericClassTypeSignature(((ClassEntry) entry).getSuperclass())); } else { sig.setSuperclassSignature(new GenericClassTypeSignature("Ljava/lang/Object;")); } for (String intr : entry.getInterfaces()) { sig.getInterfaceSignatures().add(new GenericClassTypeSignature("L" + intr + ";")); } entry.setSignature(sig); } return entry; } public static FieldEntry loadField(MessageUnpacker unpack, SourceSet set) throws IOException { startMap(unpack, 12); expectKey(unpack, "id"); int id = unpack.readInt(); if (id != AstSerializer.ENTRY_ID_FIELD) { throw new IllegalStateException("Expected field"); } FieldEntry entry = new FieldEntry(set); expectKey(unpack, "access"); entry.setAccessModifier(AccessModifier.values()[unpack.readInt()]); expectKey(unpack, "name"); entry.setName(unpack.readString()); expectKey(unpack, "owner"); entry.setOwner(unpack.readString()); expectKey(unpack, "type"); entry.setType(loadTypeSignature(unpack)); expectKey(unpack, "final"); entry.setFinal(unpack.readBool()); expectKey(unpack, "static"); entry.setStatic(unpack.readBool()); expectKey(unpack, "synthetic"); entry.setSynthetic(unpack.readBool()); expectKey(unpack, "volatile"); entry.setVolatile(unpack.readBool()); expectKey(unpack, "deprecated"); entry.setDeprecated(unpack.readBool()); expectKey(unpack, "transient"); entry.setTransient(unpack.readBool()); expectKey(unpack, "annotations"); int annotations = unpack.readArray(); for (int i = 0; i < annotations; i++) { entry.addAnnotation(loadAnnotation(unpack, set)); } return entry; } public static MethodEntry loadMethod(MessageUnpacker unpack, SourceSet set) throws IOException { startMap(unpack, 18); expectKey(unpack, "id"); int id = unpack.readInt(); if (id != AstSerializer.ENTRY_ID_METHOD) { throw new IllegalStateException("Expected method"); } MethodEntry entry = new MethodEntry(set); expectKey(unpack, "access"); entry.setAccessModifier(AccessModifier.values()[unpack.readInt()]); expectKey(unpack, "owner"); entry.setOwner(unpack.readString()); expectKey(unpack, "name"); entry.setName(unpack.readString()); expectKey(unpack, "description"); entry.setDescription(unpack.readString()); expectKey(unpack, "abstract"); entry.setAbstract(unpack.readBool()); expectKey(unpack, "final"); entry.setFinal(unpack.readBool()); expectKey(unpack, "static"); entry.setStatic(unpack.readBool()); expectKey(unpack, "synthetic"); entry.setSynthetic(unpack.readBool()); expectKey(unpack, "bridge"); entry.setBridge(unpack.readBool()); expectKey(unpack, "varargs"); entry.setVarargs(unpack.readBool()); expectKey(unpack, "strictfp"); entry.setStrictFp(unpack.readBool()); expectKey(unpack, "synchronized"); entry.setSynchronized(unpack.readBool()); expectKey(unpack, "native"); entry.setNative(unpack.readBool()); expectKey(unpack, "methodsignature"); entry.setMethodSignature(loadMethodSignature(unpack)); expectKey(unpack, "locals"); Locals locals = loadLocals(unpack, entry, set); method_locals = locals; entry.setLocals(locals); expectKey(unpack, "instructions"); if (unpack.peekType() == MessageType.NIL) { unpack.readNil(); } else { StatementBlock block = loadBlock(unpack, StatementBlock.Type.METHOD); entry.setInstructions(block); } expectKey(unpack, "annotations"); int annotations = unpack.readArray(); for (int i = 0; i < annotations; i++) { entry.addAnnotation(loadAnnotation(unpack, set)); } return entry; } public static Locals loadLocals(MessageUnpacker unpack, MethodEntry method, SourceSet set) throws IOException { int size = unpack.readArray(); Locals locals = new Locals(method); for (int i = 0; i < size; i++) { startMap(unpack, 2); expectKey(unpack, "index"); int index = unpack.readInt(); Local loc = locals.getLocal(index); expectKey(unpack, "instances"); int sz = unpack.readArray(); for (int j = 0; j < sz; j++) { startMap(unpack, 6); expectKey(unpack, "name"); String name = unpack.readString(); expectKey(unpack, "type"); TypeSignature type = loadTypeSignature(unpack); expectKey(unpack, "start"); int start = unpack.readInt(); expectKey(unpack, "end"); int end = unpack.readInt(); expectKey(unpack, "final"); boolean efinal = unpack.readBool(); LocalInstance insn = new LocalInstance(loc, name, type, start, end); insn.setEffectivelyFinal(efinal); expectKey(unpack, "annotations"); int annotations = unpack.readArray(); for (int k = 0; k < annotations; k++) { insn.getAnnotations().add(loadAnnotation(unpack, set)); } loc.addInstance(insn); } } return locals; } private static StatementBlock loadBlock(MessageUnpacker unpack, StatementBlock.Type type) throws IOException { if (unpack.peekType() == MessageType.NIL) { unpack.readNil(); return null; } int statements = unpack.readArray(); StatementBlock block = new StatementBlock(type); for (int i = 0; i < statements; i++) { block.append(loadStatement(unpack)); } return block; } private static Statement loadStatement(MessageUnpacker unpack) throws IOException { if (unpack.peekType() == MessageType.NIL) { unpack.readNil(); return null; } unpack.readMap(); expectKey(unpack, "id"); int id = unpack.readInt(); Function<MessageUnpacker, Statement> loader = statement_loaders.get(id); return loader.apply(unpack); } private static Instruction loadInstruction(MessageUnpacker unpack) throws IOException { if (unpack.peekType() == MessageType.NIL) { unpack.readNil(); return null; } unpack.readMap(); expectKey(unpack, "id"); int id = unpack.readInt(); Function<MessageUnpacker, Instruction> loader = instruction_loaders.get(id); return loader.apply(unpack); } private static Condition loadCondition(MessageUnpacker unpack) throws IOException { if (unpack.peekType() == MessageType.NIL) { unpack.readNil(); return null; } unpack.readMap(); expectKey(unpack, "id"); int id = unpack.readInt(); Function<MessageUnpacker, Condition> loader = condition_loaders.get(id); return loader.apply(unpack); } public static Annotation loadAnnotation(MessageUnpacker unpack, SourceSet set) throws IOException { startMap(unpack, 4); expectKey(unpack, "id"); int id = unpack.readInt(); if (id != AstSerializer.ENTRY_ID_ANNOTATION) { throw new IllegalStateException("Expected annotation"); } expectKey(unpack, "typename"); String typename = unpack.readString(); AnnotationType type = set.getAnnotationType(typename); Annotation anno = new Annotation(type); expectKey(unpack, "runtime"); type.setRuntimeVisible(unpack.readBool()); expectKey(unpack, "values"); int sz = unpack.readArray(); for (int i = 0; i < sz; i++) { startMap(unpack, 4); expectKey(unpack, "name"); String key = unpack.readString(); expectKey(unpack, "type"); String cl = unpack.readString(); Class<?> cls = null; try { cls = Class.forName(cl); type.setType(key, cls); } catch (ClassNotFoundException e) { Throwables.propagate(e); } expectKey(unpack, "default"); Object def = loadAnnotationObject(unpack, set); type.setDefault(key, def); expectKey(unpack, "value"); Object val = loadAnnotationObject(unpack, set); anno.setValue(key, val); } return anno; } @SuppressWarnings({"rawtypes", "unchecked"}) private static Object loadAnnotationObject(MessageUnpacker unpack, SourceSet set) throws IOException { startMap(unpack, 2); expectKey(unpack, "typename"); String cl = unpack.readString(); Class<?> type = null; try { type = Class.forName(cl); } catch (ClassNotFoundException e) { Throwables.propagate(e); } expectKey(unpack, "value"); if (type == Integer.class) { return unpack.readInt(); } else if (type == Byte.class) { return unpack.readByte(); } else if (type == Short.class) { return unpack.readShort(); } else if (type == Long.class) { return unpack.readLong(); } else if (type == Float.class) { return unpack.readFloat(); } else if (type == Double.class) { return unpack.readDouble(); } else if (type == String.class) { return unpack.readString(); } else if (type == ArrayList.class) { int sz = unpack.readArray(); List lst = new ArrayList(); for (int i = 0; i < sz; i++) { lst.add(loadAnnotationObject(unpack, set)); } } else if (type == ClassTypeSignature.class) { return loadTypeSignature(unpack); } else if (type == Annotation.class) { return loadAnnotation(unpack, set); } else if (type == EnumConstant.class) { unpack.readMap(); expectKey(unpack, "enumtype"); String enumtype = unpack.readString(); expectKey(unpack, "constant"); String cst = unpack.readString(); return new EnumConstant(enumtype, cst); } throw new IllegalStateException("Unsupported annotation value type " + type.getName()); } public static ClassSignature loadClassSignature(MessageUnpacker unpack) throws IOException { if (unpack.peekType() == MessageType.NIL) { unpack.readNil(); return null; } startMap(unpack, 4); expectKey(unpack, "id"); int id = unpack.readInt(); if (id != AstSerializer.SIGNATURE_ID_CLASS) { throw new IllegalStateException("Expected class signature"); } ClassSignature sig = new ClassSignature(); expectKey(unpack, "parameters"); int sz = unpack.readArray(); for (int i = 0; i < sz; i++) { sig.getParameters().add(loadTypeParameter(unpack)); } expectKey(unpack, "superclass"); sig.setSuperclassSignature((GenericClassTypeSignature) loadTypeSignature(unpack)); expectKey(unpack, "interfaces"); int interfaces = unpack.readArray(); for (int i = 0; i < interfaces; i++) { sig.getInterfaceSignatures().add((GenericClassTypeSignature) loadTypeSignature(unpack)); } return sig; } private static TypeParameter loadTypeParameter(MessageUnpacker unpack) throws IOException { startMap(unpack, 4); expectKey(unpack, "id"); int id = unpack.readInt(); if (id != AstSerializer.SIGNATURE_ID_PARAM) { throw new IllegalStateException("Expected type parameter"); } expectKey(unpack, "identifier"); String ident = unpack.readString(); expectKey(unpack, "classbound"); TypeSignature cl = loadTypeSignature(unpack); TypeParameter param = new TypeParameter(ident, cl); expectKey(unpack, "interfacebounds"); int sz = unpack.readArray(); for (int i = 0; i < sz; i++) { param.getInterfaceBounds().add(loadTypeSignature(unpack)); } return param; } public static MethodSignature loadMethodSignature(MessageUnpacker unpack) throws IOException { if (unpack.peekType() == MessageType.NIL) { unpack.readNil(); return null; } startMap(unpack, 5); expectKey(unpack, "id"); int id = unpack.readInt(); if (id != AstSerializer.SIGNATURE_ID_METHOD) { throw new IllegalStateException("Expected method signature"); } MethodSignature sig = new MethodSignature(); expectKey(unpack, "type_parameters"); { int sz = unpack.readArray(); for (int i = 0; i < sz; i++) { sig.getTypeParameters().add(loadTypeParameter(unpack)); } } expectKey(unpack, "parameters"); { int sz = unpack.readArray(); for (int i = 0; i < sz; i++) { sig.getParameters().add(loadTypeSignature(unpack)); } } expectKey(unpack, "exceptions"); { int sz = unpack.readArray(); for (int i = 0; i < sz; i++) { sig.getThrowsSignature().add(loadTypeSignature(unpack)); } } expectKey(unpack, "returntype"); sig.setReturnType(loadTypeSignature(unpack)); return sig; } public static TypeSignature loadTypeSignature(MessageUnpacker unpack) throws IOException { if (unpack.peekType() == MessageType.NIL) { unpack.readNil(); return null; } unpack.readMap(); expectKey(unpack, "id"); int id = unpack.readInt(); Function<MessageUnpacker, TypeSignature> loader = signature_loaders.get(id); return loader.apply(unpack); } private static LocalInstance loadLocal(MessageUnpacker unpack) throws IOException { startMap(unpack, 3); expectKey(unpack, "local"); int index = unpack.readInt(); expectKey(unpack, "start"); int start = unpack.readInt(); expectKey(unpack, "type"); String type = null; if (unpack.peekType() != MessageType.NIL) { type = unpack.readString(); } else { unpack.readNil(); } Local loc = method_locals.getLocal(index); return loc.find(start, type); } private static final Map<Integer, Function<MessageUnpacker, Statement>> statement_loaders; private static final Map<Integer, Function<MessageUnpacker, Instruction>> instruction_loaders; private static final Map<Integer, Function<MessageUnpacker, Condition>> condition_loaders; private static final Map<Integer, Function<MessageUnpacker, TypeSignature>> signature_loaders; private static final Map<Integer, Breakable> breakables = new HashMap<>(); private static Locals method_locals; static { statement_loaders = new HashMap<>(); instruction_loaders = new HashMap<>(); condition_loaders = new HashMap<>(); signature_loaders = new HashMap<>(); instruction_loaders.put(AstSerializer.STATEMENT_ID_ARRAY_ACCESS, (unpack) -> { try { expectKey(unpack, "array"); Instruction array = loadInstruction(unpack); expectKey(unpack, "index"); Instruction index = loadInstruction(unpack); ArrayAccess stmt = new ArrayAccess(array, index); return stmt; } catch (IOException e) { Throwables.propagate(e); } return null; }); statement_loaders.put(AstSerializer.STATEMENT_ID_ARRAY_ASSIGN, (unpack) -> { try { expectKey(unpack, "array"); Instruction array = loadInstruction(unpack); expectKey(unpack, "index"); Instruction index = loadInstruction(unpack); expectKey(unpack, "val"); Instruction val = loadInstruction(unpack); ArrayAssignment stmt = new ArrayAssignment(array, index, val); return stmt; } catch (IOException e) { Throwables.propagate(e); } return null; }); statement_loaders.put(AstSerializer.STATEMENT_ID_BREAK, (unpack) -> { try { expectKey(unpack, "type"); Break.Type type = Break.Type.values()[unpack.readInt()]; expectKey(unpack, "nested"); boolean nested = unpack.readBool(); expectKey(unpack, "break_id"); int key = unpack.readInt(); Breakable brk = breakables.get(key); return new Break(brk, type, nested); } catch (IOException e) { Throwables.propagate(e); } return null; }); instruction_loaders.put(AstSerializer.STATEMENT_ID_CAST, (unpack) -> { try { expectKey(unpack, "value"); Instruction val = loadInstruction(unpack); expectKey(unpack, "type"); TypeSignature type = loadTypeSignature(unpack); return new Cast(type, val); } catch (IOException e) { Throwables.propagate(e); } return null; }); statement_loaders.put(AstSerializer.STATEMENT_ID_COMMENT, (unpack) -> { try { expectKey(unpack, "comment"); int size = unpack.readArray(); List<String> text = new ArrayList<>(size); for (int i = 0; i < size; i++) { text.add(unpack.readString()); } return new Comment(text); } catch (IOException e) { Throwables.propagate(e); } return null; }); statement_loaders.put(AstSerializer.STATEMENT_ID_DO_WHILE, (unpack) -> { try { expectKey(unpack, "condition"); Condition cond = loadCondition(unpack); DoWhile loop = new DoWhile(cond, new StatementBlock(StatementBlock.Type.WHILE)); expectKey(unpack, "breakpoints"); int brk_size = unpack.readArray(); for (int i = 0; i < brk_size; i++) { breakables.put(unpack.readInt(), loop); } expectKey(unpack, "body"); StatementBlock body = loadBlock(unpack, StatementBlock.Type.WHILE); loop.setBody(body); for (Iterator<Map.Entry<Integer, Breakable>> it = breakables.entrySet().iterator(); it.hasNext();) { Map.Entry<Integer, Breakable> n = it.next(); if (n.getValue() == loop) { it.remove(); } } return loop; } catch (IOException e) {
java
MIT
e60cfaaf7a0688bc83f8b00c392521d0b162afba
2026-01-05T02:42:07.381192Z
true
Despector/Despector
https://github.com/Despector/Despector/blob/e60cfaaf7a0688bc83f8b00c392521d0b162afba/src/main/java/org/spongepowered/despector/util/serialization/MessagePrinter.java
src/main/java/org/spongepowered/despector/util/serialization/MessagePrinter.java
/* * The MIT License (MIT) * * Copyright (c) Despector <https://despector.voxelgenesis.com> * Copyright (c) contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package org.spongepowered.despector.util.serialization; import java.io.EOFException; import java.io.IOException; public class MessagePrinter { public static String print(MessageUnpacker unpack) { StringBuilder str = new StringBuilder(); try { printNext(unpack, str, 0); } catch (EOFException e) { str.append("EOF!"); } catch (IOException e) { e.printStackTrace(); } return str.toString(); } private static void printNext(MessageUnpacker unpack, StringBuilder out, int indent) throws IOException { for (int i = 0; i < indent; i++) { out.append(" "); } MessageType type = unpack.peekType(); out.append(type.name()).append(" "); switch (type) { case ARRAY: int sz = unpack.readArray(); out.append("(entryies = ").append(sz).append(")\n"); for (int i = 0; i < sz; i++) { printNext(unpack, out, indent + 1); } break; case BIN: unpack.readBinary(); out.append("\n"); break; case BOOL: boolean zval = unpack.readBool(); out.append(zval).append("\n"); break; case DOUBLE: double dval = unpack.readDouble(); out.append(dval).append("\n"); break; case FLOAT: float fval = unpack.readFloat(); out.append(fval).append("\n"); break; case INT: int ival = unpack.readInt(); out.append(ival).append("\n"); break; case LONG: long lval = unpack.readLong(); out.append(lval).append("\n"); break; case MAP: int map_sz = unpack.readMap(); out.append("(entryies = ").append(map_sz).append(")\n"); for (int i = 0; i < map_sz * 2; i++) { printNext(unpack, out, indent + 1); } break; case NIL: unpack.readNil(); out.append("\n"); break; case STRING: String str = unpack.readString(); out.append("\"").append(str).append("\"").append("\n"); break; case UINT: long uival = unpack.readUnsignedInt(); out.append(uival).append("\n"); break; case ULONG: long ulval = unpack.readUnsignedLong(); out.append(ulval).append("\n"); break; default: throw new IllegalStateException("Unsupported message type: " + type.name()); } } }
java
MIT
e60cfaaf7a0688bc83f8b00c392521d0b162afba
2026-01-05T02:42:07.381192Z
false
Despector/Despector
https://github.com/Despector/Despector/blob/e60cfaaf7a0688bc83f8b00c392521d0b162afba/src/main/java/org/spongepowered/despector/util/serialization/AstSerializer.java
src/main/java/org/spongepowered/despector/util/serialization/AstSerializer.java
/* * The MIT License (MIT) * * Copyright (c) Despector <https://despector.voxelgenesis.com> * Copyright (c) contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package org.spongepowered.despector.util.serialization; /** * Constants for serializing ast elements. */ public final class AstSerializer { public static final int VERSION = 1; public static final int ENTRY_ID_CLASS = 0x00; public static final int ENTRY_ID_ENUM = 0x01; public static final int ENTRY_ID_INTERFACE = 0x02; public static final int ENTRY_ID_METHOD = 0x03; public static final int ENTRY_ID_FIELD = 0x04; public static final int ENTRY_ID_ARRAY = 0x05; public static final int ENTRY_ID_STATEMENT_BODY = 0x06; public static final int ENTRY_ID_ANNOTATION = 0x07; public static final int ENTRY_ID_ANNOTATIONTYPE = 0x07; public static final int STATEMENT_ID_COMMENT = 0x10; public static final int STATEMENT_ID_INCREMENT = 0x11; public static final int STATEMENT_ID_RETURN = 0x12; public static final int STATEMENT_ID_THROW = 0x13; public static final int STATEMENT_ID_STATIC_INVOKE = 0x14; public static final int STATEMENT_ID_INSTANCE_INVOKE = 0x15; public static final int STATEMENT_ID_DYNAMIC_INVOKE = 0x16; public static final int STATEMENT_ID_NEW = 0x17; public static final int STATEMENT_ID_IF = 0x18; public static final int STATEMENT_ID_DO_WHILE = 0x19; public static final int STATEMENT_ID_WHILE = 0x1A; public static final int STATEMENT_ID_FOR = 0x1B; public static final int STATEMENT_ID_FOREACH = 0x1C; public static final int STATEMENT_ID_SWITCH = 0x1D; public static final int STATEMENT_ID_TRY_CATCH = 0x1E; public static final int STATEMENT_ID_TERNARY = 0x1F; public static final int STATEMENT_ID_ARRAY_ASSIGN = 0x20; public static final int STATEMENT_ID_INSTANCE_FIELD_ASSIGN = 0x21; public static final int STATEMENT_ID_STATIC_FIELD_ASSIGN = 0x22; public static final int STATEMENT_ID_LOCAL_ASSIGN = 0x23; public static final int STATEMENT_ID_NUMBER_COMPARE = 0x24; public static final int STATEMENT_ID_NEW_ARRAY = 0x25; public static final int STATEMENT_ID_INSTANCE_OF = 0x26; public static final int STATEMENT_ID_CAST = 0x27; public static final int STATEMENT_ID_OPERATOR = 0x28; public static final int STATEMENT_ID_NEGATIVE_OPERATOR = 0x29; public static final int STATEMENT_ID_ARRAY_ACCESS = 0x2A; public static final int STATEMENT_ID_INSTANCE_FIELD_ACCESS = 0x2B; public static final int STATEMENT_ID_STATIC_FIELD_ACCESS = 0x2C; public static final int STATEMENT_ID_LOCAL_ACCESS = 0x2D; public static final int STATEMENT_ID_DOUBLE_CONSTANT = 0x2E; public static final int STATEMENT_ID_FLOAT_CONSTANT = 0x2F; public static final int STATEMENT_ID_INT_CONSTANT = 0x30; public static final int STATEMENT_ID_LONG_CONSTANT = 0x31; public static final int STATEMENT_ID_NULL_CONSTANT = 0x32; public static final int STATEMENT_ID_STRING_CONSTANT = 0x33; public static final int STATEMENT_ID_TYPE_CONSTANT = 0x34; public static final int STATEMENT_ID_INVOKE = 0x35; public static final int STATEMENT_ID_BREAK = 0x36; public static final int STATEMENT_ID_MULTI_NEW_ARRAY = 0x37; public static final int STATEMENT_ID_METHOD_REF = 0x38; public static final int SIGNATURE_ID_TYPEVOID = 0x80; public static final int SIGNATURE_ID_TYPECLASS = 0x81; public static final int SIGNATURE_ID_TYPEVAR = 0x82; public static final int SIGNATURE_ID_ARG = 0x83; public static final int SIGNATURE_ID_PARAM = 0x84; public static final int SIGNATURE_ID_CLASS = 0x85; public static final int SIGNATURE_ID_METHOD = 0x86; public static final int SIGNATURE_ID_TYPEGENERIC = 0x87; public static final int CONDITION_ID_AND = 0x90; public static final int CONDITION_ID_BOOL = 0x91; public static final int CONDITION_ID_OR = 0x92; public static final int CONDITION_ID_COMPARE = 0x93; public static final int CONDITION_ID_INVERSE = 0x94; private AstSerializer() { } }
java
MIT
e60cfaaf7a0688bc83f8b00c392521d0b162afba
2026-01-05T02:42:07.381192Z
false
Despector/Despector
https://github.com/Despector/Despector/blob/e60cfaaf7a0688bc83f8b00c392521d0b162afba/src/main/java/org/spongepowered/despector/emitter/ConditionEmitter.java
src/main/java/org/spongepowered/despector/emitter/ConditionEmitter.java
/* * The MIT License (MIT) * * Copyright (c) Despector <https://despector.voxelgenesis.com> * Copyright (c) contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package org.spongepowered.despector.emitter; import org.spongepowered.despector.ast.insn.condition.Condition; /** * An emitter for a condition. */ public interface ConditionEmitter<C extends AbstractEmitterContext, T extends Condition> { /** * Emits the given condition. */ void emit(C ctx, T condition); }
java
MIT
e60cfaaf7a0688bc83f8b00c392521d0b162afba
2026-01-05T02:42:07.381192Z
false
Despector/Despector
https://github.com/Despector/Despector/blob/e60cfaaf7a0688bc83f8b00c392521d0b162afba/src/main/java/org/spongepowered/despector/emitter/EmitterSet.java
src/main/java/org/spongepowered/despector/emitter/EmitterSet.java
/* * The MIT License (MIT) * * Copyright (c) Despector <https://despector.voxelgenesis.com> * Copyright (c) contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package org.spongepowered.despector.emitter; import org.spongepowered.despector.ast.AstEntry; import org.spongepowered.despector.ast.insn.Instruction; import org.spongepowered.despector.ast.insn.condition.Condition; import org.spongepowered.despector.ast.stmt.Statement; import org.spongepowered.despector.emitter.format.EmitterFormat; import java.util.HashMap; import java.util.Map; /** * A set of emitter operations. */ public class EmitterSet { private final Map<Class<?>, AstEmitter<?,?>> emitters = new HashMap<>(); private final Map<Class<?>, StatementEmitter<?,?>> stmt_emitters = new HashMap<>(); private final Map<Class<?>, InstructionEmitter<?,?>> insn_emitters = new HashMap<>(); private final Map<Class<?>, ConditionEmitter<?,?>> cond_emitters = new HashMap<>(); private final Map<Class<?>, SpecialEmitter> special_emitters = new HashMap<>(); public EmitterSet() { } /** * Gets the given ast emitter for the given type. */ @SuppressWarnings("unchecked") public <C extends AbstractEmitterContext, T extends AstEntry> AstEmitter<C, T> getAstEmitter(Class<T> type) { return (AstEmitter<C, T>) this.emitters.get(type); } /** * Sets the given ast emitter for the given type. */ public <T extends AstEntry> void setAstEmitter(Class<? extends T> type, AstEmitter<?, T> emitter) { this.emitters.put(type, emitter); } /** * Gets the given statement emitter for the given type. */ @SuppressWarnings("unchecked") public <C extends AbstractEmitterContext, T extends Statement> StatementEmitter<C, T> getStatementEmitter(Class<T> type) { return (StatementEmitter<C, T>) this.stmt_emitters.get(type); } /** * Sets the given statement emitter for the given type. */ public <T extends Statement> void setStatementEmitter(Class<? extends T> type, StatementEmitter<?, T> emitter) { this.stmt_emitters.put(type, emitter); } /** * Gets the given instruction emitter for the given type. */ @SuppressWarnings("unchecked") public <C extends AbstractEmitterContext, T extends Instruction> InstructionEmitter<C, T> getInstructionEmitter(Class<T> type) { return (InstructionEmitter<C, T>) this.insn_emitters.get(type); } /** * Sets the given instruction emitter for the given type. */ public <T extends Instruction> void setInstructionEmitter(Class<? extends T> type, InstructionEmitter<?, T> emitter) { this.insn_emitters.put(type, emitter); } /** * Gets the given condition emitter for the given type. */ @SuppressWarnings("unchecked") public <C extends AbstractEmitterContext, T extends Condition> ConditionEmitter<C, T> getConditionEmitter(Class<T> type) { return (ConditionEmitter<C, T>) this.cond_emitters.get(type); } /** * Sets the given condition emitter for the given type. */ public <T extends Condition> void setConditionEmitter(Class<T> type, ConditionEmitter<?, T> emitter) { this.cond_emitters.put(type, emitter); } /** * Gets the given special emitter for the given type. */ @SuppressWarnings("unchecked") public <T extends SpecialEmitter> T getSpecialEmitter(Class<T> type) { return (T) this.special_emitters.get(type); } /** * Sets the given special emitter for the given type. */ public <T extends SpecialEmitter> void setSpecialEmitter(Class<T> type, T emitter) { this.special_emitters.put(type, emitter); } /** * Clones the given {@link EmitterFormat} into this emitter set. */ public void clone(EmitterSet other) { this.emitters.putAll(other.emitters); this.cond_emitters.putAll(other.cond_emitters); this.insn_emitters.putAll(other.insn_emitters); this.special_emitters.putAll(other.special_emitters); this.stmt_emitters.putAll(other.stmt_emitters); } }
java
MIT
e60cfaaf7a0688bc83f8b00c392521d0b162afba
2026-01-05T02:42:07.381192Z
false
Despector/Despector
https://github.com/Despector/Despector/blob/e60cfaaf7a0688bc83f8b00c392521d0b162afba/src/main/java/org/spongepowered/despector/emitter/InstructionEmitter.java
src/main/java/org/spongepowered/despector/emitter/InstructionEmitter.java
/* * The MIT License (MIT) * * Copyright (c) Despector <https://despector.voxelgenesis.com> * Copyright (c) contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package org.spongepowered.despector.emitter; import org.spongepowered.despector.ast.generic.TypeSignature; import org.spongepowered.despector.ast.insn.Instruction; /** * An emitter for a particular instruction type. */ public interface InstructionEmitter<C extends AbstractEmitterContext, T extends Instruction> { /** * Emits the given instruction. */ void emit(C ctx, T arg, TypeSignature type); }
java
MIT
e60cfaaf7a0688bc83f8b00c392521d0b162afba
2026-01-05T02:42:07.381192Z
false
Despector/Despector
https://github.com/Despector/Despector/blob/e60cfaaf7a0688bc83f8b00c392521d0b162afba/src/main/java/org/spongepowered/despector/emitter/package-info.java
src/main/java/org/spongepowered/despector/emitter/package-info.java
/* * The MIT License (MIT) * * Copyright (c) Despector <https://despector.voxelgenesis.com> * Copyright (c) contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ @org.spongepowered.despector.util.NonnullByDefault package org.spongepowered.despector.emitter;
java
MIT
e60cfaaf7a0688bc83f8b00c392521d0b162afba
2026-01-05T02:42:07.381192Z
false
Despector/Despector
https://github.com/Despector/Despector/blob/e60cfaaf7a0688bc83f8b00c392521d0b162afba/src/main/java/org/spongepowered/despector/emitter/Emitters.java
src/main/java/org/spongepowered/despector/emitter/Emitters.java
/* * The MIT License (MIT) * * Copyright (c) Despector <https://despector.voxelgenesis.com> * Copyright (c) contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package org.spongepowered.despector.emitter; import org.spongepowered.despector.Language; import org.spongepowered.despector.ast.insn.condition.AndCondition; import org.spongepowered.despector.ast.insn.condition.BooleanCondition; import org.spongepowered.despector.ast.insn.condition.CompareCondition; import org.spongepowered.despector.ast.insn.condition.InverseCondition; import org.spongepowered.despector.ast.insn.condition.OrCondition; import org.spongepowered.despector.ast.insn.cst.DoubleConstant; import org.spongepowered.despector.ast.insn.cst.FloatConstant; import org.spongepowered.despector.ast.insn.cst.IntConstant; import org.spongepowered.despector.ast.insn.cst.LongConstant; import org.spongepowered.despector.ast.insn.cst.NullConstant; import org.spongepowered.despector.ast.insn.cst.StringConstant; import org.spongepowered.despector.ast.insn.cst.TypeConstant; import org.spongepowered.despector.ast.insn.misc.Cast; import org.spongepowered.despector.ast.insn.misc.InstanceOf; import org.spongepowered.despector.ast.insn.misc.MultiNewArray; import org.spongepowered.despector.ast.insn.misc.NewArray; import org.spongepowered.despector.ast.insn.misc.NumberCompare; import org.spongepowered.despector.ast.insn.misc.Ternary; import org.spongepowered.despector.ast.insn.op.NegativeOperator; import org.spongepowered.despector.ast.insn.op.Operator; import org.spongepowered.despector.ast.insn.var.ArrayAccess; import org.spongepowered.despector.ast.insn.var.InstanceFieldAccess; import org.spongepowered.despector.ast.insn.var.LocalAccess; import org.spongepowered.despector.ast.insn.var.StaticFieldAccess; import org.spongepowered.despector.ast.kotlin.Elvis; import org.spongepowered.despector.ast.kotlin.When; import org.spongepowered.despector.ast.stmt.assign.ArrayAssignment; import org.spongepowered.despector.ast.stmt.assign.FieldAssignment; import org.spongepowered.despector.ast.stmt.assign.InstanceFieldAssignment; import org.spongepowered.despector.ast.stmt.assign.LocalAssignment; import org.spongepowered.despector.ast.stmt.assign.StaticFieldAssignment; import org.spongepowered.despector.ast.stmt.branch.Break; import org.spongepowered.despector.ast.stmt.branch.DoWhile; import org.spongepowered.despector.ast.stmt.branch.For; import org.spongepowered.despector.ast.stmt.branch.ForEach; import org.spongepowered.despector.ast.stmt.branch.If; import org.spongepowered.despector.ast.stmt.branch.Switch; import org.spongepowered.despector.ast.stmt.branch.TryCatch; import org.spongepowered.despector.ast.stmt.branch.While; import org.spongepowered.despector.ast.stmt.invoke.InstanceMethodInvoke; import org.spongepowered.despector.ast.stmt.invoke.InvokeStatement; import org.spongepowered.despector.ast.stmt.invoke.Lambda; import org.spongepowered.despector.ast.stmt.invoke.MethodReference; import org.spongepowered.despector.ast.stmt.invoke.New; import org.spongepowered.despector.ast.stmt.invoke.StaticMethodInvoke; import org.spongepowered.despector.ast.stmt.misc.Comment; import org.spongepowered.despector.ast.stmt.misc.Increment; import org.spongepowered.despector.ast.stmt.misc.Return; import org.spongepowered.despector.ast.stmt.misc.Throw; import org.spongepowered.despector.ast.type.AnnotationEntry; import org.spongepowered.despector.ast.type.ClassEntry; import org.spongepowered.despector.ast.type.EnumEntry; import org.spongepowered.despector.ast.type.FieldEntry; import org.spongepowered.despector.ast.type.InterfaceEntry; import org.spongepowered.despector.ast.type.MethodEntry; import org.spongepowered.despector.emitter.bytecode.BytecodeEmitter; import org.spongepowered.despector.emitter.bytecode.BytecodeEmitterContext; import org.spongepowered.despector.emitter.bytecode.instruction.BytecodeDoubleConstantEmitter; import org.spongepowered.despector.emitter.bytecode.instruction.BytecodeFloatConstantEmitter; import org.spongepowered.despector.emitter.bytecode.instruction.BytecodeInstanceMethodInvokeEmitter; import org.spongepowered.despector.emitter.bytecode.instruction.BytecodeIntConstantEmitter; import org.spongepowered.despector.emitter.bytecode.instruction.BytecodeLocalAccessEmitter; import org.spongepowered.despector.emitter.bytecode.instruction.BytecodeLongConstantEmitter; import org.spongepowered.despector.emitter.bytecode.instruction.BytecodeNullConstantEmitter; import org.spongepowered.despector.emitter.bytecode.instruction.BytecodeStaticFieldAccessEmitter; import org.spongepowered.despector.emitter.bytecode.instruction.BytecodeStringConstantEmitter; import org.spongepowered.despector.emitter.bytecode.instruction.BytecodeTypeConstantEmitter; import org.spongepowered.despector.emitter.bytecode.statement.BytecodeIfEmitter; import org.spongepowered.despector.emitter.bytecode.statement.BytecodeInvokeStatementEmitter; import org.spongepowered.despector.emitter.bytecode.statement.BytecodeLocalAssignmentEmitter; import org.spongepowered.despector.emitter.bytecode.statement.BytecodeReturnEmitter; import org.spongepowered.despector.emitter.bytecode.type.BytecodeClassEntryEmitter; import org.spongepowered.despector.emitter.bytecode.type.BytecodeMethodEntryEmitter; import org.spongepowered.despector.emitter.ir.IREmitter; import org.spongepowered.despector.emitter.ir.MethodIREmitter; import org.spongepowered.despector.emitter.java.JavaEmitter; import org.spongepowered.despector.emitter.java.JavaEmitterContext; import org.spongepowered.despector.emitter.java.condition.AndConditionEmitter; import org.spongepowered.despector.emitter.java.condition.BooleanConditionEmitter; import org.spongepowered.despector.emitter.java.condition.CompareConditionEmitter; import org.spongepowered.despector.emitter.java.condition.InverseConditionEmitter; import org.spongepowered.despector.emitter.java.condition.OrConditionEmitter; import org.spongepowered.despector.emitter.java.instruction.ArrayLoadEmitter; import org.spongepowered.despector.emitter.java.instruction.CastEmitter; import org.spongepowered.despector.emitter.java.instruction.CompareEmitter; import org.spongepowered.despector.emitter.java.instruction.DoubleConstantEmitter; import org.spongepowered.despector.emitter.java.instruction.DynamicInvokeEmitter; import org.spongepowered.despector.emitter.java.instruction.FieldAccessEmitter; import org.spongepowered.despector.emitter.java.instruction.FloatConstantEmitter; import org.spongepowered.despector.emitter.java.instruction.InstanceMethodInvokeEmitter; import org.spongepowered.despector.emitter.java.instruction.InstanceOfEmitter; import org.spongepowered.despector.emitter.java.instruction.IntConstantEmitter; import org.spongepowered.despector.emitter.java.instruction.LocalAccessEmitter; import org.spongepowered.despector.emitter.java.instruction.LongConstantEmitter; import org.spongepowered.despector.emitter.java.instruction.MethodReferenceEmitter; import org.spongepowered.despector.emitter.java.instruction.MultiNewArrayEmitter; import org.spongepowered.despector.emitter.java.instruction.NegativeEmitter; import org.spongepowered.despector.emitter.java.instruction.NewArrayEmitter; import org.spongepowered.despector.emitter.java.instruction.NewEmitter; import org.spongepowered.despector.emitter.java.instruction.NullConstantEmitter; import org.spongepowered.despector.emitter.java.instruction.OperatorEmitter; import org.spongepowered.despector.emitter.java.instruction.StaticMethodInvokeEmitter; import org.spongepowered.despector.emitter.java.instruction.StringConstantEmitter; import org.spongepowered.despector.emitter.java.instruction.TernaryEmitter; import org.spongepowered.despector.emitter.java.instruction.TypeConstantEmitter; import org.spongepowered.despector.emitter.java.special.AnnotationEmitter; import org.spongepowered.despector.emitter.java.special.AnonymousClassEmitter; import org.spongepowered.despector.emitter.java.special.GenericsEmitter; import org.spongepowered.despector.emitter.java.special.PackageEmitter; import org.spongepowered.despector.emitter.java.special.PackageInfoEmitter; import org.spongepowered.despector.emitter.java.statement.ArrayAssignmentEmitter; import org.spongepowered.despector.emitter.java.statement.BreakEmitter; import org.spongepowered.despector.emitter.java.statement.CommentEmitter; import org.spongepowered.despector.emitter.java.statement.DoWhileEmitter; import org.spongepowered.despector.emitter.java.statement.FieldAssignmentEmitter; import org.spongepowered.despector.emitter.java.statement.ForEachEmitter; import org.spongepowered.despector.emitter.java.statement.ForEmitter; import org.spongepowered.despector.emitter.java.statement.IfEmitter; import org.spongepowered.despector.emitter.java.statement.IncrementEmitter; import org.spongepowered.despector.emitter.java.statement.InvokeEmitter; import org.spongepowered.despector.emitter.java.statement.LocalAssignmentEmitter; import org.spongepowered.despector.emitter.java.statement.ReturnEmitter; import org.spongepowered.despector.emitter.java.statement.SwitchEmitter; import org.spongepowered.despector.emitter.java.statement.ThrowEmitter; import org.spongepowered.despector.emitter.java.statement.TryCatchEmitter; import org.spongepowered.despector.emitter.java.statement.WhileEmitter; import org.spongepowered.despector.emitter.java.type.AnnotationEntryEmitter; import org.spongepowered.despector.emitter.java.type.ClassEntryEmitter; import org.spongepowered.despector.emitter.java.type.EnumEntryEmitter; import org.spongepowered.despector.emitter.java.type.FieldEntryEmitter; import org.spongepowered.despector.emitter.java.type.InterfaceEntryEmitter; import org.spongepowered.despector.emitter.java.type.MethodEntryEmitter; import org.spongepowered.despector.emitter.kotlin.KotlinEmitter; import org.spongepowered.despector.emitter.kotlin.condition.KotlinBooleanConditionEmitter; import org.spongepowered.despector.emitter.kotlin.condition.KotlinCompareConditionEmitter; import org.spongepowered.despector.emitter.kotlin.condition.KotlinInverseConditionEmitter; import org.spongepowered.despector.emitter.kotlin.instruction.ElvisEmitter; import org.spongepowered.despector.emitter.kotlin.instruction.KotlinCastEmitter; import org.spongepowered.despector.emitter.kotlin.instruction.KotlinInstanceOfEmitter; import org.spongepowered.despector.emitter.kotlin.instruction.KotlinNewEmitter; import org.spongepowered.despector.emitter.kotlin.instruction.KotlinOperatorEmitter; import org.spongepowered.despector.emitter.kotlin.instruction.KotlinTernaryEmitter; import org.spongepowered.despector.emitter.kotlin.instruction.WhenEmitter; import org.spongepowered.despector.emitter.kotlin.instruction.method.KotlinInstanceMethodInvokeEmitter; import org.spongepowered.despector.emitter.kotlin.instruction.method.KotlinStaticMethodInvokeEmitter; import org.spongepowered.despector.emitter.kotlin.special.KotlinCompanionClassEmitter; import org.spongepowered.despector.emitter.kotlin.special.KotlinDataClassEmitter; import org.spongepowered.despector.emitter.kotlin.special.KotlinGenericsEmitter; import org.spongepowered.despector.emitter.kotlin.special.KotlinPackageEmitter; import org.spongepowered.despector.emitter.kotlin.statement.KotlinForEachEmitter; import org.spongepowered.despector.emitter.kotlin.statement.KotlinForEmitter; import org.spongepowered.despector.emitter.kotlin.statement.KotlinInvokeEmitter; import org.spongepowered.despector.emitter.kotlin.statement.KotlinLocalAssignmentEmitter; import org.spongepowered.despector.emitter.kotlin.type.KotlinClassEntryEmitter; import org.spongepowered.despector.emitter.kotlin.type.KotlinEnumEntryEmitter; import org.spongepowered.despector.emitter.kotlin.type.KotlinMethodEntryEmitter; import java.util.EnumMap; /** * Standard emitters. */ public final class Emitters { public static final EmitterSet JAVA_SET = new EmitterSet(); public static final EmitterSet KOTLIN_SET = new EmitterSet(); public static final EmitterSet BYTECODE_SET = new EmitterSet(); public static final EmitterSet IR_SET = new EmitterSet(); public static final Emitter<JavaEmitterContext> JAVA = new JavaEmitter(); public static final Emitter<JavaEmitterContext> KOTLIN = new KotlinEmitter(); public static final Emitter<?> WILD = new WildEmitter(); public static final Emitter<BytecodeEmitterContext> BYTECODE = new BytecodeEmitter(); public static final Emitter<JavaEmitterContext> IR = new IREmitter(); @SuppressWarnings("rawtypes") private static final EnumMap<Language, Emitter> EMITTERS = new EnumMap<>(Language.class); static { JAVA_SET.setSpecialEmitter(AnnotationEmitter.class, new AnnotationEmitter()); JAVA_SET.setSpecialEmitter(GenericsEmitter.class, new GenericsEmitter()); JAVA_SET.setSpecialEmitter(AnonymousClassEmitter.class, new AnonymousClassEmitter()); JAVA_SET.setSpecialEmitter(PackageInfoEmitter.class, new PackageInfoEmitter()); JAVA_SET.setSpecialEmitter(PackageEmitter.class, new PackageEmitter()); JAVA_SET.setAstEmitter(ClassEntry.class, new ClassEntryEmitter()); JAVA_SET.setAstEmitter(EnumEntry.class, new EnumEntryEmitter()); JAVA_SET.setAstEmitter(InterfaceEntry.class, new InterfaceEntryEmitter()); JAVA_SET.setAstEmitter(AnnotationEntry.class, new AnnotationEntryEmitter()); JAVA_SET.setAstEmitter(FieldEntry.class, new FieldEntryEmitter()); JAVA_SET.setAstEmitter(MethodEntry.class, new MethodEntryEmitter()); JAVA_SET.setStatementEmitter(ArrayAssignment.class, new ArrayAssignmentEmitter()); JAVA_SET.setStatementEmitter(Break.class, new BreakEmitter()); JAVA_SET.setStatementEmitter(Comment.class, new CommentEmitter()); JAVA_SET.setStatementEmitter(DoWhile.class, new DoWhileEmitter()); FieldAssignmentEmitter fld_assign = new FieldAssignmentEmitter(); JAVA_SET.setStatementEmitter(FieldAssignment.class, fld_assign); JAVA_SET.setStatementEmitter(InstanceFieldAssignment.class, fld_assign); JAVA_SET.setStatementEmitter(StaticFieldAssignment.class, fld_assign); JAVA_SET.setStatementEmitter(For.class, new ForEmitter()); JAVA_SET.setStatementEmitter(ForEach.class, new ForEachEmitter()); JAVA_SET.setStatementEmitter(If.class, new IfEmitter()); JAVA_SET.setStatementEmitter(Increment.class, new IncrementEmitter()); JAVA_SET.setStatementEmitter(InvokeStatement.class, new InvokeEmitter()); JAVA_SET.setStatementEmitter(LocalAssignment.class, new LocalAssignmentEmitter()); JAVA_SET.setStatementEmitter(Return.class, new ReturnEmitter()); JAVA_SET.setStatementEmitter(Switch.class, new SwitchEmitter()); JAVA_SET.setStatementEmitter(Throw.class, new ThrowEmitter()); JAVA_SET.setStatementEmitter(TryCatch.class, new TryCatchEmitter()); JAVA_SET.setStatementEmitter(While.class, new WhileEmitter()); JAVA_SET.setInstructionEmitter(ArrayAccess.class, new ArrayLoadEmitter()); JAVA_SET.setInstructionEmitter(Cast.class, new CastEmitter()); JAVA_SET.setInstructionEmitter(NumberCompare.class, new CompareEmitter()); JAVA_SET.setInstructionEmitter(DoubleConstant.class, new DoubleConstantEmitter()); FieldAccessEmitter fld = new FieldAccessEmitter(); JAVA_SET.setInstructionEmitter(InstanceFieldAccess.class, fld); JAVA_SET.setInstructionEmitter(FloatConstant.class, new FloatConstantEmitter()); JAVA_SET.setInstructionEmitter(InstanceMethodInvoke.class, new InstanceMethodInvokeEmitter()); JAVA_SET.setInstructionEmitter(InstanceOf.class, new InstanceOfEmitter()); JAVA_SET.setInstructionEmitter(IntConstant.class, new IntConstantEmitter()); JAVA_SET.setInstructionEmitter(LocalAccess.class, new LocalAccessEmitter()); JAVA_SET.setInstructionEmitter(LongConstant.class, new LongConstantEmitter()); JAVA_SET.setInstructionEmitter(NegativeOperator.class, new NegativeEmitter()); JAVA_SET.setInstructionEmitter(NewArray.class, new NewArrayEmitter()); JAVA_SET.setInstructionEmitter(New.class, new NewEmitter()); JAVA_SET.setInstructionEmitter(NullConstant.class, new NullConstantEmitter()); OperatorEmitter op = new OperatorEmitter(); JAVA_SET.setInstructionEmitter(Operator.class, op); JAVA_SET.setInstructionEmitter(StaticMethodInvoke.class, new StaticMethodInvokeEmitter()); JAVA_SET.setInstructionEmitter(StringConstant.class, new StringConstantEmitter()); JAVA_SET.setInstructionEmitter(Ternary.class, new TernaryEmitter()); JAVA_SET.setInstructionEmitter(TypeConstant.class, new TypeConstantEmitter()); JAVA_SET.setInstructionEmitter(StaticFieldAccess.class, fld); JAVA_SET.setInstructionEmitter(Lambda.class, new DynamicInvokeEmitter()); JAVA_SET.setInstructionEmitter(MultiNewArray.class, new MultiNewArrayEmitter()); JAVA_SET.setInstructionEmitter(MethodReference.class, new MethodReferenceEmitter()); JAVA_SET.setConditionEmitter(AndCondition.class, new AndConditionEmitter()); JAVA_SET.setConditionEmitter(OrCondition.class, new OrConditionEmitter()); JAVA_SET.setConditionEmitter(InverseCondition.class, new InverseConditionEmitter()); JAVA_SET.setConditionEmitter(CompareCondition.class, new CompareConditionEmitter()); JAVA_SET.setConditionEmitter(BooleanCondition.class, new BooleanConditionEmitter()); KOTLIN_SET.clone(JAVA_SET); KOTLIN_SET.setAstEmitter(ClassEntry.class, new KotlinClassEntryEmitter()); KOTLIN_SET.setAstEmitter(EnumEntry.class, new KotlinEnumEntryEmitter()); KOTLIN_SET.setAstEmitter(MethodEntry.class, new KotlinMethodEntryEmitter()); KOTLIN_SET.setSpecialEmitter(KotlinDataClassEmitter.class, new KotlinDataClassEmitter()); KOTLIN_SET.setSpecialEmitter(KotlinCompanionClassEmitter.class, new KotlinCompanionClassEmitter()); KOTLIN_SET.setSpecialEmitter(PackageEmitter.class, new KotlinPackageEmitter()); KOTLIN_SET.setSpecialEmitter(GenericsEmitter.class, new KotlinGenericsEmitter()); KOTLIN_SET.setStatementEmitter(InvokeStatement.class, new KotlinInvokeEmitter()); KOTLIN_SET.setStatementEmitter(LocalAssignment.class, new KotlinLocalAssignmentEmitter()); KOTLIN_SET.setStatementEmitter(ForEach.class, new KotlinForEachEmitter()); KOTLIN_SET.setStatementEmitter(For.class, new KotlinForEmitter()); KOTLIN_SET.setInstructionEmitter(InstanceMethodInvoke.class, new KotlinInstanceMethodInvokeEmitter()); KOTLIN_SET.setInstructionEmitter(StaticMethodInvoke.class, new KotlinStaticMethodInvokeEmitter()); KOTLIN_SET.setInstructionEmitter(Ternary.class, new KotlinTernaryEmitter()); KOTLIN_SET.setInstructionEmitter(InstanceOf.class, new KotlinInstanceOfEmitter()); KOTLIN_SET.setInstructionEmitter(Cast.class, new KotlinCastEmitter()); KOTLIN_SET.setInstructionEmitter(Elvis.class, new ElvisEmitter()); KOTLIN_SET.setInstructionEmitter(When.class, new WhenEmitter()); KOTLIN_SET.setInstructionEmitter(Operator.class, new KotlinOperatorEmitter()); KOTLIN_SET.setInstructionEmitter(New.class, new KotlinNewEmitter()); KOTLIN_SET.setConditionEmitter(BooleanCondition.class, new KotlinBooleanConditionEmitter()); KOTLIN_SET.setConditionEmitter(CompareCondition.class, new KotlinCompareConditionEmitter()); KOTLIN_SET.setConditionEmitter(InverseCondition.class, new KotlinInverseConditionEmitter()); EMITTERS.put(Language.JAVA, JAVA); EMITTERS.put(Language.KOTLIN, KOTLIN); EMITTERS.put(Language.ANY, WILD); BYTECODE_SET.setAstEmitter(ClassEntry.class, new BytecodeClassEntryEmitter()); BYTECODE_SET.setAstEmitter(MethodEntry.class, new BytecodeMethodEntryEmitter()); BYTECODE_SET.setStatementEmitter(LocalAssignment.class, new BytecodeLocalAssignmentEmitter()); BYTECODE_SET.setStatementEmitter(Return.class, new BytecodeReturnEmitter()); BYTECODE_SET.setStatementEmitter(InvokeStatement.class, new BytecodeInvokeStatementEmitter()); BYTECODE_SET.setStatementEmitter(If.class, new BytecodeIfEmitter()); BYTECODE_SET.setInstructionEmitter(IntConstant.class, new BytecodeIntConstantEmitter()); BYTECODE_SET.setInstructionEmitter(InstanceMethodInvoke.class, new BytecodeInstanceMethodInvokeEmitter()); BYTECODE_SET.setInstructionEmitter(LocalAccess.class, new BytecodeLocalAccessEmitter()); BYTECODE_SET.setInstructionEmitter(StringConstant.class, new BytecodeStringConstantEmitter()); BYTECODE_SET.setInstructionEmitter(StaticFieldAccess.class, new BytecodeStaticFieldAccessEmitter()); BYTECODE_SET.setInstructionEmitter(FloatConstant.class, new BytecodeFloatConstantEmitter()); BYTECODE_SET.setInstructionEmitter(DoubleConstant.class, new BytecodeDoubleConstantEmitter()); BYTECODE_SET.setInstructionEmitter(LongConstant.class, new BytecodeLongConstantEmitter()); BYTECODE_SET.setInstructionEmitter(NullConstant.class, new BytecodeNullConstantEmitter()); BYTECODE_SET.setInstructionEmitter(TypeConstant.class, new BytecodeTypeConstantEmitter()); IR_SET.clone(JAVA_SET); IR_SET.setAstEmitter(MethodEntry.class, new MethodIREmitter()); } /** * Gets the emitter for the given language. */ @SuppressWarnings("unchecked") public static <E extends AbstractEmitterContext> Emitter<E> get(Language lang) { return EMITTERS.get(lang); } private Emitters() { } }
java
MIT
e60cfaaf7a0688bc83f8b00c392521d0b162afba
2026-01-05T02:42:07.381192Z
false
Despector/Despector
https://github.com/Despector/Despector/blob/e60cfaaf7a0688bc83f8b00c392521d0b162afba/src/main/java/org/spongepowered/despector/emitter/StatementEmitter.java
src/main/java/org/spongepowered/despector/emitter/StatementEmitter.java
/* * The MIT License (MIT) * * Copyright (c) Despector <https://despector.voxelgenesis.com> * Copyright (c) contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package org.spongepowered.despector.emitter; import org.spongepowered.despector.ast.stmt.Statement; /** * An emitter for a particular statement type. */ public interface StatementEmitter<C extends AbstractEmitterContext, T extends Statement> { /** * Emits the given statement. */ void emit(C ctx, T stmt, boolean semicolon); }
java
MIT
e60cfaaf7a0688bc83f8b00c392521d0b162afba
2026-01-05T02:42:07.381192Z
false
Despector/Despector
https://github.com/Despector/Despector/blob/e60cfaaf7a0688bc83f8b00c392521d0b162afba/src/main/java/org/spongepowered/despector/emitter/AstEmitter.java
src/main/java/org/spongepowered/despector/emitter/AstEmitter.java
/* * The MIT License (MIT) * * Copyright (c) Despector <https://despector.voxelgenesis.com> * Copyright (c) contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package org.spongepowered.despector.emitter; import org.spongepowered.despector.ast.AstEntry; /** * An emitter for an {@link AstEntry}. */ public interface AstEmitter<C extends AbstractEmitterContext, T extends AstEntry> { /** * Emits the given entry. */ boolean emit(C ctx, T ast); }
java
MIT
e60cfaaf7a0688bc83f8b00c392521d0b162afba
2026-01-05T02:42:07.381192Z
false
Despector/Despector
https://github.com/Despector/Despector/blob/e60cfaaf7a0688bc83f8b00c392521d0b162afba/src/main/java/org/spongepowered/despector/emitter/SpecialEmitter.java
src/main/java/org/spongepowered/despector/emitter/SpecialEmitter.java
/* * The MIT License (MIT) * * Copyright (c) Despector <https://despector.voxelgenesis.com> * Copyright (c) contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package org.spongepowered.despector.emitter; /** * A marker interface for special purpose emitters. */ public interface SpecialEmitter { }
java
MIT
e60cfaaf7a0688bc83f8b00c392521d0b162afba
2026-01-05T02:42:07.381192Z
false
Despector/Despector
https://github.com/Despector/Despector/blob/e60cfaaf7a0688bc83f8b00c392521d0b162afba/src/main/java/org/spongepowered/despector/emitter/AbstractEmitterContext.java
src/main/java/org/spongepowered/despector/emitter/AbstractEmitterContext.java
/* * The MIT License (MIT) * * Copyright (c) Despector <https://despector.voxelgenesis.com> * Copyright (c) contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package org.spongepowered.despector.emitter; import static com.google.common.base.Preconditions.checkNotNull; import org.spongepowered.despector.ast.insn.Instruction; import org.spongepowered.despector.ast.stmt.Statement; import org.spongepowered.despector.ast.type.FieldEntry; import org.spongepowered.despector.ast.type.MethodEntry; import org.spongepowered.despector.ast.type.TypeEntry; import java.util.ArrayDeque; import java.util.Deque; import javax.annotation.Nullable; public abstract class AbstractEmitterContext { protected EmitterSet set; protected TypeEntry type = null; protected TypeEntry outer_type = null; protected MethodEntry method; protected FieldEntry field; protected Statement statement; protected Deque<Instruction> insn_stack = new ArrayDeque<>(); /** * Gets the current {@link EmitterSet}. */ public EmitterSet getEmitterSet() { return this.set; } /** * Sets the current {@link EmitterSet}. */ public void setEmitterSet(EmitterSet set) { this.set = checkNotNull(set, "set"); } /** * Gets the current type being emitted. */ @Nullable public TypeEntry getType() { return this.type; } /** * Sets the current type being emitted. */ public void setType(@Nullable TypeEntry type) { this.type = type; } /** * Gets the current outer type being emitted. */ @Nullable public TypeEntry getOuterType() { return this.outer_type; } public void setOuterType(@Nullable TypeEntry type) { this.outer_type = type; } /** * Gets the current method being emitted. */ @Nullable public MethodEntry getMethod() { return this.method; } /** * Sets the current method being emitted. */ public void setMethod(@Nullable MethodEntry mth) { this.method = mth; } /** * Gets the current field being emitted. */ @Nullable public FieldEntry getField() { return this.field; } /** * Sets the current field being emitted. */ public void setField(@Nullable FieldEntry fld) { this.field = fld; } /** * Gets the current statement being emitted. */ public Statement getStatement() { return this.statement; } /** * Sets the current statement being emitted. */ public void setStatement(Statement stmt) { this.statement = stmt; } /** * Gets the current instruction stack. */ public Deque<Instruction> getCurrentInstructionStack() { return this.insn_stack; } }
java
MIT
e60cfaaf7a0688bc83f8b00c392521d0b162afba
2026-01-05T02:42:07.381192Z
false
Despector/Despector
https://github.com/Despector/Despector/blob/e60cfaaf7a0688bc83f8b00c392521d0b162afba/src/main/java/org/spongepowered/despector/emitter/Emitter.java
src/main/java/org/spongepowered/despector/emitter/Emitter.java
/* * The MIT License (MIT) * * Copyright (c) Despector <https://despector.voxelgenesis.com> * Copyright (c) contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package org.spongepowered.despector.emitter; import org.spongepowered.despector.ast.type.TypeEntry; import org.spongepowered.despector.emitter.java.JavaEmitterContext; /** * A source emitter. */ public interface Emitter<C extends AbstractEmitterContext> { /** * Initializes the given {@link JavaEmitterContext} for this emitter type. */ void setup(C ctx); /** * Emits the given type to the given {@link JavaEmitterContext}. */ void emit(C ctx, TypeEntry type); }
java
MIT
e60cfaaf7a0688bc83f8b00c392521d0b162afba
2026-01-05T02:42:07.381192Z
false
Despector/Despector
https://github.com/Despector/Despector/blob/e60cfaaf7a0688bc83f8b00c392521d0b162afba/src/main/java/org/spongepowered/despector/emitter/WildEmitter.java
src/main/java/org/spongepowered/despector/emitter/WildEmitter.java
/* * The MIT License (MIT) * * Copyright (c) Despector <https://despector.voxelgenesis.com> * Copyright (c) contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package org.spongepowered.despector.emitter; import org.spongepowered.despector.Language; import org.spongepowered.despector.ast.type.TypeEntry; import org.spongepowered.despector.emitter.java.JavaEmitterContext; /** * An emitter than emits based on the type's detected language. */ public class WildEmitter implements Emitter<JavaEmitterContext> { @Override public void setup(JavaEmitterContext ctx) { } @Override public void emit(JavaEmitterContext ctx, TypeEntry type) { if (type.getLanguage() == Language.KOTLIN) { Emitters.KOTLIN.emit(ctx, type); } else { Emitters.JAVA.emit(ctx, type); } } }
java
MIT
e60cfaaf7a0688bc83f8b00c392521d0b162afba
2026-01-05T02:42:07.381192Z
false
Despector/Despector
https://github.com/Despector/Despector/blob/e60cfaaf7a0688bc83f8b00c392521d0b162afba/src/main/java/org/spongepowered/despector/emitter/ir/MethodIREmitter.java
src/main/java/org/spongepowered/despector/emitter/ir/MethodIREmitter.java
/* * The MIT License (MIT) * * Copyright (c) Despector <https://despector.voxelgenesis.com> * Copyright (c) contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package org.spongepowered.despector.emitter.ir; import org.spongepowered.despector.ast.AccessModifier; import org.spongepowered.despector.ast.Annotation; import org.spongepowered.despector.ast.Locals; import org.spongepowered.despector.ast.Locals.LVT; import org.spongepowered.despector.ast.Locals.Local; import org.spongepowered.despector.ast.Locals.LocalInstance; import org.spongepowered.despector.ast.generic.MethodSignature; import org.spongepowered.despector.ast.generic.TypeSignature; import org.spongepowered.despector.ast.stmt.Statement; import org.spongepowered.despector.ast.stmt.StatementBlock; import org.spongepowered.despector.ast.stmt.assign.StaticFieldAssignment; import org.spongepowered.despector.ast.type.EnumEntry; import org.spongepowered.despector.ast.type.InterfaceEntry; import org.spongepowered.despector.ast.type.MethodEntry; import org.spongepowered.despector.decompiler.ir.Insn; import org.spongepowered.despector.decompiler.ir.InsnBlock; import org.spongepowered.despector.emitter.AstEmitter; import org.spongepowered.despector.emitter.format.EmitterFormat.BracePosition; import org.spongepowered.despector.emitter.java.JavaEmitterContext; import org.spongepowered.despector.emitter.java.special.GenericsEmitter; import org.spongepowered.despector.util.TypeHelper; import java.util.List; /** * An emitter for methods. */ public class MethodIREmitter implements AstEmitter<JavaEmitterContext, MethodEntry> { @Override public boolean emit(JavaEmitterContext ctx, MethodEntry method) { if (method.getName().equals("<clinit>")) { int start = 0; if (method.getInstructions() != null) { for (Statement stmt : method.getInstructions().getStatements()) { if (!(stmt instanceof StaticFieldAssignment)) { break; } StaticFieldAssignment assign = (StaticFieldAssignment) stmt; if (!assign.getOwnerName().equals(method.getOwnerName())) { break; } start++; } // only need one less as we can ignore the return at the end if (start == method.getInstructions().getStatements().size() - 1) { return false; } } ctx.setMethod(method); ctx.printString("static {"); ctx.newLine(); ctx.indent(); ctx.resetDefinedLocals(); printIR(ctx, method.getIR(), method.getLocals()); ctx.newLine(); ctx.dedent(); ctx.printIndentation(); ctx.printString("}"); ctx.setMethod(null); return true; } if ("<init>".equals(method.getName()) && method.getAccessModifier() == AccessModifier.PUBLIC && method.getParamTypes().isEmpty() && method.getInstructions().getStatements().size() == 2) { // TODO this could omit somewhere the ctor is purely passing // constants to the super ctor return false; } ctx.printIndentation(); for (Annotation anno : method.getAnnotations()) { ctx.emit(anno); if (ctx.getFormat().insert_new_line_after_annotation_on_method) { ctx.newLine(); ctx.printIndentation(); } else { ctx.printString(" "); } } ctx.setMethod(method); if (!(ctx.getType() instanceof InterfaceEntry) && !(ctx.getType() instanceof EnumEntry && method.getName().equals("<init>"))) { ctx.printString(method.getAccessModifier().asString()); if (method.getAccessModifier() != AccessModifier.PACKAGE_PRIVATE) { ctx.printString(" "); } } GenericsEmitter generics = ctx.getEmitterSet().getSpecialEmitter(GenericsEmitter.class); MethodSignature sig = method.getMethodSignature(); if ("<init>".equals(method.getName())) { String name = method.getOwnerName(); name = name.substring(Math.max(name.lastIndexOf('/'), name.lastIndexOf('$')) + 1); ctx.printString(name); } else { if (method.isStatic()) { ctx.printString("static "); } if (method.isFinal()) { ctx.printString("final "); } if (method.isAbstract() && !(ctx.getType() instanceof InterfaceEntry)) { ctx.printString("abstract "); } if (sig != null) { if (!sig.getTypeParameters().isEmpty()) { generics.emitTypeParameters(ctx, sig.getTypeParameters()); ctx.printString(" "); } generics.emitTypeSignature(ctx, sig.getReturnType(), false); } else { ctx.emitType(method.getReturnType(), false); } ctx.printString(" "); ctx.printString(method.getName()); } ctx.printString(" ", ctx.getFormat().insert_space_before_opening_paren_in_method_declaration); ctx.printString("("); StatementBlock block = method.getInstructions(); int start = 0; List<String> param_types = TypeHelper.splitSig(method.getDescription()); if ("<init>".equals(method.getName()) && ctx.getType() instanceof EnumEntry) { // If this is an enum type then we skip the first two ctor // parameters // (which are the index and name of the enum constant) start += 2; } if (start >= param_types.size()) { ctx.printString(" ", ctx.getFormat().insert_space_between_empty_parens_in_method_declaration); } int param_index = start; if (!method.isStatic()) { param_index++; } // TODO support synthetic parameters properly, their types will be // missing from the signature, need to offset types when emitting for (int i = start; i < method.getParamTypes().size(); i++) { boolean varargs = method.isVarargs() && i == param_types.size() - 1; if (block == null) { if (sig != null) { // interfaces have no lvt for parameters, need to get // generic types from the method signature generics.emitTypeSignature(ctx, sig.getParameters().get(i), varargs); } else { if (method.getParamTypes().size() != param_types.size()) { ctx.emitType(param_types.get(i)); } else { ctx.emitType(method.getParamTypes().get(i), varargs); } } ctx.printString(" "); ctx.printString("local" + param_index); } else { Local local = method.getLocals().getLocal(param_index); LocalInstance insn = local.getParameterInstance(); if (insn == null) { ctx.printString("<error-type> local" + i); } else { for (Annotation anno : insn.getAnnotations()) { ctx.emit(anno); if (ctx.getFormat().insert_new_line_after_annotation_on_parameter) { ctx.indent(); ctx.indent(); ctx.newLine(); ctx.printIndentation(); ctx.dedent(); ctx.dedent(); } else { ctx.printString(" "); } } generics.emitTypeSignature(ctx, insn.getType(), varargs); ctx.printString(" "); ctx.printString(insn.getName()); } } if (i < param_types.size() - 1) { ctx.printString(" ", ctx.getFormat().insert_space_before_comma_in_method_declaration_parameters); ctx.printString(","); ctx.printString(" ", ctx.getFormat().insert_space_after_comma_in_method_declaration_parameters); ctx.markWrapPoint(ctx.getFormat().alignment_for_parameters_in_method_declaration, i + 1); } String desc = param_types.get(i); param_index++; if ("D".equals(desc) || "J".equals(desc)) { param_index++; } } ctx.printString(" ", ctx.getFormat().insert_space_before_closing_paren_in_method_declaration); ctx.printString(")"); if (!method.getMethodSignature().getThrowsSignature().isEmpty()) { ctx.printString(" throws "); boolean first = true; for (TypeSignature ex : method.getMethodSignature().getThrowsSignature()) { if (!first) { ctx.printString(" ", ctx.getFormat().insert_space_before_comma_in_method_declaration_throws); ctx.printString(","); ctx.printString(" ", ctx.getFormat().insert_space_after_comma_in_method_declaration_throws); } else { first = false; } generics.emitTypeSignature(ctx, ex, false); } } if (!method.isAbstract()) { ctx.emitBrace(ctx.getFormat().brace_position_for_method_declaration, false, ctx.getFormat().insert_space_before_opening_brace_in_method_declaration); ctx.newLine(); printIR(ctx, method.getIR(), method.getLocals()); if (ctx.getFormat().brace_position_for_method_declaration == BracePosition.NEXT_LINE_SHIFTED) { ctx.printIndentation(); ctx.printString("}"); ctx.dedent(); } else { ctx.dedent(); ctx.printIndentation(); ctx.printString("}"); } } else { ctx.printString(";"); } ctx.setMethod(null); return true; } protected static void printIR(JavaEmitterContext ctx, InsnBlock ir, Locals locals) { if (ir == null) { ctx.printString("No bytecode?"); ctx.newIndentedLine(); return; } ctx.printIndentation(); for (int i = 0; i < ir.size(); i++) { Insn next = ir.get(i); ctx.printStringf("%3d %s", i, next.toString()); ctx.newIndentedLine(); } ctx.printString("Locals:"); ctx.indent(); ctx.newIndentedLine(); for (int i = 0; i < locals.getLocalCount(); i++) { Local l = locals.getLocal(i); for (int j = 0; j < l.getLVTCount(); j++) { LVT v = l.getLVTByIndex(j); ctx.printStringf("%3d %4d %4d %s %s %s", i, v.start_pc, v.length, v.name, v.desc, v.signature); ctx.newIndentedLine(); } } ctx.dedent(); } }
java
MIT
e60cfaaf7a0688bc83f8b00c392521d0b162afba
2026-01-05T02:42:07.381192Z
false
Despector/Despector
https://github.com/Despector/Despector/blob/e60cfaaf7a0688bc83f8b00c392521d0b162afba/src/main/java/org/spongepowered/despector/emitter/ir/IREmitter.java
src/main/java/org/spongepowered/despector/emitter/ir/IREmitter.java
/* * The MIT License (MIT) * * Copyright (c) Despector <https://despector.voxelgenesis.com> * Copyright (c) contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package org.spongepowered.despector.emitter.ir; import org.spongepowered.despector.ast.type.TypeEntry; import org.spongepowered.despector.emitter.Emitter; import org.spongepowered.despector.emitter.Emitters; import org.spongepowered.despector.emitter.java.JavaEmitterContext; import org.spongepowered.despector.parallel.Timing; /** * A java source emitter. */ public class IREmitter implements Emitter<JavaEmitterContext> { @Override public void setup(JavaEmitterContext ctx) { ctx.setSemicolons(true); ctx.setEmitterSet(Emitters.IR_SET); } @Override public void emit(JavaEmitterContext ctx, TypeEntry type) { setup(ctx); long emitting_start = System.nanoTime(); ctx.emitOuterType(type); Timing.time_emitting += System.nanoTime() - emitting_start; } }
java
MIT
e60cfaaf7a0688bc83f8b00c392521d0b162afba
2026-01-05T02:42:07.381192Z
false
Despector/Despector
https://github.com/Despector/Despector/blob/e60cfaaf7a0688bc83f8b00c392521d0b162afba/src/main/java/org/spongepowered/despector/emitter/bytecode/BytecodeEmitter.java
src/main/java/org/spongepowered/despector/emitter/bytecode/BytecodeEmitter.java
/* * The MIT License (MIT) * * Copyright (c) Despector <https://despector.voxelgenesis.com> * Copyright (c) contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package org.spongepowered.despector.emitter.bytecode; import org.spongepowered.despector.ast.type.TypeEntry; import org.spongepowered.despector.emitter.Emitter; import org.spongepowered.despector.emitter.Emitters; public class BytecodeEmitter implements Emitter<BytecodeEmitterContext> { @Override public void setup(BytecodeEmitterContext ctx) { ctx.setEmitterSet(Emitters.BYTECODE_SET); } @Override public void emit(BytecodeEmitterContext ctx, TypeEntry type) { setup(ctx); ctx.emitOuterType(type); } }
java
MIT
e60cfaaf7a0688bc83f8b00c392521d0b162afba
2026-01-05T02:42:07.381192Z
false
Despector/Despector
https://github.com/Despector/Despector/blob/e60cfaaf7a0688bc83f8b00c392521d0b162afba/src/main/java/org/spongepowered/despector/emitter/bytecode/BytecodeEmitterContext.java
src/main/java/org/spongepowered/despector/emitter/bytecode/BytecodeEmitterContext.java
/* * The MIT License (MIT) * * Copyright (c) Despector <https://despector.voxelgenesis.com> * Copyright (c) contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package org.spongepowered.despector.emitter.bytecode; import com.google.common.base.Throwables; import org.objectweb.asm.ClassReader; import org.objectweb.asm.ClassVisitor; import org.objectweb.asm.ClassWriter; import org.objectweb.asm.MethodVisitor; import org.objectweb.asm.tree.AbstractInsnNode; import org.objectweb.asm.tree.ClassNode; import org.objectweb.asm.tree.MethodNode; import org.objectweb.asm.util.CheckClassAdapter; import org.objectweb.asm.util.Printer; import org.objectweb.asm.util.Textifier; import org.objectweb.asm.util.TraceMethodVisitor; import org.spongepowered.despector.ast.AstEntry; import org.spongepowered.despector.ast.generic.TypeSignature; import org.spongepowered.despector.ast.insn.Instruction; import org.spongepowered.despector.ast.insn.condition.Condition; import org.spongepowered.despector.ast.stmt.Statement; import org.spongepowered.despector.ast.type.TypeEntry; import org.spongepowered.despector.emitter.AbstractEmitterContext; import org.spongepowered.despector.emitter.AstEmitter; import org.spongepowered.despector.emitter.ConditionEmitter; import org.spongepowered.despector.emitter.InstructionEmitter; import org.spongepowered.despector.emitter.StatementEmitter; import java.io.IOException; import java.io.OutputStream; import java.io.PrintWriter; import java.io.StringWriter; import java.util.Iterator; import java.util.List; public class BytecodeEmitterContext extends AbstractEmitterContext { private static final boolean VERIFY_EMITTED_BYTECODE = Boolean.valueOf(System.getProperty("despect.bytecode.verify", "true")); private static final boolean DUMP_INSTRUCTIONS_AFTER_WRITE = Boolean.getBoolean("despect.bytecode.dump_instructions"); private final OutputStream out; private ClassVisitor cw; private MethodVisitor mv; private int maxs; private int current_stack_size; public BytecodeEmitterContext(OutputStream out) { this.out = out; } public void resetMaxs() { this.maxs = 0; } public int getMaxs() { return this.maxs; } public void updateStack(int delta) { this.current_stack_size += delta; this.maxs = Math.max(this.maxs, this.current_stack_size); } @SuppressWarnings("unchecked") public <T extends TypeEntry> void emitOuterType(T ast) { ClassWriter writer = new ClassWriter(ClassWriter.COMPUTE_MAXS | ClassWriter.COMPUTE_FRAMES); this.cw = writer; if (VERIFY_EMITTED_BYTECODE) { this.cw = new CheckClassAdapter(this.cw); } AstEmitter<AbstractEmitterContext, T> emitter = (AstEmitter<AbstractEmitterContext, T>) this.set.getAstEmitter(ast.getClass()); if (emitter == null) { throw new IllegalArgumentException("No emitter for ast entry " + ast.getClass().getName()); } emitter.emit(this, ast); this.cw.visitEnd(); byte[] clazz = writer.toByteArray(); if (DUMP_INSTRUCTIONS_AFTER_WRITE) { ClassReader cr = new ClassReader(clazz); ClassNode cn = new ClassNode(); cr.accept(cn, 0); List<MethodNode> methods = cn.methods; for (MethodNode mn : methods) { System.out.println("Method: " + mn.name + mn.desc); Printer printer = new Textifier(); TraceMethodVisitor mp = new TraceMethodVisitor(printer); for (Iterator<AbstractInsnNode> it = mn.instructions.iterator(); it.hasNext();) { AbstractInsnNode insn = it.next(); insn.accept(mp); } StringWriter sw = new StringWriter(); printer.print(new PrintWriter(sw)); String s = sw.toString(); if (s.endsWith("\n")) { s = s.substring(0, s.length() - 1); } System.out.println(s); mn.instructions.accept(mp); } } try { this.out.write(clazz); } catch (IOException e) { Throwables.propagate(e); } } @SuppressWarnings("unchecked") public <T extends AstEntry> void emitAst(T ast) { AstEmitter<AbstractEmitterContext, T> emitter = (AstEmitter<AbstractEmitterContext, T>) this.set.getAstEmitter(ast.getClass()); if (emitter == null) { throw new IllegalArgumentException("No emitter for ast entry " + ast.getClass().getName()); } emitter.emit(this, ast); } /** * Emits the given statement. */ @SuppressWarnings("unchecked") public <T extends Statement> BytecodeEmitterContext emitStatement(T obj) { StatementEmitter<AbstractEmitterContext, T> emitter = (StatementEmitter<AbstractEmitterContext, T>) this.set.getStatementEmitter(obj.getClass()); if (emitter == null) { throw new IllegalArgumentException("No emitter for statement " + obj.getClass().getName()); } Statement last = getStatement(); setStatement(obj); emitter.emit(this, obj, false); setStatement(last); return this; } /** * Emits the given instruction. */ @SuppressWarnings("unchecked") public <T extends Instruction> BytecodeEmitterContext emitInstruction(T obj, TypeSignature type) { InstructionEmitter<AbstractEmitterContext, T> emitter = (InstructionEmitter<AbstractEmitterContext, T>) this.set.getInstructionEmitter(obj.getClass()); if (emitter == null) { throw new IllegalArgumentException("No emitter for instruction " + obj.getClass().getName()); } this.insn_stack.push(obj); if (type == null) { type = obj.inferType(); } emitter.emit(this, obj, type); this.insn_stack.pop(); return this; } /** * Emits the given condition. */ @SuppressWarnings("unchecked") public <T extends Condition> BytecodeEmitterContext emitCondition(T condition) { ConditionEmitter<AbstractEmitterContext, T> emitter = (ConditionEmitter<AbstractEmitterContext, T>) this.set.getConditionEmitter(condition.getClass()); if (emitter == null) { throw new IllegalArgumentException("No emitter for condition " + condition.getClass().getName()); } emitter.emit(this, condition); return this; } public ClassVisitor getClassWriter() { return this.cw; } public MethodVisitor getMethodVisitor() { return this.mv; } public void setMethodVisitor(MethodVisitor mv) { this.mv = mv; } }
java
MIT
e60cfaaf7a0688bc83f8b00c392521d0b162afba
2026-01-05T02:42:07.381192Z
false
Despector/Despector
https://github.com/Despector/Despector/blob/e60cfaaf7a0688bc83f8b00c392521d0b162afba/src/main/java/org/spongepowered/despector/emitter/bytecode/type/BytecodeClassEntryEmitter.java
src/main/java/org/spongepowered/despector/emitter/bytecode/type/BytecodeClassEntryEmitter.java
/* * The MIT License (MIT) * * Copyright (c) Despector <https://despector.voxelgenesis.com> * Copyright (c) contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package org.spongepowered.despector.emitter.bytecode.type; import static org.objectweb.asm.Opcodes.*; import org.objectweb.asm.ClassVisitor; import org.spongepowered.despector.ast.type.ClassEntry; import org.spongepowered.despector.ast.type.FieldEntry; import org.spongepowered.despector.ast.type.MethodEntry; import org.spongepowered.despector.emitter.AstEmitter; import org.spongepowered.despector.emitter.bytecode.BytecodeEmitterContext; public class BytecodeClassEntryEmitter implements AstEmitter<BytecodeEmitterContext, ClassEntry> { @Override public boolean emit(BytecodeEmitterContext ctx, ClassEntry ast) { ClassVisitor cw = ctx.getClassWriter(); int acc = ACC_SUPER; switch (ast.getAccessModifier()) { case PUBLIC: acc |= ACC_PUBLIC; break; case PRIVATE: acc |= ACC_PRIVATE; break; case PROTECTED: acc |= ACC_PROTECTED; break; default: } if (ast.isSynthetic()) { acc |= ACC_SYNTHETIC; } if (ast.isAbstract()) { acc |= ACC_ABSTRACT; } if (ast.isFinal()) { acc |= ACC_FINAL; } if (ast.isDeprecated()) { acc |= ACC_DEPRECATED; } cw.visit(V1_8, acc, ast.getName(), ast.getSignature() == null ? null : ast.getSignature().toString(), ast.getSuperclassName(), ast.getInterfaces().toArray(new String[0])); for (MethodEntry mth : ast.getStaticMethods()) { ctx.emitAst(mth); } for (MethodEntry mth : ast.getMethods()) { ctx.emitAst(mth); } for (FieldEntry fld : ast.getStaticFields()) { ctx.emitAst(fld); } for (FieldEntry fld : ast.getFields()) { ctx.emitAst(fld); } return true; } }
java
MIT
e60cfaaf7a0688bc83f8b00c392521d0b162afba
2026-01-05T02:42:07.381192Z
false
Despector/Despector
https://github.com/Despector/Despector/blob/e60cfaaf7a0688bc83f8b00c392521d0b162afba/src/main/java/org/spongepowered/despector/emitter/bytecode/type/BytecodeMethodEntryEmitter.java
src/main/java/org/spongepowered/despector/emitter/bytecode/type/BytecodeMethodEntryEmitter.java
/* * The MIT License (MIT) * * Copyright (c) Despector <https://despector.voxelgenesis.com> * Copyright (c) contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package org.spongepowered.despector.emitter.bytecode.type; import static org.objectweb.asm.Opcodes.*; import org.objectweb.asm.Label; import org.objectweb.asm.MethodVisitor; import org.spongepowered.despector.ast.Locals.LocalInstance; import org.spongepowered.despector.ast.stmt.Statement; import org.spongepowered.despector.ast.type.MethodEntry; import org.spongepowered.despector.emitter.AstEmitter; import org.spongepowered.despector.emitter.bytecode.BytecodeEmitterContext; public class BytecodeMethodEntryEmitter implements AstEmitter<BytecodeEmitterContext, MethodEntry> { @Override public boolean emit(BytecodeEmitterContext ctx, MethodEntry ast) { int acc = 0; switch (ast.getAccessModifier()) { case PUBLIC: acc |= ACC_PUBLIC; break; case PRIVATE: acc |= ACC_PRIVATE; break; case PROTECTED: acc |= ACC_PROTECTED; break; default: } if (ast.isStatic()) { acc |= ACC_STATIC; } if (ast.isAbstract()) { acc |= ACC_ABSTRACT; } if (ast.isBridge()) { acc |= ACC_BRIDGE; } if (ast.isDeprecated()) { acc |= ACC_DEPRECATED; } if (ast.isFinal()) { acc |= ACC_FINAL; } if (ast.isNative()) { acc |= ACC_NATIVE; } if (ast.isStrictFp()) { acc |= ACC_STRICT; } if (ast.isSynchronized()) { acc |= ACC_SYNCHRONIZED; } if (ast.isSynthetic()) { acc |= ACC_SYNTHETIC; } if (ast.isVarargs()) { acc |= ACC_VARARGS; } MethodVisitor mv = ctx.getClassWriter().visitMethod(acc, ast.getName(), ast.getDescription(), null, null); ctx.setMethodVisitor(mv); mv.visitCode(); Label start = new Label(); mv.visitLabel(start); ctx.resetMaxs(); for (Statement stmt : ast.getInstructions().getStatements()) { ctx.emitStatement(stmt); } Label end = new Label(); mv.visitLabel(end); // TODO the indices we have for locals are in terms of the ir list and // are therefore useless now int maxLocal = 0; for (LocalInstance local : ast.getLocals().getAllInstances()) { if (local.getType().getDescriptor().startsWith("L")) { mv.visitLocalVariable(local.getName(), local.getType().getDescriptor(), local.getType().toString(), start, end, local.getIndex()); } else { mv.visitLocalVariable(local.getName(), local.getType().getDescriptor(), null, start, end, local.getIndex()); } maxLocal = Math.max(maxLocal, local.getIndex() + 1); } mv.visitMaxs(ctx.getMaxs(), maxLocal); mv.visitEnd(); return true; } }
java
MIT
e60cfaaf7a0688bc83f8b00c392521d0b162afba
2026-01-05T02:42:07.381192Z
false
Despector/Despector
https://github.com/Despector/Despector/blob/e60cfaaf7a0688bc83f8b00c392521d0b162afba/src/main/java/org/spongepowered/despector/emitter/bytecode/instruction/BytecodeDoubleConstantEmitter.java
src/main/java/org/spongepowered/despector/emitter/bytecode/instruction/BytecodeDoubleConstantEmitter.java
/* * The MIT License (MIT) * * Copyright (c) Despector <https://despector.voxelgenesis.com> * Copyright (c) contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package org.spongepowered.despector.emitter.bytecode.instruction; import org.objectweb.asm.MethodVisitor; import org.objectweb.asm.Opcodes; import org.spongepowered.despector.ast.generic.TypeSignature; import org.spongepowered.despector.ast.insn.cst.DoubleConstant; import org.spongepowered.despector.emitter.InstructionEmitter; import org.spongepowered.despector.emitter.bytecode.BytecodeEmitterContext; public class BytecodeDoubleConstantEmitter implements InstructionEmitter<BytecodeEmitterContext, DoubleConstant> { @Override public void emit(BytecodeEmitterContext ctx, DoubleConstant arg, TypeSignature type) { MethodVisitor mv = ctx.getMethodVisitor(); double val = arg.getConstant(); if (val == 0) { mv.visitInsn(Opcodes.DCONST_0); } else if (val == 1) { mv.visitInsn(Opcodes.DCONST_1); } else { mv.visitLdcInsn(val); } ctx.updateStack(1); } }
java
MIT
e60cfaaf7a0688bc83f8b00c392521d0b162afba
2026-01-05T02:42:07.381192Z
false
Despector/Despector
https://github.com/Despector/Despector/blob/e60cfaaf7a0688bc83f8b00c392521d0b162afba/src/main/java/org/spongepowered/despector/emitter/bytecode/instruction/BytecodeCastEmitter.java
src/main/java/org/spongepowered/despector/emitter/bytecode/instruction/BytecodeCastEmitter.java
/* * The MIT License (MIT) * * Copyright (c) Despector <https://despector.voxelgenesis.com> * Copyright (c) contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package org.spongepowered.despector.emitter.bytecode.instruction; import org.objectweb.asm.MethodVisitor; import org.objectweb.asm.Opcodes; import org.spongepowered.despector.ast.generic.ClassTypeSignature; import org.spongepowered.despector.ast.generic.TypeSignature; import org.spongepowered.despector.ast.insn.misc.Cast; import org.spongepowered.despector.emitter.InstructionEmitter; import org.spongepowered.despector.emitter.bytecode.BytecodeEmitterContext; public class BytecodeCastEmitter implements InstructionEmitter<BytecodeEmitterContext, Cast> { @Override public void emit(BytecodeEmitterContext ctx, Cast arg, TypeSignature type) { MethodVisitor mv = ctx.getMethodVisitor(); ctx.emitInstruction(arg.getValue(), null); TypeSignature to = arg.getType(); TypeSignature from = arg.getValue().inferType(); if (to == ClassTypeSignature.INT) { if (from == ClassTypeSignature.LONG) { mv.visitInsn(Opcodes.L2I); } else if (from == ClassTypeSignature.FLOAT) { mv.visitInsn(Opcodes.F2I); } else if (from == ClassTypeSignature.DOUBLE) { mv.visitInsn(Opcodes.D2I); } } else if (to == ClassTypeSignature.LONG) { if (from == ClassTypeSignature.INT) { mv.visitInsn(Opcodes.I2L); } else if (from == ClassTypeSignature.FLOAT) { mv.visitInsn(Opcodes.F2L); } else if (from == ClassTypeSignature.DOUBLE) { mv.visitInsn(Opcodes.D2L); } } else if (to == ClassTypeSignature.FLOAT) { if (from == ClassTypeSignature.LONG) { mv.visitInsn(Opcodes.L2F); } else if (from == ClassTypeSignature.INT) { mv.visitInsn(Opcodes.I2F); } else if (from == ClassTypeSignature.DOUBLE) { mv.visitInsn(Opcodes.D2F); } } else if (to == ClassTypeSignature.DOUBLE) { if (from == ClassTypeSignature.LONG) { mv.visitInsn(Opcodes.L2D); } else if (from == ClassTypeSignature.FLOAT) { mv.visitInsn(Opcodes.F2D); } else if (from == ClassTypeSignature.INT) { mv.visitInsn(Opcodes.I2D); } } mv.visitTypeInsn(Opcodes.CHECKCAST, to.getDescriptor()); } }
java
MIT
e60cfaaf7a0688bc83f8b00c392521d0b162afba
2026-01-05T02:42:07.381192Z
false
Despector/Despector
https://github.com/Despector/Despector/blob/e60cfaaf7a0688bc83f8b00c392521d0b162afba/src/main/java/org/spongepowered/despector/emitter/bytecode/instruction/BytecodeNullConstantEmitter.java
src/main/java/org/spongepowered/despector/emitter/bytecode/instruction/BytecodeNullConstantEmitter.java
/* * The MIT License (MIT) * * Copyright (c) Despector <https://despector.voxelgenesis.com> * Copyright (c) contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package org.spongepowered.despector.emitter.bytecode.instruction; import org.objectweb.asm.MethodVisitor; import org.objectweb.asm.Opcodes; import org.spongepowered.despector.ast.generic.TypeSignature; import org.spongepowered.despector.ast.insn.cst.NullConstant; import org.spongepowered.despector.emitter.InstructionEmitter; import org.spongepowered.despector.emitter.bytecode.BytecodeEmitterContext; public class BytecodeNullConstantEmitter implements InstructionEmitter<BytecodeEmitterContext, NullConstant> { @Override public void emit(BytecodeEmitterContext ctx, NullConstant arg, TypeSignature type) { MethodVisitor mv = ctx.getMethodVisitor(); mv.visitInsn(Opcodes.ACONST_NULL); ctx.updateStack(1); } }
java
MIT
e60cfaaf7a0688bc83f8b00c392521d0b162afba
2026-01-05T02:42:07.381192Z
false
Despector/Despector
https://github.com/Despector/Despector/blob/e60cfaaf7a0688bc83f8b00c392521d0b162afba/src/main/java/org/spongepowered/despector/emitter/bytecode/instruction/BytecodeArrayAccessEmitter.java
src/main/java/org/spongepowered/despector/emitter/bytecode/instruction/BytecodeArrayAccessEmitter.java
/* * The MIT License (MIT) * * Copyright (c) Despector <https://despector.voxelgenesis.com> * Copyright (c) contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package org.spongepowered.despector.emitter.bytecode.instruction; import org.objectweb.asm.MethodVisitor; import org.objectweb.asm.Opcodes; import org.spongepowered.despector.ast.generic.ClassTypeSignature; import org.spongepowered.despector.ast.generic.TypeSignature; import org.spongepowered.despector.ast.insn.var.ArrayAccess; import org.spongepowered.despector.emitter.InstructionEmitter; import org.spongepowered.despector.emitter.bytecode.BytecodeEmitterContext; public class BytecodeArrayAccessEmitter implements InstructionEmitter<BytecodeEmitterContext, ArrayAccess> { @Override public void emit(BytecodeEmitterContext ctx, ArrayAccess arg, TypeSignature type) { MethodVisitor mv = ctx.getMethodVisitor(); ctx.emitInstruction(arg.getArrayVar(), null); ctx.emitInstruction(arg.getIndex(), ClassTypeSignature.INT); TypeSignature array = TypeSignature.getArrayComponent(arg.getArrayVar().inferType()); if (array == ClassTypeSignature.INT || array == ClassTypeSignature.BOOLEAN || array == ClassTypeSignature.BYTE || array == ClassTypeSignature.SHORT || array == ClassTypeSignature.CHAR) { mv.visitInsn(Opcodes.IALOAD); } else if (array == ClassTypeSignature.LONG) { mv.visitInsn(Opcodes.LALOAD); } else if (array == ClassTypeSignature.FLOAT) { mv.visitInsn(Opcodes.FALOAD); } else if (array == ClassTypeSignature.DOUBLE) { mv.visitInsn(Opcodes.DALOAD); } else { mv.visitInsn(Opcodes.AALOAD); } ctx.updateStack(-1); } }
java
MIT
e60cfaaf7a0688bc83f8b00c392521d0b162afba
2026-01-05T02:42:07.381192Z
false
Despector/Despector
https://github.com/Despector/Despector/blob/e60cfaaf7a0688bc83f8b00c392521d0b162afba/src/main/java/org/spongepowered/despector/emitter/bytecode/instruction/BytecodeInstanceMethodInvokeEmitter.java
src/main/java/org/spongepowered/despector/emitter/bytecode/instruction/BytecodeInstanceMethodInvokeEmitter.java
/* * The MIT License (MIT) * * Copyright (c) Despector <https://despector.voxelgenesis.com> * Copyright (c) contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package org.spongepowered.despector.emitter.bytecode.instruction; import org.objectweb.asm.MethodVisitor; import org.objectweb.asm.Opcodes; import org.spongepowered.despector.ast.generic.ClassTypeSignature; import org.spongepowered.despector.ast.generic.TypeSignature; import org.spongepowered.despector.ast.stmt.invoke.InstanceMethodInvoke; import org.spongepowered.despector.emitter.InstructionEmitter; import org.spongepowered.despector.emitter.bytecode.BytecodeEmitterContext; public class BytecodeInstanceMethodInvokeEmitter implements InstructionEmitter<BytecodeEmitterContext, InstanceMethodInvoke> { @Override public void emit(BytecodeEmitterContext ctx, InstanceMethodInvoke arg, TypeSignature type) { MethodVisitor mv = ctx.getMethodVisitor(); ctx.emitInstruction(arg.getCallee(), ClassTypeSignature.of(arg.getOwner())); for (int i = 0; i < arg.getParameters().length; i++) { ctx.emitInstruction(arg.getParameters()[i], null); } mv.visitMethodInsn(getOpcode(arg.getType()), arg.getOwnerName(), arg.getMethodName(), arg.getMethodDescription(), arg.getType() == InstanceMethodInvoke.Type.INTERFACE); int delta = -1 - arg.getParameters().length; if (!arg.getReturnType().equals("V")) { delta++; } ctx.updateStack(delta); } public int getOpcode(InstanceMethodInvoke.Type type) { switch (type) { case INTERFACE: return Opcodes.INVOKEINTERFACE; case SPECIAL: return Opcodes.INVOKESPECIAL; case VIRTUAL: default: return Opcodes.INVOKEVIRTUAL; } } }
java
MIT
e60cfaaf7a0688bc83f8b00c392521d0b162afba
2026-01-05T02:42:07.381192Z
false
Despector/Despector
https://github.com/Despector/Despector/blob/e60cfaaf7a0688bc83f8b00c392521d0b162afba/src/main/java/org/spongepowered/despector/emitter/bytecode/instruction/BytecodeIntConstantEmitter.java
src/main/java/org/spongepowered/despector/emitter/bytecode/instruction/BytecodeIntConstantEmitter.java
/* * The MIT License (MIT) * * Copyright (c) Despector <https://despector.voxelgenesis.com> * Copyright (c) contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package org.spongepowered.despector.emitter.bytecode.instruction; import org.objectweb.asm.MethodVisitor; import org.objectweb.asm.Opcodes; import org.spongepowered.despector.ast.generic.TypeSignature; import org.spongepowered.despector.ast.insn.cst.IntConstant; import org.spongepowered.despector.emitter.InstructionEmitter; import org.spongepowered.despector.emitter.bytecode.BytecodeEmitterContext; public class BytecodeIntConstantEmitter implements InstructionEmitter<BytecodeEmitterContext, IntConstant> { @Override public void emit(BytecodeEmitterContext ctx, IntConstant arg, TypeSignature type) { MethodVisitor mv = ctx.getMethodVisitor(); int val = arg.getConstant(); if (val == -1) { mv.visitInsn(Opcodes.ICONST_M1); } else if (val == 0) { mv.visitInsn(Opcodes.ICONST_0); } else if (val == 1) { mv.visitInsn(Opcodes.ICONST_1); } else if (val == 2) { mv.visitInsn(Opcodes.ICONST_2); } else if (val == 3) { mv.visitInsn(Opcodes.ICONST_3); } else if (val == 4) { mv.visitInsn(Opcodes.ICONST_4); } else if (val == 5) { mv.visitInsn(Opcodes.ICONST_5); } else if (val <= Byte.MAX_VALUE && val >= Byte.MIN_VALUE) { mv.visitIntInsn(Opcodes.BIPUSH, val); } else if (val <= Short.MAX_VALUE && val >= Short.MIN_VALUE) { mv.visitIntInsn(Opcodes.SIPUSH, val); } else { mv.visitLdcInsn(val); } ctx.updateStack(1); } }
java
MIT
e60cfaaf7a0688bc83f8b00c392521d0b162afba
2026-01-05T02:42:07.381192Z
false
Despector/Despector
https://github.com/Despector/Despector/blob/e60cfaaf7a0688bc83f8b00c392521d0b162afba/src/main/java/org/spongepowered/despector/emitter/bytecode/instruction/BytecodeFloatConstantEmitter.java
src/main/java/org/spongepowered/despector/emitter/bytecode/instruction/BytecodeFloatConstantEmitter.java
/* * The MIT License (MIT) * * Copyright (c) Despector <https://despector.voxelgenesis.com> * Copyright (c) contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package org.spongepowered.despector.emitter.bytecode.instruction; import org.objectweb.asm.MethodVisitor; import org.objectweb.asm.Opcodes; import org.spongepowered.despector.ast.generic.TypeSignature; import org.spongepowered.despector.ast.insn.cst.FloatConstant; import org.spongepowered.despector.emitter.InstructionEmitter; import org.spongepowered.despector.emitter.bytecode.BytecodeEmitterContext; public class BytecodeFloatConstantEmitter implements InstructionEmitter<BytecodeEmitterContext, FloatConstant> { @Override public void emit(BytecodeEmitterContext ctx, FloatConstant arg, TypeSignature type) { MethodVisitor mv = ctx.getMethodVisitor(); float val = arg.getConstant(); if (val == 0) { mv.visitInsn(Opcodes.FCONST_0); } else if (val == 1) { mv.visitInsn(Opcodes.FCONST_1); } else if (val == 2) { mv.visitInsn(Opcodes.FCONST_2); } else { mv.visitLdcInsn(val); } ctx.updateStack(1); } }
java
MIT
e60cfaaf7a0688bc83f8b00c392521d0b162afba
2026-01-05T02:42:07.381192Z
false
Despector/Despector
https://github.com/Despector/Despector/blob/e60cfaaf7a0688bc83f8b00c392521d0b162afba/src/main/java/org/spongepowered/despector/emitter/bytecode/instruction/BytecodeStaticFieldAccessEmitter.java
src/main/java/org/spongepowered/despector/emitter/bytecode/instruction/BytecodeStaticFieldAccessEmitter.java
/* * The MIT License (MIT) * * Copyright (c) Despector <https://despector.voxelgenesis.com> * Copyright (c) contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package org.spongepowered.despector.emitter.bytecode.instruction; import org.objectweb.asm.MethodVisitor; import org.objectweb.asm.Opcodes; import org.spongepowered.despector.ast.generic.TypeSignature; import org.spongepowered.despector.ast.insn.var.StaticFieldAccess; import org.spongepowered.despector.emitter.InstructionEmitter; import org.spongepowered.despector.emitter.bytecode.BytecodeEmitterContext; public class BytecodeStaticFieldAccessEmitter implements InstructionEmitter<BytecodeEmitterContext, StaticFieldAccess> { @Override public void emit(BytecodeEmitterContext ctx, StaticFieldAccess arg, TypeSignature type) { MethodVisitor mv = ctx.getMethodVisitor(); mv.visitFieldInsn(Opcodes.GETSTATIC, arg.getOwnerName(), arg.getFieldName(), arg.getTypeDescriptor().getDescriptor()); ctx.updateStack(1); } }
java
MIT
e60cfaaf7a0688bc83f8b00c392521d0b162afba
2026-01-05T02:42:07.381192Z
false
Despector/Despector
https://github.com/Despector/Despector/blob/e60cfaaf7a0688bc83f8b00c392521d0b162afba/src/main/java/org/spongepowered/despector/emitter/bytecode/instruction/BytecodeLocalAccessEmitter.java
src/main/java/org/spongepowered/despector/emitter/bytecode/instruction/BytecodeLocalAccessEmitter.java
/* * The MIT License (MIT) * * Copyright (c) Despector <https://despector.voxelgenesis.com> * Copyright (c) contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package org.spongepowered.despector.emitter.bytecode.instruction; import org.objectweb.asm.MethodVisitor; import org.objectweb.asm.Opcodes; import org.spongepowered.despector.ast.generic.ClassTypeSignature; import org.spongepowered.despector.ast.generic.TypeSignature; import org.spongepowered.despector.ast.insn.var.LocalAccess; import org.spongepowered.despector.emitter.InstructionEmitter; import org.spongepowered.despector.emitter.bytecode.BytecodeEmitterContext; public class BytecodeLocalAccessEmitter implements InstructionEmitter<BytecodeEmitterContext, LocalAccess> { @Override public void emit(BytecodeEmitterContext ctx, LocalAccess arg, TypeSignature t) { MethodVisitor mv = ctx.getMethodVisitor(); TypeSignature type = arg.getLocal().getType(); if (type == ClassTypeSignature.INT || type == ClassTypeSignature.BOOLEAN || type == ClassTypeSignature.BYTE || type == ClassTypeSignature.SHORT || type == ClassTypeSignature.CHAR) { mv.visitVarInsn(Opcodes.ILOAD, arg.getLocal().getIndex()); } else if (type == ClassTypeSignature.LONG) { mv.visitVarInsn(Opcodes.LLOAD, arg.getLocal().getIndex()); } else if (type == ClassTypeSignature.FLOAT) { mv.visitVarInsn(Opcodes.FLOAD, arg.getLocal().getIndex()); } else if (type == ClassTypeSignature.DOUBLE) { mv.visitVarInsn(Opcodes.DLOAD, arg.getLocal().getIndex()); } else { mv.visitVarInsn(Opcodes.ALOAD, arg.getLocal().getIndex()); } ctx.updateStack(1); } }
java
MIT
e60cfaaf7a0688bc83f8b00c392521d0b162afba
2026-01-05T02:42:07.381192Z
false
Despector/Despector
https://github.com/Despector/Despector/blob/e60cfaaf7a0688bc83f8b00c392521d0b162afba/src/main/java/org/spongepowered/despector/emitter/bytecode/instruction/BytecodeLongConstantEmitter.java
src/main/java/org/spongepowered/despector/emitter/bytecode/instruction/BytecodeLongConstantEmitter.java
/* * The MIT License (MIT) * * Copyright (c) Despector <https://despector.voxelgenesis.com> * Copyright (c) contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package org.spongepowered.despector.emitter.bytecode.instruction; import org.objectweb.asm.MethodVisitor; import org.objectweb.asm.Opcodes; import org.spongepowered.despector.ast.generic.TypeSignature; import org.spongepowered.despector.ast.insn.cst.LongConstant; import org.spongepowered.despector.emitter.InstructionEmitter; import org.spongepowered.despector.emitter.bytecode.BytecodeEmitterContext; public class BytecodeLongConstantEmitter implements InstructionEmitter<BytecodeEmitterContext, LongConstant> { @Override public void emit(BytecodeEmitterContext ctx, LongConstant arg, TypeSignature type) { MethodVisitor mv = ctx.getMethodVisitor(); long val = arg.getConstant(); if (val == 0) { mv.visitInsn(Opcodes.LCONST_0); } else if (val == 1) { mv.visitInsn(Opcodes.LCONST_1); } else { mv.visitLdcInsn(val); } ctx.updateStack(1); } }
java
MIT
e60cfaaf7a0688bc83f8b00c392521d0b162afba
2026-01-05T02:42:07.381192Z
false
Despector/Despector
https://github.com/Despector/Despector/blob/e60cfaaf7a0688bc83f8b00c392521d0b162afba/src/main/java/org/spongepowered/despector/emitter/bytecode/instruction/BytecodeStringConstantEmitter.java
src/main/java/org/spongepowered/despector/emitter/bytecode/instruction/BytecodeStringConstantEmitter.java
/* * The MIT License (MIT) * * Copyright (c) Despector <https://despector.voxelgenesis.com> * Copyright (c) contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package org.spongepowered.despector.emitter.bytecode.instruction; import org.objectweb.asm.MethodVisitor; import org.spongepowered.despector.ast.generic.TypeSignature; import org.spongepowered.despector.ast.insn.cst.StringConstant; import org.spongepowered.despector.emitter.InstructionEmitter; import org.spongepowered.despector.emitter.bytecode.BytecodeEmitterContext; public class BytecodeStringConstantEmitter implements InstructionEmitter<BytecodeEmitterContext, StringConstant> { @Override public void emit(BytecodeEmitterContext ctx, StringConstant arg, TypeSignature type) { MethodVisitor mv = ctx.getMethodVisitor(); mv.visitLdcInsn(arg.getConstant()); ctx.updateStack(1); } }
java
MIT
e60cfaaf7a0688bc83f8b00c392521d0b162afba
2026-01-05T02:42:07.381192Z
false
Despector/Despector
https://github.com/Despector/Despector/blob/e60cfaaf7a0688bc83f8b00c392521d0b162afba/src/main/java/org/spongepowered/despector/emitter/bytecode/instruction/BytecodeTypeConstantEmitter.java
src/main/java/org/spongepowered/despector/emitter/bytecode/instruction/BytecodeTypeConstantEmitter.java
/* * The MIT License (MIT) * * Copyright (c) Despector <https://despector.voxelgenesis.com> * Copyright (c) contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package org.spongepowered.despector.emitter.bytecode.instruction; import org.objectweb.asm.MethodVisitor; import org.objectweb.asm.Type; import org.spongepowered.despector.ast.generic.TypeSignature; import org.spongepowered.despector.ast.insn.cst.TypeConstant; import org.spongepowered.despector.emitter.InstructionEmitter; import org.spongepowered.despector.emitter.bytecode.BytecodeEmitterContext; public class BytecodeTypeConstantEmitter implements InstructionEmitter<BytecodeEmitterContext, TypeConstant> { @Override public void emit(BytecodeEmitterContext ctx, TypeConstant arg, TypeSignature type) { MethodVisitor mv = ctx.getMethodVisitor(); mv.visitLdcInsn(Type.getType(arg.getConstant().getDescriptor())); ctx.updateStack(1); } }
java
MIT
e60cfaaf7a0688bc83f8b00c392521d0b162afba
2026-01-05T02:42:07.381192Z
false
Despector/Despector
https://github.com/Despector/Despector/blob/e60cfaaf7a0688bc83f8b00c392521d0b162afba/src/main/java/org/spongepowered/despector/emitter/bytecode/statement/BytecodeInvokeStatementEmitter.java
src/main/java/org/spongepowered/despector/emitter/bytecode/statement/BytecodeInvokeStatementEmitter.java
/* * The MIT License (MIT) * * Copyright (c) Despector <https://despector.voxelgenesis.com> * Copyright (c) contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package org.spongepowered.despector.emitter.bytecode.statement; import org.spongepowered.despector.ast.stmt.invoke.InvokeStatement; import org.spongepowered.despector.emitter.StatementEmitter; import org.spongepowered.despector.emitter.bytecode.BytecodeEmitterContext; public class BytecodeInvokeStatementEmitter implements StatementEmitter<BytecodeEmitterContext, InvokeStatement> { @Override public void emit(BytecodeEmitterContext ctx, InvokeStatement stmt, boolean semicolon) { ctx.emitInstruction(stmt.getInstruction(), null); } }
java
MIT
e60cfaaf7a0688bc83f8b00c392521d0b162afba
2026-01-05T02:42:07.381192Z
false
Despector/Despector
https://github.com/Despector/Despector/blob/e60cfaaf7a0688bc83f8b00c392521d0b162afba/src/main/java/org/spongepowered/despector/emitter/bytecode/statement/BytecodeReturnEmitter.java
src/main/java/org/spongepowered/despector/emitter/bytecode/statement/BytecodeReturnEmitter.java
/* * The MIT License (MIT) * * Copyright (c) Despector <https://despector.voxelgenesis.com> * Copyright (c) contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package org.spongepowered.despector.emitter.bytecode.statement; import org.objectweb.asm.MethodVisitor; import org.objectweb.asm.Opcodes; import org.spongepowered.despector.ast.generic.ClassTypeSignature; import org.spongepowered.despector.ast.generic.TypeSignature; import org.spongepowered.despector.ast.insn.Instruction; import org.spongepowered.despector.ast.stmt.misc.Return; import org.spongepowered.despector.emitter.StatementEmitter; import org.spongepowered.despector.emitter.bytecode.BytecodeEmitterContext; public class BytecodeReturnEmitter implements StatementEmitter<BytecodeEmitterContext, Return> { @Override public void emit(BytecodeEmitterContext ctx, Return stmt, boolean semicolon) { MethodVisitor mv = ctx.getMethodVisitor(); if (!stmt.getValue().isPresent()) { mv.visitInsn(Opcodes.RETURN); } else { ctx.updateStack(-1); Instruction insn = stmt.getValue().get(); ctx.emitInstruction(insn, ctx.getMethod().getReturnType()); TypeSignature ret = ctx.getMethod().getReturnType(); if (ret == ClassTypeSignature.INT || ret == ClassTypeSignature.BOOLEAN || ret == ClassTypeSignature.BYTE || ret == ClassTypeSignature.SHORT || ret == ClassTypeSignature.CHAR) { mv.visitInsn(Opcodes.IRETURN); } else if (ret == ClassTypeSignature.LONG) { mv.visitInsn(Opcodes.LRETURN); } else if (ret == ClassTypeSignature.FLOAT) { mv.visitInsn(Opcodes.FRETURN); } else if (ret == ClassTypeSignature.DOUBLE) { mv.visitInsn(Opcodes.DRETURN); } else { mv.visitInsn(Opcodes.ARETURN); } } } }
java
MIT
e60cfaaf7a0688bc83f8b00c392521d0b162afba
2026-01-05T02:42:07.381192Z
false
Despector/Despector
https://github.com/Despector/Despector/blob/e60cfaaf7a0688bc83f8b00c392521d0b162afba/src/main/java/org/spongepowered/despector/emitter/bytecode/statement/BytecodeIfEmitter.java
src/main/java/org/spongepowered/despector/emitter/bytecode/statement/BytecodeIfEmitter.java
/* * The MIT License (MIT) * * Copyright (c) Despector <https://despector.voxelgenesis.com> * Copyright (c) contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package org.spongepowered.despector.emitter.bytecode.statement; import org.objectweb.asm.Label; import org.objectweb.asm.MethodVisitor; import org.objectweb.asm.Opcodes; import org.spongepowered.despector.ast.insn.condition.AndCondition; import org.spongepowered.despector.ast.insn.condition.BooleanCondition; import org.spongepowered.despector.ast.insn.condition.CompareCondition; import org.spongepowered.despector.ast.insn.condition.Condition; import org.spongepowered.despector.ast.stmt.Statement; import org.spongepowered.despector.ast.stmt.branch.If; import org.spongepowered.despector.emitter.StatementEmitter; import org.spongepowered.despector.emitter.bytecode.BytecodeEmitterContext; public class BytecodeIfEmitter implements StatementEmitter<BytecodeEmitterContext, If> { private Label start; private Label end; @Override public void emit(BytecodeEmitterContext ctx, If stmt, boolean semicolon) { MethodVisitor mv = ctx.getMethodVisitor(); this.start = new Label(); this.end = new Label(); emit(ctx, stmt.getCondition()); mv.visitLabel(this.start); for (Statement b : stmt.getBody()) { ctx.emitStatement(b); } mv.visitLabel(this.end); } private void emit(BytecodeEmitterContext ctx, Condition cond) { if (cond instanceof AndCondition) { AndCondition and = (AndCondition) cond; for (Condition op : and.getOperands()) { emitInverse(ctx, op); } } } private void emitInverse(BytecodeEmitterContext ctx, Condition cond) { MethodVisitor mv = ctx.getMethodVisitor(); if (cond instanceof CompareCondition) { CompareCondition cmp = (CompareCondition) cond; ctx.emitInstruction(cmp.getLeft(), null); ctx.emitInstruction(cmp.getRight(), null); switch (cmp.getOperator()) { case NOT_EQUAL: mv.visitJumpInsn(Opcodes.IF_ACMPEQ, this.end); break; case EQUAL: mv.visitJumpInsn(Opcodes.IF_ACMPNE, this.end); break; default: throw new IllegalStateException("Unsupported compare operator: " + cmp.getOperator().name()); } } else if(cond instanceof BooleanCondition) { BooleanCondition bool = (BooleanCondition) cond; ctx.emitInstruction(bool.getConditionValue(), null); if(bool.isInverse()) { mv.visitJumpInsn(Opcodes.IFNE, this.end); } else { mv.visitJumpInsn(Opcodes.IFEQ, this.end); } } else { throw new IllegalStateException(); } } }
java
MIT
e60cfaaf7a0688bc83f8b00c392521d0b162afba
2026-01-05T02:42:07.381192Z
false
Despector/Despector
https://github.com/Despector/Despector/blob/e60cfaaf7a0688bc83f8b00c392521d0b162afba/src/main/java/org/spongepowered/despector/emitter/bytecode/statement/BytecodeLocalAssignmentEmitter.java
src/main/java/org/spongepowered/despector/emitter/bytecode/statement/BytecodeLocalAssignmentEmitter.java
/* * The MIT License (MIT) * * Copyright (c) Despector <https://despector.voxelgenesis.com> * Copyright (c) contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package org.spongepowered.despector.emitter.bytecode.statement; import org.objectweb.asm.MethodVisitor; import org.objectweb.asm.Opcodes; import org.spongepowered.despector.ast.generic.ClassTypeSignature; import org.spongepowered.despector.ast.generic.TypeSignature; import org.spongepowered.despector.ast.stmt.assign.LocalAssignment; import org.spongepowered.despector.emitter.StatementEmitter; import org.spongepowered.despector.emitter.bytecode.BytecodeEmitterContext; public class BytecodeLocalAssignmentEmitter implements StatementEmitter<BytecodeEmitterContext, LocalAssignment> { @Override public void emit(BytecodeEmitterContext ctx, LocalAssignment stmt, boolean semicolon) { MethodVisitor mv = ctx.getMethodVisitor(); TypeSignature type = stmt.getLocal().getType(); ctx.emitInstruction(stmt.getValue(), type); if (type == ClassTypeSignature.INT || type == ClassTypeSignature.BOOLEAN || type == ClassTypeSignature.BYTE || type == ClassTypeSignature.SHORT || type == ClassTypeSignature.CHAR) { mv.visitVarInsn(Opcodes.ISTORE, stmt.getLocal().getIndex()); } else if (type == ClassTypeSignature.LONG) { mv.visitVarInsn(Opcodes.LSTORE, stmt.getLocal().getIndex()); } else if (type == ClassTypeSignature.FLOAT) { mv.visitVarInsn(Opcodes.FSTORE, stmt.getLocal().getIndex()); } else if (type == ClassTypeSignature.DOUBLE) { mv.visitVarInsn(Opcodes.DSTORE, stmt.getLocal().getIndex()); } else { mv.visitVarInsn(Opcodes.ASTORE, stmt.getLocal().getIndex()); } ctx.updateStack(-1); } }
java
MIT
e60cfaaf7a0688bc83f8b00c392521d0b162afba
2026-01-05T02:42:07.381192Z
false
Despector/Despector
https://github.com/Despector/Despector/blob/e60cfaaf7a0688bc83f8b00c392521d0b162afba/src/main/java/org/spongepowered/despector/emitter/kotlin/package-info.java
src/main/java/org/spongepowered/despector/emitter/kotlin/package-info.java
/* * The MIT License (MIT) * * Copyright (c) Despector <https://despector.voxelgenesis.com> * Copyright (c) contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ @org.spongepowered.despector.util.NonnullByDefault package org.spongepowered.despector.emitter.kotlin;
java
MIT
e60cfaaf7a0688bc83f8b00c392521d0b162afba
2026-01-05T02:42:07.381192Z
false
Despector/Despector
https://github.com/Despector/Despector/blob/e60cfaaf7a0688bc83f8b00c392521d0b162afba/src/main/java/org/spongepowered/despector/emitter/kotlin/KotlinEmitterUtil.java
src/main/java/org/spongepowered/despector/emitter/kotlin/KotlinEmitterUtil.java
/* * The MIT License (MIT) * * Copyright (c) Despector <https://despector.voxelgenesis.com> * Copyright (c) contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package org.spongepowered.despector.emitter.kotlin; import org.spongepowered.despector.ast.generic.ClassTypeSignature; import org.spongepowered.despector.ast.generic.TypeSignature; import org.spongepowered.despector.emitter.java.JavaEmitterContext; /** * A utility for the kotlin emitter. */ public final class KotlinEmitterUtil { /** * Emits the given type. */ public static void emitParamType(JavaEmitterContext ctx, TypeSignature type) { if (type.isArray()) { ctx.printString("Array<"); emitParamType(ctx, TypeSignature.getArrayComponent(type)); ctx.printString(">"); } else if (type == ClassTypeSignature.OBJECT) { ctx.printString("Any"); } else { emitType(ctx, type); } } /** * Emits the given parameter type. */ public static void emitParamType(JavaEmitterContext ctx, String type) { if ("Ljava/lang/Object;".equals(type)) { ctx.printString("Any"); } else { emitType(ctx, type); } } /** * Emits the given type. */ public static void emitType(JavaEmitterContext ctx, TypeSignature type) { if (type.isArray()) { ctx.printString("Array<"); emitType(ctx, TypeSignature.getArrayComponent(type)); ctx.printString(">"); } else if (type == ClassTypeSignature.BYTE) { ctx.printString("Byte"); } else if (type == ClassTypeSignature.SHORT) { ctx.printString("Short"); } else if (type == ClassTypeSignature.INT || type == ClassTypeSignature.INTEGER_OBJECT) { ctx.printString("Int"); } else if (type == ClassTypeSignature.LONG) { ctx.printString("Long"); } else if (type == ClassTypeSignature.FLOAT) { ctx.printString("Float"); } else if (type == ClassTypeSignature.DOUBLE) { ctx.printString("Double"); } else if (type == ClassTypeSignature.BOOLEAN) { ctx.printString("Boolean"); } else if (type == ClassTypeSignature.CHAR || type == ClassTypeSignature.CHARACTER_OBJECT) { ctx.printString("Char"); } else { ctx.emitType(type, false); } } /** * Emits the given type. */ public static void emitType(JavaEmitterContext ctx, String type) { if (type.startsWith("[")) { ctx.printString("Array<"); emitType(ctx, type.substring(1)); ctx.printString(">"); } else if ("B".equals(type)) { ctx.printString("Byte"); } else if ("S".equals(type)) { ctx.printString("Short"); } else if ("I".equals(type) || "Ljava/lang/Integer;".equals(type)) { ctx.printString("Int"); } else if ("J".equals(type)) { ctx.printString("Long"); } else if ("F".equals(type)) { ctx.printString("Float"); } else if ("D".equals(type)) { ctx.printString("Double"); } else if ("Z".equals(type)) { ctx.printString("Boolean"); } else if ("C".equals(type) || "Ljava/lang/Character;".equals(type)) { ctx.printString("Char"); } else { ctx.emitType(type); } } private KotlinEmitterUtil() { } }
java
MIT
e60cfaaf7a0688bc83f8b00c392521d0b162afba
2026-01-05T02:42:07.381192Z
false
Despector/Despector
https://github.com/Despector/Despector/blob/e60cfaaf7a0688bc83f8b00c392521d0b162afba/src/main/java/org/spongepowered/despector/emitter/kotlin/KotlinEmitter.java
src/main/java/org/spongepowered/despector/emitter/kotlin/KotlinEmitter.java
/* * The MIT License (MIT) * * Copyright (c) Despector <https://despector.voxelgenesis.com> * Copyright (c) contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package org.spongepowered.despector.emitter.kotlin; import org.spongepowered.despector.ast.type.TypeEntry; import org.spongepowered.despector.emitter.Emitter; import org.spongepowered.despector.emitter.Emitters; import org.spongepowered.despector.emitter.java.ImportManager; import org.spongepowered.despector.emitter.java.JavaEmitterContext; /** * A kotlin source emitter. */ public class KotlinEmitter implements Emitter<JavaEmitterContext> { @Override public void setup(JavaEmitterContext ctx) { ctx.setSemicolons(false); ctx.setEmitterSet(Emitters.KOTLIN_SET); ImportManager imports = ctx.getImportManager(); imports.addImplicitImport("kotlin/"); imports.addImplicitImport("kotlin/annotation/"); imports.addImplicitImport("kotlin/collections/"); imports.addImplicitImport("kotlin/comparisons/"); imports.addImplicitImport("kotlin/io/"); imports.addImplicitImport("kotlin/ranges/"); imports.addImplicitImport("kotlin/sequences/"); imports.addImplicitImport("kotlin/text/"); imports.addImplicitImport("kotlin/jvm/"); } @Override public void emit(JavaEmitterContext ctx, TypeEntry type) { setup(ctx); ctx.emitOuterType(type); } }
java
MIT
e60cfaaf7a0688bc83f8b00c392521d0b162afba
2026-01-05T02:42:07.381192Z
false
Despector/Despector
https://github.com/Despector/Despector/blob/e60cfaaf7a0688bc83f8b00c392521d0b162afba/src/main/java/org/spongepowered/despector/emitter/kotlin/type/KotlinClassEntryEmitter.java
src/main/java/org/spongepowered/despector/emitter/kotlin/type/KotlinClassEntryEmitter.java
/* * The MIT License (MIT) * * Copyright (c) Despector <https://despector.voxelgenesis.com> * Copyright (c) contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package org.spongepowered.despector.emitter.kotlin.type; import org.spongepowered.despector.ast.Annotation; import org.spongepowered.despector.ast.insn.Instruction; import org.spongepowered.despector.ast.stmt.Statement; import org.spongepowered.despector.ast.stmt.assign.FieldAssignment; import org.spongepowered.despector.ast.stmt.assign.StaticFieldAssignment; import org.spongepowered.despector.ast.type.ClassEntry; import org.spongepowered.despector.ast.type.FieldEntry; import org.spongepowered.despector.ast.type.MethodEntry; import org.spongepowered.despector.ast.type.TypeEntry; import org.spongepowered.despector.ast.type.TypeEntry.InnerClassInfo; import org.spongepowered.despector.config.ConfigManager; import org.spongepowered.despector.emitter.AstEmitter; import org.spongepowered.despector.emitter.java.JavaEmitterContext; import org.spongepowered.despector.emitter.java.special.GenericsEmitter; import org.spongepowered.despector.emitter.java.type.FieldEntryEmitter; import org.spongepowered.despector.emitter.kotlin.special.KotlinCompanionClassEmitter; import org.spongepowered.despector.emitter.kotlin.special.KotlinDataClassEmitter; import org.spongepowered.despector.util.AstUtil; import java.util.Collection; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.stream.Collectors; /** * An emitter for kotlin casts. */ public class KotlinClassEntryEmitter implements AstEmitter<JavaEmitterContext, ClassEntry> { private static final Set<String> HIDDEN_ANNOTATIONS = new HashSet<>(); static { HIDDEN_ANNOTATIONS.add("kotlin/Metadata"); } @Override public boolean emit(JavaEmitterContext ctx, ClassEntry type) { if (type.getStaticMethod("copy$default") != null) { KotlinDataClassEmitter data_emitter = ctx.getEmitterSet().getSpecialEmitter(KotlinDataClassEmitter.class); data_emitter.emit(ctx, type); return true; } if (type.getName().endsWith("$Companion")) { KotlinCompanionClassEmitter companion_emitter = ctx.getEmitterSet().getSpecialEmitter(KotlinCompanionClassEmitter.class); companion_emitter.emit(ctx, type); return true; } boolean emit_class = !type.getMethods().isEmpty() || !type.getFields().isEmpty(); if (emit_class) { for (Annotation anno : type.getAnnotations()) { if (HIDDEN_ANNOTATIONS.contains(anno.getType().getName())) { continue; } ctx.printIndentation(); ctx.emit(anno); ctx.newLine(); } ctx.printIndentation(); InnerClassInfo inner_info = null; if (type.isInnerClass() && ctx.getOuterType() != null) { inner_info = ctx.getOuterType().getInnerClassInfo(type.getName()); } ctx.printString("class "); if (inner_info != null) { ctx.printString(inner_info.getSimpleName()); } else { String name = type.getName().replace('/', '.'); if (name.indexOf('.') != -1) { name = name.substring(name.lastIndexOf('.') + 1, name.length()); } name = name.replace('$', '.'); ctx.printString(name); } GenericsEmitter generics = ctx.getEmitterSet().getSpecialEmitter(GenericsEmitter.class); if (type.getSignature() != null) { generics.emitTypeParameters(ctx, type.getSignature().getParameters()); } if (!type.getSuperclass().equals("Ljava/lang/Object;")) { ctx.printString(" extends "); ctx.emitTypeName(type.getSuperclassName()); if (type.getSignature() != null && type.getSignature().getSuperclassSignature() != null) { generics.emitTypeArguments(ctx, type.getSignature().getSuperclassSignature().getArguments()); } } if (!type.getInterfaces().isEmpty()) { ctx.printString(" : "); for (int i = 0; i < type.getInterfaces().size(); i++) { ctx.emitType(type.getInterfaces().get(i)); generics.emitTypeArguments(ctx, type.getSignature().getInterfaceSignatures().get(i).getArguments()); if (i < type.getInterfaces().size() - 1) { ctx.printString(" ", ctx.getFormat().insert_space_before_comma_in_superinterfaces); ctx.printString(","); ctx.printString(" ", ctx.getFormat().insert_space_after_comma_in_superinterfaces); } } } ctx.printString(" ", ctx.getFormat().insert_space_before_opening_brace_in_type_declaration); ctx.printString("{"); ctx.newLine(ctx.getFormat().blank_lines_before_first_class_body_declaration + 1); // Ordering is static fields -> static methods -> instance fields -> // instance methods ctx.indent(); } emitStaticFields(ctx, type); emitStaticMethods(ctx, type); emitFields(ctx, type); emitMethods(ctx, type); Collection<InnerClassInfo> inners = type.getInnerClasses(); for (InnerClassInfo inner : inners) { if (inner.getOuterName() == null || !inner.getOuterName().equals(type.getName())) { continue; } TypeEntry inner_type = type.getSource().get(inner.getName()); ctx.emit(inner_type); ctx.newLine(); } if (emit_class) { ctx.dedent(); ctx.printIndentation(); ctx.printString("}"); ctx.newLine(); } return true; } /** * Emits the static fields of the given type. */ public void emitStaticFields(JavaEmitterContext ctx, ClassEntry type) { if (!type.getStaticFields().isEmpty()) { Map<String, Instruction> static_initializers = new HashMap<>(); MethodEntry static_init = type.getStaticMethod("<clinit>"); if (static_init != null && static_init.getInstructions() != null) { for (Statement stmt : static_init.getInstructions().getStatements()) { if (!(stmt instanceof StaticFieldAssignment)) { break; } StaticFieldAssignment assign = (StaticFieldAssignment) stmt; if (!assign.getOwnerName().equals(type.getName())) { break; } static_initializers.put(assign.getFieldName(), assign.getValue()); } } boolean at_least_one = false; for (FieldEntry field : type.getStaticFields()) { if (field.isSynthetic() || field.getName().equals("Companion")) { if (ConfigManager.getConfig().emitter.emit_synthetics) { ctx.printIndentation(); ctx.printString("// Synthetic"); ctx.newLine(); } else { continue; } } at_least_one = true; ctx.printIndentation(); ctx.emit(field); if (static_initializers.containsKey(field.getName())) { ctx.printString(" = "); ctx.emit(static_initializers.get(field.getName()), field.getType()); } ctx.printString(";"); ctx.newLine(); } if (at_least_one) { ctx.newLine(); } } } /** * Emits the static methods of the given type. */ public void emitStaticMethods(JavaEmitterContext ctx, ClassEntry type) { if (!type.getStaticMethods().isEmpty()) { for (MethodEntry mth : type.getStaticMethods()) { if (mth.isSynthetic()) { if (ConfigManager.getConfig().emitter.emit_synthetics) { ctx.printIndentation(); ctx.printString("// Synthetic"); ctx.newLine(); } else { continue; } } if (ctx.emit(mth)) { ctx.newLine(); ctx.newLine(); } } } } /** * Emits the instance fields of the given type. */ public void emitFields(JavaEmitterContext ctx, ClassEntry type) { if (!type.getFields().isEmpty()) { Map<FieldEntry, Instruction> initializers = new HashMap<>(); List<MethodEntry> inits = type.getMethods().stream().filter((m) -> m.getName().equals("<init>")).collect(Collectors.toList()); MethodEntry main = null; if (inits.size() == 1) { main = inits.get(0); } if (main != null && main.getInstructions() != null) { for (int i = 1; i < main.getInstructions().getStatements().size(); i++) { Statement next = main.getInstructions().getStatements().get(i); if (!(next instanceof FieldAssignment)) { break; } FieldAssignment assign = (FieldAssignment) next; if (!type.getName().equals(assign.getOwnerName())) { break; } if (AstUtil.references(assign.getValue(), null)) { break; } assign.setInitializer(true); FieldEntry fld = type.getField(assign.getFieldName()); initializers.put(fld, assign.getValue()); } } boolean at_least_one = false; for (FieldEntry field : type.getFields()) { if (field.isSynthetic()) { if (ConfigManager.getConfig().emitter.emit_synthetics) { ctx.printIndentation(); ctx.printString("// Synthetic"); ctx.newLine(); } else { continue; } } at_least_one = true; ctx.printIndentation(); ctx.emit(field); Instruction init = initializers.get(field); if (init != null) { ctx.setField(field); if (ctx.getFormat().align_type_members_on_columns && ctx.getType() != null) { int len = FieldEntryEmitter.getMaxNameLength(ctx, ctx.getType().getFields()); len -= field.getName().length(); len++; for (int i = 0; i < len; i++) { ctx.printString(" "); } } else { ctx.printString(" "); } ctx.printString("= "); ctx.emit(init, field.getType()); ctx.setField(null); } ctx.printString(";"); ctx.newLine(); } if (at_least_one) { ctx.newLine(); } } } /** * Emits the instance methods of the given type. */ public void emitMethods(JavaEmitterContext ctx, ClassEntry type) { if (!type.getMethods().isEmpty()) { for (MethodEntry mth : type.getMethods()) { if (mth.isSynthetic() || mth.getName().equals("<init>")) { if (ConfigManager.getConfig().emitter.emit_synthetics) { ctx.printIndentation(); ctx.printString("// Synthetic"); ctx.newLine(); } else { continue; } } if (ctx.emit(mth)) { ctx.newLine(); ctx.newLine(); } } } } }
java
MIT
e60cfaaf7a0688bc83f8b00c392521d0b162afba
2026-01-05T02:42:07.381192Z
false
Despector/Despector
https://github.com/Despector/Despector/blob/e60cfaaf7a0688bc83f8b00c392521d0b162afba/src/main/java/org/spongepowered/despector/emitter/kotlin/type/package-info.java
src/main/java/org/spongepowered/despector/emitter/kotlin/type/package-info.java
/* * The MIT License (MIT) * * Copyright (c) Despector <https://despector.voxelgenesis.com> * Copyright (c) contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ @org.spongepowered.despector.util.NonnullByDefault package org.spongepowered.despector.emitter.kotlin.type;
java
MIT
e60cfaaf7a0688bc83f8b00c392521d0b162afba
2026-01-05T02:42:07.381192Z
false
Despector/Despector
https://github.com/Despector/Despector/blob/e60cfaaf7a0688bc83f8b00c392521d0b162afba/src/main/java/org/spongepowered/despector/emitter/kotlin/type/KotlinMethodEntryEmitter.java
src/main/java/org/spongepowered/despector/emitter/kotlin/type/KotlinMethodEntryEmitter.java
/* * The MIT License (MIT) * * Copyright (c) Despector <https://despector.voxelgenesis.com> * Copyright (c) contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package org.spongepowered.despector.emitter.kotlin.type; import org.spongepowered.despector.ast.AccessModifier; import org.spongepowered.despector.ast.Annotation; import org.spongepowered.despector.ast.Locals.Local; import org.spongepowered.despector.ast.Locals.LocalInstance; import org.spongepowered.despector.ast.generic.MethodSignature; import org.spongepowered.despector.ast.generic.VoidTypeSignature; import org.spongepowered.despector.ast.insn.Instruction; import org.spongepowered.despector.ast.stmt.Statement; import org.spongepowered.despector.ast.stmt.StatementBlock; import org.spongepowered.despector.ast.stmt.assign.LocalAssignment; import org.spongepowered.despector.ast.stmt.assign.StaticFieldAssignment; import org.spongepowered.despector.ast.stmt.branch.If; import org.spongepowered.despector.ast.stmt.misc.Return; import org.spongepowered.despector.ast.type.MethodEntry; import org.spongepowered.despector.ast.type.TypeEntry; import org.spongepowered.despector.config.ConfigManager; import org.spongepowered.despector.emitter.java.JavaEmitterContext; import org.spongepowered.despector.emitter.java.special.GenericsEmitter; import org.spongepowered.despector.emitter.java.type.MethodEntryEmitter; import org.spongepowered.despector.emitter.kotlin.KotlinEmitterUtil; import java.util.ArrayList; import java.util.List; /** * An emitter for kotlin methods. */ public class KotlinMethodEntryEmitter extends MethodEntryEmitter { /** * Gets if this method is overriden from a super type. */ public static boolean isOverriden(MethodEntry method) { if (method.getName().equals("toString") && method.getDescription().equals("()Ljava/lang/String;")) { return true; } // TODO return false; } @Override public boolean emit(JavaEmitterContext ctx, MethodEntry method) { boolean nullable_return = false; for (Annotation anno : method.getAnnotations()) { if ("org/jetbrains/annotations/NotNull".equals(anno.getType().getName())) { continue; } if ("org/jetbrains/annotations/Nullable".equals(anno.getType().getName())) { nullable_return = true; continue; } ctx.printIndentation(); ctx.emit(anno); ctx.newLine(); } ctx.setMethod(method); if (method.getName().equals("<clinit>")) { int start = 0; if (method.getInstructions() != null) { for (Statement stmt : method.getInstructions().getStatements()) { if (!(stmt instanceof StaticFieldAssignment)) { break; } StaticFieldAssignment assign = (StaticFieldAssignment) stmt; if (!assign.getOwnerName().equals(method.getOwnerName())) { break; } start++; } // only need one less as we can ignore the return at the end if (start == method.getInstructions().getStatements().size() - 1 && !ConfigManager.getConfig().emitter.emit_synthetics) { return false; } } ctx.printIndentation(); ctx.printString("static {"); ctx.newLine(); ctx.indent(); if (method.getInstructions() == null) { ctx.printIndentation(); ctx.printString("// Error decompiling block"); printReturn(ctx, method.getReturnType()); } else { ctx.emitBody(method.getInstructions(), start); } ctx.newLine(); ctx.dedent(); ctx.printIndentation(); ctx.printString("}"); return true; } if ("<init>".equals(method.getName()) && method.getAccessModifier() == AccessModifier.PUBLIC && method.getParamTypes().isEmpty() && method.getInstructions().getStatements().size() == 2 && !ConfigManager.getConfig().emitter.emit_synthetics) { return false; } ctx.printIndentation(); GenericsEmitter generics = ctx.getEmitterSet().getSpecialEmitter(GenericsEmitter.class); MethodSignature sig = method.getMethodSignature(); if ("<init>".equals(method.getName())) { String name = method.getOwnerName(); name = name.substring(Math.max(name.lastIndexOf('/'), name.lastIndexOf('$')) + 1); ctx.printString(name); } else { if (isOverriden(method)) { ctx.printString("override "); } ctx.printString("fun "); ctx.printString(method.getName()); } List<Instruction> defaults = findDefaultValues(ctx.getType(), method); ctx.printString("("); StatementBlock block = method.getInstructions(); int param_index = 0; if (!method.isStatic()) { param_index++; } for (int i = 0; i < method.getParamTypes().size(); i++) { if (block == null) { ctx.printString("local" + param_index); ctx.printString(": "); if (sig != null) { // interfaces have no lvt for parameters, need to get // generic types from the method signature generics.emitTypeSignature(ctx, sig.getParameters().get(i), false); } else { KotlinEmitterUtil.emitParamType(ctx, method.getParamTypes().get(i)); } } else { Local local = method.getLocals().getLocal(param_index); LocalInstance insn = local.getParameterInstance(); ctx.printString(insn.getName()); ctx.printString(": "); KotlinEmitterUtil.emitParamType(ctx, insn.getType()); } if (defaults != null && defaults.size() > i) { Instruction def = defaults.get(i); ctx.printString(" = "); ctx.emit(def, null); } if (i < method.getParamTypes().size() - 1) { ctx.printString(", "); ctx.markWrapPoint(); } String desc = method.getParamTypes().get(i).getDescriptor(); param_index++; if ("D".equals(desc) || "J".equals(desc)) { param_index++; } } ctx.printString(")"); if (method.getInstructions() != null && method.getInstructions().getStatementCount() == 1) { Statement stmt = method.getInstructions().getStatement(0); if (stmt instanceof Return && ((Return) stmt).getValue().isPresent()) { ctx.printString(" = "); ctx.emit(((Return) stmt).getValue().get(), method.getReturnType()); return true; } } if (!method.getReturnType().equals(VoidTypeSignature.VOID)) { ctx.printString(": "); if (sig != null) { if (!sig.getTypeParameters().isEmpty()) { generics.emitTypeParameters(ctx, sig.getTypeParameters()); ctx.printString(" "); } generics.emitTypeSignature(ctx, sig.getReturnType(), false); } else { KotlinEmitterUtil.emitType(ctx, method.getReturnType()); } if (nullable_return) { ctx.printString("?"); } } if (!method.isAbstract()) { ctx.printString(" {"); ctx.newLine(); ctx.indent(); if (block == null) { ctx.printIndentation(); ctx.printString("// Error decompiling block"); printReturn(ctx, method.getReturnType()); } else { ctx.emitBody(block); } ctx.newLine(); ctx.dedent(); ctx.printIndentation(); ctx.printString("}"); } else { ctx.printString(";"); } ctx.setMethod(null); return true; } private List<Instruction> findDefaultValues(TypeEntry type, MethodEntry method) { MethodEntry defaults = type.getStaticMethod(method.getName() + "$default"); if (defaults == null) { return null; } List<Instruction> def = new ArrayList<>(); for (Statement stmt : defaults.getInstructions().getStatements()) { if (!(stmt instanceof If)) { continue; } LocalAssignment assign = (LocalAssignment) ((If) stmt).getBody().getStatement(0); def.add(assign.getValue()); } return def; } }
java
MIT
e60cfaaf7a0688bc83f8b00c392521d0b162afba
2026-01-05T02:42:07.381192Z
false
Despector/Despector
https://github.com/Despector/Despector/blob/e60cfaaf7a0688bc83f8b00c392521d0b162afba/src/main/java/org/spongepowered/despector/emitter/kotlin/type/KotlinEnumEntryEmitter.java
src/main/java/org/spongepowered/despector/emitter/kotlin/type/KotlinEnumEntryEmitter.java
/* * The MIT License (MIT) * * Copyright (c) Despector <https://despector.voxelgenesis.com> * Copyright (c) contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package org.spongepowered.despector.emitter.kotlin.type; import com.google.common.collect.Lists; import com.google.common.collect.Sets; import org.spongepowered.despector.ast.Annotation; import org.spongepowered.despector.ast.generic.ClassTypeSignature; import org.spongepowered.despector.ast.generic.TypeSignature; import org.spongepowered.despector.ast.stmt.Statement; import org.spongepowered.despector.ast.stmt.assign.StaticFieldAssignment; import org.spongepowered.despector.ast.stmt.invoke.New; import org.spongepowered.despector.ast.type.EnumEntry; import org.spongepowered.despector.ast.type.FieldEntry; import org.spongepowered.despector.ast.type.MethodEntry; import org.spongepowered.despector.ast.type.TypeEntry; import org.spongepowered.despector.ast.type.TypeEntry.InnerClassInfo; import org.spongepowered.despector.config.ConfigManager; import org.spongepowered.despector.emitter.AstEmitter; import org.spongepowered.despector.emitter.java.JavaEmitterContext; import org.spongepowered.despector.emitter.kotlin.KotlinEmitterUtil; import org.spongepowered.despector.util.TypeHelper; import java.util.ArrayList; import java.util.Collection; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Set; /** * An emitter for kotlin enum types. */ public class KotlinEnumEntryEmitter implements AstEmitter<JavaEmitterContext, EnumEntry> { private static final Set<String> HIDDEN_ANNOTATIONS = new HashSet<>(); static { HIDDEN_ANNOTATIONS.add("kotlin/Metadata"); } @Override public boolean emit(JavaEmitterContext ctx, EnumEntry type) { for (Annotation anno : type.getAnnotations()) { if (HIDDEN_ANNOTATIONS.contains(anno.getType().getName())) { continue; } ctx.printIndentation(); ctx.emit(anno); ctx.newLine(); } ctx.printIndentation(); ctx.printString("enum "); InnerClassInfo inner_info = null; if (type.isInnerClass() && ctx.getOuterType() != null) { inner_info = ctx.getOuterType().getInnerClassInfo(type.getName()); } ctx.printString("class "); if (inner_info != null) { ctx.printString(inner_info.getSimpleName()); } else { String name = type.getName().replace('/', '.'); if (name.indexOf('.') != -1) { name = name.substring(name.lastIndexOf('.') + 1, name.length()); } name = name.replace('$', '.'); ctx.printString(name); } if (!type.getInterfaces().isEmpty()) { ctx.printString(" : "); for (int i = 0; i < type.getInterfaces().size(); i++) { ctx.emitType(type.getInterfaces().get(i)); if (i < type.getInterfaces().size() - 1) { ctx.printString(" ", ctx.getFormat().insert_space_before_comma_in_superinterfaces); ctx.printString(","); ctx.printString(" ", ctx.getFormat().insert_space_after_comma_in_superinterfaces); } } } List<EnumField> fields = new ArrayList<>(); for (FieldEntry fld : type.getFields()) { if (fld.isSynthetic()) { continue; } EnumField efld = new EnumField(); efld.name = fld.getName(); efld.type = fld.getType(); efld.is_final = fld.isFinal(); fields.add(efld); MethodEntry getter = type.getMethod("get" + Character.toUpperCase(efld.name.charAt(0)) + efld.name.substring(1), "()" + efld.type); if (getter == null) { efld.is_private = true; } else { getter.setSynthetic(true); } } if (fields != null) { ctx.printString("("); for (int i = 0; i < fields.size(); i++) { if (i > 0) { ctx.printString(", "); } EnumField fld = fields.get(i); if (fld.is_private) { ctx.printString("private "); } if (fld.is_final) { ctx.printString("val "); } else { ctx.printString("var "); } ctx.printString(fld.name); ctx.printString(": "); KotlinEmitterUtil.emitType(ctx, fld.type); } ctx.printString(")"); } if (ctx.getFormat().insert_space_before_opening_brace_in_type_declaration) { ctx.printString(" "); } ctx.printString("{"); ctx.newLine(); ctx.newLine(); ctx.indent(); // we look through the class initializer to find the enum constant // initializers so that we can emit those specially before the rest of // the class contents. MethodEntry clinit = type.getStaticMethod("<clinit>"); List<Statement> remaining = Lists.newArrayList(); Set<String> found = Sets.newHashSet(); if (clinit != null && clinit.getInstructions() != null) { Iterator<Statement> initializers = clinit.getInstructions().getStatements().iterator(); boolean first = true; while (initializers.hasNext()) { Statement next = initializers.next(); if (!(next instanceof StaticFieldAssignment)) { break; } StaticFieldAssignment assign = (StaticFieldAssignment) next; if (assign.getFieldName().equals("$VALUES")) { continue; } if (!TypeHelper.descToType(assign.getOwnerType()).equals(type.getName()) || !(assign.getValue() instanceof New)) { remaining.add(assign); break; } if (!first) { ctx.printString(","); ctx.newLine(); } New val = (New) assign.getValue(); ctx.printIndentation(); ctx.printString(assign.getFieldName()); found.add(assign.getFieldName()); if (val.getParameters().length != 2) { ctx.printString("("); List<String> args = TypeHelper.splitSig(val.getCtorDescription()); for (int i = 2; i < val.getParameters().length; i++) { ctx.emit(val.getParameters()[i], ClassTypeSignature.of(args.get(i))); if (i < val.getParameters().length - 1) { ctx.printString(", "); } } ctx.printString(")"); } first = false; } if (!first) { ctx.printString(";"); ctx.newLine(); } // We store any remaining statements to be emitted later while (initializers.hasNext()) { remaining.add(initializers.next()); } } if (!found.isEmpty()) { ctx.newLine(); } if (!type.getStaticFields().isEmpty()) { boolean at_least_one = false; for (FieldEntry field : type.getStaticFields()) { if (field.isSynthetic()) { // Skip the values array. if (ConfigManager.getConfig().emitter.emit_synthetics) { ctx.printIndentation(); ctx.printString("// Synthetic"); ctx.newLine(); } else { continue; } } if (found.contains(field.getName())) { // Skip the fields for any of the enum constants that we // found earlier. continue; } ctx.printIndentation(); ctx.emit(field); ctx.printString(";"); ctx.newLine(); at_least_one = true; } if (at_least_one) { ctx.newLine(); } } if (!remaining.isEmpty()) { // if we found any additional statements in the class initializer // while looking for enum constants we emit them here ctx.printIndentation(); ctx.printString("static {"); ctx.newLine(); ctx.indent(); for (Statement stmt : remaining) { ctx.printIndentation(); ctx.emit(stmt, ctx.usesSemicolons()); ctx.newLine(); } ctx.dedent(); ctx.printIndentation(); ctx.printString("}"); ctx.newLine(); } if (!type.getStaticMethods().isEmpty()) { for (MethodEntry mth : type.getStaticMethods()) { if (mth.getName().equals("valueOf") || mth.getName().equals("values") || mth.getName().equals("<clinit>")) { // Can skip these boilerplate methods and the class // initializer continue; } else if (mth.isSynthetic()) { if (ConfigManager.getConfig().emitter.emit_synthetics) { ctx.printIndentation(); ctx.printString("// Synthetic"); ctx.newLine(); } else { continue; } } ctx.emit(mth); ctx.newLine(); ctx.newLine(); } } if (!type.getMethods().isEmpty()) { for (MethodEntry mth : type.getMethods()) { if (mth.isSynthetic() || mth.getName().equals("<init>")) { if (ConfigManager.getConfig().emitter.emit_synthetics) { ctx.printIndentation(); ctx.printString("// Synthetic"); ctx.newLine(); } else { continue; } } ctx.emit(mth); ctx.newLine(); ctx.newLine(); } } Collection<InnerClassInfo> inners = type.getInnerClasses(); for (InnerClassInfo inner : inners) { if (inner.getOuterName() == null || !inner.getOuterName().equals(type.getName())) { continue; } TypeEntry inner_type = type.getSource().get(inner.getName()); ctx.newLine(); ctx.emit(inner_type); } ctx.dedent(); ctx.printIndentation(); ctx.printString("}"); ctx.newLine(); return true; } /** * An enum field. */ private static class EnumField { public String name; public TypeSignature type; public boolean is_final; public boolean is_private; public EnumField() { } } }
java
MIT
e60cfaaf7a0688bc83f8b00c392521d0b162afba
2026-01-05T02:42:07.381192Z
false
Despector/Despector
https://github.com/Despector/Despector/blob/e60cfaaf7a0688bc83f8b00c392521d0b162afba/src/main/java/org/spongepowered/despector/emitter/kotlin/instruction/KotlinTernaryEmitter.java
src/main/java/org/spongepowered/despector/emitter/kotlin/instruction/KotlinTernaryEmitter.java
/* * The MIT License (MIT) * * Copyright (c) Despector <https://despector.voxelgenesis.com> * Copyright (c) contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package org.spongepowered.despector.emitter.kotlin.instruction; import org.spongepowered.despector.ast.generic.ClassTypeSignature; import org.spongepowered.despector.ast.generic.TypeSignature; import org.spongepowered.despector.ast.insn.condition.CompareCondition; import org.spongepowered.despector.ast.insn.misc.Ternary; import org.spongepowered.despector.emitter.java.JavaEmitterContext; import org.spongepowered.despector.emitter.java.instruction.TernaryEmitter; import org.spongepowered.despector.emitter.kotlin.special.KotlinRangeEmitter; /** * An emitter for kotlin ternaries. */ public class KotlinTernaryEmitter extends TernaryEmitter { @Override public void emit(JavaEmitterContext ctx, Ternary ternary, TypeSignature type) { if (type == ClassTypeSignature.BOOLEAN && checkBooleanExpression(ctx, ternary)) { return; } ctx.printString("if ("); if (ternary.getCondition() instanceof CompareCondition) { ctx.emit(ternary.getCondition()); } else { ctx.emit(ternary.getCondition()); } ctx.printString(") "); ctx.markWrapPoint(); ctx.emit(ternary.getTrueValue(), type); ctx.markWrapPoint(); ctx.printString(" else "); ctx.emit(ternary.getFalseValue(), type); } @Override public boolean checkBooleanExpression(JavaEmitterContext ctx, Ternary ternary) { if (KotlinRangeEmitter.checkRangeTernary(ctx, ternary)) { return true; } return super.checkBooleanExpression(ctx, ternary); } }
java
MIT
e60cfaaf7a0688bc83f8b00c392521d0b162afba
2026-01-05T02:42:07.381192Z
false
Despector/Despector
https://github.com/Despector/Despector/blob/e60cfaaf7a0688bc83f8b00c392521d0b162afba/src/main/java/org/spongepowered/despector/emitter/kotlin/instruction/KotlinOperatorEmitter.java
src/main/java/org/spongepowered/despector/emitter/kotlin/instruction/KotlinOperatorEmitter.java
/* * The MIT License (MIT) * * Copyright (c) Despector <https://despector.voxelgenesis.com> * Copyright (c) contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package org.spongepowered.despector.emitter.kotlin.instruction; import org.spongepowered.despector.ast.generic.TypeSignature; import org.spongepowered.despector.ast.insn.op.Operator; import org.spongepowered.despector.ast.insn.op.OperatorType; import org.spongepowered.despector.emitter.InstructionEmitter; import org.spongepowered.despector.emitter.java.JavaEmitterContext; /** * An emitter for kotlin operators. */ public class KotlinOperatorEmitter implements InstructionEmitter<JavaEmitterContext, Operator> { /** * Gets if the given operator needs to be wrapped in parens. */ public boolean needParens(OperatorType op) { switch (op) { case AND: case OR: case XOR: case SHIFT_LEFT: case SHIFT_RIGHT: case UNSIGNED_SHIFT_RIGHT: return true; case ADD: case SUBTRACT: case MULTIPLY: case DIVIDE: case REMAINDER: default: return false; } } /** * Emits the given operator. */ public void emitOp(JavaEmitterContext ctx, OperatorType op) { switch (op) { case AND: ctx.printString(" and "); break; case OR: ctx.printString(" or "); break; case XOR: ctx.printString(" xor "); break; case SHIFT_LEFT: ctx.printString(" shl "); break; case SHIFT_RIGHT: ctx.printString(" shr "); break; case UNSIGNED_SHIFT_RIGHT: ctx.printString(" ushr "); break; default: ctx.printString(" " + op.getSymbol() + " "); break; } } @Override public void emit(JavaEmitterContext ctx, Operator arg, TypeSignature type) { if (arg.getLeftOperand() instanceof Operator) { Operator right = (Operator) arg.getLeftOperand(); if (arg.getOperator().getPrecedence() > right.getOperator().getPrecedence()) { ctx.printString("("); } ctx.emit(arg.getLeftOperand(), null); if (arg.getOperator().getPrecedence() > right.getOperator().getPrecedence()) { ctx.printString(")"); } } else { ctx.emit(arg.getLeftOperand(), null); } ctx.markWrapPoint(); emitOp(ctx, arg.getOperator()); if (arg.getRightOperand() instanceof Operator) { Operator right = (Operator) arg.getRightOperand(); if (arg.getOperator().getPrecedence() > right.getOperator().getPrecedence()) { ctx.printString("("); } ctx.emit(arg.getRightOperand(), null); if (arg.getOperator().getPrecedence() > right.getOperator().getPrecedence()) { ctx.printString(")"); } } else { ctx.emit(arg.getRightOperand(), null); } } }
java
MIT
e60cfaaf7a0688bc83f8b00c392521d0b162afba
2026-01-05T02:42:07.381192Z
false
Despector/Despector
https://github.com/Despector/Despector/blob/e60cfaaf7a0688bc83f8b00c392521d0b162afba/src/main/java/org/spongepowered/despector/emitter/kotlin/instruction/package-info.java
src/main/java/org/spongepowered/despector/emitter/kotlin/instruction/package-info.java
/* * The MIT License (MIT) * * Copyright (c) Despector <https://despector.voxelgenesis.com> * Copyright (c) contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ @org.spongepowered.despector.util.NonnullByDefault package org.spongepowered.despector.emitter.kotlin.instruction;
java
MIT
e60cfaaf7a0688bc83f8b00c392521d0b162afba
2026-01-05T02:42:07.381192Z
false
Despector/Despector
https://github.com/Despector/Despector/blob/e60cfaaf7a0688bc83f8b00c392521d0b162afba/src/main/java/org/spongepowered/despector/emitter/kotlin/instruction/WhenEmitter.java
src/main/java/org/spongepowered/despector/emitter/kotlin/instruction/WhenEmitter.java
/* * The MIT License (MIT) * * Copyright (c) Despector <https://despector.voxelgenesis.com> * Copyright (c) contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package org.spongepowered.despector.emitter.kotlin.instruction; import org.spongepowered.despector.ast.Locals.LocalInstance; import org.spongepowered.despector.ast.generic.ClassTypeSignature; import org.spongepowered.despector.ast.generic.TypeSignature; import org.spongepowered.despector.ast.insn.Instruction; import org.spongepowered.despector.ast.insn.condition.BooleanCondition; import org.spongepowered.despector.ast.insn.condition.Condition; import org.spongepowered.despector.ast.insn.condition.OrCondition; import org.spongepowered.despector.ast.insn.misc.InstanceOf; import org.spongepowered.despector.ast.kotlin.When; import org.spongepowered.despector.ast.kotlin.When.Case; import org.spongepowered.despector.ast.stmt.invoke.StaticMethodInvoke; import org.spongepowered.despector.emitter.InstructionEmitter; import org.spongepowered.despector.emitter.java.JavaEmitterContext; import org.spongepowered.despector.emitter.kotlin.KotlinEmitterUtil; import java.util.List; /** * An emitter of a kotlin when instruction. */ public class WhenEmitter implements InstructionEmitter<JavaEmitterContext, When> { private void emit(JavaEmitterContext ctx, Condition cond, LocalInstance local) { if (cond instanceof BooleanCondition) { Instruction val = ((BooleanCondition) cond).getConditionValue(); if (val instanceof StaticMethodInvoke) { StaticMethodInvoke mth = (StaticMethodInvoke) val; if (mth.getMethodName().equals("areEqual") && mth.getOwner().equals("Lkotlin/jvm/internal/Intrinsics;")) { ctx.emit(mth.getParameters()[1], null); } } else if (val instanceof InstanceOf) { ctx.printString("is "); KotlinEmitterUtil.emitType(ctx, ((InstanceOf) val).getType()); } else { ctx.emit(val, ClassTypeSignature.BOOLEAN); } } else if (cond instanceof OrCondition) { List<Condition> operands = ((OrCondition) cond).getOperands(); for (int i = 0; i < operands.size(); i++) { Condition arg = operands.get(i); emit(ctx, arg, local); if (i < operands.size() - 1) { ctx.printString(", "); } } } else { ctx.emit(cond); } } @Override public void emit(JavaEmitterContext ctx, When arg, TypeSignature type) { ctx.printString("when ("); ctx.emit(arg.getArg(), null); ctx.printString(") {"); ctx.newLine(); ctx.indent(); ctx.printIndentation(); for (Case cs : arg.getCases()) { emit(ctx, cs.getCondition(), arg.getLocal()); ctx.printString(" -> "); if (cs.getBody().getStatementCount() == 0) { ctx.emit(cs.getLast(), arg.inferType()); ctx.newLine(); ctx.printIndentation(); } else { ctx.printString("{"); ctx.newLine(); ctx.indent(); ctx.printIndentation(); ctx.emitBody(cs.getBody()); ctx.emit(cs.getLast(), arg.inferType()); ctx.newLine(); ctx.dedent(); ctx.printIndentation(); ctx.printString("}"); ctx.newLine(); ctx.printIndentation(); } } ctx.printString("else -> "); if (arg.getElseBody().getStatementCount() == 0) { ctx.emit(arg.getElseBodyLast(), arg.inferType()); ctx.newLine(); } else { ctx.printString("{"); ctx.newLine(); ctx.indent(); ctx.printIndentation(); ctx.emitBody(arg.getElseBody()); ctx.emit(arg.getElseBodyLast(), arg.inferType()); ctx.newLine(); ctx.dedent(); ctx.printIndentation(); ctx.printString("}"); ctx.newLine(); } ctx.dedent(); ctx.printIndentation(); ctx.printString("}"); } }
java
MIT
e60cfaaf7a0688bc83f8b00c392521d0b162afba
2026-01-05T02:42:07.381192Z
false
Despector/Despector
https://github.com/Despector/Despector/blob/e60cfaaf7a0688bc83f8b00c392521d0b162afba/src/main/java/org/spongepowered/despector/emitter/kotlin/instruction/ElvisEmitter.java
src/main/java/org/spongepowered/despector/emitter/kotlin/instruction/ElvisEmitter.java
/* * The MIT License (MIT) * * Copyright (c) Despector <https://despector.voxelgenesis.com> * Copyright (c) contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package org.spongepowered.despector.emitter.kotlin.instruction; import org.spongepowered.despector.ast.generic.TypeSignature; import org.spongepowered.despector.ast.kotlin.Elvis; import org.spongepowered.despector.emitter.InstructionEmitter; import org.spongepowered.despector.emitter.java.JavaEmitterContext; /** * An emitter for kotlin elvis instructions. */ public class ElvisEmitter implements InstructionEmitter<JavaEmitterContext, Elvis> { @Override public void emit(JavaEmitterContext ctx, Elvis arg, TypeSignature type) { ctx.emit(arg.getArg(), type); ctx.printString(" ?: "); ctx.markWrapPoint(); ctx.emit(arg.getElse(), type); } }
java
MIT
e60cfaaf7a0688bc83f8b00c392521d0b162afba
2026-01-05T02:42:07.381192Z
false
Despector/Despector
https://github.com/Despector/Despector/blob/e60cfaaf7a0688bc83f8b00c392521d0b162afba/src/main/java/org/spongepowered/despector/emitter/kotlin/instruction/KotlinCastEmitter.java
src/main/java/org/spongepowered/despector/emitter/kotlin/instruction/KotlinCastEmitter.java
/* * The MIT License (MIT) * * Copyright (c) Despector <https://despector.voxelgenesis.com> * Copyright (c) contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package org.spongepowered.despector.emitter.kotlin.instruction; import org.spongepowered.despector.ast.generic.TypeSignature; import org.spongepowered.despector.ast.insn.misc.Cast; import org.spongepowered.despector.ast.insn.op.Operator; import org.spongepowered.despector.emitter.InstructionEmitter; import org.spongepowered.despector.emitter.java.JavaEmitterContext; /** * An emitter for kotlin casts. */ public class KotlinCastEmitter implements InstructionEmitter<JavaEmitterContext, Cast> { @Override public void emit(JavaEmitterContext ctx, Cast arg, TypeSignature type) { if (type.equals(arg.inferType())) { ctx.emit(arg.getValue(), type); return; } boolean operator = arg.getValue() instanceof Operator; ctx.printString("("); if (!operator) { ctx.printString("("); } ctx.emitType(arg.getType(), false); ctx.printString(") "); if (operator) { ctx.printString("("); } ctx.emit(arg.getValue(), null); ctx.printString(")"); } }
java
MIT
e60cfaaf7a0688bc83f8b00c392521d0b162afba
2026-01-05T02:42:07.381192Z
false
Despector/Despector
https://github.com/Despector/Despector/blob/e60cfaaf7a0688bc83f8b00c392521d0b162afba/src/main/java/org/spongepowered/despector/emitter/kotlin/instruction/KotlinInstanceOfEmitter.java
src/main/java/org/spongepowered/despector/emitter/kotlin/instruction/KotlinInstanceOfEmitter.java
/* * The MIT License (MIT) * * Copyright (c) Despector <https://despector.voxelgenesis.com> * Copyright (c) contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package org.spongepowered.despector.emitter.kotlin.instruction; import org.spongepowered.despector.ast.generic.TypeSignature; import org.spongepowered.despector.ast.insn.misc.InstanceOf; import org.spongepowered.despector.emitter.InstructionEmitter; import org.spongepowered.despector.emitter.java.JavaEmitterContext; /** * An emitter for kotlin instanceof instructions. */ public class KotlinInstanceOfEmitter implements InstructionEmitter<JavaEmitterContext, InstanceOf> { @Override public void emit(JavaEmitterContext ctx, InstanceOf arg, TypeSignature type) { ctx.emit(arg.getCheckedValue(), null); ctx.printString(" is "); ctx.emitType(arg.getType().getDescriptor()); } }
java
MIT
e60cfaaf7a0688bc83f8b00c392521d0b162afba
2026-01-05T02:42:07.381192Z
false
Despector/Despector
https://github.com/Despector/Despector/blob/e60cfaaf7a0688bc83f8b00c392521d0b162afba/src/main/java/org/spongepowered/despector/emitter/kotlin/instruction/KotlinNewEmitter.java
src/main/java/org/spongepowered/despector/emitter/kotlin/instruction/KotlinNewEmitter.java
/* * The MIT License (MIT) * * Copyright (c) Despector <https://despector.voxelgenesis.com> * Copyright (c) contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package org.spongepowered.despector.emitter.kotlin.instruction; import org.spongepowered.despector.ast.generic.ClassTypeSignature; import org.spongepowered.despector.ast.generic.GenericClassTypeSignature; import org.spongepowered.despector.ast.generic.TypeSignature; import org.spongepowered.despector.ast.insn.Instruction; import org.spongepowered.despector.ast.stmt.assign.LocalAssignment; import org.spongepowered.despector.ast.stmt.invoke.New; import org.spongepowered.despector.ast.type.ClassEntry; import org.spongepowered.despector.ast.type.TypeEntry; import org.spongepowered.despector.emitter.InstructionEmitter; import org.spongepowered.despector.emitter.java.JavaEmitterContext; import org.spongepowered.despector.emitter.java.special.AnonymousClassEmitter; import org.spongepowered.despector.util.TypeHelper; import java.util.List; /** * An emitter for a new instruction. */ public class KotlinNewEmitter implements InstructionEmitter<JavaEmitterContext, New> { @Override public void emit(JavaEmitterContext ctx, New arg, TypeSignature type) { if (arg.getType().getName().contains("$")) { String last = arg.getType().getName(); int last_inner_class = last.lastIndexOf('$'); last = last.substring(last_inner_class + 1); if (last.matches("[0-9]+")) { TypeEntry anon_type = ctx.getType().getSource().get(arg.getType().getName()); if (anon_type != null) { AnonymousClassEmitter emitter = ctx.getEmitterSet().getSpecialEmitter(AnonymousClassEmitter.class); emitter.emit(ctx, (ClassEntry) anon_type, arg); return; } System.err.println("Missing TypeEntry for anon type " + arg.getType()); } } ctx.emitType(arg.getType(), false); if (ctx.getField() != null && ctx.getField().getType().hasArguments()) { ctx.printString("<>"); } else if (ctx.getStatement() != null && ctx.getStatement() instanceof LocalAssignment) { LocalAssignment assign = (LocalAssignment) ctx.getStatement(); TypeSignature sig = assign.getLocal().getType(); if (sig != null && sig instanceof GenericClassTypeSignature && !((GenericClassTypeSignature) sig).getArguments().isEmpty()) { ctx.printString("<>"); } } ctx.printString("("); List<String> args = TypeHelper.splitSig(arg.getCtorDescription()); for (int i = 0; i < arg.getParameters().length; i++) { Instruction param = arg.getParameters()[i]; ctx.markWrapPoint(); ctx.emit(param, ClassTypeSignature.of(args.get(i))); if (i < arg.getParameters().length - 1) { ctx.printString(", "); } } ctx.printString(")"); } }
java
MIT
e60cfaaf7a0688bc83f8b00c392521d0b162afba
2026-01-05T02:42:07.381192Z
false