index
int64
repo_id
string
file_path
string
content
string
0
java-sources/ai/timefold/solver/jpyinterpreter/1.24.0/ai/timefold/jpyinterpreter
java-sources/ai/timefold/solver/jpyinterpreter/1.24.0/ai/timefold/jpyinterpreter/builtins/BinaryDunderBuiltin.java
package ai.timefold.jpyinterpreter.builtins; import java.util.List; import java.util.Map; import ai.timefold.jpyinterpreter.PythonBinaryOperator; import ai.timefold.jpyinterpreter.PythonLikeObject; import ai.timefold.jpyinterpreter.types.PythonLikeFunction; import ai.timefold.jpyinterpreter.types.PythonString; import ai.timefold.jpyinterpreter.types.errors.ValueError; public class BinaryDunderBuiltin implements PythonLikeFunction { private final String DUNDER_METHOD_NAME; public static final BinaryDunderBuiltin DIVMOD = new BinaryDunderBuiltin(PythonBinaryOperator.DIVMOD); public static final BinaryDunderBuiltin ADD = new BinaryDunderBuiltin(PythonBinaryOperator.ADD); public static final BinaryDunderBuiltin LESS_THAN = new BinaryDunderBuiltin(PythonBinaryOperator.LESS_THAN); public static final BinaryDunderBuiltin GET_ITEM = new BinaryDunderBuiltin(PythonBinaryOperator.GET_ITEM); public static final BinaryDunderBuiltin GET_ATTRIBUTE = new BinaryDunderBuiltin(PythonBinaryOperator.GET_ATTRIBUTE); public static final BinaryDunderBuiltin POWER = new BinaryDunderBuiltin(PythonBinaryOperator.POWER); public static final BinaryDunderBuiltin FORMAT = new BinaryDunderBuiltin(PythonBinaryOperator.FORMAT); public BinaryDunderBuiltin(String dunderMethodName) { DUNDER_METHOD_NAME = dunderMethodName; } public BinaryDunderBuiltin(PythonBinaryOperator operator) { DUNDER_METHOD_NAME = operator.getDunderMethod(); } @Override public PythonLikeObject $call(List<PythonLikeObject> positionalArguments, Map<PythonString, PythonLikeObject> namedArguments, PythonLikeObject callerInstance) { namedArguments = (namedArguments != null) ? namedArguments : Map.of(); if (positionalArguments.size() != 2) { throw new ValueError("Function " + DUNDER_METHOD_NAME + " expects 2 positional arguments"); } PythonLikeObject object = positionalArguments.get(0); PythonLikeObject arg = positionalArguments.get(1); PythonLikeFunction dunderMethod = (PythonLikeFunction) object.$getType().$getAttributeOrError(DUNDER_METHOD_NAME); return dunderMethod.$call(List.of(object, arg), Map.of(), null); } public PythonLikeObject invoke(PythonLikeObject object, PythonLikeObject arg) { PythonLikeFunction dunderMethod = (PythonLikeFunction) object.$getType().$getAttributeOrError(DUNDER_METHOD_NAME); return dunderMethod.$call(List.of(object, arg), Map.of(), null); } }
0
java-sources/ai/timefold/solver/jpyinterpreter/1.24.0/ai/timefold/jpyinterpreter
java-sources/ai/timefold/solver/jpyinterpreter/1.24.0/ai/timefold/jpyinterpreter/builtins/FunctionBuiltinOperations.java
package ai.timefold.jpyinterpreter.builtins; import ai.timefold.jpyinterpreter.PythonLikeObject; import ai.timefold.jpyinterpreter.types.BoundPythonLikeFunction; import ai.timefold.jpyinterpreter.types.PythonLikeFunction; import ai.timefold.jpyinterpreter.types.PythonLikeType; import ai.timefold.jpyinterpreter.types.PythonNone; public class FunctionBuiltinOperations { public static PythonLikeObject bindFunctionToInstance(final PythonLikeFunction function, final PythonLikeObject instance, final PythonLikeType type) { if (instance == PythonNone.INSTANCE) { return function; } return new BoundPythonLikeFunction(instance, function); } public static PythonLikeObject bindFunctionToType(final PythonLikeFunction function, final PythonLikeObject instance, final PythonLikeType type) { return new BoundPythonLikeFunction(type, function); } }
0
java-sources/ai/timefold/solver/jpyinterpreter/1.24.0/ai/timefold/jpyinterpreter
java-sources/ai/timefold/solver/jpyinterpreter/1.24.0/ai/timefold/jpyinterpreter/builtins/GlobalBuiltins.java
package ai.timefold.jpyinterpreter.builtins; import static ai.timefold.jpyinterpreter.types.BuiltinTypes.BASE_TYPE; import static ai.timefold.jpyinterpreter.types.BuiltinTypes.BOOLEAN_TYPE; import static ai.timefold.jpyinterpreter.types.BuiltinTypes.BYTES_TYPE; import static ai.timefold.jpyinterpreter.types.BuiltinTypes.BYTE_ARRAY_TYPE; import static ai.timefold.jpyinterpreter.types.BuiltinTypes.COMPLEX_TYPE; import static ai.timefold.jpyinterpreter.types.BuiltinTypes.DICT_TYPE; import static ai.timefold.jpyinterpreter.types.BuiltinTypes.FLOAT_TYPE; import static ai.timefold.jpyinterpreter.types.BuiltinTypes.FROZEN_SET_TYPE; import static ai.timefold.jpyinterpreter.types.BuiltinTypes.INT_TYPE; import static ai.timefold.jpyinterpreter.types.BuiltinTypes.LIST_TYPE; import static ai.timefold.jpyinterpreter.types.BuiltinTypes.NONE_TYPE; import static ai.timefold.jpyinterpreter.types.BuiltinTypes.RANGE_TYPE; import static ai.timefold.jpyinterpreter.types.BuiltinTypes.SET_TYPE; import static ai.timefold.jpyinterpreter.types.BuiltinTypes.SLICE_TYPE; import static ai.timefold.jpyinterpreter.types.BuiltinTypes.STRING_TYPE; import static ai.timefold.jpyinterpreter.types.BuiltinTypes.TUPLE_TYPE; import static ai.timefold.jpyinterpreter.types.BuiltinTypes.TYPE_TYPE; import static java.lang.StackWalker.Option.RETAIN_CLASS_REFERENCE; import java.math.BigInteger; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Objects; import java.util.Spliterator; import java.util.Spliterators; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicReference; import java.util.function.Function; import java.util.stream.IntStream; import java.util.stream.StreamSupport; import ai.timefold.jpyinterpreter.PythonBinaryOperator; import ai.timefold.jpyinterpreter.PythonBytecodeToJavaBytecodeTranslator; import ai.timefold.jpyinterpreter.PythonInterpreter; import ai.timefold.jpyinterpreter.PythonLikeObject; import ai.timefold.jpyinterpreter.PythonOverloadImplementor; import ai.timefold.jpyinterpreter.PythonUnaryOperator; import ai.timefold.jpyinterpreter.types.CPythonBackedPythonLikeObject; import ai.timefold.jpyinterpreter.types.Ellipsis; import ai.timefold.jpyinterpreter.types.NotImplemented; import ai.timefold.jpyinterpreter.types.PythonLikeFunction; import ai.timefold.jpyinterpreter.types.PythonLikeType; import ai.timefold.jpyinterpreter.types.PythonNone; import ai.timefold.jpyinterpreter.types.PythonSlice; import ai.timefold.jpyinterpreter.types.PythonString; import ai.timefold.jpyinterpreter.types.PythonSuperObject; import ai.timefold.jpyinterpreter.types.collections.DelegatePythonIterator; import ai.timefold.jpyinterpreter.types.collections.PythonLikeDict; import ai.timefold.jpyinterpreter.types.collections.PythonLikeList; import ai.timefold.jpyinterpreter.types.collections.PythonLikeTuple; import ai.timefold.jpyinterpreter.types.errors.AttributeError; import ai.timefold.jpyinterpreter.types.errors.BufferError; import ai.timefold.jpyinterpreter.types.errors.GeneratorExit; import ai.timefold.jpyinterpreter.types.errors.ImportError; import ai.timefold.jpyinterpreter.types.errors.ModuleNotFoundError; import ai.timefold.jpyinterpreter.types.errors.NameError; import ai.timefold.jpyinterpreter.types.errors.NotImplementedError; import ai.timefold.jpyinterpreter.types.errors.PythonAssertionError; import ai.timefold.jpyinterpreter.types.errors.PythonBaseException; import ai.timefold.jpyinterpreter.types.errors.PythonException; import ai.timefold.jpyinterpreter.types.errors.RecursionError; import ai.timefold.jpyinterpreter.types.errors.ReferenceError; import ai.timefold.jpyinterpreter.types.errors.RuntimeError; import ai.timefold.jpyinterpreter.types.errors.StopAsyncIteration; import ai.timefold.jpyinterpreter.types.errors.StopIteration; import ai.timefold.jpyinterpreter.types.errors.TypeError; import ai.timefold.jpyinterpreter.types.errors.UnboundLocalError; import ai.timefold.jpyinterpreter.types.errors.ValueError; import ai.timefold.jpyinterpreter.types.errors.arithmetic.ArithmeticError; import ai.timefold.jpyinterpreter.types.errors.arithmetic.FloatingPointError; import ai.timefold.jpyinterpreter.types.errors.arithmetic.OverflowError; import ai.timefold.jpyinterpreter.types.errors.arithmetic.ZeroDivisionError; import ai.timefold.jpyinterpreter.types.errors.io.BlockingIOError; import ai.timefold.jpyinterpreter.types.errors.io.ChildProcessError; import ai.timefold.jpyinterpreter.types.errors.io.EOFError; import ai.timefold.jpyinterpreter.types.errors.io.FileExistsError; import ai.timefold.jpyinterpreter.types.errors.io.FileNotFoundError; import ai.timefold.jpyinterpreter.types.errors.io.InterruptedError; import ai.timefold.jpyinterpreter.types.errors.io.IsADirectoryError; import ai.timefold.jpyinterpreter.types.errors.io.KeyboardInterrupt; import ai.timefold.jpyinterpreter.types.errors.io.MemoryError; import ai.timefold.jpyinterpreter.types.errors.io.NotADirectoryError; import ai.timefold.jpyinterpreter.types.errors.io.OSError; import ai.timefold.jpyinterpreter.types.errors.io.PermissionError; import ai.timefold.jpyinterpreter.types.errors.io.ProcessLookupError; import ai.timefold.jpyinterpreter.types.errors.io.SystemError; import ai.timefold.jpyinterpreter.types.errors.io.SystemExit; import ai.timefold.jpyinterpreter.types.errors.io.TimeoutError; import ai.timefold.jpyinterpreter.types.errors.io.connection.BrokenPipeError; import ai.timefold.jpyinterpreter.types.errors.io.connection.ConnectionAbortedError; import ai.timefold.jpyinterpreter.types.errors.io.connection.ConnectionError; import ai.timefold.jpyinterpreter.types.errors.io.connection.ConnectionRefusedError; import ai.timefold.jpyinterpreter.types.errors.io.connection.ConnectionResetError; import ai.timefold.jpyinterpreter.types.errors.lookup.IndexError; import ai.timefold.jpyinterpreter.types.errors.lookup.KeyError; import ai.timefold.jpyinterpreter.types.errors.lookup.LookupError; import ai.timefold.jpyinterpreter.types.errors.syntax.IndentationError; import ai.timefold.jpyinterpreter.types.errors.syntax.SyntaxError; import ai.timefold.jpyinterpreter.types.errors.syntax.TabError; import ai.timefold.jpyinterpreter.types.errors.unicode.UnicodeDecodeError; import ai.timefold.jpyinterpreter.types.errors.unicode.UnicodeEncodeError; import ai.timefold.jpyinterpreter.types.errors.unicode.UnicodeError; import ai.timefold.jpyinterpreter.types.errors.unicode.UnicodeTranslateError; import ai.timefold.jpyinterpreter.types.errors.warning.BytesWarning; import ai.timefold.jpyinterpreter.types.errors.warning.DeprecationWarning; import ai.timefold.jpyinterpreter.types.errors.warning.EncodingWarning; import ai.timefold.jpyinterpreter.types.errors.warning.FutureWarning; import ai.timefold.jpyinterpreter.types.errors.warning.ImportWarning; import ai.timefold.jpyinterpreter.types.errors.warning.PendingDeprecationWarning; import ai.timefold.jpyinterpreter.types.errors.warning.ResourceWarning; import ai.timefold.jpyinterpreter.types.errors.warning.RuntimeWarning; import ai.timefold.jpyinterpreter.types.errors.warning.SyntaxWarning; import ai.timefold.jpyinterpreter.types.errors.warning.UnicodeWarning; import ai.timefold.jpyinterpreter.types.errors.warning.UserWarning; import ai.timefold.jpyinterpreter.types.errors.warning.Warning; import ai.timefold.jpyinterpreter.types.numeric.PythonBoolean; import ai.timefold.jpyinterpreter.types.numeric.PythonInteger; public class GlobalBuiltins { private final static StackWalker stackWalker = getStackWalkerInstance(); private final static Map<String, PythonLikeObject> builtinConstantMap = new HashMap<>(); static { loadBuiltinConstants(); } private static StackWalker getStackWalkerInstance() { return StackWalker.getInstance(RETAIN_CLASS_REFERENCE); } public static void addBuiltinType(PythonLikeType type) { addBuiltinConstant(type.getTypeName(), type); } public static void addBuiltinConstant(String builtinName, PythonLikeObject value) { builtinConstantMap.put(builtinName, value); } public static List<PythonLikeType> getBuiltinTypes() { List<PythonLikeType> out = new ArrayList<>(); for (PythonLikeObject constant : builtinConstantMap.values()) { if (constant instanceof PythonLikeType) { out.add((PythonLikeType) constant); } } return out; } public static void loadBuiltinConstants() { // Constants addBuiltinConstant("None", PythonNone.INSTANCE); addBuiltinConstant("Ellipsis", Ellipsis.INSTANCE); addBuiltinConstant("NotImplemented", NotImplemented.INSTANCE); addBuiltinConstant("True", PythonBoolean.TRUE); addBuiltinConstant("False", PythonBoolean.FALSE); // Types addBuiltinType(BOOLEAN_TYPE); addBuiltinType(INT_TYPE); addBuiltinType(FLOAT_TYPE); addBuiltinType(COMPLEX_TYPE); addBuiltinType(TUPLE_TYPE); addBuiltinType(LIST_TYPE); addBuiltinType(SET_TYPE); addBuiltinType(FROZEN_SET_TYPE); addBuiltinType(DICT_TYPE); addBuiltinType(STRING_TYPE); addBuiltinType(BYTES_TYPE); addBuiltinType(BYTE_ARRAY_TYPE); addBuiltinType(NONE_TYPE); addBuiltinType(RANGE_TYPE); addBuiltinType(SLICE_TYPE); // Exceptions addBuiltinType(ArithmeticError.ARITHMETIC_ERROR_TYPE); addBuiltinType(FloatingPointError.FLOATING_POINT_ERROR_TYPE); addBuiltinType(OverflowError.OVERFLOW_ERROR_TYPE); addBuiltinType(ZeroDivisionError.ZERO_DIVISION_ERROR_TYPE); addBuiltinType(BrokenPipeError.BROKEN_PIPE_ERROR_TYPE); addBuiltinType(ConnectionAbortedError.CONNECTION_ABORTED_ERROR_TYPE); addBuiltinType(ConnectionError.CONNECTION_ERROR_TYPE); addBuiltinType(ConnectionRefusedError.CONNECTION_REFUSED_ERROR_TYPE); addBuiltinType(ConnectionResetError.CONNECTION_RESET_ERROR_TYPE); addBuiltinType(BlockingIOError.BLOCKING_IO_ERROR_TYPE); addBuiltinType(ChildProcessError.CHILD_PROCESS_ERROR_TYPE); addBuiltinType(EOFError.EOF_ERROR_TYPE); addBuiltinType(FileExistsError.FILE_EXISTS_ERROR_TYPE); addBuiltinType(FileNotFoundError.FILE_NOT_FOUND_ERROR_TYPE); addBuiltinType(InterruptedError.INTERRUPTED_ERROR_TYPE); addBuiltinType(IsADirectoryError.IS_A_DIRECTORY_ERROR_TYPE); addBuiltinType(KeyboardInterrupt.KEYBOARD_INTERRUPT_TYPE); addBuiltinType(MemoryError.MEMORY_ERROR_TYPE); addBuiltinType(NotADirectoryError.NOT_A_DIRECTORY_ERROR_TYPE); addBuiltinType(OSError.OS_ERROR_TYPE); addBuiltinType(PermissionError.PERMISSION_ERROR_TYPE); addBuiltinType(ProcessLookupError.PROCESS_LOOKUP_ERROR_TYPE); addBuiltinType(SystemError.SYSTEM_ERROR_TYPE); addBuiltinType(SystemExit.SYSTEM_EXIT_TYPE); addBuiltinType(TimeoutError.TIMEOUT_ERROR_TYPE); addBuiltinType(IndexError.INDEX_ERROR_TYPE); addBuiltinType(KeyError.KEY_ERROR_TYPE); addBuiltinType(LookupError.LOOKUP_ERROR_TYPE); addBuiltinType(IndentationError.INDENTATION_ERROR_TYPE); addBuiltinType(SyntaxError.SYNTAX_ERROR_TYPE); addBuiltinType(TabError.TAB_ERROR_TYPE); addBuiltinType(UnicodeDecodeError.UNICODE_DECODE_ERROR_TYPE); addBuiltinType(UnicodeEncodeError.UNICODE_ENCODE_ERROR_TYPE); addBuiltinType(UnicodeError.UNICODE_ERROR_TYPE); addBuiltinType(UnicodeTranslateError.UNICODE_TRANSLATE_ERROR_TYPE); addBuiltinType(BytesWarning.BYTES_WARNING_TYPE); addBuiltinType(DeprecationWarning.DEPRECATION_WARNING_TYPE); addBuiltinType(EncodingWarning.ENCODING_WARNING_TYPE); addBuiltinType(FutureWarning.FUTURE_WARNING_TYPE); addBuiltinType(ImportWarning.IMPORT_WARNING_TYPE); addBuiltinType(PendingDeprecationWarning.PENDING_DEPRECATION_WARNING_TYPE); addBuiltinType(ResourceWarning.RESOURCE_WARNING_TYPE); addBuiltinType(RuntimeWarning.RUNTIME_WARNING_TYPE); addBuiltinType(SyntaxWarning.SYNTAX_WARNING_TYPE); addBuiltinType(UnicodeWarning.UNICODE_WARNING_TYPE); addBuiltinType(UserWarning.USER_WARNING_TYPE); addBuiltinType(Warning.WARNING_TYPE); addBuiltinType(AttributeError.ATTRIBUTE_ERROR_TYPE); addBuiltinType(BufferError.BUFFER_ERROR_TYPE); addBuiltinType(GeneratorExit.GENERATOR_EXIT_TYPE); addBuiltinType(ImportError.IMPORT_ERROR_TYPE); addBuiltinType(ModuleNotFoundError.MODULE_NOT_FOUND_ERROR_TYPE); addBuiltinType(NameError.NAME_ERROR_TYPE); addBuiltinType(NotImplementedError.NOT_IMPLEMENTED_ERROR_TYPE); addBuiltinType(PythonAssertionError.ASSERTION_ERROR_TYPE); addBuiltinType(PythonBaseException.BASE_EXCEPTION_TYPE); addBuiltinType(PythonException.EXCEPTION_TYPE); addBuiltinType(RecursionError.RECURSION_ERROR_TYPE); addBuiltinType(ReferenceError.REFERENCE_ERROR_TYPE); addBuiltinType(RuntimeError.RUNTIME_ERROR_TYPE); addBuiltinType(StopAsyncIteration.STOP_ASYNC_ITERATION_TYPE); addBuiltinType(StopIteration.STOP_ITERATION_TYPE); addBuiltinType(UnboundLocalError.UNBOUND_LOCAL_ERROR_TYPE); addBuiltinType(TypeError.TYPE_ERROR_TYPE); addBuiltinType(ValueError.VALUE_ERROR_TYPE); PythonOverloadImplementor.createDeferredDispatches(); } public static PythonLikeObject lookup(PythonInterpreter interpreter, String builtinName) { switch (builtinName) { case "abs": return UnaryDunderBuiltin.ABS; case "all": return ((PythonLikeFunction) GlobalBuiltins::all); case "any": return ((PythonLikeFunction) GlobalBuiltins::any); case "ascii": return ((PythonLikeFunction) GlobalBuiltins::ascii); case "bin": return ((PythonLikeFunction) GlobalBuiltins::bin); case "bool": return BOOLEAN_TYPE; case "bytes": return BYTES_TYPE; case "bytearray": return BYTE_ARRAY_TYPE; case "callable": return ((PythonLikeFunction) GlobalBuiltins::callable); case "chr": return ((PythonLikeFunction) GlobalBuiltins::chr); case "delattr": return ((PythonLikeFunction) GlobalBuiltins::delattr); case "divmod": return ((PythonLikeFunction) GlobalBuiltins::divmod); case "dict": return DICT_TYPE; case "enumerate": return ((PythonLikeFunction) GlobalBuiltins::enumerate); case "filter": return ((PythonLikeFunction) GlobalBuiltins::filter); case "float": return FLOAT_TYPE; case "format": return ((PythonLikeFunction) GlobalBuiltins::format); case "frozenset": return FROZEN_SET_TYPE; case "getattr": return ((PythonLikeFunction) GlobalBuiltins::getattr); case "globals": return ((PythonLikeFunction) GlobalBuiltins::globals); case "hasattr": return ((PythonLikeFunction) GlobalBuiltins::hasattr); case "hash": return UnaryDunderBuiltin.HASH; case "hex": return ((PythonLikeFunction) GlobalBuiltins::hex); case "id": return ((PythonLikeFunction) GlobalBuiltins::id); case "input": return GlobalBuiltins.input(interpreter); case "int": return INT_TYPE; case "isinstance": return ((PythonLikeFunction) GlobalBuiltins::isinstance); case "issubclass": return ((PythonLikeFunction) GlobalBuiltins::issubclass); case "iter": return UnaryDunderBuiltin.ITERATOR; // TODO: Iterator with sentinel value case "len": return UnaryDunderBuiltin.LENGTH; case "list": return LIST_TYPE; case "locals": return ((PythonLikeFunction) GlobalBuiltins::locals); case "map": return ((PythonLikeFunction) GlobalBuiltins::map); case "min": return ((PythonLikeFunction) GlobalBuiltins::min); case "max": return ((PythonLikeFunction) GlobalBuiltins::max); case "next": return UnaryDunderBuiltin.NEXT; case "object": return BASE_TYPE; case "oct": return ((PythonLikeFunction) GlobalBuiltins::oct); case "ord": return ((PythonLikeFunction) GlobalBuiltins::ord); case "pow": return ((PythonLikeFunction) GlobalBuiltins::pow); case "print": return GlobalBuiltins.print(interpreter); case "range": return RANGE_TYPE; case "repr": return UnaryDunderBuiltin.REPRESENTATION; case "reversed": return ((PythonLikeFunction) GlobalBuiltins::reversed); case "round": return ((PythonLikeFunction) GlobalBuiltins::round); case "set": return SET_TYPE; case "setattr": return ((PythonLikeFunction) GlobalBuiltins::setattr); case "slice": return PythonSlice.SLICE_TYPE; case "sorted": return ((PythonLikeFunction) GlobalBuiltins::sorted); case "str": return STRING_TYPE; case "sum": return ((PythonLikeFunction) GlobalBuiltins::sum); case "super": return ((PythonLikeFunction) GlobalBuiltins::superOfCaller); case "tuple": return TUPLE_TYPE; case "type": return TYPE_TYPE; case "vars": return ((PythonLikeFunction) GlobalBuiltins::vars); case "zip": return ((PythonLikeFunction) GlobalBuiltins::zip); case "__import__": return GlobalBuiltins.importFunction(interpreter); default: return builtinConstantMap.get(builtinName); } } public static PythonLikeObject lookupOrError(PythonInterpreter interpreter, String builtinName) { PythonLikeObject out = lookup(interpreter, builtinName); if (out == null) { throw new IllegalArgumentException(builtinName + " does not exist in global scope"); } return out; } public static PythonBoolean all(List<PythonLikeObject> positionalArgs, Map<PythonString, PythonLikeObject> keywordArgs, PythonLikeObject instance) { Iterator<PythonLikeObject> iterator; if (positionalArgs.size() == 1 && keywordArgs.isEmpty()) { iterator = (Iterator<PythonLikeObject>) UnaryDunderBuiltin.ITERATOR.invoke(positionalArgs.get(0)); } else if (positionalArgs.isEmpty() && keywordArgs.size() == 1 && keywordArgs.containsKey(PythonString.valueOf("iterable"))) { iterator = (Iterator<PythonLikeObject>) UnaryDunderBuiltin.ITERATOR .invoke(keywordArgs.get(PythonString.valueOf("iterable"))); } else { throw new ValueError("all expects 1 argument, got " + positionalArgs.size()); } while (iterator.hasNext()) { PythonLikeObject element = iterator.next(); if (!PythonBoolean.isTruthful(element)) { return PythonBoolean.FALSE; } } return PythonBoolean.TRUE; } public static PythonBoolean any(List<PythonLikeObject> positionalArgs, Map<PythonString, PythonLikeObject> keywordArgs, PythonLikeObject instance) { Iterator<PythonLikeObject> iterator; if (positionalArgs.size() == 1 && keywordArgs.isEmpty()) { iterator = (Iterator<PythonLikeObject>) UnaryDunderBuiltin.ITERATOR.invoke(positionalArgs.get(0)); } else if (positionalArgs.isEmpty() && keywordArgs.size() == 1 && keywordArgs.containsKey(PythonString.valueOf("iterable"))) { iterator = (Iterator<PythonLikeObject>) UnaryDunderBuiltin.ITERATOR .invoke(keywordArgs.get(PythonString.valueOf("iterable"))); } else { throw new ValueError("any expects 1 argument, got " + positionalArgs.size()); } while (iterator.hasNext()) { PythonLikeObject element = iterator.next(); if (PythonBoolean.isTruthful(element)) { return PythonBoolean.TRUE; } } return PythonBoolean.FALSE; } public static PythonString ascii(List<PythonLikeObject> positionalArgs, Map<PythonString, PythonLikeObject> keywordArgs, PythonLikeObject instance) { PythonLikeObject object; if (positionalArgs.size() == 1 && keywordArgs.isEmpty()) { object = positionalArgs.get(0); } else if (positionalArgs.isEmpty() && keywordArgs.size() == 1 && keywordArgs.containsKey(PythonString.valueOf("object"))) { object = keywordArgs.get(PythonString.valueOf("object")); } else { throw new ValueError("ascii expects 1 argument, got " + positionalArgs.size()); } PythonString reprString = (PythonString) UnaryDunderBuiltin.REPRESENTATION.invoke(object); String asciiString = reprString.value.codePoints().flatMap((character) -> { if (character < 128) { return IntStream.of(character); } else { // \Uxxxxxxxx IntStream.Builder builder = IntStream.builder().add('\\').add('U'); String hexString = Integer.toHexString(character); for (int i = 8; i > hexString.length(); i--) { builder.add('0'); } hexString.codePoints().forEach(builder); return builder.build(); } }).collect(StringBuilder::new, StringBuilder::appendCodePoint, StringBuilder::append).toString(); return PythonString.valueOf(asciiString); } public static PythonString bin(List<PythonLikeObject> positionalArgs, Map<PythonString, PythonLikeObject> keywordArgs, PythonLikeObject instance) { PythonLikeObject object; if (positionalArgs.size() == 1 && keywordArgs.isEmpty()) { object = positionalArgs.get(0); } else if (positionalArgs.isEmpty() && keywordArgs.size() == 1 && keywordArgs.containsKey(PythonString.valueOf("x"))) { object = keywordArgs.get(PythonString.valueOf("x")); } else { throw new ValueError("bin expects 1 argument, got " + positionalArgs.size()); } PythonInteger integer; if (object instanceof PythonInteger) { integer = (PythonInteger) object; } else { integer = (PythonInteger) UnaryDunderBuiltin.INDEX.invoke(object); } String binaryString = integer.value.toString(2); if (binaryString.startsWith("-")) { return PythonString.valueOf("-0b" + binaryString.substring(1)); } else { return PythonString.valueOf("0b" + binaryString); } } public static PythonBoolean callable(List<PythonLikeObject> positionalArgs, Map<PythonString, PythonLikeObject> keywordArgs, PythonLikeObject instance) { PythonLikeObject object; if (positionalArgs.size() == 1 && keywordArgs.isEmpty()) { object = positionalArgs.get(0); } else if (positionalArgs.isEmpty() && keywordArgs.size() == 1 && keywordArgs.containsKey(PythonString.valueOf("object"))) { object = keywordArgs.get(PythonString.valueOf("object")); } else { throw new ValueError("callable expects 1 argument, got " + positionalArgs.size()); } return PythonBoolean.valueOf(object instanceof PythonLikeFunction); } public static PythonString chr(List<PythonLikeObject> positionalArgs, Map<PythonString, PythonLikeObject> keywordArgs, PythonLikeObject instance) { PythonLikeObject object; if (positionalArgs.size() == 1 && keywordArgs.isEmpty()) { object = positionalArgs.get(0); } else if (positionalArgs.isEmpty() && keywordArgs.size() == 1 && keywordArgs.containsKey(PythonString.valueOf("i"))) { object = keywordArgs.get(PythonString.valueOf("i")); } else { throw new ValueError("chr expects 1 argument, got " + positionalArgs.size()); } PythonInteger integer = (PythonInteger) object; if (integer.value.compareTo(BigInteger.valueOf(0x10FFFF)) > 0 || integer.value.compareTo(BigInteger.ZERO) < 0) { throw new ValueError("Integer (" + integer + ") outside valid range for chr (0 through 1,114,111)"); } return PythonString.valueOf(Character.toString(integer.value.intValueExact())); } public static PythonNone delattr(List<PythonLikeObject> positionalArgs, Map<PythonString, PythonLikeObject> keywordArgs, PythonLikeObject instance) { PythonLikeObject object; PythonString name; if (positionalArgs.size() == 2) { object = positionalArgs.get(0); name = (PythonString) positionalArgs.get(1); } else if (positionalArgs.size() == 1 && keywordArgs.containsKey(PythonString.valueOf("name"))) { object = positionalArgs.get(0); name = (PythonString) keywordArgs.get(PythonString.valueOf("name")); } else if (positionalArgs.size() == 0 && keywordArgs.containsKey(PythonString.valueOf("object")) && keywordArgs.containsKey(PythonString.valueOf("name"))) { object = keywordArgs.get(PythonString.valueOf("object")); name = (PythonString) keywordArgs.get(PythonString.valueOf("name")); } else { throw new ValueError("delattr expects 2 argument, got " + positionalArgs.size()); } object.$deleteAttribute(name.value); return PythonNone.INSTANCE; } public static PythonLikeObject divmod(List<PythonLikeObject> positionalArgs, Map<PythonString, PythonLikeObject> keywordArgs, PythonLikeObject instance) { PythonLikeObject left; PythonLikeObject right; if (positionalArgs.size() == 2) { left = positionalArgs.get(0); right = positionalArgs.get(1); } else { throw new TypeError("divmod() expects 2 positional arguments"); } PythonLikeObject maybeDivmod = left.$getType().$getAttributeOrNull("__divmod__"); if (maybeDivmod != null) { PythonLikeObject result = ((PythonLikeFunction) maybeDivmod).$call(List.of(left, right), Map.of(), null); if (result != NotImplemented.INSTANCE) { return result; } maybeDivmod = right.$getType().$getAttributeOrNull("__rdivmod__"); if (maybeDivmod != null) { result = ((PythonLikeFunction) maybeDivmod).$call(List.of(right, left), Map.of(), null); if (result != NotImplemented.INSTANCE) { return result; } else { PythonLikeObject maybeDiv = left.$getType().$getAttributeOrNull("__floordiv__"); PythonLikeObject maybeMod = left.$getType().$getAttributeOrNull("__mod__"); if (maybeDiv != null && maybeMod != null) { PythonLikeObject divResult = ((PythonLikeFunction) maybeDiv).$call(List.of(left, right), Map.of(), null); PythonLikeObject modResult = ((PythonLikeFunction) maybeMod).$call(List.of(left, right), Map.of(), null); if (divResult != NotImplemented.INSTANCE && modResult != NotImplemented.INSTANCE) { return PythonLikeTuple.fromItems(divResult, modResult); } else { maybeDiv = right.$getType().$getAttributeOrNull("__rfloordiv__"); maybeMod = right.$getType().$getAttributeOrNull("__rmod__"); if (maybeDiv != null && maybeMod != null) { divResult = ((PythonLikeFunction) maybeDiv).$call(List.of(right, left), Map.of(), null); modResult = ((PythonLikeFunction) maybeMod).$call(List.of(right, left), Map.of(), null); if (divResult != NotImplemented.INSTANCE && modResult != NotImplemented.INSTANCE) { return PythonLikeTuple.fromItems(divResult, modResult); } else { throw new TypeError( "Unsupported operands for divmod: " + left.$getType() + ", " + right.$getType()); } } } } else { maybeDiv = right.$getType().$getAttributeOrNull("__rfloordiv__"); maybeMod = right.$getType().$getAttributeOrNull("__rmod__"); if (maybeDiv != null && maybeMod != null) { PythonLikeObject divResult = ((PythonLikeFunction) maybeDiv).$call(List.of(right, left), Map.of(), null); PythonLikeObject modResult = ((PythonLikeFunction) maybeMod).$call(List.of(right, left), Map.of(), null); if (divResult != NotImplemented.INSTANCE && modResult != NotImplemented.INSTANCE) { return PythonLikeTuple.fromItems(divResult, modResult); } else { throw new TypeError( "Unsupported operands for divmod: " + left.$getType() + ", " + right.$getType()); } } } } } } else { maybeDivmod = right.$getType().$getAttributeOrNull("__rdivmod__"); if (maybeDivmod != null) { PythonLikeObject result = ((PythonLikeFunction) maybeDivmod).$call(List.of(right, left), Map.of(), null); if (result != NotImplemented.INSTANCE) { return result; } else { PythonLikeObject maybeDiv = left.$getType().$getAttributeOrNull("__floordiv__"); PythonLikeObject maybeMod = left.$getType().$getAttributeOrNull("__mod__"); if (maybeDiv != null && maybeMod != null) { PythonLikeObject divResult = ((PythonLikeFunction) maybeDiv).$call(List.of(left, right), Map.of(), null); PythonLikeObject modResult = ((PythonLikeFunction) maybeMod).$call(List.of(left, right), Map.of(), null); if (divResult != NotImplemented.INSTANCE && modResult != NotImplemented.INSTANCE) { return PythonLikeTuple.fromItems(divResult, modResult); } else { maybeDiv = right.$getType().$getAttributeOrNull("__rfloordiv__"); maybeMod = right.$getType().$getAttributeOrNull("__rmod__"); if (maybeDiv != null && maybeMod != null) { divResult = ((PythonLikeFunction) maybeDiv).$call(List.of(right, left), Map.of(), null); modResult = ((PythonLikeFunction) maybeMod).$call(List.of(right, left), Map.of(), null); if (divResult != NotImplemented.INSTANCE && modResult != NotImplemented.INSTANCE) { return PythonLikeTuple.fromItems(divResult, modResult); } else { throw new TypeError( "Unsupported operands for divmod: " + left.$getType() + ", " + right.$getType()); } } } } else { maybeDiv = right.$getType().$getAttributeOrNull("__rfloordiv__"); maybeMod = right.$getType().$getAttributeOrNull("__rmod__"); if (maybeDiv != null && maybeMod != null) { PythonLikeObject divResult = ((PythonLikeFunction) maybeDiv).$call(List.of(right, left), Map.of(), null); PythonLikeObject modResult = ((PythonLikeFunction) maybeMod).$call(List.of(right, left), Map.of(), null); if (divResult != NotImplemented.INSTANCE && modResult != NotImplemented.INSTANCE) { return PythonLikeTuple.fromItems(divResult, modResult); } else { throw new TypeError( "Unsupported operands for divmod: " + left.$getType() + ", " + right.$getType()); } } } } } else { PythonLikeObject maybeDiv = left.$getType().$getAttributeOrNull("__floordiv__"); PythonLikeObject maybeMod = left.$getType().$getAttributeOrNull("__mod__"); if (maybeDiv != null && maybeMod != null) { PythonLikeObject divResult = ((PythonLikeFunction) maybeDiv).$call(List.of(left, right), Map.of(), null); PythonLikeObject modResult = ((PythonLikeFunction) maybeMod).$call(List.of(left, right), Map.of(), null); if (divResult != NotImplemented.INSTANCE && modResult != NotImplemented.INSTANCE) { return PythonLikeTuple.fromItems(divResult, modResult); } else { maybeDiv = right.$getType().$getAttributeOrNull("__rfloordiv__"); maybeMod = right.$getType().$getAttributeOrNull("__rmod__"); if (maybeDiv != null && maybeMod != null) { divResult = ((PythonLikeFunction) maybeDiv).$call(List.of(right, left), Map.of(), null); modResult = ((PythonLikeFunction) maybeMod).$call(List.of(right, left), Map.of(), null); if (divResult != NotImplemented.INSTANCE && modResult != NotImplemented.INSTANCE) { return PythonLikeTuple.fromItems(divResult, modResult); } else { throw new TypeError( "Unsupported operands for divmod: " + left.$getType() + ", " + right.$getType()); } } } } else { maybeDiv = right.$getType().$getAttributeOrNull("__rfloordiv__"); maybeMod = right.$getType().$getAttributeOrNull("__rmod__"); if (maybeDiv != null && maybeMod != null) { PythonLikeObject divResult = ((PythonLikeFunction) maybeDiv).$call(List.of(right, left), Map.of(), null); PythonLikeObject modResult = ((PythonLikeFunction) maybeMod).$call(List.of(right, left), Map.of(), null); if (divResult != NotImplemented.INSTANCE && modResult != NotImplemented.INSTANCE) { return PythonLikeTuple.fromItems(divResult, modResult); } else { throw new TypeError( "Unsupported operands for divmod: " + left.$getType() + ", " + right.$getType()); } } } } } return PythonNone.INSTANCE; } public static PythonLikeObject enumerate(List<PythonLikeObject> positionalArgs, Map<PythonString, PythonLikeObject> keywordArgs, PythonLikeObject instance) { PythonLikeObject iterable; PythonLikeObject start = PythonInteger.valueOf(0); if (positionalArgs.size() == 2) { iterable = positionalArgs.get(0); start = positionalArgs.get(1); } else if (positionalArgs.size() == 1) { iterable = positionalArgs.get(0); if (keywordArgs.containsKey(PythonString.valueOf("start"))) { start = keywordArgs.get(PythonString.valueOf("start")); } } else if (positionalArgs.size() == 0 && keywordArgs.containsKey(PythonString.valueOf("iterable"))) { iterable = keywordArgs.get(PythonString.valueOf("iterable")); if (keywordArgs.containsKey(PythonString.valueOf("start"))) { start = keywordArgs.get(PythonString.valueOf("start")); } } else { throw new ValueError("enumerate expects 1 or 2 argument, got " + positionalArgs.size()); } final PythonLikeObject iterator = UnaryDunderBuiltin.ITERATOR.invoke(iterable); final AtomicReference<PythonLikeObject> currentValue = new AtomicReference(null); final AtomicReference<PythonLikeObject> currentIndex = new AtomicReference(start); final AtomicBoolean shouldCallNext = new AtomicBoolean(true); return new DelegatePythonIterator(new Iterator<PythonLikeObject>() { @Override public boolean hasNext() { if (shouldCallNext.get()) { try { currentValue.set(UnaryDunderBuiltin.NEXT.invoke(iterator)); } catch (StopIteration e) { currentValue.set(null); shouldCallNext.set(false); return false; } shouldCallNext.set(false); return true; } else { // we already called next return currentValue.get() != null; } } @Override public PythonLikeObject next() { PythonLikeObject value; if (currentValue.get() != null) { shouldCallNext.set(true); value = currentValue.get(); currentValue.set(null); } else { value = UnaryDunderBuiltin.NEXT.invoke(iterator); shouldCallNext.set(true); } PythonLikeObject index = currentIndex.get(); currentIndex.set(BinaryDunderBuiltin.ADD.invoke(index, PythonInteger.valueOf(1))); return PythonLikeTuple.fromItems(index, value); } }); } public static DelegatePythonIterator filter(List<PythonLikeObject> positionalArgs, Map<PythonString, PythonLikeObject> keywordArgs, PythonLikeObject instance) { PythonLikeObject function; PythonLikeObject iterable; if (positionalArgs.size() == 2 && keywordArgs.isEmpty()) { function = positionalArgs.get(0); iterable = positionalArgs.get(1); } else if (positionalArgs.size() == 1) { function = positionalArgs.get(0); iterable = keywordArgs.get(PythonString.valueOf("iterable")); if (iterable == null) { throw new ValueError("iterable is None"); } } else if (positionalArgs.size() == 0) { function = keywordArgs.get(PythonString.valueOf("function")); iterable = keywordArgs.get(PythonString.valueOf("iterable")); if (iterable == null) { throw new ValueError("iterable is None"); } if (function == null) { function = PythonNone.INSTANCE; } } else { throw new ValueError("filter expects 2 argument, got " + positionalArgs.size()); } Iterator iterator; if (iterable instanceof Collection) { iterator = ((Collection) iterable).iterator(); } else if (iterable instanceof Iterator) { iterator = (Iterator) iterable; } else { iterator = (Iterator) UnaryDunderBuiltin.ITERATOR.invoke(iterable); } PythonLikeFunction predicate; if (function == PythonNone.INSTANCE) { predicate = (pos, keywords, callerInstance) -> pos.get(0); } else { predicate = (PythonLikeFunction) function; } return new DelegatePythonIterator(StreamSupport.stream( Spliterators.spliteratorUnknownSize(iterator, Spliterator.ORDERED), false) .filter(element -> PythonBoolean .isTruthful(predicate.$call(List.of((PythonLikeObject) element), Map.of(), null))) .iterator()); } public static PythonLikeObject format(List<PythonLikeObject> positionalArgs, Map<PythonString, PythonLikeObject> keywordArgs, PythonLikeObject instance) { PythonLikeObject toFormat; PythonLikeObject formatSpec = PythonString.valueOf(""); if (positionalArgs.size() == 2 && keywordArgs.isEmpty()) { toFormat = positionalArgs.get(0); formatSpec = positionalArgs.get(1); } else if (positionalArgs.size() == 1) { toFormat = positionalArgs.get(0); if (keywordArgs.containsKey(PythonString.valueOf("format_spec"))) { formatSpec = keywordArgs.get(PythonString.valueOf("format_spec")); } } else if (positionalArgs.size() == 0 && keywordArgs.containsKey(PythonString.valueOf("value"))) { toFormat = keywordArgs.get(PythonString.valueOf("value")); if (keywordArgs.containsKey(PythonString.valueOf("format_spec"))) { formatSpec = keywordArgs.get(PythonString.valueOf("format_spec")); } } else { throw new ValueError("format expects 1 or 2 arguments, got " + positionalArgs.size()); } return toFormat.$method$__format__((PythonString) formatSpec); } public static PythonLikeObject getattr(List<PythonLikeObject> positionalArgs, Map<PythonString, PythonLikeObject> keywordArgs, PythonLikeObject instance) { PythonLikeObject object; PythonString name; PythonLikeObject defaultValue = null; if (positionalArgs.size() == 3) { object = positionalArgs.get(0); name = (PythonString) positionalArgs.get(1); defaultValue = positionalArgs.get(2); } else if (positionalArgs.size() == 2) { object = positionalArgs.get(0); name = (PythonString) positionalArgs.get(1); defaultValue = keywordArgs.get(PythonString.valueOf("default")); } else if (positionalArgs.size() == 1 && keywordArgs.containsKey(PythonString.valueOf("name"))) { object = positionalArgs.get(0); name = (PythonString) keywordArgs.get(PythonString.valueOf("name")); defaultValue = keywordArgs.get(PythonString.valueOf("default")); } else if (positionalArgs.size() == 0 && keywordArgs.containsKey(PythonString.valueOf("object")) && keywordArgs.containsKey(PythonString.valueOf("name"))) { object = keywordArgs.get(PythonString.valueOf("object")); name = (PythonString) keywordArgs.get(PythonString.valueOf("name")); defaultValue = keywordArgs.get(PythonString.valueOf("default")); } else { throw new ValueError("getattr expects 2 or 3 arguments, got " + positionalArgs.size()); } PythonLikeFunction getAttribute = (PythonLikeFunction) object.$getType().$getAttributeOrError("__getattribute__"); try { return getAttribute.$call(List.of(object, name), Map.of(), null); } catch (AttributeError attributeError) { if (defaultValue != null) { return defaultValue; } else { throw attributeError; } } } public static PythonLikeDict globals(List<PythonLikeObject> positionalArgs, Map<PythonString, PythonLikeObject> keywordArgs, PythonLikeObject instance) { if (!positionalArgs.isEmpty() && keywordArgs.isEmpty()) { throw new ValueError("globals expects 0 arguments, got " + positionalArgs.size()); } Class<?> callerClass = stackWalker.getCallerClass(); try { Map globalsMap = (Map) callerClass.getField(PythonBytecodeToJavaBytecodeTranslator.GLOBALS_MAP_STATIC_FIELD_NAME).get(null); return PythonLikeDict.mirror(globalsMap); } catch (NoSuchFieldException | IllegalAccessException e) { throw new IllegalStateException("Caller (" + callerClass + ") is not a generated class", e); } } public static PythonBoolean hasattr(List<PythonLikeObject> positionalArgs, Map<PythonString, PythonLikeObject> keywordArgs, PythonLikeObject instance) { try { getattr(positionalArgs, keywordArgs, instance); return PythonBoolean.TRUE; } catch (AttributeError error) { return PythonBoolean.FALSE; } } public static PythonString hex(List<PythonLikeObject> positionalArgs, Map<PythonString, PythonLikeObject> keywordArgs, PythonLikeObject instance) { PythonLikeObject object; if (positionalArgs.size() == 1 && keywordArgs.isEmpty()) { object = positionalArgs.get(0); } else if (positionalArgs.isEmpty() && keywordArgs.size() == 1 && keywordArgs.containsKey(PythonString.valueOf("x"))) { object = keywordArgs.get(PythonString.valueOf("x")); } else { throw new ValueError("hex expects 1 argument, got " + positionalArgs.size()); } PythonInteger integer; if (object instanceof PythonInteger) { integer = (PythonInteger) object; } else { integer = (PythonInteger) UnaryDunderBuiltin.INDEX.invoke(object); } String hexString = integer.value.toString(16); if (hexString.startsWith("-")) { return PythonString.valueOf("-0x" + hexString.substring(1)); } else { return PythonString.valueOf("0x" + hexString); } } public static PythonInteger id(List<PythonLikeObject> positionalArgs, Map<PythonString, PythonLikeObject> keywordArgs, PythonLikeObject instance) { PythonLikeObject object; if (positionalArgs.size() == 1 && keywordArgs.isEmpty()) { object = positionalArgs.get(0); } else if (positionalArgs.isEmpty() && keywordArgs.size() == 1 && keywordArgs.containsKey(PythonString.valueOf("object"))) { object = keywordArgs.get(PythonString.valueOf("object")); } else { throw new ValueError("id expects 1 argument, got " + positionalArgs.size()); } if (object instanceof CPythonBackedPythonLikeObject) { CPythonBackedPythonLikeObject cPythonBackedPythonLikeObject = (CPythonBackedPythonLikeObject) object; if (cPythonBackedPythonLikeObject.$cpythonId != null) { return cPythonBackedPythonLikeObject.$cpythonId; } } return PythonInteger.valueOf(System.identityHashCode(object)); } public static PythonLikeFunction input(PythonInterpreter interpreter) { return (positionalArguments, namedArguments, callerInstance) -> { PythonString prompt = null; if (positionalArguments.size() == 1) { prompt = (PythonString) positionalArguments.get(0); } else if (positionalArguments.size() == 0 && namedArguments.containsKey(PythonString.valueOf("prompt"))) { prompt = (PythonString) namedArguments.get(PythonString.valueOf("prompt")); } else { throw new ValueError("input expects 0 or 1 arguments, got " + positionalArguments.size()); } if (prompt != null) { interpreter.write(prompt.value); } String line = interpreter.readLine(); return PythonString.valueOf(line); }; } public static PythonBoolean isinstance(List<PythonLikeObject> positionalArgs, Map<PythonString, PythonLikeObject> keywordArgs, PythonLikeObject instance) { PythonLikeObject object; PythonLikeObject classInfo; if (positionalArgs.size() == 2) { object = positionalArgs.get(0); classInfo = positionalArgs.get(1); } else if (positionalArgs.size() == 1 && keywordArgs.containsKey(PythonString.valueOf("classinfo"))) { object = positionalArgs.get(0); classInfo = keywordArgs.get(PythonString.valueOf("classinfo")); } else if (positionalArgs.size() == 0 && keywordArgs.containsKey(PythonString.valueOf("object")) && keywordArgs.containsKey(PythonString.valueOf("classinfo"))) { object = keywordArgs.get(PythonString.valueOf("object")); classInfo = keywordArgs.get(PythonString.valueOf("classinfo")); } else { throw new ValueError("isinstance expects 2 arguments, got " + positionalArgs.size()); } if (classInfo instanceof PythonLikeType) { return PythonBoolean.valueOf(((PythonLikeType) classInfo).isInstance(object)); } else if (classInfo instanceof List) { for (PythonLikeObject possibleType : (List<PythonLikeObject>) classInfo) { if (isinstance(List.of(object, possibleType), null, instance).getBooleanValue()) { return PythonBoolean.TRUE; } } return PythonBoolean.FALSE; } else { throw new ValueError("classInfo (" + classInfo + ") is not a tuple of types or a type"); // TODO: Use TypeError } } public static PythonBoolean issubclass(List<PythonLikeObject> positionalArgs, Map<PythonString, PythonLikeObject> keywordArgs, PythonLikeObject instance) { PythonLikeType type; PythonLikeObject classInfo; if (positionalArgs.size() == 2) { if (!(positionalArgs.get(0) instanceof PythonLikeType)) { throw new TypeError("issubclass argument 0 must be a class, not " + positionalArgs.get(0).$getType()); } type = (PythonLikeType) positionalArgs.get(0); classInfo = positionalArgs.get(1); } else if (positionalArgs.size() == 1 && keywordArgs.containsKey(PythonString.valueOf("classinfo"))) { if (!(positionalArgs.get(0) instanceof PythonLikeType)) { throw new TypeError("issubclass argument 0 must be a class, not " + positionalArgs.get(0).$getType()); } type = (PythonLikeType) positionalArgs.get(0); classInfo = keywordArgs.get(PythonString.valueOf("classinfo")); } else if (positionalArgs.size() == 0 && keywordArgs.containsKey(PythonString.valueOf("class")) && keywordArgs.containsKey(PythonString.valueOf("classinfo"))) { if (!(keywordArgs.get(PythonString.valueOf("class")) instanceof PythonLikeType)) { throw new TypeError("issubclass argument 0 must be a class, not " + positionalArgs.get(0).$getType()); } type = (PythonLikeType) keywordArgs.get(PythonString.valueOf("class")); classInfo = keywordArgs.get(PythonString.valueOf("classinfo")); } else { throw new ValueError("isinstance expects 2 arguments, got " + positionalArgs.size()); } if (classInfo instanceof PythonLikeType) { return PythonBoolean.valueOf(type.isSubclassOf((PythonLikeType) classInfo)); } else if (classInfo instanceof List) { for (PythonLikeObject possibleType : (List<PythonLikeObject>) classInfo) { if (issubclass(List.of(type, possibleType), null, instance).getBooleanValue()) { return PythonBoolean.TRUE; } } return PythonBoolean.FALSE; } else { throw new ValueError("classInfo (" + classInfo + ") is not a tuple of types or a type"); // TODO: Use TypeError } } public static PythonLikeDict locals(List<PythonLikeObject> positionalArgs, Map<PythonString, PythonLikeObject> keywordArgs, PythonLikeObject instance) { throw new ValueError("builtin locals() is not supported when executed in Java bytecode"); } public static DelegatePythonIterator map(List<PythonLikeObject> positionalArgs, Map<PythonString, PythonLikeObject> keywordArgs, PythonLikeObject instance) { PythonLikeFunction function; List<PythonLikeObject> iterableList = new ArrayList<>(); if (positionalArgs.size() >= 2 && keywordArgs.isEmpty()) { function = (PythonLikeFunction) positionalArgs.get(0); iterableList = positionalArgs.subList(1, positionalArgs.size()); } else if (positionalArgs.size() == 1 && keywordArgs.containsKey(PythonString.valueOf("iterable"))) { function = (PythonLikeFunction) positionalArgs.get(0); iterableList.add(keywordArgs.get(PythonString.valueOf("iterable"))); } else if (positionalArgs.size() == 0 && keywordArgs.containsKey(PythonString.valueOf("function")) && keywordArgs.containsKey(PythonString.valueOf("iterable"))) { function = (PythonLikeFunction) keywordArgs.get(PythonString.valueOf("function")); iterableList.add(keywordArgs.get(PythonString.valueOf("iterable"))); } else { throw new ValueError("map expects at least 2 argument, got " + positionalArgs.size()); } final List<Iterator> iteratorList = new ArrayList<>(iterableList.size()); for (PythonLikeObject iterable : iterableList) { Iterator iterator; if (iterable instanceof Collection) { iterator = ((Collection) iterable).iterator(); } else if (iterable instanceof Iterator) { iterator = (Iterator) iterable; } else { iterator = (Iterator) UnaryDunderBuiltin.ITERATOR.invoke(iterable); } iteratorList.add(iterator); } Iterator<List<PythonLikeObject>> iteratorIterator = new Iterator<List<PythonLikeObject>>() { @Override public boolean hasNext() { return iteratorList.stream().allMatch(Iterator::hasNext); } @Override public List<PythonLikeObject> next() { List<PythonLikeObject> out = new ArrayList<>(iteratorList.size()); for (Iterator iterator : iteratorList) { out.add((PythonLikeObject) iterator.next()); } return out; } }; return new DelegatePythonIterator(StreamSupport.stream( Spliterators.spliteratorUnknownSize(iteratorIterator, Spliterator.ORDERED), false) .map(element -> function.$call(element, Map.of(), null)) .iterator()); } public static PythonLikeObject min(List<PythonLikeObject> positionalArgs, Map<PythonString, PythonLikeObject> keywordArgs, PythonLikeObject instance) { if (positionalArgs.isEmpty()) { PythonLikeObject defaultValue = keywordArgs.get(PythonString.valueOf("default")); if (!keywordArgs.containsKey(PythonString.valueOf("default"))) { throw new ValueError("No arguments were passed to min, and no default was provided"); } return defaultValue; } else if (positionalArgs.size() == 1) { Iterator<Comparable> iterator = (Iterator<Comparable>) ((PythonLikeFunction) (positionalArgs.get(0).$getType() .$getAttributeOrError("__iter__"))).$call(List.of(positionalArgs.get(0)), Map.of(), null); Comparable min = null; for (Iterator<Comparable> it = iterator; it.hasNext();) { Comparable item = it.next(); if (min == null) { min = item; } else { if (item.compareTo(min) < 0) { min = item; } } } if (min == null) { PythonLikeObject defaultValue = keywordArgs.get(PythonString.valueOf("default")); if (!keywordArgs.containsKey(PythonString.valueOf("default"))) { throw new ValueError("Iterable is empty, and no default was provided"); } return defaultValue; } else { return (PythonLikeObject) min; } } else { Comparable min = (Comparable) positionalArgs.get(0); for (PythonLikeObject item : positionalArgs) { Comparable comparableItem = (Comparable) item; if (comparableItem.compareTo(min) < 0) { min = comparableItem; } } return (PythonLikeObject) min; } } public static PythonLikeObject max(List<PythonLikeObject> positionalArgs, Map<PythonString, PythonLikeObject> keywordArgs, PythonLikeObject instance) { if (positionalArgs.isEmpty()) { PythonLikeObject defaultValue = keywordArgs.get(PythonString.valueOf("default")); if (!keywordArgs.containsKey(PythonString.valueOf("default"))) { throw new ValueError("No arguments were passed to max, and no default was provided"); } return defaultValue; } else if (positionalArgs.size() == 1) { Iterator<Comparable> iterator = (Iterator<Comparable>) ((PythonLikeFunction) (positionalArgs.get(0).$getType() .$getAttributeOrError("__iter__"))).$call(List.of(positionalArgs.get(0)), Map.of(), null); Comparable max = null; for (Iterator<Comparable> it = iterator; it.hasNext();) { Comparable item = it.next(); if (max == null) { max = item; } else { if (item.compareTo(max) > 0) { max = item; } } } if (max == null) { PythonLikeObject defaultValue = keywordArgs.get(PythonString.valueOf("default")); if (!keywordArgs.containsKey(PythonString.valueOf("default"))) { throw new ValueError("Iterable is empty, and no default was provided"); } return defaultValue; } else { return (PythonLikeObject) max; } } else { Comparable max = (Comparable) positionalArgs.get(0); for (PythonLikeObject item : positionalArgs) { Comparable comparableItem = (Comparable) item; if (comparableItem.compareTo(max) > 0) { max = comparableItem; } } return (PythonLikeObject) max; } } public static PythonString oct(List<PythonLikeObject> positionalArgs, Map<PythonString, PythonLikeObject> keywordArgs, PythonLikeObject instance) { PythonLikeObject object; if (positionalArgs.size() == 1 && keywordArgs.isEmpty()) { object = positionalArgs.get(0); } else if (positionalArgs.isEmpty() && keywordArgs.size() == 1 && keywordArgs.containsKey(PythonString.valueOf("x"))) { object = keywordArgs.get(PythonString.valueOf("x")); } else { throw new ValueError("oct expects 1 argument, got " + positionalArgs.size()); } PythonInteger integer; if (object instanceof PythonInteger) { integer = (PythonInteger) object; } else { integer = (PythonInteger) UnaryDunderBuiltin.INDEX.invoke(object); } String octString = integer.value.toString(8); if (octString.startsWith("-")) { return PythonString.valueOf("-0o" + octString.substring(1)); } else { return PythonString.valueOf("0o" + octString); } } public static PythonInteger ord(List<PythonLikeObject> positionalArgs, Map<PythonString, PythonLikeObject> keywordArgs, PythonLikeObject instance) { PythonString character; if (positionalArgs.size() == 1 && keywordArgs.isEmpty()) { character = (PythonString) positionalArgs.get(0); } else if (positionalArgs.isEmpty() && keywordArgs.size() == 1 && keywordArgs.containsKey(PythonString.valueOf("c"))) { character = (PythonString) keywordArgs.get(PythonString.valueOf("c")); } else { throw new ValueError("ord expects 1 argument, got " + positionalArgs.size()); } if (character.length() != 1) { throw new ValueError("String \"" + character + "\" does not represent a single character"); } return PythonInteger.valueOf(character.value.charAt(0)); } public static PythonLikeObject pow(List<PythonLikeObject> positionalArgs, Map<PythonString, PythonLikeObject> keywordArgs, PythonLikeObject instance) { PythonLikeObject base; PythonLikeObject exp; PythonLikeObject mod = null; if (positionalArgs.size() == 3 && keywordArgs.isEmpty()) { base = positionalArgs.get(0); exp = positionalArgs.get(1); mod = positionalArgs.get(2); } else if (positionalArgs.size() == 2) { base = positionalArgs.get(0); exp = positionalArgs.get(1); mod = keywordArgs.get(PythonString.valueOf("mod")); } else if (positionalArgs.size() == 1 && keywordArgs.containsKey(PythonString.valueOf("exp"))) { base = positionalArgs.get(0); exp = keywordArgs.get(PythonString.valueOf("exp")); mod = keywordArgs.get(PythonString.valueOf("mod")); } else if (positionalArgs.isEmpty() && keywordArgs.containsKey(PythonString.valueOf("base")) && keywordArgs.containsKey(PythonString.valueOf("exp"))) { base = keywordArgs.get(PythonString.valueOf("base")); exp = keywordArgs.get(PythonString.valueOf("exp")); mod = keywordArgs.get(PythonString.valueOf("mod")); } else { throw new ValueError("pow expects 2 or 3 arguments, got " + positionalArgs.size()); } if (mod == null) { return BinaryDunderBuiltin.POWER.invoke(base, exp); } else { return TernaryDunderBuiltin.POWER.invoke(base, exp, mod); } } public static PythonLikeFunction print(PythonInterpreter interpreter) { return (positionalArgs, keywordArgs, callerInstance) -> { List<PythonLikeObject> objects = positionalArgs; String sep; if (!keywordArgs.containsKey(PythonString.valueOf("sep")) || keywordArgs.get(PythonString.valueOf("sep")) == PythonNone.INSTANCE) { sep = " "; } else { sep = ((PythonString) keywordArgs.get(PythonString.valueOf("sep"))).value; } String end; if (!keywordArgs.containsKey(PythonString.valueOf("end")) || keywordArgs.get(PythonString.valueOf("end")) == PythonNone.INSTANCE) { end = "\n"; } else { end = ((PythonString) keywordArgs.get(PythonString.valueOf("end"))).value; } // TODO: support file keyword arg boolean flush; if (!keywordArgs.containsKey(PythonString.valueOf("flush")) || keywordArgs.get(PythonString.valueOf("flush")) == PythonNone.INSTANCE) { flush = false; } else { flush = ((PythonBoolean) keywordArgs.get(PythonString.valueOf("flush"))).getBooleanValue(); } for (int i = 0; i < objects.size() - 1; i++) { interpreter.write(UnaryDunderBuiltin.STR.invoke(objects.get(i)).toString()); interpreter.write(sep); } if (!objects.isEmpty()) { interpreter.write(UnaryDunderBuiltin.STR.invoke(objects.get(objects.size() - 1)).toString()); } interpreter.write(end); if (flush) { System.out.flush(); } return PythonNone.INSTANCE; }; }; public static PythonLikeObject reversed(List<PythonLikeObject> positionalArgs, Map<PythonString, PythonLikeObject> keywordArgs, PythonLikeObject instance) { PythonLikeObject sequence; if (positionalArgs.size() != 1) { throw new ValueError("reversed() expects 1 argument, got " + positionalArgs.size()); } sequence = positionalArgs.get(0); PythonLikeType sequenceType = sequence.$getType(); if (sequenceType.$getAttributeOrNull(PythonUnaryOperator.REVERSED.getDunderMethod()) != null) { return UnaryDunderBuiltin.REVERSED.invoke(sequence); } if (sequenceType.$getAttributeOrNull(PythonUnaryOperator.LENGTH.getDunderMethod()) != null && sequenceType.$getAttributeOrNull(PythonBinaryOperator.GET_ITEM.getDunderMethod()) != null) { PythonInteger length = (PythonInteger) UnaryDunderBuiltin.LENGTH.invoke(sequence); Iterator<PythonLikeObject> reversedIterator = new Iterator<>() { PythonInteger current = length.subtract(PythonInteger.ONE); @Override public boolean hasNext() { return current.compareTo(PythonInteger.ZERO) >= 0; } @Override public PythonLikeObject next() { PythonLikeObject out = BinaryDunderBuiltin.GET_ITEM.invoke(sequence, current); current = current.subtract(PythonInteger.ONE); return out; } }; return new DelegatePythonIterator(reversedIterator); } throw new ValueError(sequenceType + " does not has a __reversed__ method and does not implement the Sequence protocol"); } public static PythonLikeObject round(List<PythonLikeObject> positionalArgs, Map<PythonString, PythonLikeObject> keywordArgs, PythonLikeObject instance) { if (!(positionalArgs.size() == 1 || positionalArgs.size() == 2)) { throw new ValueError("round() expects 1 or 2 arguments, got " + positionalArgs.size()); } PythonLikeObject number = positionalArgs.get(0); PythonLikeType numberType = number.$getType(); if (numberType.$getAttributeOrNull("__round__") != null) { return ((PythonLikeFunction) numberType.$getAttributeOrNull("__round__")).$call(positionalArgs, keywordArgs, null); } throw new ValueError(numberType + " does not has a __round__ method"); } public static PythonLikeObject setattr(List<PythonLikeObject> positionalArgs, Map<PythonString, PythonLikeObject> keywordArgs, PythonLikeObject instance) { PythonLikeObject object; PythonString name; PythonLikeObject value; if (positionalArgs.size() == 3) { object = positionalArgs.get(0); name = (PythonString) positionalArgs.get(1); value = positionalArgs.get(2); } else if (positionalArgs.size() == 2 && keywordArgs.containsKey(PythonString.valueOf("value"))) { object = positionalArgs.get(0); name = (PythonString) positionalArgs.get(1); value = keywordArgs.get(PythonString.valueOf("value")); } else if (positionalArgs.size() == 1 && keywordArgs.containsKey(PythonString.valueOf("name")) && keywordArgs.containsKey(PythonString.valueOf("value"))) { object = positionalArgs.get(0); name = (PythonString) keywordArgs.get(PythonString.valueOf("name")); value = keywordArgs.get(PythonString.valueOf("value")); } else if (positionalArgs.size() == 0 && keywordArgs.containsKey(PythonString.valueOf("object")) && keywordArgs.containsKey(PythonString.valueOf("name")) && keywordArgs.containsKey(PythonString.valueOf("value"))) { object = keywordArgs.get(PythonString.valueOf("object")); name = (PythonString) keywordArgs.get(PythonString.valueOf("name")); value = keywordArgs.get(PythonString.valueOf("value")); } else { throw new ValueError("setattr expects 2 or 3 arguments, got " + positionalArgs.size()); } return TernaryDunderBuiltin.SETATTR.invoke(object, name, value); } public static PythonLikeObject sorted(List<PythonLikeObject> positionalArgs, Map<PythonString, PythonLikeObject> keywordArgs, PythonLikeObject instance) { PythonLikeObject iterable = positionalArgs.get(0); boolean isReversed = false; if (keywordArgs.containsKey(PythonString.valueOf("reverse"))) { isReversed = ((PythonBoolean) keywordArgs.get(PythonString.valueOf("reverse"))).getBooleanValue(); } PythonLikeList out = new PythonLikeList(); if (iterable instanceof Collection) { out.addAll((Collection) iterable); } else { Iterator<PythonLikeObject> iterator = (Iterator<PythonLikeObject>) UnaryDunderBuiltin.ITERATOR.invoke(iterable); iterator.forEachRemaining(out::add); } Comparator keyComparator = isReversed ? Comparator.reverseOrder() : Comparator.naturalOrder(); List<KeyTuple> decoratedList = null; if (keywordArgs.containsKey(PythonString.valueOf("key"))) { PythonLikeObject key = keywordArgs.get(PythonString.valueOf("key")); if (key != PythonNone.INSTANCE) { final PythonLikeFunction keyFunction = (PythonLikeFunction) key; final Function keyExtractor = item -> keyFunction.$call(List.of((PythonLikeObject) item), Map.of(), null); decoratedList = new ArrayList<>(out.size()); for (int i = 0; i < out.size(); i++) { decoratedList.add( new KeyTuple((PythonLikeObject) keyExtractor.apply(out.get(i)), i, (PythonLikeObject) out.get(i))); } } else { keyComparator = isReversed ? Comparator.reverseOrder() : Comparator.naturalOrder(); } } else { keyComparator = isReversed ? Comparator.reverseOrder() : Comparator.naturalOrder(); } if (decoratedList != null) { Collections.sort(decoratedList, keyComparator); out.clear(); for (KeyTuple keyTuple : decoratedList) { out.add(keyTuple.source); } } else { Collections.sort(out, keyComparator); } return out; } public static PythonLikeObject sum(List<PythonLikeObject> positionalArgs, Map<PythonString, PythonLikeObject> keywordArgs, PythonLikeObject instance) { PythonLikeObject iterable; PythonLikeObject start; if (positionalArgs.size() == 2) { iterable = positionalArgs.get(0); start = positionalArgs.get(1); } else if (positionalArgs.size() == 1) { iterable = positionalArgs.get(0); start = keywordArgs.getOrDefault(PythonString.valueOf("start"), PythonInteger.ZERO); } else if (positionalArgs.size() == 0) { iterable = keywordArgs.get(PythonString.valueOf("iterable")); start = keywordArgs.getOrDefault(PythonString.valueOf("start"), PythonInteger.ZERO); } else { throw new ValueError("sum() expects 1 or 2 arguments, got " + positionalArgs.size()); } PythonLikeObject current = start; Iterator<PythonLikeObject> iterator = (Iterator<PythonLikeObject>) UnaryDunderBuiltin.ITERATOR.invoke(iterable); while (iterator.hasNext()) { PythonLikeObject item = iterator.next(); current = BinaryDunderBuiltin.ADD.invoke(current, item); } return current; } public static PythonSuperObject superOfCaller(List<PythonLikeObject> positionalArgs, Map<PythonString, PythonLikeObject> keywordArgs, PythonLikeObject instance) { if (positionalArgs.isEmpty()) { Class<?> callerClass = stackWalker.getCallerClass(); try { PythonLikeType pythonClass = (PythonLikeType) callerClass .getField(PythonBytecodeToJavaBytecodeTranslator.CLASS_CELL_STATIC_FIELD_NAME).get(null); if (pythonClass == null) { throw new RuntimeError("super(): no arguments"); } if (instance != null) { return new PythonSuperObject(pythonClass, instance); } else { return new PythonSuperObject(pythonClass); } } catch (IllegalAccessException | NoSuchFieldException e) { throw new RuntimeError("super(): no arguments"); } } else if (positionalArgs.size() == 1) { PythonLikeType pythonClass = (PythonLikeType) positionalArgs.get(0); return new PythonSuperObject(pythonClass); } else if (positionalArgs.size() == 2) { PythonLikeType pythonClass = (PythonLikeType) positionalArgs.get(0); instance = positionalArgs.get(1); return new PythonSuperObject(pythonClass, instance); } else { throw new TypeError("super() takes 0 to 2 arguments, got " + positionalArgs.size()); } } public static PythonLikeObject vars(List<PythonLikeObject> positionalArgs, Map<PythonString, PythonLikeObject> keywordArgs, PythonLikeObject instance) { if (positionalArgs.isEmpty()) { throw new ValueError("0-argument version of vars is not supported when executed in Java bytecode"); } return positionalArgs.get(0).$getAttributeOrError("__dict__"); } public static DelegatePythonIterator zip(List<PythonLikeObject> positionalArgs, Map<PythonString, PythonLikeObject> keywordArgs, PythonLikeObject instance) { List<PythonLikeObject> iterableList = positionalArgs; boolean isStrict = false; if (keywordArgs.containsKey(PythonString.valueOf("strict"))) { isStrict = ((PythonBoolean) keywordArgs.get(PythonString.valueOf("strict"))).getBooleanValue(); } final List<Iterator> iteratorList = new ArrayList<>(iterableList.size()); for (PythonLikeObject iterable : iterableList) { Iterator iterator; if (iterable instanceof Collection) { iterator = ((Collection) iterable).iterator(); } else if (iterable instanceof Iterator) { iterator = (Iterator) iterable; } else { iterator = (Iterator) UnaryDunderBuiltin.ITERATOR.invoke(iterable); } iteratorList.add(iterator); } final boolean isStrictFinal = isStrict; if (iteratorList.isEmpty()) { // Return an empty iterator if there are no iterators return new DelegatePythonIterator(iteratorList.iterator()); } Iterator<List<PythonLikeObject>> iteratorIterator = new Iterator<List<PythonLikeObject>>() { @Override public boolean hasNext() { if (isStrictFinal) { int firstWithoutNext = -1; int firstWithNext = -1; for (int i = 0; i < iteratorList.size(); i++) { if (iteratorList.get(i).hasNext() && firstWithNext == -1) { firstWithNext = i; } else if (!iteratorList.get(i).hasNext() && firstWithoutNext == -1) { firstWithoutNext = i; } if (firstWithNext != -1 && firstWithoutNext != -1) { throw new ValueError( "zip() argument " + firstWithNext + " longer than argument " + firstWithoutNext); } } return firstWithoutNext == -1; } else { return iteratorList.stream().allMatch(Iterator::hasNext); } } @Override public List<PythonLikeObject> next() { PythonLikeTuple out = new PythonLikeTuple(); for (Iterator iterator : iteratorList) { out.add((PythonLikeObject) iterator.next()); } return out; } }; return new DelegatePythonIterator(iteratorIterator); } public static PythonLikeFunction importFunction(PythonInterpreter pythonInterpreter) { return (positionalArguments, namedArguments, callerInstance) -> { PythonString name; PythonLikeDict<PythonString, PythonLikeObject> globals; PythonLikeDict<PythonString, PythonLikeObject> locals; PythonLikeTuple fromlist; PythonInteger level; if (positionalArguments.size() == 0) { name = (PythonString) namedArguments.get(PythonString.valueOf("name")); if (name == null) { throw new ValueError("name is required for __import__()"); } globals = (PythonLikeDict) namedArguments.getOrDefault(PythonString.valueOf("globals"), new PythonLikeDict()); locals = (PythonLikeDict) namedArguments.getOrDefault(PythonString.valueOf("locals"), new PythonLikeDict()); fromlist = (PythonLikeTuple) namedArguments.getOrDefault(PythonString.valueOf("fromlist"), new PythonLikeTuple()); level = (PythonInteger) namedArguments.getOrDefault(PythonString.valueOf("level"), PythonInteger.ZERO); } else if (positionalArguments.size() == 1) { name = (PythonString) positionalArguments.get(0); globals = (PythonLikeDict) namedArguments.getOrDefault(PythonString.valueOf("globals"), new PythonLikeDict()); locals = (PythonLikeDict) namedArguments.getOrDefault(PythonString.valueOf("locals"), new PythonLikeDict()); fromlist = (PythonLikeTuple) namedArguments.getOrDefault(PythonString.valueOf("fromlist"), new PythonLikeTuple()); level = (PythonInteger) namedArguments.getOrDefault(PythonString.valueOf("level"), PythonInteger.ZERO); } else if (positionalArguments.size() == 2) { name = (PythonString) positionalArguments.get(0); globals = (PythonLikeDict) positionalArguments.get(1); locals = (PythonLikeDict) namedArguments.getOrDefault(PythonString.valueOf("locals"), new PythonLikeDict()); fromlist = (PythonLikeTuple) namedArguments.getOrDefault(PythonString.valueOf("fromlist"), new PythonLikeTuple()); level = (PythonInteger) namedArguments.getOrDefault(PythonString.valueOf("level"), PythonInteger.ZERO); } else if (positionalArguments.size() == 3) { name = (PythonString) positionalArguments.get(0); globals = (PythonLikeDict) positionalArguments.get(1); locals = (PythonLikeDict) positionalArguments.get(2); fromlist = (PythonLikeTuple) namedArguments.getOrDefault(PythonString.valueOf("fromlist"), new PythonLikeTuple()); level = (PythonInteger) namedArguments.getOrDefault(PythonString.valueOf("level"), PythonInteger.ZERO); } else if (positionalArguments.size() == 4) { name = (PythonString) positionalArguments.get(0); globals = (PythonLikeDict) positionalArguments.get(1); locals = (PythonLikeDict) positionalArguments.get(2); fromlist = (PythonLikeTuple) positionalArguments.get(3); level = (PythonInteger) namedArguments.getOrDefault(PythonString.valueOf("level"), PythonInteger.ZERO); } else if (positionalArguments.size() == 5) { name = (PythonString) positionalArguments.get(0); globals = (PythonLikeDict) positionalArguments.get(1); locals = (PythonLikeDict) positionalArguments.get(2); fromlist = (PythonLikeTuple) positionalArguments.get(3); level = (PythonInteger) positionalArguments.get(4); } else { throw new ValueError("__import__ expects 1 to 5 arguments, got " + positionalArguments.size()); } Map<String, PythonLikeObject> stringGlobals = new HashMap<>(); Map<String, PythonLikeObject> stringLocals = new HashMap<>(); for (PythonLikeObject key : globals.keySet()) { stringGlobals.put(((PythonString) key).value, globals.get(key)); } for (PythonLikeObject key : locals.keySet()) { stringLocals.put(((PythonString) key).value, globals.get(key)); } return pythonInterpreter.importModule(level, (List) fromlist, stringGlobals, stringLocals, name.value); }; } private final static class KeyTuple implements Comparable<KeyTuple> { final PythonLikeObject key; final int index; final PythonLikeObject source; public KeyTuple(PythonLikeObject key, int index, PythonLikeObject source) { this.key = key; this.index = index; this.source = source; } @Override public int compareTo(KeyTuple other) { PythonBoolean result = (PythonBoolean) BinaryDunderBuiltin.LESS_THAN.invoke(key, other.key); if (result.getBooleanValue()) { return -1; } result = (PythonBoolean) BinaryDunderBuiltin.LESS_THAN.invoke(other.key, key); if (result.getBooleanValue()) { return 1; } return index - other.index; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } KeyTuple keyTuple = (KeyTuple) o; return index == keyTuple.index && key.equals(keyTuple.key); } @Override public int hashCode() { return Objects.hash(key, index); } } }
0
java-sources/ai/timefold/solver/jpyinterpreter/1.24.0/ai/timefold/jpyinterpreter
java-sources/ai/timefold/solver/jpyinterpreter/1.24.0/ai/timefold/jpyinterpreter/builtins/ObjectBuiltinOperations.java
package ai.timefold.jpyinterpreter.builtins; public class ObjectBuiltinOperations { }
0
java-sources/ai/timefold/solver/jpyinterpreter/1.24.0/ai/timefold/jpyinterpreter
java-sources/ai/timefold/solver/jpyinterpreter/1.24.0/ai/timefold/jpyinterpreter/builtins/TernaryDunderBuiltin.java
package ai.timefold.jpyinterpreter.builtins; import java.util.List; import java.util.Map; import ai.timefold.jpyinterpreter.PythonLikeObject; import ai.timefold.jpyinterpreter.PythonTernaryOperator; import ai.timefold.jpyinterpreter.types.PythonLikeFunction; import ai.timefold.jpyinterpreter.types.PythonString; import ai.timefold.jpyinterpreter.types.errors.ValueError; public class TernaryDunderBuiltin implements PythonLikeFunction { private final String DUNDER_METHOD_NAME; public static final TernaryDunderBuiltin POWER = new TernaryDunderBuiltin("__pow__"); public static final TernaryDunderBuiltin SETATTR = new TernaryDunderBuiltin(PythonTernaryOperator.SET_ATTRIBUTE); public static final TernaryDunderBuiltin GET_DESCRIPTOR = new TernaryDunderBuiltin(PythonTernaryOperator.GET); public TernaryDunderBuiltin(String dunderMethodName) { DUNDER_METHOD_NAME = dunderMethodName; } public TernaryDunderBuiltin(PythonTernaryOperator operator) { DUNDER_METHOD_NAME = operator.getDunderMethod(); } @Override public PythonLikeObject $call(List<PythonLikeObject> positionalArguments, Map<PythonString, PythonLikeObject> namedArguments, PythonLikeObject callerInstance) { if (positionalArguments.size() != 3) { throw new ValueError("Function " + DUNDER_METHOD_NAME + " expects 3 positional arguments"); } PythonLikeObject object = positionalArguments.get(0); PythonLikeObject arg1 = positionalArguments.get(1); PythonLikeObject arg2 = positionalArguments.get(2); PythonLikeFunction dunderMethod = (PythonLikeFunction) object.$getType().$getAttributeOrError(DUNDER_METHOD_NAME); return dunderMethod.$call(List.of(object, arg1, arg2), Map.of(), null); } public PythonLikeObject invoke(PythonLikeObject object, PythonLikeObject arg1, PythonLikeObject arg2) { PythonLikeFunction dunderMethod = (PythonLikeFunction) object.$getType().$getAttributeOrError(DUNDER_METHOD_NAME); return dunderMethod.$call(List.of(object, arg1, arg2), Map.of(), null); } }
0
java-sources/ai/timefold/solver/jpyinterpreter/1.24.0/ai/timefold/jpyinterpreter
java-sources/ai/timefold/solver/jpyinterpreter/1.24.0/ai/timefold/jpyinterpreter/builtins/UnaryDunderBuiltin.java
package ai.timefold.jpyinterpreter.builtins; import java.util.List; import java.util.Map; import ai.timefold.jpyinterpreter.PythonLikeObject; import ai.timefold.jpyinterpreter.PythonUnaryOperator; import ai.timefold.jpyinterpreter.types.PythonLikeFunction; import ai.timefold.jpyinterpreter.types.PythonString; import ai.timefold.jpyinterpreter.types.errors.ValueError; public class UnaryDunderBuiltin implements PythonLikeFunction { private final String DUNDER_METHOD_NAME; public static final UnaryDunderBuiltin ABS = new UnaryDunderBuiltin(PythonUnaryOperator.ABS); public static final UnaryDunderBuiltin HASH = new UnaryDunderBuiltin(PythonUnaryOperator.HASH); public static final UnaryDunderBuiltin INT = new UnaryDunderBuiltin(PythonUnaryOperator.AS_INT); public static final UnaryDunderBuiltin FLOAT = new UnaryDunderBuiltin(PythonUnaryOperator.AS_FLOAT); public static final UnaryDunderBuiltin INDEX = new UnaryDunderBuiltin(PythonUnaryOperator.AS_INDEX); public static final UnaryDunderBuiltin ITERATOR = new UnaryDunderBuiltin(PythonUnaryOperator.ITERATOR); public static final UnaryDunderBuiltin LENGTH = new UnaryDunderBuiltin(PythonUnaryOperator.LENGTH); public static final UnaryDunderBuiltin NEXT = new UnaryDunderBuiltin(PythonUnaryOperator.NEXT); public static final UnaryDunderBuiltin REVERSED = new UnaryDunderBuiltin(PythonUnaryOperator.REVERSED); public static final UnaryDunderBuiltin REPRESENTATION = new UnaryDunderBuiltin(PythonUnaryOperator.REPRESENTATION); public static final UnaryDunderBuiltin STR = new UnaryDunderBuiltin(PythonUnaryOperator.AS_STRING); public UnaryDunderBuiltin(String dunderMethodName) { DUNDER_METHOD_NAME = dunderMethodName; } public UnaryDunderBuiltin(PythonUnaryOperator operator) { DUNDER_METHOD_NAME = operator.getDunderMethod(); } @Override public PythonLikeObject $call(List<PythonLikeObject> positionalArguments, Map<PythonString, PythonLikeObject> namedArguments, PythonLikeObject callerInstance) { if (positionalArguments.size() != 1) { throw new ValueError("Function " + DUNDER_METHOD_NAME + " expects 1 positional argument"); } PythonLikeObject object = positionalArguments.get(0); PythonLikeFunction dunderMethod = (PythonLikeFunction) object.$getType().$getAttributeOrError(DUNDER_METHOD_NAME); return dunderMethod.$call(List.of(object), Map.of(), null); } public PythonLikeObject invoke(PythonLikeObject object) { PythonLikeFunction dunderMethod = (PythonLikeFunction) object.$getType().$getAttributeOrError(DUNDER_METHOD_NAME); return dunderMethod.$call(List.of(object), Map.of(), null); } }
0
java-sources/ai/timefold/solver/jpyinterpreter/1.24.0/ai/timefold/jpyinterpreter
java-sources/ai/timefold/solver/jpyinterpreter/1.24.0/ai/timefold/jpyinterpreter/dag/BasicBlock.java
package ai.timefold.jpyinterpreter.dag; import java.util.List; import java.util.Objects; import ai.timefold.jpyinterpreter.opcodes.Opcode; public class BasicBlock { int startAtIndex; List<Opcode> blockOpcodeList; public BasicBlock(int startAtIndex, List<Opcode> blockOpcodeList) { this.startAtIndex = startAtIndex; this.blockOpcodeList = blockOpcodeList; } public int getStartInclusive() { return startAtIndex; } public int getEndExclusive() { return startAtIndex + blockOpcodeList.size(); } public Opcode getLeader() { return blockOpcodeList.get(0); } public Opcode getFinalOpcode() { return blockOpcodeList.get(blockOpcodeList.size() - 1); } public boolean containsIndex(int index) { return getStartInclusive() <= index && index < getEndExclusive(); } public List<Opcode> getBlockOpcodeList() { return blockOpcodeList; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } BasicBlock that = (BasicBlock) o; return startAtIndex == that.startAtIndex; } @Override public int hashCode() { return Objects.hash(startAtIndex); } @Override public String toString() { return "BasicBlock{" + "startAtIndex=" + startAtIndex + ", blockOpcodeList=" + blockOpcodeList + '}'; } }
0
java-sources/ai/timefold/solver/jpyinterpreter/1.24.0/ai/timefold/jpyinterpreter
java-sources/ai/timefold/solver/jpyinterpreter/1.24.0/ai/timefold/jpyinterpreter/dag/FlowGraph.java
package ai.timefold.jpyinterpreter.dag; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Objects; import java.util.function.BiConsumer; import java.util.stream.Collectors; import ai.timefold.jpyinterpreter.ExceptionBlock; import ai.timefold.jpyinterpreter.FunctionMetadata; import ai.timefold.jpyinterpreter.PythonBytecodeToJavaBytecodeTranslator; import ai.timefold.jpyinterpreter.StackMetadata; import ai.timefold.jpyinterpreter.opcodes.Opcode; import ai.timefold.jpyinterpreter.types.BuiltinTypes; import ai.timefold.jpyinterpreter.types.errors.PythonBaseException; public class FlowGraph { BasicBlock initialBlock; List<BasicBlock> basicBlockList; Map<BasicBlock, List<BasicBlock>> basicBlockToSourcesMap; Map<BasicBlock, List<JumpSource>> basicBlockToJumpSourcesMap; Map<IndexBranchPair, JumpSource> opcodeIndexToJumpSourceMap; List<StackMetadata> stackMetadataForOperations; private FlowGraph(BasicBlock initialBlock, List<BasicBlock> basicBlockList, Map<BasicBlock, List<BasicBlock>> basicBlockToSourcesMap, Map<BasicBlock, List<JumpSource>> basicBlockToJumpSourcesMap, Map<IndexBranchPair, JumpSource> opcodeIndexToJumpSourceMap) { this.initialBlock = initialBlock; this.basicBlockList = basicBlockList; this.basicBlockToSourcesMap = basicBlockToSourcesMap; this.basicBlockToJumpSourcesMap = basicBlockToJumpSourcesMap; this.opcodeIndexToJumpSourceMap = opcodeIndexToJumpSourceMap; } public List<StackMetadata> getStackMetadataForOperations() { return stackMetadataForOperations; } @SuppressWarnings("unchecked") public <T extends Opcode> void visitOperations(Class<T> opcodeClass, BiConsumer<? super T, StackMetadata> visitor) { for (BasicBlock basicBlock : basicBlockList) { for (Opcode opcode : basicBlock.getBlockOpcodeList()) { if (opcodeClass.isAssignableFrom(opcode.getClass())) { StackMetadata stackMetadata = stackMetadataForOperations.get(opcode.getBytecodeIndex()); if (!stackMetadata.isDeadCode()) { visitor.accept((T) opcode, stackMetadata); } } } } } public static FlowGraph createFlowGraph(FunctionMetadata functionMetadata, StackMetadata initialStackMetadata, List<Opcode> opcodeList) { List<Integer> leaderIndexList = new ArrayList<>(); boolean wasPreviousInstructionGoto = true; // True so first instruction get added as a leader for (int i = 0; i < opcodeList.size(); i++) { if (wasPreviousInstructionGoto || opcodeList.get(i).isJumpTarget() || functionMetadata.pythonCompiledFunction.co_exceptiontable.containsJumpTarget(i)) { leaderIndexList.add(i); } wasPreviousInstructionGoto = opcodeList.get(i).isForcedJump(); } List<BasicBlock> basicBlockList = new ArrayList<>(leaderIndexList.size()); Map<Integer, BasicBlock> jumpTargetToBasicBlock = new HashMap<>(); for (int i = 0; i < leaderIndexList.size() - 1; i++) { basicBlockList.add(new BasicBlock(leaderIndexList.get(i), opcodeList.subList(leaderIndexList.get(i), leaderIndexList.get(i + 1)))); jumpTargetToBasicBlock.put(leaderIndexList.get(i), basicBlockList.get(i)); } basicBlockList.add(new BasicBlock(leaderIndexList.get(leaderIndexList.size() - 1), opcodeList.subList(leaderIndexList.get(leaderIndexList.size() - 1), opcodeList.size()))); jumpTargetToBasicBlock.put(leaderIndexList.get(leaderIndexList.size() - 1), basicBlockList.get(leaderIndexList.size() - 1)); BasicBlock initialBlock = basicBlockList.get(0); Map<BasicBlock, List<BasicBlock>> basicBlockToSourcesMap = new HashMap<>(); Map<BasicBlock, List<JumpSource>> basicBlockToJumpSourcesMap = new HashMap<>(); Map<IndexBranchPair, JumpSource> opcodeIndexToJumpSourceMap = new HashMap<>(); for (BasicBlock basicBlock : basicBlockList) { basicBlockToSourcesMap.put(basicBlock, new ArrayList<>()); } for (BasicBlock basicBlock : basicBlockList) { for (Opcode opcode : basicBlock.getBlockOpcodeList()) { for (int branch = 0; branch < opcode.getPossibleNextBytecodeIndexList().size(); branch++) { int jumpTarget = opcode.getPossibleNextBytecodeIndexList().get(branch); if (!basicBlock.containsIndex(jumpTarget) || jumpTarget <= opcode.getBytecodeIndex()) { BasicBlock jumpTargetBlock = jumpTargetToBasicBlock.get(jumpTarget); JumpSource jumpSource = new JumpSource(basicBlock); basicBlockToSourcesMap.computeIfAbsent(jumpTargetBlock, key -> new ArrayList<>()).add(basicBlock); basicBlockToJumpSourcesMap.computeIfAbsent(jumpTargetBlock, key -> new ArrayList<>()).add(jumpSource); opcodeIndexToJumpSourceMap.put(new IndexBranchPair(opcode.getBytecodeIndex(), branch), jumpSource); } } } } FlowGraph out = new FlowGraph(initialBlock, basicBlockList, basicBlockToSourcesMap, basicBlockToJumpSourcesMap, opcodeIndexToJumpSourceMap); out.computeStackMetadataForOperations(functionMetadata, initialStackMetadata); return out; } private static StackMetadata getExceptionStackMetadata(ExceptionBlock exceptionBlock, FunctionMetadata functionMetadata, StackMetadata initialStackMetadata, StackMetadata previousStackMetadata) { if (previousStackMetadata == StackMetadata.DEAD_CODE) { previousStackMetadata = initialStackMetadata; } while (previousStackMetadata.getStackSize() < exceptionBlock.getStackDepth()) { previousStackMetadata = previousStackMetadata.pushTemp(BuiltinTypes.NONE_TYPE); } while (previousStackMetadata.getStackSize() > exceptionBlock.getStackDepth()) { previousStackMetadata = previousStackMetadata.pop(); } if (exceptionBlock.isPushLastIndex()) { return previousStackMetadata.pushTemp(BuiltinTypes.INT_TYPE) .pushTemp(PythonBaseException.BASE_EXCEPTION_TYPE); } else { return previousStackMetadata.pushTemp(PythonBaseException.BASE_EXCEPTION_TYPE); } } private void computeStackMetadataForOperations(FunctionMetadata functionMetadata, StackMetadata initialStackMetadata) { Map<Integer, StackMetadata> opcodeIndexToStackMetadata = new HashMap<>(); opcodeIndexToStackMetadata.put(0, initialStackMetadata); for (BasicBlock basicBlock : basicBlockList) { for (Opcode opcode : basicBlock.getBlockOpcodeList()) { StackMetadata currentStackMetadata = opcodeIndexToStackMetadata.computeIfAbsent(opcode.getBytecodeIndex(), k -> StackMetadata.DEAD_CODE); List<Integer> branchList = opcode.getPossibleNextBytecodeIndexList(); List<StackMetadata> nextStackMetadataList; try { nextStackMetadataList = currentStackMetadata.isDeadCode() ? branchList.stream().map(i -> StackMetadata.DEAD_CODE).collect(Collectors.toList()) : opcode.getStackMetadataAfterInstructionForBranches(functionMetadata, currentStackMetadata); } catch (Throwable t) { throw new IllegalStateException("Failed to calculate successor stack metadata for opcode (" + opcode + ") with prior stack metadata (" + currentStackMetadata + ").", t); } for (int i = 0; i < branchList.size(); i++) { IndexBranchPair indexBranchPair = new IndexBranchPair(opcode.getBytecodeIndex(), i); int nextBytecodeIndex = branchList.get(i); StackMetadata nextStackMetadata = nextStackMetadataList.get(i); if (opcodeIndexToJumpSourceMap.containsKey(indexBranchPair)) { opcodeIndexToJumpSourceMap.get(indexBranchPair).setStackMetadata(nextStackMetadata); } try { opcodeIndexToStackMetadata.merge(nextBytecodeIndex, nextStackMetadata, StackMetadata::unifyWith); } catch (IllegalArgumentException e) { throw new IllegalStateException( "Cannot unify block starting at " + nextBytecodeIndex + ": different stack sizes;\n" + PythonBytecodeToJavaBytecodeTranslator .getPythonBytecodeListing(functionMetadata.pythonCompiledFunction), e); } } } } for (ExceptionBlock exceptionBlock : functionMetadata.pythonCompiledFunction.co_exceptiontable .getEntries()) { try { opcodeIndexToStackMetadata.merge(exceptionBlock.getTargetInstruction(), getExceptionStackMetadata(exceptionBlock, functionMetadata, initialStackMetadata, opcodeIndexToStackMetadata.getOrDefault(exceptionBlock.getBlockStartInstructionInclusive(), StackMetadata.DEAD_CODE)), StackMetadata::unifyWith); } catch (IllegalArgumentException e) { throw new IllegalStateException( "Cannot unify block starting at " + exceptionBlock.getTargetInstruction() + ": different stack sizes;\n" + PythonBytecodeToJavaBytecodeTranslator .getPythonBytecodeListing(functionMetadata.pythonCompiledFunction), e); } } boolean hasChanged; do { // Keep unifying until no changes are detected hasChanged = false; for (BasicBlock basicBlock : basicBlockList) { StackMetadata originalMetadata = opcodeIndexToStackMetadata.get(basicBlock.startAtIndex); StackMetadata newMetadata = originalMetadata; for (JumpSource jumpSource : basicBlockToJumpSourcesMap.getOrDefault(basicBlock, Collections.emptyList())) { newMetadata = newMetadata.unifyWith(jumpSource.getStackMetadata()); } hasChanged |= !newMetadata.equals(originalMetadata); opcodeIndexToStackMetadata.put(basicBlock.startAtIndex, newMetadata); for (Opcode opcode : basicBlock.getBlockOpcodeList()) { StackMetadata currentStackMetadata = opcodeIndexToStackMetadata.get(opcode.getBytecodeIndex()); List<Integer> branchList = opcode.getPossibleNextBytecodeIndexList(); List<StackMetadata> nextStackMetadataList; try { nextStackMetadataList = currentStackMetadata.isDeadCode() ? branchList.stream().map(i -> StackMetadata.DEAD_CODE).collect(Collectors.toList()) : opcode.getStackMetadataAfterInstructionForBranches(functionMetadata, currentStackMetadata); } catch (Throwable t) { throw new IllegalStateException("Failed to calculate successor stack metadata for opcode (" + opcode + ") with prior stack metadata (" + currentStackMetadata + ").", t); } for (int i = 0; i < branchList.size(); i++) { IndexBranchPair indexBranchPair = new IndexBranchPair(opcode.getBytecodeIndex(), i); int nextBytecodeIndex = branchList.get(i); StackMetadata nextStackMetadata = nextStackMetadataList.get(i); if (opcodeIndexToJumpSourceMap.containsKey(indexBranchPair)) { opcodeIndexToJumpSourceMap.get(indexBranchPair).setStackMetadata(nextStackMetadata); } try { StackMetadata originalOpcodeMetadata = opcodeIndexToStackMetadata.get(nextBytecodeIndex); StackMetadata newOpcodeMetadata = opcodeIndexToStackMetadata.merge(nextBytecodeIndex, nextStackMetadata, StackMetadata::unifyWith); hasChanged |= !newOpcodeMetadata.equals(originalOpcodeMetadata); } catch (IllegalArgumentException e) { throw new IllegalStateException( "Cannot unify branch (" + indexBranchPair.branch + ": to index " + indexBranchPair.index + ") stack metadata (" + nextStackMetadata + ") for source opcode (" + opcode + ") with" + "prior stack metadata (" + opcodeIndexToStackMetadata.get(nextBytecodeIndex) + "): different stack sizes;\n" + PythonBytecodeToJavaBytecodeTranslator .getPythonBytecodeListing(functionMetadata.pythonCompiledFunction), e); } } } } for (ExceptionBlock exceptionBlock : functionMetadata.pythonCompiledFunction.co_exceptiontable .getEntries()) { try { StackMetadata originalOpcodeMetadata = opcodeIndexToStackMetadata.get(exceptionBlock.getTargetInstruction()); StackMetadata newOpcodeMetadata = opcodeIndexToStackMetadata.merge(exceptionBlock.getTargetInstruction(), getExceptionStackMetadata(exceptionBlock, functionMetadata, initialStackMetadata, opcodeIndexToStackMetadata.getOrDefault(exceptionBlock.getBlockStartInstructionInclusive(), StackMetadata.DEAD_CODE)), StackMetadata::unifyWith); hasChanged |= !newOpcodeMetadata.equals(originalOpcodeMetadata); } catch (IllegalArgumentException e) { throw new IllegalStateException( "Cannot unify block starting at " + exceptionBlock.getTargetInstruction() + ": different stack sizes;\n" + PythonBytecodeToJavaBytecodeTranslator .getPythonBytecodeListing(functionMetadata.pythonCompiledFunction), e); } } } while (hasChanged); stackMetadataForOperations = opcodeIndexToStackMetadata .entrySet() .stream() .sorted(Map.Entry.comparingByKey()) .map(Map.Entry::getValue) .collect(Collectors.toList()); } private static class IndexBranchPair { final Integer index; final Integer branch; public IndexBranchPair(Integer index, Integer branch) { this.index = index; this.branch = branch; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } IndexBranchPair that = (IndexBranchPair) o; return index.equals(that.index) && branch.equals(that.branch); } @Override public int hashCode() { return Objects.hash(index, branch); } @Override public String toString() { return "IndexBranchPair{" + "index=" + index + ", branch=" + branch + '}'; } } }
0
java-sources/ai/timefold/solver/jpyinterpreter/1.24.0/ai/timefold/jpyinterpreter
java-sources/ai/timefold/solver/jpyinterpreter/1.24.0/ai/timefold/jpyinterpreter/dag/JumpSource.java
package ai.timefold.jpyinterpreter.dag; import ai.timefold.jpyinterpreter.StackMetadata; public class JumpSource { BasicBlock fromBasicBlock; StackMetadata stackMetadata; public JumpSource(BasicBlock fromBasicBlock) { this.fromBasicBlock = fromBasicBlock; } public StackMetadata getStackMetadata() { return stackMetadata; } public void setStackMetadata(StackMetadata stackMetadata) { this.stackMetadata = stackMetadata; } @Override public String toString() { return "JumpSource{" + "fromBasicBlock=" + fromBasicBlock + ", stackMetadata=" + stackMetadata + '}'; } }
0
java-sources/ai/timefold/solver/jpyinterpreter/1.24.0/ai/timefold/jpyinterpreter
java-sources/ai/timefold/solver/jpyinterpreter/1.24.0/ai/timefold/jpyinterpreter/implementors/CollectionImplementor.java
package ai.timefold.jpyinterpreter.implementors; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.List; import java.util.Map; import java.util.Set; import ai.timefold.jpyinterpreter.FunctionMetadata; import ai.timefold.jpyinterpreter.LocalVariableHelper; import ai.timefold.jpyinterpreter.PythonBinaryOperator; import ai.timefold.jpyinterpreter.PythonBytecodeInstruction; import ai.timefold.jpyinterpreter.PythonLikeObject; import ai.timefold.jpyinterpreter.PythonTernaryOperator; import ai.timefold.jpyinterpreter.PythonUnaryOperator; import ai.timefold.jpyinterpreter.StackMetadata; import ai.timefold.jpyinterpreter.types.PythonSlice; import ai.timefold.jpyinterpreter.types.collections.PythonLikeList; import ai.timefold.jpyinterpreter.types.collections.PythonLikeTuple; import ai.timefold.jpyinterpreter.types.errors.StopIteration; import ai.timefold.jpyinterpreter.types.numeric.PythonInteger; import org.objectweb.asm.Label; import org.objectweb.asm.MethodVisitor; import org.objectweb.asm.Opcodes; import org.objectweb.asm.Type; /** * Implementations of opcodes related to collections (list, tuple, set, dict). */ public class CollectionImplementor { /** * TOS is an iterator; perform TOS' = next(TOS). * If TOS is exhausted (which is indicated when it raises a {@link StopIteration} exception), * Jump relatively by the instruction argument and pop TOS. Otherwise, * leave TOS below TOS' and go to the next instruction. * * Note: {@link StopIteration} does not fill its stack trace, which make it much more efficient than * normal exceptions. */ public static void iterateIterator(MethodVisitor methodVisitor, int jumpTarget, StackMetadata stackMetadata, FunctionMetadata functionMetadata) { Label tryStartLabel = new Label(); Label tryEndLabel = new Label(); Label catchStartLabel = new Label(); Label catchEndLabel = new Label(); Label loopEndLabel = functionMetadata.bytecodeCounterToLabelMap.computeIfAbsent(jumpTarget, key -> new Label()); int[] storedStack = StackManipulationImplementor.storeStack(methodVisitor, stackMetadata); methodVisitor.visitTryCatchBlock(tryStartLabel, tryEndLabel, catchStartLabel, Type.getInternalName(StopIteration.class)); methodVisitor.visitLabel(tryStartLabel); methodVisitor.visitInsn(Opcodes.DUP); DunderOperatorImplementor.unaryOperator(methodVisitor, PythonUnaryOperator.NEXT); methodVisitor.visitLabel(tryEndLabel); methodVisitor.visitJumpInsn(Opcodes.GOTO, catchEndLabel); methodVisitor.visitLabel(catchStartLabel); methodVisitor.visitInsn(Opcodes.POP); methodVisitor.visitJumpInsn(Opcodes.GOTO, loopEndLabel); methodVisitor.visitLabel(catchEndLabel); functionMetadata.bytecodeCounterToCodeArgumenterList .computeIfAbsent(jumpTarget, key -> new ArrayList<>()) .add(() -> { StackManipulationImplementor.restoreStack(methodVisitor, stackMetadata, storedStack); methodVisitor.visitInsn(Opcodes.POP); }); } /** * TOS is an iterable; push {@code toUnpack} elements from it to the stack * (with first item of the iterable as the new TOS). Raise an exception if it does not * have exactly {@code toUnpack} elements. */ public static void unpackSequence(MethodVisitor methodVisitor, int toUnpack, LocalVariableHelper localVariableHelper) { // Initialize size and unpacked elements local variables int sizeLocal = localVariableHelper.newLocal(); methodVisitor.visitInsn(Opcodes.ICONST_0); localVariableHelper.writeTemp(methodVisitor, Type.INT_TYPE, sizeLocal); int[] unpackedLocals = new int[toUnpack]; for (int i = 0; i < toUnpack; i++) { unpackedLocals[i] = localVariableHelper.newLocal(); methodVisitor.visitInsn(Opcodes.ACONST_NULL); localVariableHelper.writeTemp(methodVisitor, Type.getType(Object.class), unpackedLocals[i]); } // Get the iterator for the iterable DunderOperatorImplementor.unaryOperator(methodVisitor, PythonUnaryOperator.ITERATOR); // Surround the unpacking code in a try...finally block Label tryStartLabel = new Label(); Label tryEndLabel = new Label(); Label finallyStartLabel = new Label(); methodVisitor.visitTryCatchBlock(tryStartLabel, tryEndLabel, finallyStartLabel, null); methodVisitor.visitLabel(tryStartLabel); for (int i = 0; i < toUnpack + 1; i++) { // Call the next method of the iterator methodVisitor.visitInsn(Opcodes.DUP); DunderOperatorImplementor.unaryOperator(methodVisitor, PythonUnaryOperator.NEXT); if (i < toUnpack) { // Store the unpacked value in a local localVariableHelper.writeTemp(methodVisitor, Type.getType(Object.class), unpackedLocals[i]); } else { // Try to get more elements to see if the iterable contain exactly enough methodVisitor.visitInsn(Opcodes.POP); } // increment size localVariableHelper.incrementTemp(methodVisitor, sizeLocal); } methodVisitor.visitLabel(tryEndLabel); methodVisitor.visitLabel(finallyStartLabel); Label toFewElements = new Label(); Label toManyElements = new Label(); Label exactNumberOfElements = new Label(); // Pop off the iterator methodVisitor.visitInsn(Opcodes.POP); // Check if too few localVariableHelper.readTemp(methodVisitor, Type.INT_TYPE, sizeLocal); methodVisitor.visitLdcInsn(toUnpack); methodVisitor.visitJumpInsn(Opcodes.IF_ICMPLT, toFewElements); // Check if too many localVariableHelper.readTemp(methodVisitor, Type.INT_TYPE, sizeLocal); methodVisitor.visitLdcInsn(toUnpack); methodVisitor.visitJumpInsn(Opcodes.IF_ICMPGT, toManyElements); // Must have exactly enough methodVisitor.visitJumpInsn(Opcodes.GOTO, exactNumberOfElements); // TODO: Throw ValueError instead methodVisitor.visitLabel(toFewElements); methodVisitor.visitTypeInsn(Opcodes.NEW, Type.getInternalName(IllegalArgumentException.class)); methodVisitor.visitInsn(Opcodes.DUP); // Build error message string methodVisitor.visitTypeInsn(Opcodes.NEW, Type.getInternalName(StringBuilder.class)); methodVisitor.visitInsn(Opcodes.DUP); methodVisitor.visitLdcInsn("not enough values to unpack (expected " + toUnpack + ", got "); methodVisitor.visitMethodInsn(Opcodes.INVOKESPECIAL, Type.getInternalName(StringBuilder.class), "<init>", Type.getMethodDescriptor(Type.VOID_TYPE, Type.getType(String.class)), false); localVariableHelper.readTemp(methodVisitor, Type.INT_TYPE, sizeLocal); methodVisitor.visitMethodInsn(Opcodes.INVOKEVIRTUAL, Type.getInternalName(StringBuilder.class), "append", Type.getMethodDescriptor(Type.getType(StringBuilder.class), Type.INT_TYPE), false); methodVisitor.visitLdcInsn(")"); methodVisitor.visitMethodInsn(Opcodes.INVOKEVIRTUAL, Type.getInternalName(StringBuilder.class), "append", Type.getMethodDescriptor(Type.getType(StringBuilder.class), Type.getType(String.class)), false); methodVisitor.visitMethodInsn(Opcodes.INVOKEVIRTUAL, Type.getInternalName(Object.class), "toString", Type.getMethodDescriptor(Type.getType(String.class)), false); // Call the constructor of the Error methodVisitor.visitMethodInsn(Opcodes.INVOKESPECIAL, Type.getInternalName(IllegalArgumentException.class), "<init>", Type.getMethodDescriptor(Type.VOID_TYPE, Type.getType(String.class)), false); // And throw it methodVisitor.visitInsn(Opcodes.ATHROW); methodVisitor.visitLabel(toManyElements); methodVisitor.visitTypeInsn(Opcodes.NEW, Type.getInternalName(IllegalArgumentException.class)); methodVisitor.visitInsn(Opcodes.DUP); methodVisitor.visitLdcInsn("too many values to unpack (expected " + toUnpack + ")"); methodVisitor.visitMethodInsn(Opcodes.INVOKESPECIAL, Type.getInternalName(IllegalArgumentException.class), "<init>", Type.getMethodDescriptor(Type.VOID_TYPE, Type.getType(String.class)), false); methodVisitor.visitInsn(Opcodes.ATHROW); methodVisitor.visitLabel(exactNumberOfElements); for (int i = toUnpack - 1; i >= 0; i--) { // Unlike all other collection operators, UNPACK_SEQUENCE unpacks the result in reverse order localVariableHelper.readTemp(methodVisitor, Type.getType(Object.class), unpackedLocals[i]); } localVariableHelper.freeLocal(); for (int i = 0; i < toUnpack; i++) { localVariableHelper.freeLocal(); } } /** * TOS is an iterable; push {@code toUnpack} elements from it to the stack * (with first item of the iterable as the new TOS). Below the elements in the stack * is a list containing the remaining elements in the iterable (empty if there are none). * Raise an exception if it has less than {@code toUnpack} elements. */ public static void unpackSequenceWithTail(MethodVisitor methodVisitor, int toUnpack, LocalVariableHelper localVariableHelper) { // TODO: Correctly handle when high byte is set // Initialize size, unpacked elements and tail local variables int sizeLocal = localVariableHelper.newLocal(); methodVisitor.visitInsn(Opcodes.ICONST_0); localVariableHelper.writeTemp(methodVisitor, Type.INT_TYPE, sizeLocal); int[] unpackedLocals = new int[toUnpack]; for (int i = 0; i < toUnpack; i++) { unpackedLocals[i] = localVariableHelper.newLocal(); methodVisitor.visitInsn(Opcodes.ACONST_NULL); localVariableHelper.writeTemp(methodVisitor, Type.getType(Object.class), unpackedLocals[i]); } int tailLocal = localVariableHelper.newLocal(); CollectionImplementor.buildCollection(PythonLikeList.class, methodVisitor, 0); localVariableHelper.writeTemp(methodVisitor, Type.getType(Object.class), tailLocal); // Get the iterator for the iterable DunderOperatorImplementor.unaryOperator(methodVisitor, PythonUnaryOperator.ITERATOR); // Surround the unpacking code in a try...finally block Label tryStartLabel = new Label(); Label tryEndLabel = new Label(); Label finallyStartLabel = new Label(); methodVisitor.visitTryCatchBlock(tryStartLabel, tryEndLabel, finallyStartLabel, null); methodVisitor.visitLabel(tryStartLabel); for (int i = 0; i < toUnpack; i++) { // Call the next method of the iterator methodVisitor.visitInsn(Opcodes.DUP); DunderOperatorImplementor.unaryOperator(methodVisitor, PythonUnaryOperator.NEXT); // Store the unpacked value in a local localVariableHelper.writeTemp(methodVisitor, Type.getType(Object.class), unpackedLocals[i]); // increment size localVariableHelper.incrementTemp(methodVisitor, sizeLocal); } // Keep iterating through the iterable until StopIteration is raised to get all of its elements Label tailLoopStart = new Label(); methodVisitor.visitLabel(tailLoopStart); methodVisitor.visitInsn(Opcodes.DUP); DunderOperatorImplementor.unaryOperator(methodVisitor, PythonUnaryOperator.NEXT); localVariableHelper.readTemp(methodVisitor, Type.getType(Object.class), tailLocal); methodVisitor.visitInsn(Opcodes.SWAP); methodVisitor.visitMethodInsn(Opcodes.INVOKEINTERFACE, Type.getInternalName(Collection.class), "add", Type.getMethodDescriptor(Type.BOOLEAN_TYPE, Type.getType(Object.class)), true); methodVisitor.visitInsn(Opcodes.POP); // Pop the return value of add methodVisitor.visitJumpInsn(Opcodes.GOTO, tailLoopStart); methodVisitor.visitLabel(tryEndLabel); methodVisitor.visitLabel(finallyStartLabel); Label exactNumberOfElements = new Label(); // Pop off the iterator methodVisitor.visitInsn(Opcodes.POP); // Check if too few localVariableHelper.readTemp(methodVisitor, Type.INT_TYPE, sizeLocal); methodVisitor.visitLdcInsn(toUnpack); methodVisitor.visitJumpInsn(Opcodes.IF_ICMPGE, exactNumberOfElements); // TODO: Throw ValueError instead methodVisitor.visitTypeInsn(Opcodes.NEW, Type.getInternalName(IllegalArgumentException.class)); methodVisitor.visitInsn(Opcodes.DUP); // Build error message string methodVisitor.visitTypeInsn(Opcodes.NEW, Type.getInternalName(StringBuilder.class)); methodVisitor.visitInsn(Opcodes.DUP); methodVisitor.visitLdcInsn("not enough values to unpack (expected " + toUnpack + ", got "); methodVisitor.visitMethodInsn(Opcodes.INVOKESPECIAL, Type.getInternalName(StringBuilder.class), "<init>", Type.getMethodDescriptor(Type.VOID_TYPE, Type.getType(String.class)), false); localVariableHelper.readTemp(methodVisitor, Type.INT_TYPE, sizeLocal); methodVisitor.visitMethodInsn(Opcodes.INVOKEVIRTUAL, Type.getInternalName(StringBuilder.class), "append", Type.getMethodDescriptor(Type.getType(StringBuilder.class), Type.INT_TYPE), false); methodVisitor.visitLdcInsn(")"); methodVisitor.visitMethodInsn(Opcodes.INVOKEVIRTUAL, Type.getInternalName(StringBuilder.class), "append", Type.getMethodDescriptor(Type.getType(StringBuilder.class), Type.getType(String.class)), false); methodVisitor.visitMethodInsn(Opcodes.INVOKEVIRTUAL, Type.getInternalName(Object.class), "toString", Type.getMethodDescriptor(Type.getType(String.class)), false); // Call the constructor of the Error methodVisitor.visitMethodInsn(Opcodes.INVOKESPECIAL, Type.getInternalName(IllegalArgumentException.class), "<init>", Type.getMethodDescriptor(Type.VOID_TYPE, Type.getType(String.class)), false); // And throw it methodVisitor.visitInsn(Opcodes.ATHROW); methodVisitor.visitLabel(exactNumberOfElements); // Unlike all other collection operators, UNPACK_SEQUENCE unpacks the result in reverse order localVariableHelper.readTemp(methodVisitor, Type.getType(Object.class), tailLocal); for (int i = toUnpack - 1; i >= 0; i--) { localVariableHelper.readTemp(methodVisitor, Type.getType(Object.class), unpackedLocals[i]); } localVariableHelper.freeLocal(); for (int i = 0; i < toUnpack; i++) { localVariableHelper.freeLocal(); } localVariableHelper.freeLocal(); } /** * Constructs a collection from the top {@code itemCount} on the stack. * {@code collectionType} MUST implement PythonLikeObject and define * a reverseAdd(PythonLikeObject) method. Basically generate the following code: * * <pre> * CollectionType collection = new CollectionType(itemCount); * collection.reverseAdd(TOS); * collection.reverseAdd(TOS1); * ... * collection.reverseAdd(TOS(itemCount - 1)); * </pre> * * @param collectionType The type of collection to create * @param itemCount The number of items to put into collection from the stack */ public static void buildCollection(Class<?> collectionType, MethodVisitor methodVisitor, int itemCount) { String typeInternalName = Type.getInternalName(collectionType); methodVisitor.visitTypeInsn(Opcodes.NEW, typeInternalName); methodVisitor.visitInsn(Opcodes.DUP); methodVisitor.visitLdcInsn(itemCount); methodVisitor.visitMethodInsn(Opcodes.INVOKESPECIAL, typeInternalName, "<init>", Type.getMethodDescriptor(Type.VOID_TYPE, Type.INT_TYPE), false); for (int i = 0; i < itemCount; i++) { methodVisitor.visitInsn(Opcodes.DUP_X1); methodVisitor.visitInsn(Opcodes.SWAP); methodVisitor.visitMethodInsn(Opcodes.INVOKEVIRTUAL, typeInternalName, "reverseAdd", Type.getMethodDescriptor(Type.VOID_TYPE, Type.getType(PythonLikeObject.class)), false); } } /** * Convert TOS from a List to a tuple. Basically generates this code * * <pre> * TOS' = PythonLikeTuple.fromList(TOS); * </pre> */ public static void convertListToTuple(MethodVisitor methodVisitor) { methodVisitor.visitMethodInsn(Opcodes.INVOKESTATIC, Type.getInternalName(PythonLikeTuple.class), "fromList", Type.getMethodDescriptor(Type.getType(PythonLikeTuple.class), Type.getType(List.class)), false); } /** * Constructs a map from the top {@code 2 * itemCount} on the stack. * {@code mapType} MUST implement PythonLikeObject. Basically generate the following code: * * <pre> * MapType collection = new MapType(itemCount); * collection.put(TOS1, TOS); * collection.put(TOS3, TOS2); * ... * collection.put(TTOS(2*itemCount - 1), TOS(2*itemCount - 2)); * </pre> * * @param mapType The type of map to create * @param itemCount The number of key value pairs to put into map from the stack */ public static void buildMap(Class<? extends Map> mapType, MethodVisitor methodVisitor, int itemCount) { String typeInternalName = Type.getInternalName(mapType); methodVisitor.visitTypeInsn(Opcodes.NEW, typeInternalName); methodVisitor.visitInsn(Opcodes.DUP); methodVisitor.visitMethodInsn(Opcodes.INVOKESPECIAL, typeInternalName, "<init>", "()V", false); for (int i = 0; i < itemCount; i++) { methodVisitor.visitInsn(Opcodes.DUP_X2); StackManipulationImplementor.rotateThree(methodVisitor); methodVisitor.visitMethodInsn(Opcodes.INVOKEINTERFACE, Type.getInternalName(Map.class), "put", Type.getMethodDescriptor(Type.getType(Object.class), Type.getType(Object.class), Type.getType(Object.class)), true); methodVisitor.visitInsn(Opcodes.POP); // pop return value of "put" } } /** * Constructs a map from the top {@code itemCount + 1} on the stack. * TOS is a tuple containing keys; TOS1-TOS(itemCount) are the values * {@code mapType} MUST implement PythonLikeObject. Basically generate the following code: * * <pre> * MapType collection = new MapType(); * collection.put(TOS[0], TOS1); * collection.put(TOS[1], TOS2); * ... * collection.put(TOS[itemCount-1], TOS(itemCount)); * </pre> * * @param mapType The type of map to create * @param itemCount The number of key value pairs to put into map from the stack */ public static void buildConstKeysMap(Class<? extends Map> mapType, MethodVisitor methodVisitor, int itemCount) { String typeInternalName = Type.getInternalName(mapType); methodVisitor.visitTypeInsn(Opcodes.NEW, typeInternalName); methodVisitor.visitInsn(Opcodes.DUP); methodVisitor.visitMethodInsn(Opcodes.INVOKESPECIAL, typeInternalName, "<init>", "()V", false); for (int i = 0; i < itemCount; i++) { // Stack is value, keyTuple, Map methodVisitor.visitInsn(Opcodes.DUP_X2); StackManipulationImplementor.rotateThree(methodVisitor); // Stack is Map, Map, value, keyTuple methodVisitor.visitInsn(Opcodes.DUP_X2); //Stack is Map, keyTuple, Map, value, keyTuple methodVisitor.visitLdcInsn(itemCount - i - 1); // We are adding in reverse order methodVisitor.visitMethodInsn(Opcodes.INVOKEINTERFACE, Type.getInternalName(List.class), "get", Type.getMethodDescriptor(Type.getType(Object.class), Type.getType(int.class)), true); // Stack is Map, keyTuple, Map, value, key methodVisitor.visitInsn(Opcodes.SWAP); // Stack is Map, keyTuple, Map, key, value methodVisitor.visitMethodInsn(Opcodes.INVOKEINTERFACE, Type.getInternalName(Map.class), "put", Type.getMethodDescriptor(Type.getType(Object.class), Type.getType(Object.class), Type.getType(Object.class)), true); methodVisitor.visitInsn(Opcodes.POP); // pop return value of "put" // Stack is Map, keyTuple methodVisitor.visitInsn(Opcodes.SWAP); } // Stack is keyTuple, Map // Pop the keyTuple off the stack methodVisitor.visitInsn(Opcodes.SWAP); methodVisitor.visitInsn(Opcodes.POP); } /** * Implements TOS1 in TOS. TOS must be a collection/object that implement the "__contains__" dunder method. */ public static void containsOperator(MethodVisitor methodVisitor, StackMetadata stackMetadata, PythonBytecodeInstruction instruction) { StackManipulationImplementor.swap(methodVisitor); DunderOperatorImplementor.binaryOperator(methodVisitor, stackMetadata .pop(2) .push(stackMetadata.getTOSValueSource()) .push(stackMetadata.getValueSourceForStackIndex(1)), PythonBinaryOperator.CONTAINS); // TODO: implement fallback on __iter__ if __contains__ does not exist if (instruction.arg() == 1) { PythonBuiltinOperatorImplementor.performNotOnTOS(methodVisitor); } } /** * Implements TOS1[TOS] = TOS2. TOS1 must be a collection/object that implement the "__setitem__" dunder method. */ public static void setItem(FunctionMetadata functionMetadata, StackMetadata stackMetadata) { MethodVisitor methodVisitor = functionMetadata.methodVisitor; // Stack is TOS2, TOS1, TOS StackManipulationImplementor.rotateThree(methodVisitor); StackManipulationImplementor.rotateThree(methodVisitor); // Stack is TOS1, TOS, TOS2 DunderOperatorImplementor.ternaryOperator(functionMetadata, stackMetadata.pop(3) .push(stackMetadata.getValueSourceForStackIndex(1)) .push(stackMetadata.getValueSourceForStackIndex(0)) .push(stackMetadata.getValueSourceForStackIndex(2)), PythonTernaryOperator.SET_ITEM); StackManipulationImplementor.popTOS(methodVisitor); } /** * Calls collection.add(TOS[i], TOS). TOS[i] remains on stack; TOS is popped. Used to implement list/set comprehensions. */ public static void collectionAdd(FunctionMetadata functionMetadata, StackMetadata stackMetadata, PythonBytecodeInstruction instruction) { MethodVisitor methodVisitor = functionMetadata.methodVisitor; // instruction.arg is distance from TOS StackManipulationImplementor.duplicateToTOS(functionMetadata, stackMetadata, instruction.arg()); StackManipulationImplementor.swap(methodVisitor); methodVisitor.visitMethodInsn(Opcodes.INVOKEINTERFACE, Type.getInternalName(Collection.class), "add", Type.getMethodDescriptor(Type.BOOLEAN_TYPE, Type.getType(Object.class)), true); StackManipulationImplementor.popTOS(methodVisitor); // pop Collection.add return value } /** * Calls collection.addAll(TOS[i], TOS). TOS[i] remains on stack; TOS is popped. Used to build lists/maps. */ public static void collectionAddAll(FunctionMetadata functionMetadata, StackMetadata stackMetadata, PythonBytecodeInstruction instruction) { MethodVisitor methodVisitor = functionMetadata.methodVisitor; // instruction.arg is distance from TOS StackManipulationImplementor.duplicateToTOS(functionMetadata, stackMetadata, instruction.arg()); StackManipulationImplementor.swap(methodVisitor); methodVisitor.visitMethodInsn(Opcodes.INVOKEINTERFACE, Type.getInternalName(Collection.class), "addAll", Type.getMethodDescriptor(Type.BOOLEAN_TYPE, Type.getType(Collection.class)), true); StackManipulationImplementor.popTOS(methodVisitor); // pop Collection.add return value } /** * Calls map.put(TOS1[i], TOS1, TOS). TOS1[i] remains on stack; TOS and TOS1 are popped. Used to implement map * comprehensions. */ public static void mapPut(FunctionMetadata functionMetadata, StackMetadata stackMetadata, PythonBytecodeInstruction instruction) { MethodVisitor methodVisitor = functionMetadata.methodVisitor; // instruction.arg is distance from TOS1, so add 1 to get distance from TOS StackManipulationImplementor.duplicateToTOS(functionMetadata, stackMetadata, instruction.arg() + 1); StackManipulationImplementor.rotateThree(methodVisitor); methodVisitor.visitMethodInsn(Opcodes.INVOKEINTERFACE, Type.getInternalName(Map.class), "put", Type.getMethodDescriptor(Type.getType(Object.class), Type.getType(Object.class), Type.getType(Object.class)), true); StackManipulationImplementor.popTOS(methodVisitor); // pop Map.put return value } /** * Calls map.putAll(TOS[i], TOS). TOS[i] remains on stack; TOS is popped. Used to build maps */ public static void mapPutAll(FunctionMetadata functionMetadata, StackMetadata stackMetadata, PythonBytecodeInstruction instruction) { MethodVisitor methodVisitor = functionMetadata.methodVisitor; // instruction.arg is distance from TOS StackManipulationImplementor.duplicateToTOS(functionMetadata, stackMetadata, instruction.arg()); StackManipulationImplementor.swap(methodVisitor); methodVisitor.visitMethodInsn(Opcodes.INVOKEINTERFACE, Type.getInternalName(Map.class), "putAll", Type.getMethodDescriptor(Type.VOID_TYPE, Type.getType(Map.class)), true); } /** * Calls map.putAll(TOS1[i], TOS) if TOS does not share any common keys with TOS[i]. * If TOS shares common keys with TOS[i], an exception is thrown. * TOS1[i] remains on stack; TOS is popped. Used to build maps */ public static void mapPutAllOnlyIfAllNewElseThrow(FunctionMetadata functionMetadata, StackMetadata stackMetadata, PythonBytecodeInstruction instruction) { MethodVisitor methodVisitor = functionMetadata.methodVisitor; // instruction.arg is distance from TOS StackManipulationImplementor.duplicateToTOS(functionMetadata, stackMetadata, instruction.arg()); StackManipulationImplementor.swap(methodVisitor); // Duplicate both maps so we can get their key sets StackManipulationImplementor.duplicateTOSAndTOS1(methodVisitor); methodVisitor.visitMethodInsn(Opcodes.INVOKEINTERFACE, Type.getInternalName(Map.class), "keySet", Type.getMethodDescriptor(Type.getType(Set.class)), true); StackManipulationImplementor.swap(methodVisitor); methodVisitor.visitMethodInsn(Opcodes.INVOKEINTERFACE, Type.getInternalName(Map.class), "keySet", Type.getMethodDescriptor(Type.getType(Set.class)), true); // Check if the two key sets are disjoints methodVisitor.visitMethodInsn(Opcodes.INVOKESTATIC, Type.getInternalName(Collections.class), "disjoint", Type.getMethodDescriptor(Type.BOOLEAN_TYPE, Type.getType(Collection.class), Type.getType(Collection.class)), false); Label performPutAllLabel = new Label(); methodVisitor.visitJumpInsn(Opcodes.IFNE, performPutAllLabel); // if result == 1 (i.e. true), do the putAll operation // else, throw a new exception methodVisitor.visitTypeInsn(Opcodes.NEW, Type.getInternalName(IllegalArgumentException.class)); methodVisitor.visitInsn(Opcodes.DUP); methodVisitor.visitMethodInsn(Opcodes.INVOKESPECIAL, Type.getInternalName(IllegalArgumentException.class), "<init>", Type.getMethodDescriptor(Type.VOID_TYPE), false); methodVisitor.visitInsn(Opcodes.ATHROW); methodVisitor.visitLabel(performPutAllLabel); methodVisitor.visitMethodInsn(Opcodes.INVOKEINTERFACE, Type.getInternalName(Map.class), "putAll", Type.getMethodDescriptor(Type.VOID_TYPE, Type.getType(Map.class)), true); } public static void buildSlice(FunctionMetadata functionMetadata, StackMetadata stackMetadata, int argCount) { MethodVisitor methodVisitor = functionMetadata.methodVisitor; LocalVariableHelper localVariableHelper = stackMetadata.localVariableHelper; if (argCount == 2) { // Push 1 as the third argument (step) methodVisitor.visitFieldInsn(Opcodes.GETSTATIC, Type.getInternalName(PythonInteger.class), "ONE", Type.getDescriptor(PythonInteger.class)); } else if (argCount == 3) { // do nothing; third argument already on stack } else { throw new IllegalArgumentException("arg for BUILD_SLICE must be 2 or 3"); } // Store step in temp variable (need to move slice down 2) int stepTemp = localVariableHelper.newLocal(); localVariableHelper.writeTemp(methodVisitor, Type.getType(PythonLikeObject.class), stepTemp); methodVisitor.visitTypeInsn(Opcodes.NEW, Type.getInternalName(PythonSlice.class)); methodVisitor.visitInsn(Opcodes.DUP_X2); methodVisitor.visitInsn(Opcodes.DUP_X2); methodVisitor.visitInsn(Opcodes.POP); // Restore step localVariableHelper.readTemp(methodVisitor, Type.getType(PythonLikeObject.class), stepTemp); localVariableHelper.freeLocal(); // Create the slice methodVisitor.visitMethodInsn(Opcodes.INVOKESPECIAL, Type.getInternalName(PythonSlice.class), "<init>", Type.getMethodDescriptor(Type.VOID_TYPE, Type.getType(PythonLikeObject.class), Type.getType(PythonLikeObject.class), Type.getType(PythonLikeObject.class)), false); } }
0
java-sources/ai/timefold/solver/jpyinterpreter/1.24.0/ai/timefold/jpyinterpreter
java-sources/ai/timefold/solver/jpyinterpreter/1.24.0/ai/timefold/jpyinterpreter/implementors/DelegatingInterfaceImplementor.java
package ai.timefold.jpyinterpreter.implementors; import java.lang.reflect.Field; import java.lang.reflect.Method; import java.lang.reflect.Modifier; import java.util.Collections; import java.util.IdentityHashMap; import java.util.List; import java.util.Map; import ai.timefold.jpyinterpreter.PythonBytecodeToJavaBytecodeTranslator; import ai.timefold.jpyinterpreter.PythonClassTranslator; import ai.timefold.jpyinterpreter.PythonCompiledClass; import ai.timefold.jpyinterpreter.PythonLikeObject; import ai.timefold.jpyinterpreter.types.errors.TypeError; import ai.timefold.jpyinterpreter.util.MethodVisitorAdapters; import ai.timefold.jpyinterpreter.util.arguments.ArgumentSpec; import org.objectweb.asm.ClassWriter; import org.objectweb.asm.MethodVisitor; import org.objectweb.asm.Opcodes; import org.objectweb.asm.Type; public class DelegatingInterfaceImplementor extends JavaInterfaceImplementor { final String internalClassName; final Class<?> interfaceClass; final Map<String, PythonClassTranslator.InterfaceDeclaration> methodNameToFieldDescriptor; public DelegatingInterfaceImplementor(String internalClassName, Class<?> interfaceClass, Map<String, PythonClassTranslator.InterfaceDeclaration> methodNameToFieldDescriptor) { this.internalClassName = internalClassName; this.interfaceClass = interfaceClass; this.methodNameToFieldDescriptor = methodNameToFieldDescriptor; } @Override public Class<?> getInterfaceClass() { return interfaceClass; } @Override public void implement(ClassWriter classWriter, PythonCompiledClass compiledClass) { for (Method method : interfaceClass.getMethods()) { if (!Modifier.isStatic(method.getModifiers()) && method.getDeclaringClass().isInterface()) { implementMethod(classWriter, compiledClass, method); } } } private void implementMethod(ClassWriter classWriter, PythonCompiledClass compiledClass, Method interfaceMethod) { if (!methodNameToFieldDescriptor.containsKey(interfaceMethod.getName())) { if (interfaceMethod.isDefault()) { return; } else { throw new TypeError("Class %s cannot implement interface %s because it does not implement method %s." .formatted(compiledClass.className, interfaceMethod.getDeclaringClass().getName(), interfaceMethod.getName())); } } var interfaceMethodDescriptor = Type.getMethodDescriptor(interfaceMethod); // Generates interfaceMethod(A a, B b, ...) { return delegate.interfaceMethod(a, b, ...); } var interfaceMethodVisitor = classWriter.visitMethod(Modifier.PUBLIC, interfaceMethod.getName(), interfaceMethodDescriptor, null, null); interfaceMethodVisitor = MethodVisitorAdapters.adapt(interfaceMethodVisitor, interfaceMethod.getName(), interfaceMethodDescriptor); for (var parameter : interfaceMethod.getParameters()) { interfaceMethodVisitor.visitParameter(parameter.getName(), 0); } interfaceMethodVisitor.visitCode(); interfaceMethodVisitor.visitVarInsn(Opcodes.ALOAD, 0); interfaceMethodVisitor.visitTypeInsn(Opcodes.NEW, Type.getInternalName(IdentityHashMap.class)); interfaceMethodVisitor.visitInsn(Opcodes.DUP); interfaceMethodVisitor.visitMethodInsn(Opcodes.INVOKESPECIAL, Type.getInternalName(IdentityHashMap.class), "<init>", Type.getMethodDescriptor(Type.VOID_TYPE), false); interfaceMethodVisitor.visitVarInsn(Opcodes.ASTORE, interfaceMethod.getParameterCount() + 1); // Generates TOS = MyClass.methodInstance.getClass().getField(ARGUMENT_SPEC_INSTANCE_FIELD).get(MyClass.methodInstance); var functionInterfaceDeclaration = methodNameToFieldDescriptor.get(interfaceMethod.getName()); interfaceMethodVisitor.visitVarInsn(Opcodes.ALOAD, 0); interfaceMethodVisitor.visitFieldInsn(Opcodes.GETSTATIC, internalClassName, PythonClassTranslator.getJavaMethodHolderName(interfaceMethod.getName()), functionInterfaceDeclaration.descriptor()); interfaceMethodVisitor.visitMethodInsn(Opcodes.INVOKEVIRTUAL, Type.getInternalName(Object.class), "getClass", Type.getMethodDescriptor(Type.getType(Class.class)), false); interfaceMethodVisitor.visitLdcInsn(PythonBytecodeToJavaBytecodeTranslator.ARGUMENT_SPEC_INSTANCE_FIELD_NAME); interfaceMethodVisitor.visitMethodInsn(Opcodes.INVOKEVIRTUAL, Type.getInternalName(Class.class), "getField", Type.getMethodDescriptor(Type.getType(Field.class), Type.getType(String.class)), false); interfaceMethodVisitor.visitFieldInsn(Opcodes.GETSTATIC, internalClassName, PythonClassTranslator.getJavaMethodHolderName(interfaceMethod.getName()), functionInterfaceDeclaration.descriptor()); interfaceMethodVisitor.visitMethodInsn(Opcodes.INVOKEVIRTUAL, Type.getInternalName(Field.class), "get", Type.getMethodDescriptor(Type.getType(Object.class), Type.getType(Object.class)), false); interfaceMethodVisitor.visitTypeInsn(Opcodes.CHECKCAST, Type.getInternalName(ArgumentSpec.class)); var methodType = functionInterfaceDeclaration.methodType(); int argumentCount = methodType.getArgumentCount(); prepareParametersForMethodCallFromArgumentSpec(interfaceMethod, interfaceMethodVisitor, argumentCount, methodType, true); Type[] javaParameterTypes = new Type[Math.max(0, argumentCount - 1)]; for (int i = 1; i < argumentCount; i++) { javaParameterTypes[i - 1] = methodType.getArgumentTypes()[i]; } var methodReturnType = PythonClassTranslator.getVirtualFunctionReturnType(compiledClass.instanceFunctionNameToPythonBytecode .get(interfaceMethod.getName())); String javaMethodDescriptor = Type.getMethodDescriptor(methodReturnType, javaParameterTypes); interfaceMethodVisitor.visitMethodInsn(Opcodes.INVOKEVIRTUAL, internalClassName, PythonClassTranslator.getJavaMethodName(interfaceMethod.getName()), javaMethodDescriptor, false); var returnType = interfaceMethod.getReturnType(); if (returnType.equals(void.class)) { interfaceMethodVisitor.visitInsn(Opcodes.RETURN); } else { if (returnType.isPrimitive()) { JavaPythonTypeConversionImplementor.loadTypeClass(returnType, interfaceMethodVisitor); } else { interfaceMethodVisitor.visitLdcInsn(Type.getType(returnType)); } interfaceMethodVisitor.visitInsn(Opcodes.SWAP); interfaceMethodVisitor.visitMethodInsn(Opcodes.INVOKESTATIC, Type.getInternalName(JavaPythonTypeConversionImplementor.class), "convertPythonObjectToJavaType", Type.getMethodDescriptor(Type.getType(Object.class), Type.getType(Class.class), Type.getType( PythonLikeObject.class)), false); if (returnType.isPrimitive()) { JavaPythonTypeConversionImplementor.unboxBoxedPrimitiveType(returnType, interfaceMethodVisitor); interfaceMethodVisitor.visitInsn(Type.getType(returnType).getOpcode(Opcodes.IRETURN)); } else { interfaceMethodVisitor.visitTypeInsn(Opcodes.CHECKCAST, Type.getInternalName(returnType)); interfaceMethodVisitor.visitInsn(Opcodes.ARETURN); } } interfaceMethodVisitor.visitMaxs(interfaceMethod.getParameterCount() + 2, 1); interfaceMethodVisitor.visitEnd(); } public static void prepareParametersForMethodCallFromArgumentSpec(Method interfaceMethod, MethodVisitor interfaceMethodVisitor, int argumentCount, Type methodType, boolean skipSelf) { int parameterStart = skipSelf ? 1 : 0; interfaceMethodVisitor.visitLdcInsn(interfaceMethod.getParameterCount()); interfaceMethodVisitor.visitTypeInsn(Opcodes.ANEWARRAY, Type.getInternalName(PythonLikeObject.class)); interfaceMethodVisitor.visitVarInsn(Opcodes.ASTORE, interfaceMethod.getParameterCount() + 2); for (int i = 0; i < interfaceMethod.getParameterCount(); i++) { var parameterType = interfaceMethod.getParameterTypes()[i]; interfaceMethodVisitor.visitVarInsn(Opcodes.ALOAD, interfaceMethod.getParameterCount() + 2); interfaceMethodVisitor.visitLdcInsn(i); interfaceMethodVisitor.visitVarInsn(Type.getType(parameterType).getOpcode(Opcodes.ILOAD), i + 1); if (parameterType.isPrimitive()) { JavaPythonTypeConversionImplementor.boxPrimitiveType(parameterType, interfaceMethodVisitor); } interfaceMethodVisitor.visitVarInsn(Opcodes.ALOAD, interfaceMethod.getParameterCount() + 1); interfaceMethodVisitor.visitMethodInsn(Opcodes.INVOKESTATIC, Type.getInternalName(JavaPythonTypeConversionImplementor.class), "wrapJavaObject", Type.getMethodDescriptor(Type.getType(PythonLikeObject.class), Type.getType(Object.class), Type.getType( Map.class)), false); interfaceMethodVisitor.visitInsn(Opcodes.AASTORE); } interfaceMethodVisitor.visitVarInsn(Opcodes.ALOAD, interfaceMethod.getParameterCount() + 2); interfaceMethodVisitor.visitMethodInsn(Opcodes.INVOKESTATIC, Type.getInternalName(List.class), "of", Type.getMethodDescriptor(Type.getType(List.class), Type.getType(Object[].class)), true); interfaceMethodVisitor.visitMethodInsn(Opcodes.INVOKESTATIC, Type.getInternalName(Collections.class), "emptyMap", Type.getMethodDescriptor(Type.getType(Map.class)), false); interfaceMethodVisitor.visitMethodInsn(Opcodes.INVOKEVIRTUAL, Type.getInternalName(ArgumentSpec.class), "extractArgumentList", Type.getMethodDescriptor( Type.getType(List.class), Type.getType(List.class), Type.getType(Map.class)), false); for (int i = 0; i < argumentCount - parameterStart; i++) { interfaceMethodVisitor.visitInsn(Opcodes.DUP); interfaceMethodVisitor.visitLdcInsn(i); interfaceMethodVisitor.visitMethodInsn(Opcodes.INVOKEINTERFACE, Type.getInternalName(List.class), "get", Type.getMethodDescriptor(Type.getType(Object.class), Type.INT_TYPE), true); interfaceMethodVisitor.visitTypeInsn(Opcodes.CHECKCAST, methodType.getArgumentTypes()[i + parameterStart].getInternalName()); interfaceMethodVisitor.visitInsn(Opcodes.SWAP); } interfaceMethodVisitor.visitInsn(Opcodes.POP); } }
0
java-sources/ai/timefold/solver/jpyinterpreter/1.24.0/ai/timefold/jpyinterpreter
java-sources/ai/timefold/solver/jpyinterpreter/1.24.0/ai/timefold/jpyinterpreter/implementors/DunderOperatorImplementor.java
package ai.timefold.jpyinterpreter.implementors; import java.util.Collections; import java.util.List; import java.util.Map; import java.util.Optional; import ai.timefold.jpyinterpreter.CompareOp; import ai.timefold.jpyinterpreter.FunctionMetadata; import ai.timefold.jpyinterpreter.LocalVariableHelper; import ai.timefold.jpyinterpreter.MethodDescriptor; import ai.timefold.jpyinterpreter.PythonBinaryOperator; import ai.timefold.jpyinterpreter.PythonFunctionSignature; import ai.timefold.jpyinterpreter.PythonLikeObject; import ai.timefold.jpyinterpreter.PythonTernaryOperator; import ai.timefold.jpyinterpreter.PythonUnaryOperator; import ai.timefold.jpyinterpreter.StackMetadata; import ai.timefold.jpyinterpreter.types.BuiltinTypes; import ai.timefold.jpyinterpreter.types.NotImplemented; import ai.timefold.jpyinterpreter.types.PythonKnownFunctionType; import ai.timefold.jpyinterpreter.types.PythonLikeFunction; import ai.timefold.jpyinterpreter.types.PythonLikeType; import ai.timefold.jpyinterpreter.types.PythonSlice; import ai.timefold.jpyinterpreter.types.collections.PythonLikeList; import ai.timefold.jpyinterpreter.types.errors.TypeError; import org.objectweb.asm.Label; import org.objectweb.asm.MethodVisitor; import org.objectweb.asm.Opcodes; import org.objectweb.asm.Type; /** * Implementations of opcodes that delegate to dunder/magic methods. */ public class DunderOperatorImplementor { public static void unaryOperator(MethodVisitor methodVisitor, StackMetadata stackMetadata, PythonUnaryOperator operator) { PythonLikeType operand = Optional.ofNullable(stackMetadata.getTOSType()).orElse(BuiltinTypes.BASE_TYPE); Optional<PythonKnownFunctionType> maybeKnownFunctionType = operand.getMethodType(operator.getDunderMethod()); if (maybeKnownFunctionType.isPresent()) { PythonKnownFunctionType knownFunctionType = maybeKnownFunctionType.get(); Optional<PythonFunctionSignature> maybeFunctionSignature = knownFunctionType.getFunctionForParameters(); if (maybeFunctionSignature.isPresent()) { PythonFunctionSignature functionSignature = maybeFunctionSignature.get(); MethodDescriptor methodDescriptor = functionSignature.getMethodDescriptor(); if (methodDescriptor.getParameterTypes().length < 1) { methodVisitor.visitTypeInsn(Opcodes.CHECKCAST, methodDescriptor.getDeclaringClassInternalName()); } else { methodVisitor.visitTypeInsn(Opcodes.CHECKCAST, methodDescriptor.getParameterTypes()[0].getInternalName()); } functionSignature.getMethodDescriptor().callMethod(methodVisitor); } else { unaryOperator(methodVisitor, operator); } } else { unaryOperator(methodVisitor, operator); } } /** * Performs a unary dunder operation on TOS. Generate codes that look like this: * * <pre> * BiFunction[List, Map, Result] operand_method = TOS.$getType().$getAttributeOrError(operator.getDunderMethod()); * List args = new ArrayList(1); * args.set(0) = TOS * pop TOS * TOS' = operand_method.apply(args, null) * </pre> * */ public static void unaryOperator(MethodVisitor methodVisitor, PythonUnaryOperator operator) { methodVisitor.visitInsn(Opcodes.DUP); methodVisitor.visitMethodInsn(Opcodes.INVOKEINTERFACE, Type.getInternalName(PythonLikeObject.class), "$getType", Type.getMethodDescriptor(Type.getType(PythonLikeType.class)), true); methodVisitor.visitLdcInsn(operator.getDunderMethod()); methodVisitor.visitMethodInsn(Opcodes.INVOKEINTERFACE, Type.getInternalName(PythonLikeObject.class), "$getAttributeOrError", Type.getMethodDescriptor(Type.getType(PythonLikeObject.class), Type.getType(String.class)), true); // Stack is now TOS, method methodVisitor.visitInsn(Opcodes.DUP_X1); methodVisitor.visitInsn(Opcodes.POP); // Stack is now method, TOS methodVisitor.visitTypeInsn(Opcodes.NEW, Type.getInternalName(PythonLikeList.class)); methodVisitor.visitInsn(Opcodes.DUP); methodVisitor.visitMethodInsn(Opcodes.INVOKESPECIAL, Type.getInternalName(PythonLikeList.class), "<init>", Type.getMethodDescriptor(Type.VOID_TYPE), false); // Stack is now method, TOS, argList pushArgumentIntoList(methodVisitor); // Stack is now method, argList methodVisitor.visitMethodInsn(Opcodes.INVOKESTATIC, Type.getInternalName(Collections.class), "emptyMap", Type.getMethodDescriptor(Type.getType(Map.class)), false); methodVisitor.visitInsn(Opcodes.ACONST_NULL); methodVisitor.visitMethodInsn(Opcodes.INVOKEINTERFACE, Type.getInternalName(PythonLikeFunction.class), "$call", Type.getMethodDescriptor(Type.getType(PythonLikeObject.class), Type.getType(List.class), Type.getType(Map.class), Type.getType(PythonLikeObject.class)), true); } public static void binaryOperator(MethodVisitor methodVisitor, StackMetadata stackMetadata, PythonBinaryOperator operator) { binaryOperator(methodVisitor, stackMetadata, operator, true, true, false); } private static void binaryOperator(MethodVisitor methodVisitor, StackMetadata stackMetadata, PythonBinaryOperator operator, boolean isLeft, boolean leftCheckSuccessful, boolean forceFallback) { PythonLikeType leftOperand = Optional.ofNullable(stackMetadata.getTypeAtStackIndex(1)).orElse(BuiltinTypes.BASE_TYPE); PythonLikeType rightOperand = Optional.ofNullable(stackMetadata.getTypeAtStackIndex(0)).orElse(BuiltinTypes.BASE_TYPE); PythonBinaryOperator actualOperator = operator; if (forceFallback || (!isLeft && operator.getFallbackOperation().isPresent())) { actualOperator = operator.getFallbackOperation().get(); } Optional<PythonKnownFunctionType> maybeKnownFunctionType = isLeft ? leftOperand.getMethodType(actualOperator.getDunderMethod()) : rightOperand.getMethodType(actualOperator.getRightDunderMethod()); if (maybeKnownFunctionType.isEmpty() && operator.getFallbackOperation().isPresent()) { maybeKnownFunctionType = isLeft ? leftOperand.getMethodType(operator.getFallbackOperation().get().getDunderMethod()) : rightOperand.getMethodType(operator.getFallbackOperation().get().getRightDunderMethod()); actualOperator = operator.getFallbackOperation().get(); } if (maybeKnownFunctionType.isPresent()) { PythonKnownFunctionType knownFunctionType = maybeKnownFunctionType.get(); Optional<PythonFunctionSignature> maybeFunctionSignature = isLeft ? knownFunctionType.getFunctionForParameters(rightOperand) : knownFunctionType.getFunctionForParameters(leftOperand); if (maybeFunctionSignature.isPresent()) { PythonFunctionSignature functionSignature = maybeFunctionSignature.get(); MethodDescriptor methodDescriptor = functionSignature.getMethodDescriptor(); boolean needToCheckForNotImplemented = (actualOperator.hasRightDunderMethod() || actualOperator.getFallbackOperation().isPresent()) && BuiltinTypes.NOT_IMPLEMENTED_TYPE.isSubclassOf(functionSignature.getReturnType()); if (isLeft) { if (methodDescriptor.getParameterTypes().length < 2) { methodVisitor.visitInsn(Opcodes.SWAP); methodVisitor.visitTypeInsn(Opcodes.CHECKCAST, methodDescriptor.getDeclaringClassInternalName()); methodVisitor.visitInsn(Opcodes.SWAP); methodVisitor.visitTypeInsn(Opcodes.CHECKCAST, methodDescriptor.getParameterTypes()[0].getInternalName()); } else { methodVisitor.visitInsn(Opcodes.SWAP); methodVisitor.visitTypeInsn(Opcodes.CHECKCAST, methodDescriptor.getParameterTypes()[0].getInternalName()); methodVisitor.visitInsn(Opcodes.SWAP); methodVisitor.visitTypeInsn(Opcodes.CHECKCAST, methodDescriptor.getParameterTypes()[1].getInternalName()); } } else { if (methodDescriptor.getParameterTypes().length < 2) { methodVisitor.visitInsn(Opcodes.SWAP); methodVisitor.visitTypeInsn(Opcodes.CHECKCAST, methodDescriptor.getParameterTypes()[0].getInternalName()); methodVisitor.visitInsn(Opcodes.SWAP); methodVisitor.visitTypeInsn(Opcodes.CHECKCAST, methodDescriptor.getDeclaringClassInternalName()); } else { methodVisitor.visitInsn(Opcodes.SWAP); methodVisitor.visitTypeInsn(Opcodes.CHECKCAST, methodDescriptor.getParameterTypes()[1].getInternalName()); methodVisitor.visitInsn(Opcodes.SWAP); methodVisitor.visitTypeInsn(Opcodes.CHECKCAST, methodDescriptor.getParameterTypes()[0].getInternalName()); } } if (needToCheckForNotImplemented) { methodVisitor.visitInsn(Opcodes.DUP2); } if (!isLeft) { methodVisitor.visitInsn(Opcodes.SWAP); } functionSignature.getMethodDescriptor().callMethod(methodVisitor); if (needToCheckForNotImplemented) { methodVisitor.visitInsn(Opcodes.DUP); methodVisitor.visitFieldInsn(Opcodes.GETSTATIC, Type.getInternalName(NotImplemented.class), "INSTANCE", Type.getDescriptor(NotImplemented.class)); Label ifNotImplemented = new Label(); Label done = new Label(); methodVisitor.visitJumpInsn(Opcodes.IF_ACMPEQ, ifNotImplemented); methodVisitor.visitInsn(Opcodes.DUP_X2); methodVisitor.visitInsn(Opcodes.POP); methodVisitor.visitInsn(Opcodes.POP2); methodVisitor.visitJumpInsn(Opcodes.GOTO, done); methodVisitor.visitLabel(ifNotImplemented); if (isLeft) { methodVisitor.visitInsn(Opcodes.POP); if (actualOperator.getFallbackOperation().isPresent()) { binaryOperator(methodVisitor, stackMetadata, operator, true, true, true); } else { binaryOperator(methodVisitor, stackMetadata, operator, false, true, false); } } else { methodVisitor.visitInsn(Opcodes.POP); raiseUnsupportedType(methodVisitor, stackMetadata.localVariableHelper, operator); } methodVisitor.visitLabel(done); } } else if (isLeft && actualOperator.hasRightDunderMethod()) { binaryOperator(methodVisitor, stackMetadata, operator, false, false, false); } else if (!isLeft && leftCheckSuccessful) { binaryOperatorOnlyRight(methodVisitor, stackMetadata.localVariableHelper, actualOperator); } else { binaryOperator(methodVisitor, stackMetadata.localVariableHelper, operator); } } else if (isLeft && actualOperator.hasRightDunderMethod()) { binaryOperator(methodVisitor, stackMetadata, operator, false, false, false); } else if (!isLeft && leftCheckSuccessful) { binaryOperatorOnlyRight(methodVisitor, stackMetadata.localVariableHelper, actualOperator); } else { binaryOperator(methodVisitor, stackMetadata.localVariableHelper, operator); } } private static void raiseUnsupportedType(MethodVisitor methodVisitor, LocalVariableHelper localVariableHelper, PythonBinaryOperator operator) { int right = localVariableHelper.newLocal(); int left = localVariableHelper.newLocal(); localVariableHelper.writeTemp(methodVisitor, Type.getType(PythonLikeObject.class), left); localVariableHelper.writeTemp(methodVisitor, Type.getType(PythonLikeObject.class), right); methodVisitor.visitTypeInsn(Opcodes.NEW, Type.getInternalName(TypeError.class)); methodVisitor.visitInsn(Opcodes.DUP); methodVisitor.visitTypeInsn(Opcodes.NEW, Type.getInternalName(StringBuilder.class)); methodVisitor.visitInsn(Opcodes.DUP); methodVisitor.visitMethodInsn(Opcodes.INVOKESPECIAL, Type.getInternalName(StringBuilder.class), "<init>", Type.getMethodDescriptor(Type.VOID_TYPE), false); if (!operator.getOperatorSymbol().isEmpty()) { methodVisitor.visitLdcInsn("unsupported operand type(s) for " + operator.getOperatorSymbol() + ": '"); methodVisitor.visitMethodInsn(Opcodes.INVOKEVIRTUAL, Type.getInternalName(StringBuilder.class), "append", Type.getMethodDescriptor(Type.getType(StringBuilder.class), Type.getType(String.class)), false); localVariableHelper.readTemp(methodVisitor, Type.getType(PythonLikeObject.class), left); methodVisitor.visitMethodInsn(Opcodes.INVOKEINTERFACE, Type.getInternalName(PythonLikeObject.class), "$getType", Type.getMethodDescriptor(Type.getType(PythonLikeType.class)), true); methodVisitor.visitMethodInsn(Opcodes.INVOKEVIRTUAL, Type.getInternalName(PythonLikeType.class), "getTypeName", Type.getMethodDescriptor(Type.getType(String.class)), false); methodVisitor.visitMethodInsn(Opcodes.INVOKEVIRTUAL, Type.getInternalName(StringBuilder.class), "append", Type.getMethodDescriptor(Type.getType(StringBuilder.class), Type.getType(String.class)), false); methodVisitor.visitLdcInsn("' and '"); methodVisitor.visitMethodInsn(Opcodes.INVOKEVIRTUAL, Type.getInternalName(StringBuilder.class), "append", Type.getMethodDescriptor(Type.getType(StringBuilder.class), Type.getType(String.class)), false); localVariableHelper.readTemp(methodVisitor, Type.getType(PythonLikeObject.class), right); methodVisitor.visitMethodInsn(Opcodes.INVOKEINTERFACE, Type.getInternalName(PythonLikeObject.class), "$getType", Type.getMethodDescriptor(Type.getType(PythonLikeType.class)), true); methodVisitor.visitMethodInsn(Opcodes.INVOKEVIRTUAL, Type.getInternalName(PythonLikeType.class), "getTypeName", Type.getMethodDescriptor(Type.getType(String.class)), false); methodVisitor.visitMethodInsn(Opcodes.INVOKEVIRTUAL, Type.getInternalName(StringBuilder.class), "append", Type.getMethodDescriptor(Type.getType(StringBuilder.class), Type.getType(String.class)), false); methodVisitor.visitLdcInsn("'"); methodVisitor.visitMethodInsn(Opcodes.INVOKEVIRTUAL, Type.getInternalName(StringBuilder.class), "append", Type.getMethodDescriptor(Type.getType(StringBuilder.class), Type.getType(String.class)), false); methodVisitor.visitMethodInsn(Opcodes.INVOKEVIRTUAL, Type.getInternalName(StringBuilder.class), "toString", Type.getMethodDescriptor(Type.getType(String.class)), false); localVariableHelper.freeLocal(); localVariableHelper.freeLocal(); methodVisitor.visitMethodInsn(Opcodes.INVOKESPECIAL, Type.getInternalName(TypeError.class), "<init>", Type.getMethodDescriptor(Type.VOID_TYPE, Type.getType(String.class)), false); methodVisitor.visitInsn(Opcodes.ATHROW); } else { localVariableHelper.freeLocal(); localVariableHelper.freeLocal(); switch (operator) { case GET_ITEM: // TODO: Error message default: methodVisitor.visitInsn(Opcodes.POP); methodVisitor.visitMethodInsn(Opcodes.INVOKESPECIAL, Type.getInternalName(TypeError.class), "<init>", Type.getMethodDescriptor(Type.VOID_TYPE), false); methodVisitor.visitInsn(Opcodes.ATHROW); } } } /** * Performs a binary dunder operation on TOS and TOS1. Generate codes that look like this: * * <pre> * BiFunction[List, Map, Result] operand_method = TOS1.$getType().$getAttributeOrError(operator.getDunderMethod()); * List args = new ArrayList(2); * args.set(0) = TOS1 * args.set(1) = TOS * pop TOS, TOS1 * TOS' = operand_method.apply(args, null) * </pre> * */ public static void binaryOperator(MethodVisitor methodVisitor, LocalVariableHelper localVariableHelper, PythonBinaryOperator operator) { Label noLeftMethod = new Label(); methodVisitor.visitInsn(Opcodes.DUP2); if (operator.hasRightDunderMethod() || operator.getFallbackOperation().isPresent()) { methodVisitor.visitInsn(Opcodes.DUP2); } methodVisitor.visitInsn(Opcodes.SWAP); // Stack is now (TOS1, TOS,)? TOS, TOS1 methodVisitor.visitInsn(Opcodes.DUP); methodVisitor.visitMethodInsn(Opcodes.INVOKEINTERFACE, Type.getInternalName(PythonLikeObject.class), "$getType", Type.getMethodDescriptor(Type.getType(PythonLikeType.class)), true); methodVisitor.visitLdcInsn(operator.getDunderMethod()); methodVisitor.visitMethodInsn(Opcodes.INVOKEINTERFACE, Type.getInternalName(PythonLikeObject.class), "$getAttributeOrNull", Type.getMethodDescriptor(Type.getType(PythonLikeObject.class), Type.getType(String.class)), true); methodVisitor.visitInsn(Opcodes.DUP); methodVisitor.visitInsn(Opcodes.ACONST_NULL); methodVisitor.visitJumpInsn(Opcodes.IF_ACMPEQ, noLeftMethod); // Stack is now(TOS1, TOS,)? TOS, TOS1, method methodVisitor.visitInsn(Opcodes.DUP_X2); methodVisitor.visitInsn(Opcodes.POP); // Stack is now (TOS1, TOS,)? method, TOS, TOS1 methodVisitor.visitTypeInsn(Opcodes.NEW, Type.getInternalName(PythonLikeList.class)); methodVisitor.visitInsn(Opcodes.DUP); methodVisitor.visitMethodInsn(Opcodes.INVOKESPECIAL, Type.getInternalName(PythonLikeList.class), "<init>", Type.getMethodDescriptor(Type.VOID_TYPE), false); // Stack is now (TOS1, TOS,)? method, TOS, TOS1, argList pushArgumentIntoList(methodVisitor); pushArgumentIntoList(methodVisitor); // Stack is now (TOS1, TOS,)? method, argList methodVisitor.visitMethodInsn(Opcodes.INVOKESTATIC, Type.getInternalName(Collections.class), "emptyMap", Type.getMethodDescriptor(Type.getType(Map.class)), false); methodVisitor.visitInsn(Opcodes.ACONST_NULL); methodVisitor.visitMethodInsn(Opcodes.INVOKEINTERFACE, Type.getInternalName(PythonLikeFunction.class), "$call", Type.getMethodDescriptor(Type.getType(PythonLikeObject.class), Type.getType(List.class), Type.getType(Map.class), Type.getType(PythonLikeObject.class)), true); // Stack is now (TOS1, TOS,)? method_result methodVisitor.visitInsn(Opcodes.DUP); methodVisitor.visitFieldInsn(Opcodes.GETSTATIC, Type.getInternalName(NotImplemented.class), "INSTANCE", Type.getDescriptor(NotImplemented.class)); Label ifNotImplemented = new Label(); Label done = new Label(); methodVisitor.visitJumpInsn(Opcodes.IF_ACMPEQ, ifNotImplemented); // Stack is TOS1, TOS, method_result if (operator.hasRightDunderMethod() || operator.getFallbackOperation().isPresent()) { methodVisitor.visitInsn(Opcodes.DUP_X2); methodVisitor.visitInsn(Opcodes.POP); methodVisitor.visitInsn(Opcodes.POP2); } // Stack is method_result methodVisitor.visitJumpInsn(Opcodes.GOTO, done); methodVisitor.visitLabel(noLeftMethod); methodVisitor.visitInsn(Opcodes.POP2); methodVisitor.visitLabel(ifNotImplemented); methodVisitor.visitInsn(Opcodes.POP); Label raiseError = new Label(); if (operator.getFallbackOperation().isPresent()) { binaryOperator(methodVisitor, localVariableHelper, operator.getFallbackOperation().get()); methodVisitor.visitJumpInsn(Opcodes.GOTO, done); } else if (operator.hasRightDunderMethod()) { Label noRightMethod = new Label(); // Stack is now TOS1, TOS methodVisitor.visitInsn(Opcodes.DUP); methodVisitor.visitMethodInsn(Opcodes.INVOKEINTERFACE, Type.getInternalName(PythonLikeObject.class), "$getType", Type.getMethodDescriptor(Type.getType(PythonLikeType.class)), true); methodVisitor.visitLdcInsn(operator.getRightDunderMethod()); methodVisitor.visitMethodInsn(Opcodes.INVOKEINTERFACE, Type.getInternalName(PythonLikeObject.class), "$getAttributeOrNull", Type.getMethodDescriptor(Type.getType(PythonLikeObject.class), Type.getType(String.class)), true); methodVisitor.visitInsn(Opcodes.DUP); methodVisitor.visitInsn(Opcodes.ACONST_NULL); methodVisitor.visitJumpInsn(Opcodes.IF_ACMPEQ, noRightMethod); // Stack is now TOS1, TOS, method methodVisitor.visitInsn(Opcodes.DUP_X2); methodVisitor.visitInsn(Opcodes.POP); // Stack is now method, TOS1, TOS methodVisitor.visitTypeInsn(Opcodes.NEW, Type.getInternalName(PythonLikeList.class)); methodVisitor.visitInsn(Opcodes.DUP); methodVisitor.visitMethodInsn(Opcodes.INVOKESPECIAL, Type.getInternalName(PythonLikeList.class), "<init>", Type.getMethodDescriptor(Type.VOID_TYPE), false); // Stack is now method, TOS1, TOS, argList pushArgumentIntoList(methodVisitor); pushArgumentIntoList(methodVisitor); // Stack is now method, argList methodVisitor.visitMethodInsn(Opcodes.INVOKESTATIC, Type.getInternalName(Collections.class), "emptyMap", Type.getMethodDescriptor(Type.getType(Map.class)), false); methodVisitor.visitInsn(Opcodes.ACONST_NULL); methodVisitor.visitMethodInsn(Opcodes.INVOKEINTERFACE, Type.getInternalName(PythonLikeFunction.class), "$call", Type.getMethodDescriptor(Type.getType(PythonLikeObject.class), Type.getType(List.class), Type.getType(Map.class), Type.getType(PythonLikeObject.class)), true); // Stack is now method_result methodVisitor.visitInsn(Opcodes.DUP); methodVisitor.visitFieldInsn(Opcodes.GETSTATIC, Type.getInternalName(NotImplemented.class), "INSTANCE", Type.getDescriptor(NotImplemented.class)); methodVisitor.visitJumpInsn(Opcodes.IF_ACMPNE, done); // Stack is TOS1, TOS, NotImplemented methodVisitor.visitInsn(Opcodes.POP); methodVisitor.visitJumpInsn(Opcodes.GOTO, raiseError); methodVisitor.visitLabel(noRightMethod); methodVisitor.visitInsn(Opcodes.POP); methodVisitor.visitInsn(Opcodes.POP2); } methodVisitor.visitLabel(raiseError); methodVisitor.visitInsn(Opcodes.SWAP); raiseUnsupportedType(methodVisitor, localVariableHelper, operator); methodVisitor.visitLabel(done); methodVisitor.visitInsn(Opcodes.DUP_X2); methodVisitor.visitInsn(Opcodes.POP); methodVisitor.visitInsn(Opcodes.POP2); } public static void binaryOperatorOnlyRight(MethodVisitor methodVisitor, LocalVariableHelper localVariableHelper, PythonBinaryOperator operator) { Label done = new Label(); Label raiseError = new Label(); Label noRightMethod = new Label(); methodVisitor.visitInsn(Opcodes.DUP2); // Stack is now TOS1, TOS methodVisitor.visitInsn(Opcodes.DUP); methodVisitor.visitMethodInsn(Opcodes.INVOKEINTERFACE, Type.getInternalName(PythonLikeObject.class), "$getType", Type.getMethodDescriptor(Type.getType(PythonLikeType.class)), true); methodVisitor.visitLdcInsn(operator.getRightDunderMethod()); methodVisitor.visitMethodInsn(Opcodes.INVOKEINTERFACE, Type.getInternalName(PythonLikeObject.class), "$getAttributeOrNull", Type.getMethodDescriptor(Type.getType(PythonLikeObject.class), Type.getType(String.class)), true); methodVisitor.visitInsn(Opcodes.DUP); methodVisitor.visitInsn(Opcodes.ACONST_NULL); methodVisitor.visitJumpInsn(Opcodes.IF_ACMPEQ, noRightMethod); // Stack is now TOS1, TOS, method methodVisitor.visitInsn(Opcodes.DUP_X2); methodVisitor.visitInsn(Opcodes.POP); // Stack is now method, TOS1, TOS methodVisitor.visitTypeInsn(Opcodes.NEW, Type.getInternalName(PythonLikeList.class)); methodVisitor.visitInsn(Opcodes.DUP); methodVisitor.visitMethodInsn(Opcodes.INVOKESPECIAL, Type.getInternalName(PythonLikeList.class), "<init>", Type.getMethodDescriptor(Type.VOID_TYPE), false); // Stack is now method, TOS1, TOS, argList pushArgumentIntoList(methodVisitor); pushArgumentIntoList(methodVisitor); // Stack is now method, argList methodVisitor.visitMethodInsn(Opcodes.INVOKESTATIC, Type.getInternalName(Collections.class), "emptyMap", Type.getMethodDescriptor(Type.getType(Map.class)), false); methodVisitor.visitInsn(Opcodes.ACONST_NULL); methodVisitor.visitMethodInsn(Opcodes.INVOKEINTERFACE, Type.getInternalName(PythonLikeFunction.class), "$call", Type.getMethodDescriptor(Type.getType(PythonLikeObject.class), Type.getType(List.class), Type.getType(Map.class), Type.getType(PythonLikeObject.class)), true); // Stack is now method_result methodVisitor.visitInsn(Opcodes.DUP); methodVisitor.visitFieldInsn(Opcodes.GETSTATIC, Type.getInternalName(NotImplemented.class), "INSTANCE", Type.getDescriptor(NotImplemented.class)); methodVisitor.visitJumpInsn(Opcodes.IF_ACMPNE, done); // Stack is TOS1, TOS, NotImplemented methodVisitor.visitInsn(Opcodes.POP); methodVisitor.visitJumpInsn(Opcodes.GOTO, raiseError); methodVisitor.visitLabel(noRightMethod); methodVisitor.visitInsn(Opcodes.POP); methodVisitor.visitInsn(Opcodes.POP2); methodVisitor.visitLabel(raiseError); methodVisitor.visitInsn(Opcodes.SWAP); raiseUnsupportedType(methodVisitor, localVariableHelper, operator); methodVisitor.visitLabel(done); methodVisitor.visitInsn(Opcodes.DUP_X2); methodVisitor.visitInsn(Opcodes.POP); methodVisitor.visitInsn(Opcodes.POP2); } /** * Performs a ternary dunder operation on TOS, TOS1 and TOS2. Generate codes that look like this: * * <pre> * BiFunction[List, Map, Result] operand_method = TOS2.$getType().$getAttributeOrError(operator.getDunderMethod()); * List args = new ArrayList(2); * args.set(0) = TOS2 * args.set(1) = TOS1 * args.set(2) = TOS * pop TOS, TOS1, TOS2 * TOS' = operand_method.apply(args, null) * </pre> * */ public static void ternaryOperator(FunctionMetadata functionMetadata, StackMetadata stackMetadata, PythonTernaryOperator operator) { MethodVisitor methodVisitor = functionMetadata.methodVisitor; StackManipulationImplementor.rotateThree(methodVisitor); methodVisitor.visitInsn(Opcodes.SWAP); // Stack is now TOS, TOS1, TOS2 methodVisitor.visitInsn(Opcodes.DUP); methodVisitor.visitMethodInsn(Opcodes.INVOKEINTERFACE, Type.getInternalName(PythonLikeObject.class), "$getType", Type.getMethodDescriptor(Type.getType(PythonLikeType.class)), true); methodVisitor.visitLdcInsn(operator.getDunderMethod()); methodVisitor.visitMethodInsn(Opcodes.INVOKEINTERFACE, Type.getInternalName(PythonLikeObject.class), "$getAttributeOrError", Type.getMethodDescriptor(Type.getType(PythonLikeObject.class), Type.getType(String.class)), true); // Stack is now TOS, TOS1, TOS2, method StackManipulationImplementor.rotateFour(functionMetadata, stackMetadata.pop(3) .push(stackMetadata.getValueSourceForStackIndex(0)) .push(stackMetadata.getValueSourceForStackIndex(1)) .push(stackMetadata.getValueSourceForStackIndex(2)) .pushTemp(BuiltinTypes.FUNCTION_TYPE)); // Stack is now method, TOS, TOS1, TOS2 methodVisitor.visitTypeInsn(Opcodes.NEW, Type.getInternalName(PythonLikeList.class)); methodVisitor.visitInsn(Opcodes.DUP); methodVisitor.visitMethodInsn(Opcodes.INVOKESPECIAL, Type.getInternalName(PythonLikeList.class), "<init>", Type.getMethodDescriptor(Type.VOID_TYPE), false); // Stack is now method, TOS, TOS1, TOS2, argList pushArgumentIntoList(methodVisitor); pushArgumentIntoList(methodVisitor); pushArgumentIntoList(methodVisitor); // Stack is now method, argList methodVisitor.visitMethodInsn(Opcodes.INVOKESTATIC, Type.getInternalName(Collections.class), "emptyMap", Type.getMethodDescriptor(Type.getType(Map.class)), false); methodVisitor.visitInsn(Opcodes.ACONST_NULL); methodVisitor.visitMethodInsn(Opcodes.INVOKEINTERFACE, Type.getInternalName(PythonLikeFunction.class), "$call", Type.getMethodDescriptor(Type.getType(PythonLikeObject.class), Type.getType(List.class), Type.getType(Map.class), Type.getType(PythonLikeObject.class)), true); } /** * TOS is a list and TOS1 is an argument. Pushes TOS1 into TOS, and leave TOS on the stack (pops TOS1). */ private static void pushArgumentIntoList(MethodVisitor methodVisitor) { methodVisitor.visitInsn(Opcodes.DUP_X1); methodVisitor.visitInsn(Opcodes.SWAP); methodVisitor.visitMethodInsn(Opcodes.INVOKEINTERFACE, Type.getInternalName(List.class), "add", Type.getMethodDescriptor(Type.BOOLEAN_TYPE, Type.getType(Object.class)), true); methodVisitor.visitInsn(Opcodes.POP); } /** * Compares TOS and TOS1 via their dunder methods. {@code CompareOp} indicates the operation * to perform. */ public static void compareValues(MethodVisitor methodVisitor, StackMetadata stackMetadata, CompareOp op) { switch (op) { case LESS_THAN: binaryOperator(methodVisitor, stackMetadata, PythonBinaryOperator.LESS_THAN); break; case LESS_THAN_OR_EQUALS: binaryOperator(methodVisitor, stackMetadata, PythonBinaryOperator.LESS_THAN_OR_EQUAL); break; case EQUALS: case NOT_EQUALS: binaryOpOverridingLeftIfSpecific(methodVisitor, stackMetadata, op); break; case GREATER_THAN: binaryOperator(methodVisitor, stackMetadata, PythonBinaryOperator.GREATER_THAN); break; case GREATER_THAN_OR_EQUALS: binaryOperator(methodVisitor, stackMetadata, PythonBinaryOperator.GREATER_THAN_OR_EQUAL); break; default: throw new IllegalStateException("Unhandled branch: " + op); } } private static void binaryOpOverridingLeftIfSpecific(MethodVisitor methodVisitor, StackMetadata stackMetadata, CompareOp op) { switch (op) { case EQUALS: case NOT_EQUALS: break; default: throw new IllegalArgumentException("Should only be called for equals and not equals"); } PythonBinaryOperator operator = (op == CompareOp.EQUALS) ? PythonBinaryOperator.EQUAL : PythonBinaryOperator.NOT_EQUAL; // If we know TOS1 defines == or !=, we don't need to go here if (stackMetadata.getTypeAtStackIndex(1).getDefiningTypeOrNull(operator.getDunderMethod()) != BuiltinTypes.BASE_TYPE) { binaryOperator(methodVisitor, stackMetadata, operator); return; } methodVisitor.visitInsn(Opcodes.SWAP); methodVisitor.visitInsn(Opcodes.DUP_X1); methodVisitor.visitMethodInsn(Opcodes.INVOKEINTERFACE, Type.getInternalName(PythonLikeObject.class), "$getType", Type.getMethodDescriptor(Type.getType(PythonLikeType.class)), true); methodVisitor.visitLdcInsn(operator.getDunderMethod()); methodVisitor.visitMethodInsn(Opcodes.INVOKEVIRTUAL, Type.getInternalName(PythonLikeType.class), "getDefiningTypeOrNull", Type.getMethodDescriptor(Type.getType(PythonLikeType.class), Type.getType(String.class)), false); methodVisitor.visitFieldInsn(Opcodes.GETSTATIC, Type.getInternalName(BuiltinTypes.class), "BASE_TYPE", Type.getDescriptor(PythonLikeType.class)); Label ifDefined = new Label(); methodVisitor.visitJumpInsn(Opcodes.IF_ACMPNE, ifDefined); methodVisitor.visitInsn(Opcodes.SWAP); methodVisitor.visitLabel(ifDefined); binaryOperator(methodVisitor, stackMetadata.localVariableHelper, operator); } public static void getSlice(FunctionMetadata functionMetadata, StackMetadata stackMetadata) { // stack: ..., collection, start, end var methodVisitor = functionMetadata.methodVisitor; methodVisitor.visitTypeInsn(Opcodes.NEW, Type.getInternalName(PythonSlice.class)); methodVisitor.visitInsn(Opcodes.DUP_X2); methodVisitor.visitInsn(Opcodes.DUP_X2); methodVisitor.visitInsn(Opcodes.POP); methodVisitor.visitInsn(Opcodes.ACONST_NULL); // stack: ..., collection, <uninit slice>, <uninit slice>, start, end, null methodVisitor.visitMethodInsn(Opcodes.INVOKESPECIAL, Type.getInternalName(PythonSlice.class), "<init>", Type.getMethodDescriptor(Type.VOID_TYPE, Type.getType(PythonLikeObject.class), Type.getType(PythonLikeObject.class), Type.getType(PythonLikeObject.class)), false); // stack: ..., collection, slice DunderOperatorImplementor.binaryOperator(methodVisitor, stackMetadata .pop(3).pushTemps(stackMetadata.getTypeAtStackIndex(2), BuiltinTypes.SLICE_TYPE), PythonBinaryOperator.GET_ITEM); } public static void storeSlice(FunctionMetadata functionMetadata, StackMetadata stackMetadata) { // stack: ..., values, collection, start, end var methodVisitor = functionMetadata.methodVisitor; methodVisitor.visitTypeInsn(Opcodes.NEW, Type.getInternalName(PythonSlice.class)); methodVisitor.visitInsn(Opcodes.DUP_X2); methodVisitor.visitInsn(Opcodes.DUP_X2); methodVisitor.visitInsn(Opcodes.POP); methodVisitor.visitInsn(Opcodes.ACONST_NULL); // stack: ..., values, collection, <uninit slice>, <uninit slice>, start, end, null methodVisitor.visitMethodInsn(Opcodes.INVOKESPECIAL, Type.getInternalName(PythonSlice.class), "<init>", Type.getMethodDescriptor(Type.VOID_TYPE, Type.getType(PythonLikeObject.class), Type.getType(PythonLikeObject.class), Type.getType(PythonLikeObject.class)), false); // stack: ..., values, collection, slice methodVisitor.visitInsn(Opcodes.DUP_X2); methodVisitor.visitInsn(Opcodes.POP); // stack: ..., slice, values, collection methodVisitor.visitInsn(Opcodes.DUP_X2); methodVisitor.visitInsn(Opcodes.POP); // stack: ..., collection, slice, values DunderOperatorImplementor.ternaryOperator(functionMetadata, stackMetadata .pop(4).pushTemps(stackMetadata.getTypeAtStackIndex(2), BuiltinTypes.SLICE_TYPE, stackMetadata.getTypeAtStackIndex(3)), PythonTernaryOperator.SET_ITEM); methodVisitor.visitInsn(Opcodes.POP); } }
0
java-sources/ai/timefold/solver/jpyinterpreter/1.24.0/ai/timefold/jpyinterpreter
java-sources/ai/timefold/solver/jpyinterpreter/1.24.0/ai/timefold/jpyinterpreter/implementors/ExceptionImplementor.java
package ai.timefold.jpyinterpreter.implementors; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.List; import java.util.Map; import java.util.function.BiConsumer; import ai.timefold.jpyinterpreter.ExceptionBlock; import ai.timefold.jpyinterpreter.FunctionMetadata; import ai.timefold.jpyinterpreter.LocalVariableHelper; import ai.timefold.jpyinterpreter.PythonBytecodeInstruction; import ai.timefold.jpyinterpreter.PythonBytecodeToJavaBytecodeTranslator; import ai.timefold.jpyinterpreter.PythonInterpreter; import ai.timefold.jpyinterpreter.PythonLikeObject; import ai.timefold.jpyinterpreter.PythonUnaryOperator; import ai.timefold.jpyinterpreter.PythonVersion; import ai.timefold.jpyinterpreter.StackMetadata; import ai.timefold.jpyinterpreter.ValueSourceInfo; import ai.timefold.jpyinterpreter.opcodes.OpcodeWithoutSource; import ai.timefold.jpyinterpreter.opcodes.descriptor.ControlOpDescriptor; import ai.timefold.jpyinterpreter.types.BoundPythonLikeFunction; import ai.timefold.jpyinterpreter.types.PythonLikeFunction; import ai.timefold.jpyinterpreter.types.PythonLikeType; import ai.timefold.jpyinterpreter.types.collections.PythonLikeTuple; import ai.timefold.jpyinterpreter.types.errors.PythonAssertionError; import ai.timefold.jpyinterpreter.types.errors.PythonBaseException; import ai.timefold.jpyinterpreter.types.errors.PythonTraceback; import ai.timefold.jpyinterpreter.types.errors.StopIteration; import ai.timefold.jpyinterpreter.types.numeric.PythonBoolean; import ai.timefold.jpyinterpreter.types.numeric.PythonInteger; import org.objectweb.asm.Label; import org.objectweb.asm.MethodVisitor; import org.objectweb.asm.Opcodes; import org.objectweb.asm.Type; /** * Implementations of opcodes related to exceptions */ public class ExceptionImplementor { /** * Creates an AssertionError and pushes it to the stack. */ public static void createAssertionError(MethodVisitor methodVisitor) { methodVisitor.visitTypeInsn(Opcodes.NEW, Type.getInternalName(PythonAssertionError.class)); methodVisitor.visitInsn(Opcodes.DUP); methodVisitor.visitMethodInsn(Opcodes.INVOKESPECIAL, Type.getInternalName(PythonAssertionError.class), "<init>", Type.getMethodDescriptor(Type.VOID_TYPE), false); } /** * Reraise the last exception (stored in the exception local variable slot) */ public static void reraiseLast(MethodVisitor methodVisitor, LocalVariableHelper localVariableHelper) { localVariableHelper.readCurrentException(methodVisitor); methodVisitor.visitTypeInsn(Opcodes.CHECKCAST, Type.getInternalName(Throwable.class)); methodVisitor.visitInsn(Opcodes.ATHROW); } /** * TOS is an exception or an exception type. Reraise it (i.e. throw it). */ public static void reraise(MethodVisitor methodVisitor) { methodVisitor.visitInsn(Opcodes.DUP); methodVisitor.visitTypeInsn(Opcodes.INSTANCEOF, Type.getInternalName(Throwable.class)); Label ifNotThrowable = new Label(); methodVisitor.visitJumpInsn(Opcodes.IFEQ, ifNotThrowable); methodVisitor.visitTypeInsn(Opcodes.CHECKCAST, Type.getInternalName(Throwable.class)); methodVisitor.visitInsn(Opcodes.ATHROW); methodVisitor.visitLabel(ifNotThrowable); // Construct an instance of the type and throw it CollectionImplementor.buildCollection(PythonLikeTuple.class, methodVisitor, 0); methodVisitor.visitMethodInsn(Opcodes.INVOKESTATIC, Type.getInternalName(Collections.class), "emptyMap", Type.getMethodDescriptor(Type.getType(Map.class)), false); methodVisitor.visitInsn(Opcodes.ACONST_NULL); methodVisitor.visitMethodInsn(Opcodes.INVOKEINTERFACE, Type.getInternalName(PythonLikeFunction.class), "$call", Type.getMethodDescriptor(Type.getType(PythonLikeObject.class), Type.getType(List.class), Type.getType(Map.class), Type.getType(PythonLikeObject.class)), true); methodVisitor.visitTypeInsn(Opcodes.CHECKCAST, Type.getInternalName(Throwable.class)); methodVisitor.visitInsn(Opcodes.ATHROW); } /** * TOS is an exception; TOS1 is a type or an exception instance. Raise * TOS1 with TOS as its cause. */ public static void raiseWithCause(MethodVisitor methodVisitor) { StackManipulationImplementor.swap(methodVisitor); Label ifExceptionIsInstanceStart = new Label(); methodVisitor.visitInsn(Opcodes.DUP); methodVisitor.visitTypeInsn(Opcodes.INSTANCEOF, Type.getInternalName(PythonLikeType.class)); methodVisitor.visitJumpInsn(Opcodes.IFEQ, ifExceptionIsInstanceStart); // Exception is type: turn it to instance via its constructor FunctionImplementor.callGenericFunction(methodVisitor, 0); // a type is callable; calling it results in calling its constructor methodVisitor.visitLabel(ifExceptionIsInstanceStart); methodVisitor.visitTypeInsn(Opcodes.CHECKCAST, Type.getInternalName(Throwable.class)); StackManipulationImplementor.swap(methodVisitor); methodVisitor.visitTypeInsn(Opcodes.CHECKCAST, Type.getInternalName(Throwable.class)); methodVisitor.visitMethodInsn(Opcodes.INVOKEVIRTUAL, Type.getInternalName(Throwable.class), "initCause", Type.getMethodDescriptor(Type.getType(Throwable.class), Type.getType(Throwable.class)), false); reraise(methodVisitor); } /** * Raise an exception, with the stack and effect varying depending on {@code instruction.arg}: * * instruction.arg = 0: Stack is empty. Reraise the last exception. * instruction.arg = 1: TOS is an exception or exception type; raise it. * instruction.arg = 2: TOS1 is an exception/exception type, and TOS is the cause. Raise TOS1 with TOS as the cause. */ public static void raiseWithOptionalExceptionAndCause(MethodVisitor methodVisitor, PythonBytecodeInstruction instruction, LocalVariableHelper localVariableHelper) { switch (instruction.arg()) { case 0 -> reraiseLast(methodVisitor, localVariableHelper); case 1 -> reraise(methodVisitor); case 2 -> raiseWithCause(methodVisitor); default -> throw new IllegalStateException("Impossible argc value (" + instruction.arg() + ") for RAISE_VARARGS."); } } /** * Creates a try...finally block. Python also treat catch blocks as finally blocks, which * are handled via the {@link ControlOpDescriptor#JUMP_IF_NOT_EXC_MATCH} instruction. * {@code instruction.arg} is the difference in bytecode offset to the first catch/finally block. */ public static void createTryFinallyBlock(FunctionMetadata functionMetadata, StackMetadata stackMetadata, int handlerLocation, Map<Integer, Label> bytecodeCounterToLabelMap, BiConsumer<Integer, Runnable> bytecodeCounterCodeArgumentConsumer) { var methodVisitor = functionMetadata.methodVisitor; var className = functionMetadata.className; // Store the stack in local variables so the except block has access to them int[] stackLocals = StackManipulationImplementor.storeStack(methodVisitor, stackMetadata); Label finallyStart = bytecodeCounterToLabelMap.computeIfAbsent(handlerLocation, key -> new Label()); Label tryStart = new Label(); methodVisitor.visitTryCatchBlock(tryStart, finallyStart, finallyStart, Type.getInternalName(PythonBaseException.class)); methodVisitor.visitLabel(tryStart); // At finallyStart, stack is expected to be: // in Python 3.10 and below // [(stack-before-try), instruction, level, label, tb, value, exception] // or in Python 3.11 and above // [(stack-before-try), instruction, level, label, tb, value, exception] ; where: // (stack-before-try) = the stack state before the try statement // (see https://github.com/python/cpython/blob/b6558d768f19584ad724be23030603280f9e6361/Python/compile.c#L3241-L3268 ) // instruction = instruction that created the block // level = stack depth at the time the block was created // label = label to go to for exception // (see https://stackoverflow.com/a/66720684) // tb = stack trace // exception = exception instance // value = the exception instance again? // Results from Python 3.10 seems to indicate both exception and value are exception // instances, since Python 3.10 use RERAISE on exception (TOS) // and stores value into the exception variable (TOS1) // Python 3.11 and above use a different code path bytecodeCounterCodeArgumentConsumer.accept(handlerLocation, () -> { // Stack is exception // Duplicate exception to the current exception variable slot so we can reraise it if needed stackMetadata.localVariableHelper.writeCurrentException(methodVisitor); StackManipulationImplementor.restoreStack(methodVisitor, stackMetadata, stackLocals); // Stack is (stack-before-try) // Instruction PythonConstantsImplementor.loadNone(methodVisitor); // We don't use it // Stack is (stack-before-try), instruction // Stack Size methodVisitor.visitLdcInsn(stackMetadata.getStackSize()); methodVisitor.visitMethodInsn(Opcodes.INVOKESTATIC, Type.getInternalName(PythonInteger.class), "valueOf", Type.getMethodDescriptor(Type.getType(PythonInteger.class), Type.INT_TYPE), false); // Stack is (stack-before-try), instruction, stack-size // Label PythonConstantsImplementor.loadNone(methodVisitor); // We don't use it // Stack is (stack-before-try), instruction, stack-size, label methodVisitor.visitVarInsn(Opcodes.ALOAD, 0); methodVisitor.visitTypeInsn(Opcodes.CHECKCAST, className); // needed cast; type confusion on this? methodVisitor.visitFieldInsn(Opcodes.GETFIELD, className, PythonBytecodeToJavaBytecodeTranslator.INTERPRETER_INSTANCE_FIELD_NAME, Type.getDescriptor(PythonInterpreter.class)); methodVisitor.visitMethodInsn(Opcodes.INVOKEINTERFACE, Type.getInternalName(PythonInterpreter.class), "getTraceback", Type.getMethodDescriptor(Type.getType(PythonTraceback.class)), true); // Stack is (stack-before-try), instruction, stack-size, label, traceback // Load exception stackMetadata.localVariableHelper.readCurrentException(methodVisitor); // Stack is (stack-before-try), instruction, stack-size, label, traceback, exception // Get exception value methodVisitor.visitInsn(Opcodes.DUP); // Stack is (stack-before-try), instruction, stack-size, label, traceback, value, exception }); } public static void startExceptOrFinally(FunctionMetadata functionMetadata, StackMetadata stackMetadata) { MethodVisitor methodVisitor = functionMetadata.methodVisitor; LocalVariableHelper localVariableHelper = stackMetadata.localVariableHelper; // Clear the exception since it was handled methodVisitor.visitInsn(Opcodes.ACONST_NULL); localVariableHelper.writeCurrentException(methodVisitor); // Pop off the block if (functionMetadata.pythonCompiledFunction.pythonVersion.isAtLeast(PythonVersion.PYTHON_3_11)) { methodVisitor.visitInsn(Opcodes.POP); } else { methodVisitor.visitInsn(Opcodes.POP); methodVisitor.visitInsn(Opcodes.POP); methodVisitor.visitInsn(Opcodes.POP); } } public static void setupWith(int jumpTarget, FunctionMetadata functionMetadata, StackMetadata stackMetadata) { MethodVisitor methodVisitor = functionMetadata.methodVisitor; methodVisitor.visitInsn(Opcodes.DUP); // duplicate context_manager twice; need one for __enter__, two for __exit__ methodVisitor.visitInsn(Opcodes.DUP); // First load the method __exit__ methodVisitor.visitMethodInsn(Opcodes.INVOKEINTERFACE, Type.getInternalName(PythonLikeObject.class), "$getType", Type.getMethodDescriptor(Type.getType(PythonLikeType.class)), true); methodVisitor.visitLdcInsn("__exit__"); methodVisitor.visitMethodInsn(Opcodes.INVOKEINTERFACE, Type.getInternalName(PythonLikeObject.class), "$getAttributeOrError", Type.getMethodDescriptor(Type.getType(PythonLikeObject.class), Type.getType(String.class)), true); methodVisitor.visitTypeInsn(Opcodes.CHECKCAST, Type.getInternalName(PythonLikeFunction.class)); // bind it to the context_manager methodVisitor.visitTypeInsn(Opcodes.NEW, Type.getInternalName(BoundPythonLikeFunction.class)); methodVisitor.visitInsn(Opcodes.DUP_X2); methodVisitor.visitInsn(Opcodes.DUP_X2); methodVisitor.visitInsn(Opcodes.POP); methodVisitor.visitMethodInsn(Opcodes.INVOKESPECIAL, Type.getInternalName(BoundPythonLikeFunction.class), "<init>", Type.getMethodDescriptor(Type.VOID_TYPE, Type.getType(PythonLikeObject.class), Type.getType(PythonLikeFunction.class)), false); // Swap __exit__ method with duplicated context_manager methodVisitor.visitInsn(Opcodes.SWAP); // Call __enter__ DunderOperatorImplementor.unaryOperator(methodVisitor, stackMetadata, PythonUnaryOperator.ENTER); int enterResult = stackMetadata.localVariableHelper.newLocal(); // store enter result in temp, so it does not get saved in try block stackMetadata.localVariableHelper.writeTemp(methodVisitor, Type.getType(PythonLikeObject.class), enterResult); // Create a try...finally block pointing to delta StackMetadata currentStackMetadata = stackMetadata .pop() .push(ValueSourceInfo.of(new OpcodeWithoutSource(), PythonLikeFunction.getFunctionType(), stackMetadata.getTOSValueSource())); createTryFinallyBlock(functionMetadata, currentStackMetadata, jumpTarget, functionMetadata.bytecodeCounterToLabelMap, (bytecodeIndex, runnable) -> { functionMetadata.bytecodeCounterToCodeArgumenterList .computeIfAbsent(bytecodeIndex, key -> new ArrayList<>()).add(runnable); }); // Push enter result back to the stack stackMetadata.localVariableHelper.readTemp(methodVisitor, Type.getType(PythonLikeObject.class), enterResult); // cannot free, since try block store stack in locals => freeing enterResult messes up indexing of locals } public static void beforeWith(FunctionMetadata functionMetadata, StackMetadata stackMetadata) { MethodVisitor methodVisitor = functionMetadata.methodVisitor; methodVisitor.visitInsn(Opcodes.DUP); // duplicate context_manager twice; need one for __enter__, two for __exit__ methodVisitor.visitInsn(Opcodes.DUP); // First load the method __exit__ methodVisitor.visitMethodInsn(Opcodes.INVOKEINTERFACE, Type.getInternalName(PythonLikeObject.class), "$getType", Type.getMethodDescriptor(Type.getType(PythonLikeType.class)), true); methodVisitor.visitLdcInsn("__exit__"); methodVisitor.visitMethodInsn(Opcodes.INVOKEINTERFACE, Type.getInternalName(PythonLikeObject.class), "$getAttributeOrError", Type.getMethodDescriptor(Type.getType(PythonLikeObject.class), Type.getType(String.class)), true); methodVisitor.visitTypeInsn(Opcodes.CHECKCAST, Type.getInternalName(PythonLikeFunction.class)); // bind it to the context_manager methodVisitor.visitTypeInsn(Opcodes.NEW, Type.getInternalName(BoundPythonLikeFunction.class)); methodVisitor.visitInsn(Opcodes.DUP_X2); methodVisitor.visitInsn(Opcodes.DUP_X2); methodVisitor.visitInsn(Opcodes.POP); methodVisitor.visitMethodInsn(Opcodes.INVOKESPECIAL, Type.getInternalName(BoundPythonLikeFunction.class), "<init>", Type.getMethodDescriptor(Type.VOID_TYPE, Type.getType(PythonLikeObject.class), Type.getType(PythonLikeFunction.class)), false); // Swap __exit__ method with duplicated context_manager methodVisitor.visitInsn(Opcodes.SWAP); // Call __enter__ DunderOperatorImplementor.unaryOperator(methodVisitor, stackMetadata, PythonUnaryOperator.ENTER); int enterResult = stackMetadata.localVariableHelper.newLocal(); // store enter result in temp, so it does not get saved in try block stackMetadata.localVariableHelper.writeTemp(methodVisitor, Type.getType(PythonLikeObject.class), enterResult); // Push enter result back to the stack stackMetadata.localVariableHelper.readTemp(methodVisitor, Type.getType(PythonLikeObject.class), enterResult); // cannot free, since try block store stack in locals => freeing enterResult messes up indexing of locals } public static void startExceptBlock(FunctionMetadata functionMetadata, StackMetadata stackMetadata, ExceptionBlock exceptionBlock) { // In Python 3.11 and above, the stack here is // [(stack-before-try), exception] MethodVisitor methodVisitor = functionMetadata.methodVisitor; // Stack is exception // Duplicate exception to the current exception variable slot so we can reraise it if needed stackMetadata.localVariableHelper.writeCurrentException(methodVisitor); StackManipulationImplementor.restoreExceptionTableStack(functionMetadata, stackMetadata, exceptionBlock); // Stack is (stack-before-try) if (exceptionBlock.isPushLastIndex()) { // Load 0 for last index since we don't use it methodVisitor.visitFieldInsn(Opcodes.GETSTATIC, Type.getInternalName(PythonInteger.class), "ZERO", Type.getDescriptor(PythonInteger.class)); } // Load exception stackMetadata.localVariableHelper.readCurrentException(methodVisitor); // Stack is (stack-before-try), index?, exception } public static void pushExcInfo(FunctionMetadata functionMetadata, StackMetadata stackMetadata) { MethodVisitor methodVisitor = functionMetadata.methodVisitor; LocalVariableHelper localVariableHelper = stackMetadata.localVariableHelper; localVariableHelper.readCurrentException(methodVisitor); methodVisitor.visitInsn(Opcodes.SWAP); } public static void checkExcMatch(FunctionMetadata functionMetadata, StackMetadata stackMetadata) { MethodVisitor methodVisitor = functionMetadata.methodVisitor; methodVisitor.visitInsn(Opcodes.DUP2); methodVisitor.visitTypeInsn(Opcodes.CHECKCAST, Type.getInternalName(PythonLikeType.class)); methodVisitor.visitInsn(Opcodes.SWAP); methodVisitor.visitMethodInsn(Opcodes.INVOKEVIRTUAL, Type.getInternalName(PythonLikeType.class), "isInstance", Type.getMethodDescriptor(Type.BOOLEAN_TYPE, Type.getType(PythonLikeObject.class)), false); methodVisitor.visitMethodInsn(Opcodes.INVOKESTATIC, Type.getInternalName(PythonBoolean.class), "valueOf", Type.getMethodDescriptor(Type.getType(PythonBoolean.class), Type.BOOLEAN_TYPE), false); methodVisitor.visitInsn(Opcodes.SWAP); methodVisitor.visitInsn(Opcodes.POP); } public static void handleExceptionInWith(FunctionMetadata functionMetadata, StackMetadata stackMetadata) { MethodVisitor methodVisitor = functionMetadata.methodVisitor; LocalVariableHelper localVariableHelper = stackMetadata.localVariableHelper; // First, store the top 7 items in the stack to be restored later int exception = localVariableHelper.newLocal(); int exceptionArgs = localVariableHelper.newLocal(); int traceback = localVariableHelper.newLocal(); int label = localVariableHelper.newLocal(); int stackSize = localVariableHelper.newLocal(); int instruction = localVariableHelper.newLocal(); int exitFunction = localVariableHelper.newLocal(); if (functionMetadata.pythonCompiledFunction.pythonVersion.isBefore(PythonVersion.PYTHON_3_11)) { localVariableHelper.writeTemp(methodVisitor, Type.getType(PythonLikeObject.class), exception); localVariableHelper.writeTemp(methodVisitor, Type.getType(PythonLikeObject.class), exceptionArgs); localVariableHelper.writeTemp(methodVisitor, Type.getType(PythonLikeObject.class), traceback); localVariableHelper.writeTemp(methodVisitor, Type.getType(PythonLikeObject.class), label); localVariableHelper.writeTemp(methodVisitor, Type.getType(PythonLikeObject.class), stackSize); localVariableHelper.writeTemp(methodVisitor, Type.getType(PythonLikeObject.class), instruction); } else { localVariableHelper.writeTemp(methodVisitor, Type.getType(PythonLikeObject.class), exception); localVariableHelper.writeTemp(methodVisitor, Type.getType(PythonLikeObject.class), exceptionArgs); localVariableHelper.writeTemp(methodVisitor, Type.getType(PythonLikeObject.class), traceback); } localVariableHelper.writeTemp(methodVisitor, Type.getType(PythonLikeObject.class), exitFunction); // load exitFunction localVariableHelper.readTemp(methodVisitor, Type.getType(PythonLikeObject.class), exitFunction); methodVisitor.visitTypeInsn(Opcodes.CHECKCAST, Type.getInternalName(PythonLikeFunction.class)); // create the argument list // (exc_type, exc_value, traceback) methodVisitor.visitTypeInsn(Opcodes.NEW, Type.getInternalName(ArrayList.class)); methodVisitor.visitInsn(Opcodes.DUP); methodVisitor.visitLdcInsn(3); methodVisitor.visitMethodInsn(Opcodes.INVOKESPECIAL, Type.getInternalName(ArrayList.class), "<init>", Type.getMethodDescriptor(Type.VOID_TYPE, Type.INT_TYPE), false); methodVisitor.visitInsn(Opcodes.DUP); localVariableHelper.readTemp(methodVisitor, Type.getType(PythonLikeObject.class), exception); methodVisitor.visitMethodInsn(Opcodes.INVOKEINTERFACE, Type.getInternalName(PythonLikeObject.class), "$getType", Type.getMethodDescriptor(Type.getType(PythonLikeType.class)), true); methodVisitor.visitMethodInsn(Opcodes.INVOKEINTERFACE, Type.getInternalName(Collection.class), "add", Type.getMethodDescriptor(Type.BOOLEAN_TYPE, Type.getType(Object.class)), true); methodVisitor.visitInsn(Opcodes.POP); methodVisitor.visitInsn(Opcodes.DUP); localVariableHelper.readTemp(methodVisitor, Type.getType(PythonLikeObject.class), exception); methodVisitor.visitMethodInsn(Opcodes.INVOKEINTERFACE, Type.getInternalName(Collection.class), "add", Type.getMethodDescriptor(Type.BOOLEAN_TYPE, Type.getType(Object.class)), true); methodVisitor.visitInsn(Opcodes.POP); methodVisitor.visitInsn(Opcodes.DUP); localVariableHelper.readTemp(methodVisitor, Type.getType(PythonLikeObject.class), traceback); methodVisitor.visitMethodInsn(Opcodes.INVOKEINTERFACE, Type.getInternalName(Collection.class), "add", Type.getMethodDescriptor(Type.BOOLEAN_TYPE, Type.getType(Object.class)), true); methodVisitor.visitInsn(Opcodes.POP); // Use null for keywords methodVisitor.visitMethodInsn(Opcodes.INVOKESTATIC, Type.getInternalName(Collections.class), "emptyMap", Type.getMethodDescriptor(Type.getType(Map.class)), false); methodVisitor.visitInsn(Opcodes.ACONST_NULL); // Call the exit function methodVisitor.visitMethodInsn(Opcodes.INVOKEINTERFACE, Type.getInternalName(PythonLikeFunction.class), "$call", Type.getMethodDescriptor(Type.getType(PythonLikeObject.class), Type.getType(List.class), Type.getType(Map.class), Type.getType(PythonLikeObject.class)), true); // Restore the stack, raising the returned value to the top of the stack localVariableHelper.readTemp(methodVisitor, Type.getType(PythonLikeObject.class), exitFunction); methodVisitor.visitInsn(Opcodes.SWAP); if (functionMetadata.pythonCompiledFunction.pythonVersion.isBefore(PythonVersion.PYTHON_3_11)) { localVariableHelper.readTemp(methodVisitor, Type.getType(PythonLikeObject.class), instruction); methodVisitor.visitInsn(Opcodes.SWAP); localVariableHelper.readTemp(methodVisitor, Type.getType(PythonLikeObject.class), stackSize); methodVisitor.visitInsn(Opcodes.SWAP); localVariableHelper.readTemp(methodVisitor, Type.getType(PythonLikeObject.class), label); methodVisitor.visitInsn(Opcodes.SWAP); } localVariableHelper.readTemp(methodVisitor, Type.getType(PythonLikeObject.class), traceback); methodVisitor.visitInsn(Opcodes.SWAP); localVariableHelper.readTemp(methodVisitor, Type.getType(PythonLikeObject.class), exceptionArgs); methodVisitor.visitInsn(Opcodes.SWAP); localVariableHelper.readTemp(methodVisitor, Type.getType(PythonLikeObject.class), exception); methodVisitor.visitInsn(Opcodes.SWAP); // Free the 7 temps localVariableHelper.freeLocal(); localVariableHelper.freeLocal(); localVariableHelper.freeLocal(); localVariableHelper.freeLocal(); localVariableHelper.freeLocal(); localVariableHelper.freeLocal(); localVariableHelper.freeLocal(); } public static void getValueFromStopIterationOrReraise(FunctionMetadata functionMetadata, StackMetadata stackMetadata) { var methodVisitor = functionMetadata.methodVisitor; Label isStopIteration = new Label(); methodVisitor.visitInsn(Opcodes.DUP); methodVisitor.visitTypeInsn(Opcodes.INSTANCEOF, Type.getInternalName(StopIteration.class)); methodVisitor.visitJumpInsn(Opcodes.IFNE, isStopIteration); ExceptionImplementor.reraise(methodVisitor); methodVisitor.visitLabel(isStopIteration); methodVisitor.visitTypeInsn(Opcodes.CHECKCAST, Type.getInternalName(StopIteration.class)); methodVisitor.visitMethodInsn(Opcodes.INVOKEVIRTUAL, Type.getInternalName(StopIteration.class), "getValue", Type.getMethodDescriptor(Type.getType(PythonLikeObject.class)), false); } }
0
java-sources/ai/timefold/solver/jpyinterpreter/1.24.0/ai/timefold/jpyinterpreter
java-sources/ai/timefold/solver/jpyinterpreter/1.24.0/ai/timefold/jpyinterpreter/implementors/FunctionImplementor.java
package ai.timefold.jpyinterpreter.implementors; import java.lang.reflect.Constructor; import java.lang.reflect.InvocationTargetException; import java.util.Collections; import java.util.List; import java.util.Map; import java.util.stream.Collectors; import ai.timefold.jpyinterpreter.FunctionMetadata; import ai.timefold.jpyinterpreter.LocalVariableHelper; import ai.timefold.jpyinterpreter.PythonBytecodeInstruction; import ai.timefold.jpyinterpreter.PythonBytecodeToJavaBytecodeTranslator; import ai.timefold.jpyinterpreter.PythonCompiledFunction; import ai.timefold.jpyinterpreter.PythonInterpreter; import ai.timefold.jpyinterpreter.PythonLikeObject; import ai.timefold.jpyinterpreter.PythonVersion; import ai.timefold.jpyinterpreter.StackMetadata; import ai.timefold.jpyinterpreter.ValueSourceInfo; import ai.timefold.jpyinterpreter.types.BuiltinTypes; import ai.timefold.jpyinterpreter.types.PythonCode; import ai.timefold.jpyinterpreter.types.PythonKnownFunctionType; import ai.timefold.jpyinterpreter.types.PythonLikeFunction; import ai.timefold.jpyinterpreter.types.PythonLikeGenericType; import ai.timefold.jpyinterpreter.types.PythonLikeType; import ai.timefold.jpyinterpreter.types.PythonString; import ai.timefold.jpyinterpreter.types.collections.PythonLikeDict; import ai.timefold.jpyinterpreter.types.collections.PythonLikeTuple; import org.objectweb.asm.Label; import org.objectweb.asm.MethodVisitor; import org.objectweb.asm.Opcodes; import org.objectweb.asm.Type; /** * Implements opcodes related to functions */ public class FunctionImplementor { public static void callBinaryMethod(FunctionMetadata functionMetadata, StackMetadata stackMetadata, MethodVisitor methodVisitor, String methodName) { methodVisitor.visitInsn(Opcodes.SWAP); methodVisitor.visitInsn(Opcodes.DUP); methodVisitor.visitMethodInsn(Opcodes.INVOKEINTERFACE, Type.getInternalName(PythonLikeObject.class), "$getType", Type.getMethodDescriptor(Type.getType(PythonLikeType.class)), true); methodVisitor.visitLdcInsn(methodName); methodVisitor.visitMethodInsn(Opcodes.INVOKEINTERFACE, Type.getInternalName(PythonLikeObject.class), "$getAttributeOrError", Type.getMethodDescriptor(Type.getType(PythonLikeObject.class), Type.getType(String.class)), true); methodVisitor.visitInsn(Opcodes.DUP_X2); methodVisitor.visitInsn(Opcodes.POP); methodVisitor.visitInsn(Opcodes.SWAP); CollectionImplementor.buildCollection(PythonLikeTuple.class, methodVisitor, 2); methodVisitor.visitMethodInsn(Opcodes.INVOKESTATIC, Type.getInternalName(Collections.class), "emptyMap", Type.getMethodDescriptor(Type.getType(Map.class)), false); getCallerInstance(functionMetadata, stackMetadata); methodVisitor.visitMethodInsn(Opcodes.INVOKEINTERFACE, Type.getInternalName(PythonLikeFunction.class), "$call", Type.getMethodDescriptor(Type.getType(PythonLikeObject.class), Type.getType(List.class), Type.getType(Map.class), Type.getType(PythonLikeObject.class)), true); } public static void callBinaryMethod(MethodVisitor methodVisitor, String methodName) { methodVisitor.visitInsn(Opcodes.SWAP); methodVisitor.visitInsn(Opcodes.DUP); methodVisitor.visitMethodInsn(Opcodes.INVOKEINTERFACE, Type.getInternalName(PythonLikeObject.class), "$getType", Type.getMethodDescriptor(Type.getType(PythonLikeType.class)), true); methodVisitor.visitLdcInsn(methodName); methodVisitor.visitMethodInsn(Opcodes.INVOKEINTERFACE, Type.getInternalName(PythonLikeObject.class), "$getAttributeOrError", Type.getMethodDescriptor(Type.getType(PythonLikeObject.class), Type.getType(String.class)), true); methodVisitor.visitInsn(Opcodes.DUP_X2); methodVisitor.visitInsn(Opcodes.POP); methodVisitor.visitInsn(Opcodes.SWAP); CollectionImplementor.buildCollection(PythonLikeTuple.class, methodVisitor, 2); methodVisitor.visitMethodInsn(Opcodes.INVOKESTATIC, Type.getInternalName(Collections.class), "emptyMap", Type.getMethodDescriptor(Type.getType(Map.class)), false); methodVisitor.visitInsn(Opcodes.ACONST_NULL); methodVisitor.visitMethodInsn(Opcodes.INVOKEINTERFACE, Type.getInternalName(PythonLikeFunction.class), "$call", Type.getMethodDescriptor(Type.getType(PythonLikeObject.class), Type.getType(List.class), Type.getType(Map.class), Type.getType(PythonLikeObject.class)), true); } /** * Loads a method named co_names[namei] from the TOS object. TOS is popped. This bytecode distinguishes two cases: * if TOS has a method with the correct name, the bytecode pushes the unbound method and TOS. * TOS will be used as the first argument (self) by CALL_METHOD when calling the unbound method. * Otherwise, NULL and the object return by the attribute lookup are pushed. */ public static void loadMethod(FunctionMetadata functionMetadata, StackMetadata stackMetadata, int nameIndex) { var methodVisitor = functionMetadata.methodVisitor; var function = functionMetadata.pythonCompiledFunction; var className = functionMetadata.className; PythonLikeType stackTosType = stackMetadata.getTOSType(); PythonLikeType tosType; boolean isTosType; if (stackTosType instanceof PythonLikeGenericType) { tosType = ((PythonLikeGenericType) stackTosType).getOrigin(); isTosType = true; } else { tosType = stackTosType; isTosType = false; } tosType.getMethodType(functionMetadata.pythonCompiledFunction.co_names.get(nameIndex)).ifPresentOrElse( knownFunctionType -> { if (isTosType && knownFunctionType.isStaticMethod()) { methodVisitor.visitLdcInsn(function.co_names.get(nameIndex)); methodVisitor.visitMethodInsn(Opcodes.INVOKEINTERFACE, Type.getInternalName(PythonLikeObject.class), "$getAttributeOrNull", Type.getMethodDescriptor(Type.getType(PythonLikeObject.class), Type.getType(String.class)), true); methodVisitor.visitInsn(Opcodes.ACONST_NULL); if (functionMetadata.pythonCompiledFunction.pythonVersion.isAtLeast(PythonVersion.PYTHON_3_11)) { // Need to move NULL behind method methodVisitor.visitInsn(Opcodes.DUP_X1); methodVisitor.visitInsn(Opcodes.POP); } } else if (!isTosType && knownFunctionType.isStaticMethod()) { methodVisitor.visitMethodInsn(Opcodes.INVOKEINTERFACE, Type.getInternalName(PythonLikeObject.class), "$getType", Type.getMethodDescriptor(Type.getType(PythonLikeType.class)), true); methodVisitor.visitLdcInsn(function.co_names.get(nameIndex)); methodVisitor.visitMethodInsn(Opcodes.INVOKEINTERFACE, Type.getInternalName(PythonLikeObject.class), "$getAttributeOrNull", Type.getMethodDescriptor(Type.getType(PythonLikeObject.class), Type.getType(String.class)), true); methodVisitor.visitInsn(Opcodes.ACONST_NULL); if (functionMetadata.pythonCompiledFunction.pythonVersion.isAtLeast(PythonVersion.PYTHON_3_11)) { // Need to move NULL behind method methodVisitor.visitInsn(Opcodes.DUP_X1); methodVisitor.visitInsn(Opcodes.POP); } } else if (isTosType && knownFunctionType.isClassMethod()) { methodVisitor.visitInsn(Opcodes.DUP); methodVisitor.visitLdcInsn(function.co_names.get(nameIndex)); methodVisitor.visitMethodInsn(Opcodes.INVOKEINTERFACE, Type.getInternalName(PythonLikeObject.class), "$getAttributeOrNull", Type.getMethodDescriptor(Type.getType(PythonLikeObject.class), Type.getType(String.class)), true); methodVisitor.visitInsn(Opcodes.SWAP); } else if (!isTosType && knownFunctionType.isClassMethod()) { methodVisitor.visitInsn(Opcodes.DUP); methodVisitor.visitMethodInsn(Opcodes.INVOKEINTERFACE, Type.getInternalName(PythonLikeObject.class), "$getType", Type.getMethodDescriptor(Type.getType(PythonLikeType.class)), true); methodVisitor.visitLdcInsn(function.co_names.get(nameIndex)); methodVisitor.visitMethodInsn(Opcodes.INVOKEINTERFACE, Type.getInternalName(PythonLikeObject.class), "$getAttributeOrNull", Type.getMethodDescriptor(Type.getType(PythonLikeObject.class), Type.getType(String.class)), true); methodVisitor.visitInsn(Opcodes.SWAP); } else if (isTosType) { methodVisitor.visitInsn(Opcodes.DUP); methodVisitor.visitLdcInsn(function.co_names.get(nameIndex)); methodVisitor.visitMethodInsn(Opcodes.INVOKEINTERFACE, Type.getInternalName(PythonLikeObject.class), "$getAttributeOrNull", Type.getMethodDescriptor(Type.getType(PythonLikeObject.class), Type.getType(String.class)), true); methodVisitor.visitInsn(Opcodes.SWAP); } else { methodVisitor.visitInsn(Opcodes.DUP); methodVisitor.visitMethodInsn(Opcodes.INVOKEINTERFACE, Type.getInternalName(PythonLikeObject.class), "$getType", Type.getMethodDescriptor(Type.getType(PythonLikeType.class)), true); methodVisitor.visitLdcInsn(function.co_names.get(nameIndex)); methodVisitor.visitMethodInsn(Opcodes.INVOKEINTERFACE, Type.getInternalName(PythonLikeObject.class), "$getAttributeOrNull", Type.getMethodDescriptor(Type.getType(PythonLikeObject.class), Type.getType(String.class)), true); methodVisitor.visitInsn(Opcodes.SWAP); } }, () -> loadGenericMethod(functionMetadata, methodVisitor, className, function, stackMetadata, nameIndex)); } /** * Loads a method named co_names[namei] from the TOS object. TOS is popped. This bytecode distinguishes two cases: * if TOS has a method with the correct name, the bytecode pushes the unbound method and TOS. * TOS will be used as the first argument (self) by CALL_METHOD when calling the unbound method. * Otherwise, NULL and the object return by the attribute lookup are pushed. */ private static void loadGenericMethod(FunctionMetadata functionMetadata, MethodVisitor methodVisitor, String className, PythonCompiledFunction function, StackMetadata stackMetadata, int nameIndex) { methodVisitor.visitInsn(Opcodes.DUP); methodVisitor.visitMethodInsn(Opcodes.INVOKEINTERFACE, Type.getInternalName(PythonLikeObject.class), "$getType", Type.getMethodDescriptor(Type.getType(PythonLikeType.class)), true); methodVisitor.visitLdcInsn(function.co_names.get(nameIndex)); methodVisitor.visitMethodInsn(Opcodes.INVOKEVIRTUAL, Type.getInternalName(PythonLikeType.class), "loadMethod", Type.getMethodDescriptor(Type.getType(PythonLikeObject.class), Type.getType(String.class)), false); methodVisitor.visitInsn(Opcodes.DUP); methodVisitor.visitInsn(Opcodes.ACONST_NULL); Label blockEnd = new Label(); methodVisitor.visitJumpInsn(Opcodes.IF_ACMPNE, blockEnd); // TOS is null; type does not have attribute; do normal attribute lookup // Stack is object, null methodVisitor.visitInsn(Opcodes.POP); ObjectImplementor.getAttribute(functionMetadata, stackMetadata, nameIndex); // Stack is method methodVisitor.visitInsn(Opcodes.ACONST_NULL); if (functionMetadata.pythonCompiledFunction.pythonVersion.isBefore(PythonVersion.PYTHON_3_11)) { // Python 3.11+ swap these methodVisitor.visitInsn(Opcodes.SWAP); } methodVisitor.visitLabel(blockEnd); // Stack is either: // object, method if it was in type // null, method if it was not in type (Or method, null if Python 3.11+) methodVisitor.visitInsn(Opcodes.SWAP); // Stack is now: // method, object if it was in type // method, null if it was not in type (and prior to Python 3.11+) // null, method if it was not in type (if Python 3.11+) } public static void setCallKeywordNameTuple(FunctionMetadata functionMetadata, StackMetadata stackMetadata, int constantIndex) { LocalVariableHelper localVariableHelper = stackMetadata.localVariableHelper; PythonConstantsImplementor.loadConstant(functionMetadata.methodVisitor, functionMetadata.className, constantIndex); localVariableHelper.writeCallKeywords(functionMetadata.methodVisitor); } /** * Calls a function. argc is the number of positional arguments. Keyword arguments are stored in a local variable. * Keyword arguments (if any) are at the top of the stack, followed by, positional arguments. * Below them either self and an unbound method object or NULL and an arbitrary callable). * All of them are popped and the return value is pushed. */ public static void call(FunctionMetadata functionMetadata, StackMetadata stackMetadata, int argumentCount) { PythonLikeType functionType = stackMetadata.getTypeAtStackIndex(argumentCount + 1); if (functionType instanceof PythonLikeGenericType) { functionType = ((PythonLikeGenericType) functionType).getOrigin().getConstructorType().orElse(null); } if (functionType instanceof PythonKnownFunctionType) { PythonKnownFunctionType knownFunctionType = (PythonKnownFunctionType) functionType; List<String> keywordArgumentNameList = stackMetadata.getCallKeywordNameList(); List<PythonLikeType> callStackParameterTypes = stackMetadata.getValueSourcesUpToStackIndex(argumentCount) .stream().map(ValueSourceInfo::getValueType).collect(Collectors.toList()); knownFunctionType .getFunctionForParameters(argumentCount - keywordArgumentNameList.size(), keywordArgumentNameList, callStackParameterTypes) .ifPresentOrElse(functionSignature -> { KnownCallImplementor.callPython311andAbove(functionSignature, functionMetadata, stackMetadata, argumentCount, stackMetadata.getCallKeywordNameList()); }, () -> callGeneric(functionMetadata, stackMetadata, argumentCount)); } else { functionType = stackMetadata.getTypeAtStackIndex(argumentCount); if (functionType instanceof PythonLikeGenericType) { functionType = ((PythonLikeGenericType) functionType).getOrigin().getConstructorType().orElse(null); } if (functionType instanceof PythonKnownFunctionType) { PythonKnownFunctionType knownFunctionType = (PythonKnownFunctionType) functionType; List<String> keywordArgumentNameList = stackMetadata.getCallKeywordNameList(); List<PythonLikeType> callStackParameterTypes = stackMetadata.getValueSourcesUpToStackIndex(argumentCount) .stream().map(ValueSourceInfo::getValueType).collect(Collectors.toList()); knownFunctionType .getFunctionForParameters(argumentCount - keywordArgumentNameList.size(), keywordArgumentNameList, callStackParameterTypes) .ifPresentOrElse(functionSignature -> { KnownCallImplementor.callPython311andAbove(functionSignature, functionMetadata, stackMetadata, argumentCount, stackMetadata.getCallKeywordNameList()); }, () -> callGeneric(functionMetadata, stackMetadata, argumentCount)); } else { callGeneric(functionMetadata, stackMetadata, argumentCount); } } } private static void callGeneric(FunctionMetadata functionMetadata, StackMetadata stackMetadata, int argumentCount) { MethodVisitor methodVisitor = functionMetadata.methodVisitor; LocalVariableHelper localVariableHelper = stackMetadata.localVariableHelper; int keywordArgs = localVariableHelper.newLocal(); int positionalArgs = localVariableHelper.newLocal(); localVariableHelper.readCallKeywords(methodVisitor); CollectionImplementor.buildCollection(TupleMapPair.class, methodVisitor, argumentCount + 1); methodVisitor.visitInsn(Opcodes.DUP); methodVisitor.visitFieldInsn(Opcodes.GETFIELD, Type.getInternalName(TupleMapPair.class), "tuple", Type.getDescriptor(PythonLikeTuple.class)); localVariableHelper.writeTemp(methodVisitor, Type.getType(PythonLikeTuple.class), positionalArgs); methodVisitor.visitFieldInsn(Opcodes.GETFIELD, Type.getInternalName(TupleMapPair.class), "map", Type.getDescriptor(PythonLikeDict.class)); localVariableHelper.writeTemp(methodVisitor, Type.getType(PythonLikeDict.class), keywordArgs); // Stack is (null or method), (obj or method) methodVisitor.visitInsn(Opcodes.SWAP); // Stack is (obj or method) (null or method) Label ifNullStart = new Label(); Label blockEnd = new Label(); methodVisitor.visitInsn(Opcodes.DUP); methodVisitor.visitInsn(Opcodes.ACONST_NULL); methodVisitor.visitJumpInsn(Opcodes.IF_ACMPEQ, ifNullStart); // Stack is obj, method StackManipulationImplementor.swap(methodVisitor); // Stack is method, obj localVariableHelper.readTemp(methodVisitor, Type.getType(PythonLikeTuple.class), positionalArgs); methodVisitor.visitInsn(Opcodes.SWAP); methodVisitor.visitInsn(Opcodes.ICONST_0); // Stack is method, argList, obj, index methodVisitor.visitInsn(Opcodes.SWAP); // Stack is method, argList, argList, index, obj methodVisitor.visitMethodInsn(Opcodes.INVOKEINTERFACE, Type.getInternalName(List.class), "add", Type.getMethodDescriptor(Type.VOID_TYPE, Type.INT_TYPE, Type.getType(Object.class)), true); // Stack is method localVariableHelper.readTemp(methodVisitor, Type.getType(PythonLikeTuple.class), positionalArgs); // Stack is method, positionalArgs methodVisitor.visitJumpInsn(Opcodes.GOTO, blockEnd); methodVisitor.visitLabel(ifNullStart); // Stack is method, null methodVisitor.visitInsn(Opcodes.POP); // Stack is method localVariableHelper.readTemp(methodVisitor, Type.getType(PythonLikeTuple.class), positionalArgs); // Stack is method, positionalArgs methodVisitor.visitLabel(blockEnd); localVariableHelper.readTemp(methodVisitor, Type.getType(PythonLikeDict.class), keywordArgs); // Stack is method, positionalArgs, keywordArgs getCallerInstance(functionMetadata, stackMetadata); // Stack is callable, positionalArgs, keywordArgs, null methodVisitor.visitMethodInsn(Opcodes.INVOKEINTERFACE, Type.getInternalName(PythonLikeFunction.class), "$call", Type.getMethodDescriptor(Type.getType(PythonLikeObject.class), Type.getType(List.class), Type.getType(Map.class), Type.getType(PythonLikeObject.class)), true); localVariableHelper.resetCallKeywords(methodVisitor); localVariableHelper.freeLocal(); localVariableHelper.freeLocal(); } /** * Calls a method. argc is the number of positional arguments. Keyword arguments are not supported. * This opcode is designed to be used with LOAD_METHOD. Positional arguments are on top of the stack. * Below them, the two items described in LOAD_METHOD are on the stack * (either self and an unbound method object or NULL and an arbitrary callable). * All of them are popped and the return value is pushed. */ public static void callMethod(FunctionMetadata functionMetadata, StackMetadata stackMetadata, MethodVisitor methodVisitor, PythonBytecodeInstruction instruction, LocalVariableHelper localVariableHelper) { PythonLikeType functionType = stackMetadata.getTypeAtStackIndex(instruction.arg() + 1); if (functionType instanceof PythonKnownFunctionType) { PythonKnownFunctionType knownFunctionType = (PythonKnownFunctionType) functionType; PythonLikeType[] parameterTypes = new PythonLikeType[instruction.arg()]; for (int i = 0; i < parameterTypes.length; i++) { parameterTypes[parameterTypes.length - i - 1] = stackMetadata.getTypeAtStackIndex(i); } knownFunctionType.getFunctionForParameters(parameterTypes) .ifPresentOrElse(functionSignature -> { KnownCallImplementor.callMethod(functionSignature, methodVisitor, localVariableHelper, instruction.arg()); methodVisitor.visitInsn(Opcodes.SWAP); methodVisitor.visitInsn(Opcodes.POP); if (knownFunctionType.isStaticMethod()) { methodVisitor.visitInsn(Opcodes.SWAP); methodVisitor.visitInsn(Opcodes.POP); } }, () -> callGenericMethod(functionMetadata, stackMetadata, methodVisitor, instruction, localVariableHelper)); } else { callGenericMethod(functionMetadata, stackMetadata, methodVisitor, instruction, localVariableHelper); } } private static void callGenericMethod(FunctionMetadata functionMetadata, StackMetadata stackMetadata, MethodVisitor methodVisitor, PythonBytecodeInstruction instruction, LocalVariableHelper localVariableHelper) { // Stack is method, (obj or null), arg0, ..., arg(argc - 1) CollectionImplementor.buildCollection(PythonLikeTuple.class, methodVisitor, instruction.arg()); methodVisitor.visitInsn(Opcodes.SWAP); // Stack is method, argList, (obj or null) Label ifNullStart = new Label(); Label blockEnd = new Label(); methodVisitor.visitInsn(Opcodes.DUP); methodVisitor.visitInsn(Opcodes.ACONST_NULL); methodVisitor.visitJumpInsn(Opcodes.IF_ACMPEQ, ifNullStart); // Stack is method, argList, obj StackManipulationImplementor.duplicateToTOS(functionMetadata, stackMetadata, 1); StackManipulationImplementor.swap(methodVisitor); // Stack is method, argList, argList, obj methodVisitor.visitInsn(Opcodes.ICONST_0); // Stack is method, argList, argList, obj, index methodVisitor.visitInsn(Opcodes.SWAP); // Stack is method, argList, argList, index, obj methodVisitor.visitMethodInsn(Opcodes.INVOKEINTERFACE, Type.getInternalName(List.class), "add", Type.getMethodDescriptor(Type.VOID_TYPE, Type.INT_TYPE, Type.getType(Object.class)), true); // Stack is method, argList methodVisitor.visitJumpInsn(Opcodes.GOTO, blockEnd); methodVisitor.visitLabel(ifNullStart); // Stack is method, argList, null methodVisitor.visitInsn(Opcodes.POP); // Stack is method, argList methodVisitor.visitLabel(blockEnd); methodVisitor.visitMethodInsn(Opcodes.INVOKESTATIC, Type.getInternalName(Collections.class), "emptyMap", Type.getMethodDescriptor(Type.getType(Map.class)), false); // Stack is method, argList getCallerInstance(functionMetadata, stackMetadata); // Stack is callable, argument_list, null methodVisitor.visitMethodInsn(Opcodes.INVOKEINTERFACE, Type.getInternalName(PythonLikeFunction.class), "$call", Type.getMethodDescriptor(Type.getType(PythonLikeObject.class), Type.getType(List.class), Type.getType(Map.class), Type.getType(PythonLikeObject.class)), true); } /** * Calls a function. TOS...TOS[argc - 1] are the arguments to the function. * TOS[argc] is the function to call. TOS...TOS[argc] are all popped and * the result is pushed onto the stack. */ public static void callFunction(FunctionMetadata functionMetadata, StackMetadata stackMetadata, MethodVisitor methodVisitor, PythonBytecodeInstruction instruction) { PythonLikeType functionType = stackMetadata.getTypeAtStackIndex(instruction.arg()); if (functionType instanceof PythonLikeGenericType) { functionType = ((PythonLikeGenericType) functionType).getOrigin().getConstructorType().orElse(null); } if (functionType instanceof PythonKnownFunctionType) { PythonKnownFunctionType knownFunctionType = (PythonKnownFunctionType) functionType; knownFunctionType.getDefaultFunctionSignature() .ifPresentOrElse(functionSignature -> { KnownCallImplementor.callWithoutKeywords(functionSignature, functionMetadata, stackMetadata, instruction.arg()); methodVisitor.visitInsn(Opcodes.SWAP); methodVisitor.visitInsn(Opcodes.POP); }, () -> callGenericFunction(functionMetadata, stackMetadata, methodVisitor, instruction)); } else { callGenericFunction(functionMetadata, stackMetadata, methodVisitor, instruction); } } public static void callGenericFunction(FunctionMetadata functionMetadata, StackMetadata stackMetadata, MethodVisitor methodVisitor, PythonBytecodeInstruction instruction) { callGenericFunction(functionMetadata, stackMetadata, methodVisitor, instruction.arg()); } public static void callGenericFunction(MethodVisitor methodVisitor, int argCount) { // stack is callable, arg0, arg1, ..., arg(argc - 1) CollectionImplementor.buildCollection(PythonLikeTuple.class, methodVisitor, argCount); methodVisitor.visitMethodInsn(Opcodes.INVOKESTATIC, Type.getInternalName(Collections.class), "emptyMap", Type.getMethodDescriptor(Type.getType(Map.class)), false); methodVisitor.visitInsn(Opcodes.ACONST_NULL); // Stack is callable, argument_list, null methodVisitor.visitMethodInsn(Opcodes.INVOKEINTERFACE, Type.getInternalName(PythonLikeFunction.class), "$call", Type.getMethodDescriptor(Type.getType(PythonLikeObject.class), Type.getType(List.class), Type.getType(Map.class), Type.getType(PythonLikeObject.class)), true); } public static void callGenericFunction(FunctionMetadata functionMetadata, StackMetadata stackMetadata, MethodVisitor methodVisitor, int argCount) { // stack is callable, arg0, arg1, ..., arg(argc - 1) CollectionImplementor.buildCollection(PythonLikeTuple.class, methodVisitor, argCount); methodVisitor.visitMethodInsn(Opcodes.INVOKESTATIC, Type.getInternalName(Collections.class), "emptyMap", Type.getMethodDescriptor(Type.getType(Map.class)), false); getCallerInstance(functionMetadata, stackMetadata); // Stack is callable, argument_list, null methodVisitor.visitMethodInsn(Opcodes.INVOKEINTERFACE, Type.getInternalName(PythonLikeFunction.class), "$call", Type.getMethodDescriptor(Type.getType(PythonLikeObject.class), Type.getType(List.class), Type.getType(Map.class), Type.getType(PythonLikeObject.class)), true); } /** * Calls a function. TOS is a tuple containing keyword names. * TOS[1]...TOS[len(TOS)] are the keyword arguments to the function (TOS[1] is (TOS)[0], TOS[2] is (TOS)[1], ...). * TOS[len(TOS) + 1]...TOS[argc + 1] are the positional arguments (rightmost first). * TOS[argc + 2] is the function to call. TOS...TOS[argc + 2] are all popped and * the result is pushed onto the stack. */ public static void callFunctionWithKeywords(FunctionMetadata functionMetadata, StackMetadata stackMetadata, MethodVisitor methodVisitor, PythonBytecodeInstruction instruction) { PythonLikeType functionType = stackMetadata.getTypeAtStackIndex(instruction.arg() + 1); if (functionType instanceof PythonLikeGenericType) { functionType = ((PythonLikeGenericType) functionType).getOrigin().getConstructorType().orElse(null); } if (functionType instanceof PythonKnownFunctionType) { PythonKnownFunctionType knownFunctionType = (PythonKnownFunctionType) functionType; knownFunctionType.getDefaultFunctionSignature() .ifPresentOrElse(functionSignature -> { KnownCallImplementor.callWithKeywordsAndUnwrapSelf(functionSignature, functionMetadata, stackMetadata, instruction.arg()); methodVisitor.visitInsn(Opcodes.SWAP); methodVisitor.visitInsn(Opcodes.POP); }, () -> callGenericFunction(functionMetadata, stackMetadata, methodVisitor, instruction)); } else { callGenericFunctionWithKeywords(functionMetadata, stackMetadata, methodVisitor, instruction); } } /** * Calls a function. TOS is a tuple containing keyword names. * TOS[1]...TOS[len(TOS)] are the keyword arguments to the function (TOS[1] is (TOS)[0], TOS[2] is (TOS)[1], ...). * TOS[len(TOS) + 1]...TOS[argc + 1] are the positional arguments (rightmost first). * TOS[argc + 2] is the function to call. TOS...TOS[argc + 2] are all popped and * the result is pushed onto the stack. */ public static void callGenericFunctionWithKeywords(FunctionMetadata functionMetadata, StackMetadata stackMetadata, MethodVisitor methodVisitor, PythonBytecodeInstruction instruction) { // stack is callable, arg0, arg1, ..., arg(argc - len(keys)), ..., arg(argc - 1), keys // We know the total number of arguments, but not the number of individual positional/keyword arguments // Since Java Bytecode require consistent stack frames (i.e. the body of a loop must start with // the same number of elements in the stack), we need to add the tuple/map in the same object // which will delegate it to either the tuple or the map depending on position and the first item size CollectionImplementor.buildCollection(TupleMapPair.class, methodVisitor, instruction.arg() + 1); // stack is callable, tupleMapPair methodVisitor.visitInsn(Opcodes.DUP); methodVisitor.visitFieldInsn(Opcodes.GETFIELD, Type.getInternalName(TupleMapPair.class), "tuple", Type.getDescriptor(PythonLikeTuple.class)); // stack is callable, tupleMapPair, positionalArgs methodVisitor.visitInsn(Opcodes.SWAP); methodVisitor.visitFieldInsn(Opcodes.GETFIELD, Type.getInternalName(TupleMapPair.class), "map", Type.getDescriptor(PythonLikeDict.class)); getCallerInstance(functionMetadata, stackMetadata); // Stack is callable, positionalArgs, keywordArgs methodVisitor.visitMethodInsn(Opcodes.INVOKEINTERFACE, Type.getInternalName(PythonLikeFunction.class), "$call", Type.getMethodDescriptor(Type.getType(PythonLikeObject.class), Type.getType(List.class), Type.getType(Map.class), Type.getType(PythonLikeObject.class)), true); } /** * Calls a function. If the lowest bit of instruction.arg is set, TOS is a mapping object containing keyword * arguments, TOS[1] is an iterable containing positional arguments and TOS[2] is callable. Otherwise, * TOS is an iterable containing positional arguments and TOS[1] is callable. */ public static void callFunctionUnpack(FunctionMetadata functionMetadata, StackMetadata stackMetadata, PythonBytecodeInstruction instruction) { if ((instruction.arg() & 1) == 1) { callFunctionUnpackMapAndIterable(functionMetadata, stackMetadata, functionMetadata.methodVisitor); } else { callFunctionUnpackIterable(functionMetadata, stackMetadata, functionMetadata.methodVisitor); } } public static void callFunctionUnpackMapAndIterable(FunctionMetadata functionMetadata, StackMetadata stackMetadata, MethodVisitor methodVisitor) { getCallerInstance(functionMetadata, stackMetadata); methodVisitor.visitMethodInsn(Opcodes.INVOKEINTERFACE, Type.getInternalName(PythonLikeFunction.class), "$call", Type.getMethodDescriptor(Type.getType(PythonLikeObject.class), Type.getType(List.class), Type.getType(Map.class), Type.getType(PythonLikeObject.class)), true); if (functionMetadata.pythonCompiledFunction.pythonVersion.isAtLeast(PythonVersion.PYTHON_3_11)) { methodVisitor.visitInsn(Opcodes.SWAP); methodVisitor.visitInsn(Opcodes.POP); } } public static void callFunctionUnpackIterable(FunctionMetadata functionMetadata, StackMetadata stackMetadata, MethodVisitor methodVisitor) { methodVisitor.visitMethodInsn(Opcodes.INVOKESTATIC, Type.getInternalName(Collections.class), "emptyMap", Type.getMethodDescriptor(Type.getType(Map.class)), false); getCallerInstance(functionMetadata, stackMetadata); methodVisitor.visitMethodInsn(Opcodes.INVOKEINTERFACE, Type.getInternalName(PythonLikeFunction.class), "$call", Type.getMethodDescriptor(Type.getType(PythonLikeObject.class), Type.getType(List.class), Type.getType(Map.class), Type.getType(PythonLikeObject.class)), true); if (functionMetadata.pythonCompiledFunction.pythonVersion.isAtLeast(PythonVersion.PYTHON_3_11)) { methodVisitor.visitInsn(Opcodes.SWAP); methodVisitor.visitInsn(Opcodes.POP); } } private static void getCallerInstance(FunctionMetadata functionMetadata, StackMetadata stackMetadata) { MethodVisitor methodVisitor = functionMetadata.methodVisitor; if (functionMetadata.pythonCompiledFunction.totalArgCount() > 0) { // Use null as the key for the current instance, used by super() stackMetadata.localVariableHelper.readLocal(methodVisitor, 0); } else { // Put the current instance as null methodVisitor.visitInsn(Opcodes.ACONST_NULL); } } /** * Creates a function. The stack depends on {@code instruction.arg}: * * - If (arg &amp; 1) == 1, a tuple of default values for positional-only and positional-or-keyword parameters in positional * order * - If (arg &amp; 2) == 2, a dictionary of keyword-only parameters’ default values * - If (arg &amp; 4) == 4, an annotation dictionary * - If (arg &amp; 8) == 8, a tuple containing cells for free variables * * The stack will contain the following items, in the given order: * * TOP * [Mandatory] Function Name * [Mandatory] Class of the PythonLikeFunction to create * [Optional, flag = 0x8] A tuple containing the cells for free variables * [Optional, flag = 0x4] A tuple containing key,value pairs for the annotation directory * [Optional, flag = 0x2] A dictionary of keyword-only parameters’ default values * [Optional, flag = 0x1] A tuple of default values for positional-only and positional-or-keyword parameters in positional * order * BOTTOM * * All arguments are popped. A new instance of Class is created with the arguments and pushed to the stack. */ public static void createFunction(FunctionMetadata functionMetadata, StackMetadata stackMetadata, PythonBytecodeInstruction instruction) { MethodVisitor methodVisitor = functionMetadata.methodVisitor; String className = functionMetadata.className; if (functionMetadata.pythonCompiledFunction.pythonVersion.isAtLeast(PythonVersion.PYTHON_3_11)) { // Python 3.11 and above removed qualified name, so we need to get it from the code object's class methodVisitor.visitTypeInsn(Opcodes.CHECKCAST, Type.getInternalName(PythonCode.class)); methodVisitor.visitInsn(Opcodes.DUP); // TODO: maybe create qualifiedName field in PythonCode? methodVisitor.visitFieldInsn(Opcodes.GETFIELD, Type.getInternalName(PythonCode.class), "functionClass", Type.getDescriptor(Class.class)); // TODO: get qualified name from static field? methodVisitor.visitMethodInsn(Opcodes.INVOKEVIRTUAL, Type.getInternalName(Class.class), "getName", Type.getMethodDescriptor(Type.getType(String.class)), false); methodVisitor.visitMethodInsn(Opcodes.INVOKESTATIC, Type.getInternalName(PythonString.class), "valueOf", Type.getMethodDescriptor(Type.getType(PythonString.class), Type.getType(String.class)), false); stackMetadata = stackMetadata.pushTemp(BuiltinTypes.STRING_TYPE); } int providedOptionalArgs = Integer.bitCount(instruction.arg()); // If the argument present, decrement providedOptionalArgs to keep argument shifting logic the same // Ex: present, missing, present, present -> need to shift default for missing down by 4 = 2 + (3 - 1) // Ex: present, present, missing, present -> need to shift default for missing down by 3 = 2 + (3 - 2) // Ex: present, missing1, missing2, present -> need to shift default for missing1 down by 3 = 2 + (2 - 1), // need to shift default for missing2 down by 3 = 2 + (2 - 1) StackMetadata tempStackmetadata = stackMetadata; if ((instruction.arg() & 1) != 1) { CollectionImplementor.buildCollection(PythonLikeTuple.class, methodVisitor, 0); tempStackmetadata = tempStackmetadata.pushTemp(BuiltinTypes.TUPLE_TYPE); tempStackmetadata = StackManipulationImplementor.shiftTOSDownBy(functionMetadata, tempStackmetadata, 2 + providedOptionalArgs); } else { providedOptionalArgs--; } if ((instruction.arg() & 2) != 2) { CollectionImplementor.buildMap(PythonLikeDict.class, methodVisitor, 0); tempStackmetadata = tempStackmetadata.pushTemp(BuiltinTypes.DICT_TYPE); tempStackmetadata = StackManipulationImplementor.shiftTOSDownBy(functionMetadata, tempStackmetadata, 2 + providedOptionalArgs); } else { providedOptionalArgs--; } if ((instruction.arg() & 4) != 4) { // In Python 3.10 and above, it a tuple of string; in 3.9 and below, a dict if (functionMetadata.pythonCompiledFunction.pythonVersion.isBefore(PythonVersion.PYTHON_3_10)) { CollectionImplementor.buildMap(PythonLikeDict.class, methodVisitor, 0); tempStackmetadata = tempStackmetadata.pushTemp(BuiltinTypes.DICT_TYPE); tempStackmetadata = StackManipulationImplementor.shiftTOSDownBy(functionMetadata, tempStackmetadata, 2 + providedOptionalArgs); } else { CollectionImplementor.buildCollection(PythonLikeTuple.class, methodVisitor, 0); tempStackmetadata = tempStackmetadata.pushTemp(BuiltinTypes.TUPLE_TYPE); tempStackmetadata = StackManipulationImplementor.shiftTOSDownBy(functionMetadata, tempStackmetadata, 2 + providedOptionalArgs); } } else { providedOptionalArgs--; } if ((instruction.arg() & 8) != 8) { CollectionImplementor.buildCollection(PythonLikeTuple.class, methodVisitor, 0); tempStackmetadata = tempStackmetadata.pushTemp(BuiltinTypes.TUPLE_TYPE); tempStackmetadata = StackManipulationImplementor.shiftTOSDownBy(functionMetadata, tempStackmetadata, 2 + providedOptionalArgs); } // Stack is now: // default positional args, default keyword args, annotation directory tuple, cell tuple, function class, function name // Do type casts for name string and code object methodVisitor.visitTypeInsn(Opcodes.CHECKCAST, Type.getInternalName(PythonString.class)); methodVisitor.visitInsn(Opcodes.SWAP); methodVisitor.visitTypeInsn(Opcodes.CHECKCAST, Type.getInternalName(PythonCode.class)); // Pass the current function's interpreter to the new function instance methodVisitor.visitVarInsn(Opcodes.ALOAD, 0); methodVisitor.visitFieldInsn(Opcodes.GETFIELD, className, PythonBytecodeToJavaBytecodeTranslator.INTERPRETER_INSTANCE_FIELD_NAME, Type.getDescriptor(PythonInterpreter.class)); // Need to change constructor depending on Python version if (functionMetadata.pythonCompiledFunction.pythonVersion.isBefore(PythonVersion.PYTHON_3_10)) { methodVisitor.visitMethodInsn(Opcodes.INVOKESTATIC, Type.getInternalName(FunctionImplementor.class), "createInstance", Type.getMethodDescriptor(Type.getType(PythonLikeFunction.class), Type.getType(PythonLikeTuple.class), Type.getType(PythonLikeDict.class), Type.getType(PythonLikeDict.class), Type.getType(PythonLikeTuple.class), Type.getType(PythonString.class), Type.getType(PythonCode.class), Type.getType(PythonInterpreter.class)), false); } else { methodVisitor.visitMethodInsn(Opcodes.INVOKESTATIC, Type.getInternalName(FunctionImplementor.class), "createInstance", Type.getMethodDescriptor(Type.getType(PythonLikeFunction.class), Type.getType(PythonLikeTuple.class), Type.getType(PythonLikeDict.class), Type.getType(PythonLikeTuple.class), Type.getType(PythonLikeTuple.class), Type.getType(PythonString.class), Type.getType(PythonCode.class), Type.getType(PythonInterpreter.class)), false); } } // For Python 3.9 and below @SuppressWarnings("unused") public static PythonLikeFunction createInstance(PythonLikeTuple defaultPositionalArgs, PythonLikeDict defaultKeywordArgs, PythonLikeDict annotationDict, PythonLikeTuple closure, PythonString functionName, PythonCode code, PythonInterpreter pythonInterpreter) { return createInstance(defaultPositionalArgs, defaultKeywordArgs, annotationDict.toFlattenKeyValueTuple(), closure, functionName, code.functionClass, pythonInterpreter); } // For Python 3.10 and above @SuppressWarnings("unused") public static PythonLikeFunction createInstance(PythonLikeTuple defaultPositionalArgs, PythonLikeDict defaultKeywordArgs, PythonLikeTuple annotationTuple, PythonLikeTuple closure, PythonString functionName, PythonCode code, PythonInterpreter pythonInterpreter) { return createInstance(defaultPositionalArgs, defaultKeywordArgs, annotationTuple, closure, functionName, code.functionClass, pythonInterpreter); } public static <T> T createInstance(PythonLikeTuple defaultPositionalArgs, PythonLikeDict defaultKeywordArgs, PythonLikeTuple annotationTuple, PythonLikeTuple closure, PythonString functionName, Class<T> functionClass, PythonInterpreter pythonInterpreter) { PythonLikeDict annotationDirectory = new PythonLikeDict(); for (int i = 0; i < (annotationTuple.size() >> 1); i++) { annotationDirectory.put(annotationTuple.get(i * 2), annotationTuple.get(i * 2 + 1)); } try { Constructor<T> constructor = functionClass.getConstructor(PythonLikeTuple.class, PythonLikeDict.class, PythonLikeDict.class, PythonLikeTuple.class, PythonString.class, PythonInterpreter.class); return (T) constructor.newInstance(defaultPositionalArgs, defaultKeywordArgs, annotationDirectory, closure, functionName, pythonInterpreter); } catch (NoSuchMethodException | InvocationTargetException | InstantiationException | IllegalAccessException e) { throw new RuntimeException(e); } } public static class TupleMapPair { public PythonLikeTuple tuple; public PythonLikeDict map; List<PythonLikeObject> mapKeyTuple; final int totalNumberOfPositionalAndKeywordArguments; public TupleMapPair(int itemsToPop) { tuple = null; // Tuple is created when we know how many items are in it mapKeyTuple = null; // mapKeyTuple is the first item reverseAdded map = new PythonLikeDict(); this.totalNumberOfPositionalAndKeywordArguments = itemsToPop - 1; } public void reverseAdd(PythonLikeObject object) { if (mapKeyTuple == null) { mapKeyTuple = (List<PythonLikeObject>) object; tuple = new PythonLikeTuple(totalNumberOfPositionalAndKeywordArguments - mapKeyTuple.size()); return; } if (map.size() < mapKeyTuple.size()) { map.put(mapKeyTuple.get(mapKeyTuple.size() - map.size() - 1), object); } else { tuple.reverseAdd(object); } } } }
0
java-sources/ai/timefold/solver/jpyinterpreter/1.24.0/ai/timefold/jpyinterpreter
java-sources/ai/timefold/solver/jpyinterpreter/1.24.0/ai/timefold/jpyinterpreter/implementors/GeneratorImplementor.java
package ai.timefold.jpyinterpreter.implementors; import java.util.ArrayList; import java.util.List; import ai.timefold.jpyinterpreter.BytecodeSwitchImplementor; import ai.timefold.jpyinterpreter.FunctionMetadata; import ai.timefold.jpyinterpreter.PythonBinaryOperator; import ai.timefold.jpyinterpreter.PythonBytecodeInstruction; import ai.timefold.jpyinterpreter.PythonGeneratorTranslator; import ai.timefold.jpyinterpreter.PythonLikeObject; import ai.timefold.jpyinterpreter.PythonUnaryOperator; import ai.timefold.jpyinterpreter.StackMetadata; import ai.timefold.jpyinterpreter.types.PythonGenerator; import ai.timefold.jpyinterpreter.types.PythonLikeType; import ai.timefold.jpyinterpreter.types.errors.StopIteration; import org.objectweb.asm.Label; import org.objectweb.asm.MethodVisitor; import org.objectweb.asm.Opcodes; import org.objectweb.asm.Type; public class GeneratorImplementor { public static void restoreGeneratorState(FunctionMetadata functionMetadata, StackMetadata stackMetadata) { MethodVisitor methodVisitor = functionMetadata.methodVisitor; methodVisitor.visitVarInsn(Opcodes.ALOAD, 0); methodVisitor.visitFieldInsn(Opcodes.GETFIELD, functionMetadata.className, PythonGeneratorTranslator.GENERATOR_STACK, Type.getDescriptor(List.class)); for (int i = stackMetadata.getStackSize() - 1; i >= 0; i--) { methodVisitor.visitInsn(Opcodes.DUP); methodVisitor.visitLdcInsn(i); methodVisitor.visitMethodInsn(Opcodes.INVOKEINTERFACE, Type.getInternalName(List.class), "get", Type.getMethodDescriptor(Type.getType(Object.class), Type.INT_TYPE), true); methodVisitor.visitTypeInsn(Opcodes.CHECKCAST, stackMetadata.getTypeAtStackIndex(i).getJavaTypeInternalName()); methodVisitor.visitInsn(Opcodes.SWAP); } methodVisitor.visitInsn(Opcodes.POP); } private static void saveGeneratorState(PythonBytecodeInstruction instruction, FunctionMetadata functionMetadata, StackMetadata stackMetadata) { MethodVisitor methodVisitor = functionMetadata.methodVisitor; // Store stack in generatorStack methodVisitor.visitTypeInsn(Opcodes.NEW, Type.getInternalName(ArrayList.class)); methodVisitor.visitInsn(Opcodes.DUP); methodVisitor.visitLdcInsn(stackMetadata.getStackSize()); methodVisitor.visitMethodInsn(Opcodes.INVOKESPECIAL, Type.getInternalName(ArrayList.class), "<init>", Type.getMethodDescriptor(Type.VOID_TYPE, Type.INT_TYPE), false); methodVisitor.visitInsn(Opcodes.DUP); methodVisitor.visitVarInsn(Opcodes.ALOAD, 0); methodVisitor.visitInsn(Opcodes.SWAP); methodVisitor.visitFieldInsn(Opcodes.PUTFIELD, functionMetadata.className, PythonGeneratorTranslator.GENERATOR_STACK, Type.getDescriptor(List.class)); for (int i = 0; i < stackMetadata.getStackSize() - 1; i++) { methodVisitor.visitInsn(Opcodes.DUP_X1); methodVisitor.visitInsn(Opcodes.SWAP); methodVisitor.visitMethodInsn(Opcodes.INVOKEINTERFACE, Type.getInternalName(List.class), "add", Type.getMethodDescriptor(Type.BOOLEAN_TYPE, Type.getType(Object.class)), true); methodVisitor.visitInsn(Opcodes.POP); // Do not use return value of add } methodVisitor.visitInsn(Opcodes.POP); // Set the generator state methodVisitor.visitVarInsn(Opcodes.ALOAD, 0); methodVisitor.visitLdcInsn(instruction.offset() + 1); methodVisitor.visitFieldInsn(Opcodes.PUTFIELD, functionMetadata.className, PythonGeneratorTranslator.GENERATOR_STATE, Type.INT_TYPE.getDescriptor()); } public static void yieldValue(PythonBytecodeInstruction instruction, FunctionMetadata functionMetadata, StackMetadata stackMetadata) { MethodVisitor methodVisitor = functionMetadata.methodVisitor; // First, store TOS in yieldedValue methodVisitor.visitVarInsn(Opcodes.ALOAD, 0); methodVisitor.visitInsn(Opcodes.SWAP); methodVisitor.visitTypeInsn(Opcodes.CHECKCAST, Type.getInternalName(PythonLikeObject.class)); methodVisitor.visitFieldInsn(Opcodes.PUTFIELD, functionMetadata.className, PythonGeneratorTranslator.YIELDED_VALUE, Type.getDescriptor(PythonLikeObject.class)); // Next, save stack and generator position saveGeneratorState(instruction, functionMetadata, stackMetadata); // return control to the caller methodVisitor.visitInsn(Opcodes.RETURN); } public static void yieldFrom(PythonBytecodeInstruction instruction, FunctionMetadata functionMetadata, StackMetadata stackMetadata) { MethodVisitor methodVisitor = functionMetadata.methodVisitor; // TODO: Find out what TOS, which is usually None, is used for // Pop TOS (Unknown what is used for) methodVisitor.visitInsn(Opcodes.POP); // Store the subiterator into yieldFromIterator methodVisitor.visitVarInsn(Opcodes.ALOAD, 0); methodVisitor.visitInsn(Opcodes.SWAP); methodVisitor.visitFieldInsn(Opcodes.PUTFIELD, functionMetadata.className, PythonGeneratorTranslator.YIELD_FROM_ITERATOR, Type.getDescriptor(PythonLikeObject.class)); // Save stack and position // Store stack in both locals and fields, just in case the iterator stops iteration immediately int[] storedStack = StackManipulationImplementor.storeStack(methodVisitor, stackMetadata.pop(2)); saveGeneratorState(instruction, functionMetadata, stackMetadata.pop(2)); Label tryStartLabel = new Label(); Label tryEndLabel = new Label(); Label catchStartLabel = new Label(); Label catchEndLabel = new Label(); methodVisitor.visitTryCatchBlock(tryStartLabel, tryEndLabel, catchStartLabel, Type.getInternalName(StopIteration.class)); methodVisitor.visitLabel(tryStartLabel); methodVisitor.visitVarInsn(Opcodes.ALOAD, 0); methodVisitor.visitInsn(Opcodes.DUP); methodVisitor.visitFieldInsn(Opcodes.GETFIELD, functionMetadata.className, PythonGeneratorTranslator.YIELD_FROM_ITERATOR, Type.getDescriptor(PythonLikeObject.class)); DunderOperatorImplementor.unaryOperator(methodVisitor, PythonUnaryOperator.NEXT); methodVisitor.visitTypeInsn(Opcodes.CHECKCAST, Type.getInternalName(PythonLikeObject.class)); methodVisitor.visitFieldInsn(Opcodes.PUTFIELD, functionMetadata.className, PythonGeneratorTranslator.YIELDED_VALUE, Type.getDescriptor(PythonLikeObject.class)); methodVisitor.visitInsn(Opcodes.RETURN); // subiterator yielded something; return control to caller methodVisitor.visitLabel(tryEndLabel); methodVisitor.visitLabel(catchStartLabel); methodVisitor.visitInsn(Opcodes.POP); // pop the StopIteration exception methodVisitor.visitLabel(catchEndLabel); // Set yieldFromIterator to null since it is finished methodVisitor.visitVarInsn(Opcodes.ALOAD, 0); methodVisitor.visitInsn(Opcodes.ACONST_NULL); methodVisitor.visitFieldInsn(Opcodes.PUTFIELD, functionMetadata.className, PythonGeneratorTranslator.YIELD_FROM_ITERATOR, Type.getDescriptor(PythonLikeObject.class)); // Restore the stack, since subiterator was empty, and resume execution StackManipulationImplementor.restoreStack(methodVisitor, stackMetadata.pop(2), storedStack); // Since the subiterator was empty, push None to TOS PythonConstantsImplementor.loadNone(methodVisitor); } public static void progressSubgenerator(FunctionMetadata functionMetadata, StackMetadata stackMetadata, int jumpTarget) { MethodVisitor methodVisitor = functionMetadata.methodVisitor; int[] stackVariables = StackManipulationImplementor.storeStack(methodVisitor, stackMetadata); Label wasNotSentValue = new Label(); Label wasNotThrownValue = new Label(); Label iterateSubiterator = new Label(); // Stack is subgenerator, sentValue // Duplicate subgenerator methodVisitor.visitInsn(Opcodes.SWAP); methodVisitor.visitInsn(Opcodes.DUP_X1); methodVisitor.visitInsn(Opcodes.SWAP); // Duplicate sent value methodVisitor.visitInsn(Opcodes.DUP); // Check if sent a value PythonConstantsImplementor.loadNone(methodVisitor); methodVisitor.visitJumpInsn(Opcodes.IF_ACMPEQ, wasNotSentValue); methodVisitor.visitLdcInsn(1); methodVisitor.visitJumpInsn(Opcodes.GOTO, iterateSubiterator); methodVisitor.visitLabel(wasNotSentValue); // Check if thrown a value methodVisitor.visitInsn(Opcodes.POP); methodVisitor.visitVarInsn(Opcodes.ALOAD, 0); methodVisitor.visitFieldInsn(Opcodes.GETFIELD, Type.getInternalName(PythonGenerator.class), "thrownValue", Type.getDescriptor(Throwable.class)); methodVisitor.visitInsn(Opcodes.DUP); methodVisitor.visitInsn(Opcodes.ACONST_NULL); methodVisitor.visitJumpInsn(Opcodes.IF_ACMPEQ, wasNotThrownValue); methodVisitor.visitLdcInsn(2); methodVisitor.visitJumpInsn(Opcodes.GOTO, iterateSubiterator); methodVisitor.visitLabel(wasNotThrownValue); // Else, should call next so it will also works with iterables methodVisitor.visitInsn(Opcodes.POP); methodVisitor.visitInsn(Opcodes.ACONST_NULL); methodVisitor.visitLdcInsn(0); methodVisitor.visitLabel(iterateSubiterator); // Stack is subgenerator, sent/thrownValue, switchCaseLabel Label tryStartLabel = new Label(); Label tryEndLabel = new Label(); Label catchStartLabel = new Label(); Label catchEndLabel = new Label(); methodVisitor.visitTryCatchBlock(tryStartLabel, tryEndLabel, catchStartLabel, Type.getInternalName(StopIteration.class)); methodVisitor.visitLabel(tryStartLabel); BytecodeSwitchImplementor.createIntSwitch(methodVisitor, List.of(0, 1, 2), key -> { Label generatorOperationDone = new Label(); switch (key) { case 0: { // next methodVisitor.visitLdcInsn("next"); methodVisitor.visitInsn(Opcodes.POP); methodVisitor.visitInsn(Opcodes.POP); DunderOperatorImplementor.unaryOperator(methodVisitor, PythonUnaryOperator.NEXT); break; } case 1: { // send methodVisitor.visitLdcInsn("send"); methodVisitor.visitInsn(Opcodes.POP); methodVisitor.visitVarInsn(Opcodes.ALOAD, 0); PythonConstantsImplementor.loadNone(methodVisitor); methodVisitor.visitFieldInsn(Opcodes.PUTFIELD, Type.getInternalName(PythonGenerator.class), "sentValue", Type.getDescriptor(PythonLikeObject.class)); FunctionImplementor.callBinaryMethod(methodVisitor, PythonBinaryOperator.SEND.dunderMethod); break; } case 2: { // throw methodVisitor.visitLdcInsn("throw"); methodVisitor.visitInsn(Opcodes.POP); methodVisitor.visitTypeInsn(Opcodes.CHECKCAST, Type.getInternalName(Throwable.class)); methodVisitor.visitVarInsn(Opcodes.ALOAD, 0); methodVisitor.visitInsn(Opcodes.ACONST_NULL); methodVisitor.visitFieldInsn(Opcodes.PUTFIELD, Type.getInternalName(PythonGenerator.class), "thrownValue", Type.getDescriptor(Throwable.class)); methodVisitor.visitInsn(Opcodes.SWAP); // Stack is now Throwable, Generator // Check if the subgenerator has a "throw" method methodVisitor.visitInsn(Opcodes.DUP); methodVisitor.visitMethodInsn(Opcodes.INVOKEINTERFACE, Type.getInternalName(PythonLikeObject.class), "$getType", Type.getMethodDescriptor(Type.getType(PythonLikeType.class)), true); methodVisitor.visitLdcInsn("throw"); methodVisitor.visitMethodInsn(Opcodes.INVOKEINTERFACE, Type.getInternalName(PythonLikeObject.class), "$getAttributeOrNull", Type.getMethodDescriptor(Type.getType(PythonLikeObject.class), Type.getType(String.class)), true); // Stack is now Throwable, Generator, maybeMethod Label ifThrowMethodPresent = new Label(); methodVisitor.visitInsn(Opcodes.ACONST_NULL); methodVisitor.visitJumpInsn(Opcodes.IF_ACMPNE, ifThrowMethodPresent); // does not have a throw method // Set yieldFromIterator to null since it is finished methodVisitor.visitVarInsn(Opcodes.ALOAD, 0); methodVisitor.visitInsn(Opcodes.ACONST_NULL); methodVisitor.visitFieldInsn(Opcodes.PUTFIELD, functionMetadata.className, PythonGeneratorTranslator.YIELD_FROM_ITERATOR, Type.getDescriptor(PythonLikeObject.class)); methodVisitor.visitInsn(Opcodes.POP); methodVisitor.visitInsn(Opcodes.ATHROW); methodVisitor.visitLabel(ifThrowMethodPresent); // Swap so it Generator, Throwable instead of Throwable, Generator methodVisitor.visitInsn(Opcodes.SWAP); FunctionImplementor.callBinaryMethod(methodVisitor, PythonBinaryOperator.THROW.dunderMethod); break; } } methodVisitor.visitTypeInsn(Opcodes.CHECKCAST, Type.getInternalName(PythonLikeObject.class)); }, () -> { methodVisitor.visitTypeInsn(Opcodes.NEW, Type.getInternalName(IllegalStateException.class)); methodVisitor.visitInsn(Opcodes.DUP); methodVisitor.visitMethodInsn(Opcodes.INVOKESPECIAL, Type.getInternalName(IllegalStateException.class), "<init>", Type.getMethodDescriptor(Type.VOID_TYPE), false); methodVisitor.visitInsn(Opcodes.ATHROW); }, false); methodVisitor.visitLabel(tryEndLabel); methodVisitor.visitJumpInsn(Opcodes.GOTO, catchEndLabel); methodVisitor.visitLabel(catchStartLabel); methodVisitor.visitInsn(Opcodes.POP); // pop the StopIteration exception StackManipulationImplementor.restoreStack(methodVisitor, stackMetadata, stackVariables); JumpImplementor.jumpAbsolute(functionMetadata, stackMetadata, jumpTarget); methodVisitor.visitLabel(catchEndLabel); } public static void getYieldFromIter(FunctionMetadata functionMetadata, StackMetadata stackMetadata) { MethodVisitor methodVisitor = functionMetadata.methodVisitor; Label isGeneratorOrCoroutine = new Label(); methodVisitor.visitInsn(Opcodes.DUP); methodVisitor.visitTypeInsn(Opcodes.INSTANCEOF, Type.getInternalName(PythonGenerator.class)); methodVisitor.visitJumpInsn(Opcodes.IFNE, isGeneratorOrCoroutine); // not a generator/coroutine DunderOperatorImplementor.unaryOperator(methodVisitor, stackMetadata, PythonUnaryOperator.ITERATOR); methodVisitor.visitLabel(isGeneratorOrCoroutine); } public static void endGenerator(FunctionMetadata functionMetadata, StackMetadata stackMetadata) { MethodVisitor methodVisitor = functionMetadata.methodVisitor; // First, store TOS in yieldedValue methodVisitor.visitVarInsn(Opcodes.ALOAD, 0); methodVisitor.visitInsn(Opcodes.SWAP); methodVisitor.visitTypeInsn(Opcodes.CHECKCAST, Type.getInternalName(PythonLikeObject.class)); methodVisitor.visitFieldInsn(Opcodes.PUTFIELD, functionMetadata.className, PythonGeneratorTranslator.YIELDED_VALUE, Type.getDescriptor(PythonLikeObject.class)); // Next, set generatorStack to null methodVisitor.visitVarInsn(Opcodes.ALOAD, 0); methodVisitor.visitInsn(Opcodes.ACONST_NULL); methodVisitor.visitFieldInsn(Opcodes.PUTFIELD, functionMetadata.className, PythonGeneratorTranslator.GENERATOR_STACK, Type.getDescriptor(List.class)); // Set the generator state methodVisitor.visitVarInsn(Opcodes.ALOAD, 0); methodVisitor.visitLdcInsn(-1); methodVisitor.visitFieldInsn(Opcodes.PUTFIELD, functionMetadata.className, PythonGeneratorTranslator.GENERATOR_STATE, Type.INT_TYPE.getDescriptor()); methodVisitor.visitInsn(Opcodes.RETURN); } public static void generatorStart(FunctionMetadata functionMetadata, StackMetadata stackMetadata) { MethodVisitor methodVisitor = functionMetadata.methodVisitor; methodVisitor.visitInsn(Opcodes.POP); // Despite stackMetadata says it empty, the stack actually has // one item: the first sent item, which MUST BE None } }
0
java-sources/ai/timefold/solver/jpyinterpreter/1.24.0/ai/timefold/jpyinterpreter
java-sources/ai/timefold/solver/jpyinterpreter/1.24.0/ai/timefold/jpyinterpreter/implementors/JavaComparableImplementor.java
package ai.timefold.jpyinterpreter.implementors; import java.lang.reflect.Modifier; import ai.timefold.jpyinterpreter.CompareOp; import ai.timefold.jpyinterpreter.PythonClassTranslator; import ai.timefold.jpyinterpreter.PythonCompiledClass; import ai.timefold.jpyinterpreter.PythonCompiledFunction; import ai.timefold.jpyinterpreter.types.PythonLikeType; import ai.timefold.jpyinterpreter.types.errors.NotImplementedError; import org.objectweb.asm.ClassWriter; import org.objectweb.asm.Label; import org.objectweb.asm.MethodVisitor; import org.objectweb.asm.Opcodes; import org.objectweb.asm.Type; public class JavaComparableImplementor extends JavaInterfaceImplementor { final String internalClassName; final CompareOp compareOp; public JavaComparableImplementor(String internalClassName, String method) { this.internalClassName = internalClassName; this.compareOp = CompareOp.getOpForDunderMethod(method); switch (compareOp) { case LESS_THAN: case LESS_THAN_OR_EQUALS: case GREATER_THAN: case GREATER_THAN_OR_EQUALS: break; default: throw new IllegalStateException("Cannot use " + method + " for comparisons"); } } @Override public Class<?> getInterfaceClass() { return Comparable.class; } private void typeCheck(MethodVisitor methodVisitor) { methodVisitor.visitInsn(Opcodes.DUP); methodVisitor.visitTypeInsn(Opcodes.INSTANCEOF, internalClassName); Label isInstanceOfClass = new Label(); methodVisitor.visitJumpInsn(Opcodes.IFNE, isInstanceOfClass); // Throw an exception since the argument is not a Python Like Object methodVisitor.visitTypeInsn(Opcodes.NEW, Type.getInternalName(NotImplementedError.class)); methodVisitor.visitInsn(Opcodes.DUP); methodVisitor.visitLdcInsn("compareTo arg 0 is not an instance of " + internalClassName); methodVisitor.visitMethodInsn(Opcodes.INVOKESPECIAL, Type.getInternalName(NotImplementedError.class), "<init>", Type.getMethodDescriptor(Type.VOID_TYPE, Type.getType(String.class)), false); methodVisitor.visitInsn(Opcodes.ATHROW); methodVisitor.visitLabel(isInstanceOfClass); methodVisitor.visitTypeInsn(Opcodes.CHECKCAST, internalClassName); } @Override public void implement(ClassWriter classWriter, PythonCompiledClass compiledClass) { MethodVisitor methodVisitor = classWriter.visitMethod(Modifier.PUBLIC, "compareTo", Type.getMethodDescriptor(Type.INT_TYPE, Type.getType(Object.class)), null, null); methodVisitor.visitParameter("other", 0); methodVisitor.visitCode(); switch (compareOp) { case LESS_THAN: implementCompareToWithLessThan(methodVisitor, compiledClass); break; case LESS_THAN_OR_EQUALS: implementCompareToWithLessThanOrEqual(methodVisitor, compiledClass); break; case GREATER_THAN: implementCompareToWithGreaterThan(methodVisitor, compiledClass); break; case GREATER_THAN_OR_EQUALS: implementCompareToWithGreaterThanOrEqual(methodVisitor, compiledClass); break; default: throw new IllegalStateException("Impossible state: " + compareOp + " is not a comparison operator"); } methodVisitor.visitMaxs(0, 0); methodVisitor.visitEnd(); } // The following code exploit these fact: // a < b == a < b // a > b == b < a // !(a >= b) == a < b // !(a <= b) == a > b == b < a private void implementCompareToWithLessThan(MethodVisitor methodVisitor, PythonCompiledClass pythonCompiledClass) { PythonCompiledFunction comparisonFunction = pythonCompiledClass.instanceFunctionNameToPythonBytecode.get("__lt__"); String comparisonMethodName = PythonClassTranslator.getJavaMethodName("__lt__"); implementCompareTo(methodVisitor, comparisonFunction, comparisonMethodName, false, true); } private void implementCompareToWithGreaterThan(MethodVisitor methodVisitor, PythonCompiledClass pythonCompiledClass) { PythonCompiledFunction comparisonFunction = pythonCompiledClass.instanceFunctionNameToPythonBytecode.get("__gt__"); String comparisonMethodName = PythonClassTranslator.getJavaMethodName("__gt__"); implementCompareTo(methodVisitor, comparisonFunction, comparisonMethodName, false, false); } private void implementCompareToWithLessThanOrEqual(MethodVisitor methodVisitor, PythonCompiledClass pythonCompiledClass) { PythonCompiledFunction comparisonFunction = pythonCompiledClass.instanceFunctionNameToPythonBytecode.get("__le__"); String comparisonMethodName = PythonClassTranslator.getJavaMethodName("__le__"); implementCompareTo(methodVisitor, comparisonFunction, comparisonMethodName, true, false); } private void implementCompareToWithGreaterThanOrEqual(MethodVisitor methodVisitor, PythonCompiledClass pythonCompiledClass) { PythonCompiledFunction comparisonFunction = pythonCompiledClass.instanceFunctionNameToPythonBytecode.get("__ge__"); String comparisonMethodName = PythonClassTranslator.getJavaMethodName("__ge__"); implementCompareTo(methodVisitor, comparisonFunction, comparisonMethodName, true, true); } /** * Create this code: * * <pre> * if (self < other) == not negateComparisionResult: * return isLessThan? -1 : 1 * elif (other < self) == True: * return isLessThan? 1 : -1 * else: * return 0 * </pre> * * The negateComparisonResult turns __ge__ and __le__ into __lt__ and __gt__ respectively. * isLessThan reverses the comparison if false. * */ private void implementCompareTo(MethodVisitor methodVisitor, PythonCompiledFunction comparisonFunction, String comparisonMethodName, boolean negateComparisionResult, boolean isLessThan) { PythonLikeType parameterType = comparisonFunction.getParameterTypes().get(1); Type returnType = PythonClassTranslator.getVirtualFunctionReturnType(comparisonFunction); methodVisitor.visitVarInsn(Opcodes.ALOAD, 0); methodVisitor.visitVarInsn(Opcodes.ALOAD, 1); typeCheck(methodVisitor); methodVisitor.visitInsn(Opcodes.DUP2); methodVisitor.visitMethodInsn(Opcodes.INVOKEVIRTUAL, internalClassName, comparisonMethodName, Type.getMethodDescriptor(returnType, Type.getType(parameterType.getJavaTypeDescriptor())), false); Label ifSelfNotLessThanOther = new Label(); if (negateComparisionResult) { PythonConstantsImplementor.loadFalse(methodVisitor); } else { PythonConstantsImplementor.loadTrue(methodVisitor); } methodVisitor.visitJumpInsn(Opcodes.IF_ACMPNE, ifSelfNotLessThanOther); methodVisitor.visitInsn(isLessThan ? Opcodes.ICONST_M1 : Opcodes.ICONST_1); methodVisitor.visitInsn(Opcodes.IRETURN); methodVisitor.visitLabel(ifSelfNotLessThanOther); methodVisitor.visitInsn(Opcodes.SWAP); methodVisitor.visitMethodInsn(Opcodes.INVOKEVIRTUAL, internalClassName, comparisonMethodName, Type.getMethodDescriptor(returnType, Type.getType(parameterType.getJavaTypeDescriptor())), false); Label ifOtherNotLessThanSelf = new Label(); if (negateComparisionResult) { PythonConstantsImplementor.loadFalse(methodVisitor); } else { PythonConstantsImplementor.loadTrue(methodVisitor); } methodVisitor.visitJumpInsn(Opcodes.IF_ACMPNE, ifOtherNotLessThanSelf); methodVisitor.visitInsn(isLessThan ? Opcodes.ICONST_1 : Opcodes.ICONST_M1); methodVisitor.visitInsn(Opcodes.IRETURN); methodVisitor.visitLabel(ifOtherNotLessThanSelf); methodVisitor.visitInsn(Opcodes.ICONST_0); methodVisitor.visitInsn(Opcodes.IRETURN); } }
0
java-sources/ai/timefold/solver/jpyinterpreter/1.24.0/ai/timefold/jpyinterpreter
java-sources/ai/timefold/solver/jpyinterpreter/1.24.0/ai/timefold/jpyinterpreter/implementors/JavaEqualsImplementor.java
package ai.timefold.jpyinterpreter.implementors; import java.lang.reflect.Modifier; import ai.timefold.jpyinterpreter.PythonClassTranslator; import ai.timefold.jpyinterpreter.PythonCompiledClass; import ai.timefold.jpyinterpreter.PythonCompiledFunction; import ai.timefold.jpyinterpreter.types.PythonLikeType; import org.objectweb.asm.ClassWriter; import org.objectweb.asm.Label; import org.objectweb.asm.MethodVisitor; import org.objectweb.asm.Opcodes; import org.objectweb.asm.Type; public class JavaEqualsImplementor extends JavaInterfaceImplementor { final String internalClassName; public JavaEqualsImplementor(String internalClassName) { this.internalClassName = internalClassName; } @Override public Class<?> getInterfaceClass() { return Object.class; } private void typeCheck(MethodVisitor methodVisitor, PythonLikeType parameterType) { methodVisitor.visitInsn(Opcodes.DUP); methodVisitor.visitTypeInsn(Opcodes.INSTANCEOF, parameterType.getJavaTypeInternalName()); Label isInstanceOfClass = new Label(); methodVisitor.visitJumpInsn(Opcodes.IFNE, isInstanceOfClass); // Return false since the objects cannot be compared for equals methodVisitor.visitInsn(Opcodes.ICONST_0); methodVisitor.visitInsn(Opcodes.IRETURN); // Cast methodVisitor.visitLabel(isInstanceOfClass); methodVisitor.visitTypeInsn(Opcodes.CHECKCAST, parameterType.getJavaTypeInternalName()); } @Override public void implement(ClassWriter classWriter, PythonCompiledClass compiledClass) { PythonCompiledFunction comparisonFunction = compiledClass.instanceFunctionNameToPythonBytecode.get("__eq__"); PythonLikeType parameterType = comparisonFunction.getParameterTypes().get(1); String methodName = PythonClassTranslator.getJavaMethodName("__eq__"); Type returnType = PythonClassTranslator.getVirtualFunctionReturnType(comparisonFunction); MethodVisitor methodVisitor = classWriter.visitMethod(Modifier.PUBLIC, "equals", Type.getMethodDescriptor(Type.BOOLEAN_TYPE, Type.getType(Object.class)), null, null); methodVisitor.visitParameter("other", 0); methodVisitor.visitCode(); methodVisitor.visitVarInsn(Opcodes.ALOAD, 0); methodVisitor.visitVarInsn(Opcodes.ALOAD, 1); typeCheck(methodVisitor, parameterType); methodVisitor.visitMethodInsn(Opcodes.INVOKEVIRTUAL, internalClassName, methodName, Type.getMethodDescriptor(returnType, Type.getType(parameterType.getJavaTypeDescriptor())), false); Label ifNotEquals = new Label(); PythonConstantsImplementor.loadTrue(methodVisitor); methodVisitor.visitJumpInsn(Opcodes.IF_ACMPNE, ifNotEquals); methodVisitor.visitInsn(Opcodes.ICONST_1); methodVisitor.visitInsn(Opcodes.IRETURN); methodVisitor.visitLabel(ifNotEquals); methodVisitor.visitInsn(Opcodes.ICONST_0); methodVisitor.visitInsn(Opcodes.IRETURN); methodVisitor.visitMaxs(0, 0); methodVisitor.visitEnd(); } }
0
java-sources/ai/timefold/solver/jpyinterpreter/1.24.0/ai/timefold/jpyinterpreter
java-sources/ai/timefold/solver/jpyinterpreter/1.24.0/ai/timefold/jpyinterpreter/implementors/JavaHashCodeImplementor.java
package ai.timefold.jpyinterpreter.implementors; import java.lang.reflect.Modifier; import ai.timefold.jpyinterpreter.PythonClassTranslator; import ai.timefold.jpyinterpreter.PythonCompiledClass; import ai.timefold.jpyinterpreter.PythonCompiledFunction; import org.objectweb.asm.ClassWriter; import org.objectweb.asm.MethodVisitor; import org.objectweb.asm.Opcodes; import org.objectweb.asm.Type; public class JavaHashCodeImplementor extends JavaInterfaceImplementor { final String internalClassName; public JavaHashCodeImplementor(String internalClassName) { this.internalClassName = internalClassName; } @Override public Class<?> getInterfaceClass() { return Object.class; } @Override public void implement(ClassWriter classWriter, PythonCompiledClass compiledClass) { PythonCompiledFunction comparisonFunction = compiledClass.instanceFunctionNameToPythonBytecode.get("__hash__"); String methodName = PythonClassTranslator.getJavaMethodName("__hash__"); Type returnType = PythonClassTranslator.getVirtualFunctionReturnType(comparisonFunction); MethodVisitor methodVisitor = classWriter.visitMethod(Modifier.PUBLIC, "hashCode", Type.getMethodDescriptor(Type.INT_TYPE), null, null); methodVisitor.visitCode(); methodVisitor.visitVarInsn(Opcodes.ALOAD, 0); methodVisitor.visitMethodInsn(Opcodes.INVOKEVIRTUAL, internalClassName, methodName, Type.getMethodDescriptor(returnType), false); methodVisitor.visitMethodInsn(Opcodes.INVOKEVIRTUAL, Type.getInternalName(Object.class), "hashCode", Type.getMethodDescriptor(Type.INT_TYPE), false); methodVisitor.visitInsn(Opcodes.IRETURN); methodVisitor.visitMaxs(0, 0); methodVisitor.visitEnd(); } }
0
java-sources/ai/timefold/solver/jpyinterpreter/1.24.0/ai/timefold/jpyinterpreter
java-sources/ai/timefold/solver/jpyinterpreter/1.24.0/ai/timefold/jpyinterpreter/implementors/JavaInterfaceImplementor.java
package ai.timefold.jpyinterpreter.implementors; import ai.timefold.jpyinterpreter.PythonCompiledClass; import org.objectweb.asm.ClassWriter; public abstract class JavaInterfaceImplementor { public abstract Class<?> getInterfaceClass(); public abstract void implement(ClassWriter classWriter, PythonCompiledClass compiledClass); @Override public final boolean equals(Object o) { if (!(o instanceof JavaInterfaceImplementor)) { return false; } if (getInterfaceClass().equals(Object.class)) { return getClass().equals(o.getClass()); } return getInterfaceClass().equals(((JavaInterfaceImplementor) o).getInterfaceClass()); } @Override public final int hashCode() { return getInterfaceClass().hashCode(); } }
0
java-sources/ai/timefold/solver/jpyinterpreter/1.24.0/ai/timefold/jpyinterpreter
java-sources/ai/timefold/solver/jpyinterpreter/1.24.0/ai/timefold/jpyinterpreter/implementors/JavaPythonTypeConversionImplementor.java
package ai.timefold.jpyinterpreter.implementors; import java.lang.reflect.Field; import java.math.BigDecimal; import java.math.BigInteger; import java.util.IdentityHashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; import ai.timefold.jpyinterpreter.LocalVariableHelper; import ai.timefold.jpyinterpreter.MethodDescriptor; import ai.timefold.jpyinterpreter.PythonClassTranslator; import ai.timefold.jpyinterpreter.PythonLikeObject; import ai.timefold.jpyinterpreter.StackMetadata; import ai.timefold.jpyinterpreter.types.BuiltinTypes; import ai.timefold.jpyinterpreter.types.Coercible; import ai.timefold.jpyinterpreter.types.PythonByteArray; import ai.timefold.jpyinterpreter.types.PythonBytes; import ai.timefold.jpyinterpreter.types.PythonCode; import ai.timefold.jpyinterpreter.types.PythonLikeFunction; import ai.timefold.jpyinterpreter.types.PythonLikeType; import ai.timefold.jpyinterpreter.types.PythonNone; import ai.timefold.jpyinterpreter.types.PythonString; import ai.timefold.jpyinterpreter.types.collections.DelegatePythonIterator; import ai.timefold.jpyinterpreter.types.collections.PythonIterator; import ai.timefold.jpyinterpreter.types.collections.PythonLikeDict; import ai.timefold.jpyinterpreter.types.collections.PythonLikeFrozenSet; import ai.timefold.jpyinterpreter.types.collections.PythonLikeList; import ai.timefold.jpyinterpreter.types.collections.PythonLikeSet; import ai.timefold.jpyinterpreter.types.collections.PythonLikeTuple; import ai.timefold.jpyinterpreter.types.errors.TypeError; import ai.timefold.jpyinterpreter.types.numeric.PythonBoolean; import ai.timefold.jpyinterpreter.types.numeric.PythonDecimal; import ai.timefold.jpyinterpreter.types.numeric.PythonFloat; import ai.timefold.jpyinterpreter.types.numeric.PythonInteger; import ai.timefold.jpyinterpreter.types.numeric.PythonNumber; import ai.timefold.jpyinterpreter.types.wrappers.JavaObjectWrapper; import ai.timefold.jpyinterpreter.types.wrappers.OpaqueJavaReference; import ai.timefold.jpyinterpreter.types.wrappers.OpaquePythonReference; import ai.timefold.jpyinterpreter.types.wrappers.PythonObjectWrapper; import org.objectweb.asm.MethodVisitor; import org.objectweb.asm.Opcodes; import org.objectweb.asm.Type; /** * Implementations of opcodes and operations that require Java to Python or Python to Java conversions. */ public class JavaPythonTypeConversionImplementor { /** * Wraps {@code object} to a PythonLikeObject. */ public static PythonLikeObject wrapJavaObject(Object object) { return wrapJavaObject(object, new IdentityHashMap<>()); } public static PythonLikeObject wrapJavaObject(Object object, Map<Object, PythonLikeObject> createdObjectMap) { if (object == null) { return PythonNone.INSTANCE; } var existingObject = createdObjectMap.get(object); if (existingObject != null) { return existingObject; } if (object instanceof OpaqueJavaReference opaqueJavaReference) { return opaqueJavaReference.proxy(); } if (object instanceof PythonLikeObject instance) { // Object already a PythonLikeObject; need to do nothing return instance; } if (object instanceof Byte || object instanceof Short || object instanceof Integer || object instanceof Long) { return PythonInteger.valueOf(((Number) object).longValue()); } if (object instanceof BigInteger integer) { return PythonInteger.valueOf(integer); } if (object instanceof BigDecimal decimal) { return new PythonDecimal(decimal); } if (object instanceof Float || object instanceof Double) { return PythonFloat.valueOf(((Number) object).doubleValue()); } if (object instanceof Boolean booleanValue) { return PythonBoolean.valueOf(booleanValue); } if (object instanceof String string) { return PythonString.valueOf(string); } if (object instanceof Iterator<?> iterator) { return new DelegatePythonIterator<>(iterator); } if (object instanceof List<?> list) { PythonLikeList<?> out = new PythonLikeList<>(); createdObjectMap.put(object, out); for (Object item : list) { out.add(wrapJavaObject(item)); } return out; } if (object instanceof Set<?> set) { PythonLikeSet<?> out = new PythonLikeSet<>(); createdObjectMap.put(object, out); for (Object item : set) { out.add(wrapJavaObject(item)); } return out; } if (object instanceof Map<?, ?> map) { PythonLikeDict<?, ?> out = new PythonLikeDict<>(); createdObjectMap.put(object, out); var entrySet = map.entrySet(); for (var entry : entrySet) { out.put(wrapJavaObject(entry.getKey()), wrapJavaObject(entry.getValue())); } return out; } if (object instanceof Class<?> maybeFunctionClass && Set.of(maybeFunctionClass.getInterfaces()).contains(PythonLikeFunction.class)) { return new PythonCode((Class<? extends PythonLikeFunction>) maybeFunctionClass); } if (object instanceof OpaquePythonReference opaquePythonReference) { return new PythonObjectWrapper(opaquePythonReference); } // Default: return a JavaObjectWrapper return new JavaObjectWrapper(object, createdObjectMap); } /** * Get the {@link PythonLikeType} of a java {@link Class}. */ public static PythonLikeType getPythonLikeType(Class<?> javaClass) { if (PythonNone.class.equals(javaClass)) { return BuiltinTypes.NONE_TYPE; } if (PythonLikeObject.class.equals(javaClass)) { return BuiltinTypes.BASE_TYPE; } if (byte.class.equals(javaClass) || short.class.equals(javaClass) || int.class.equals(javaClass) || long.class.equals(javaClass) || Byte.class.equals(javaClass) || Short.class.equals(javaClass) || Integer.class.equals(javaClass) || Long.class.equals(javaClass) || BigInteger.class.equals(javaClass) || PythonInteger.class.equals(javaClass)) { return BuiltinTypes.INT_TYPE; } if (BigDecimal.class.equals(javaClass) || PythonDecimal.class.equals(javaClass)) { return BuiltinTypes.DECIMAL_TYPE; } if (float.class.equals(javaClass) || double.class.equals(javaClass) || Float.class.equals(javaClass) || Double.class.equals(javaClass) || PythonFloat.class.equals(javaClass)) { return BuiltinTypes.FLOAT_TYPE; } if (PythonNumber.class.equals(javaClass)) { return BuiltinTypes.NUMBER_TYPE; } if (boolean.class.equals(javaClass) || Boolean.class.equals(javaClass) || PythonBoolean.class.equals(javaClass)) { return BuiltinTypes.BOOLEAN_TYPE; } if (String.class.equals(javaClass) || PythonString.class.equals(javaClass)) { return BuiltinTypes.STRING_TYPE; } if (PythonBytes.class.equals(javaClass)) { return BuiltinTypes.BYTES_TYPE; } if (PythonByteArray.class.equals(javaClass)) { return BuiltinTypes.BYTE_ARRAY_TYPE; } if (Iterator.class.equals(javaClass) || PythonIterator.class.equals(javaClass)) { return BuiltinTypes.ITERATOR_TYPE; } if (List.class.equals(javaClass) || PythonLikeList.class.equals(javaClass)) { return BuiltinTypes.LIST_TYPE; } if (PythonLikeTuple.class.equals(javaClass)) { return BuiltinTypes.TUPLE_TYPE; } if (Set.class.equals(javaClass) || PythonLikeSet.class.equals(javaClass)) { return BuiltinTypes.SET_TYPE; } if (PythonLikeFrozenSet.class.equals(javaClass)) { return BuiltinTypes.FROZEN_SET_TYPE; } if (Map.class.equals(javaClass) || PythonLikeDict.class.equals(javaClass)) { return BuiltinTypes.DICT_TYPE; } if (PythonLikeType.class.equals(javaClass)) { return BuiltinTypes.TYPE_TYPE; } try { Field typeField = javaClass.getField(PythonClassTranslator.TYPE_FIELD_NAME); Object maybeType = typeField.get(null); if (maybeType instanceof PythonLikeType) { return (PythonLikeType) maybeType; } if (PythonLikeFunction.class.isAssignableFrom(javaClass)) { return PythonLikeFunction.getFunctionType(); } return JavaObjectWrapper.getPythonTypeForClass(javaClass); } catch (NoSuchFieldException | IllegalAccessException e) { if (PythonLikeFunction.class.isAssignableFrom(javaClass)) { return PythonLikeFunction.getFunctionType(); } return JavaObjectWrapper.getPythonTypeForClass(javaClass); } } /** * Converts a {@code PythonLikeObject} to the given {@code type}. */ @SuppressWarnings("unchecked") public static <T> T convertPythonObjectToJavaType(Class<? extends T> type, PythonLikeObject object) { if (object == null || type.isAssignableFrom(object.getClass())) { // Can directly assign; no modification needed return (T) object; } if (object instanceof PythonNone) { return null; } if (object instanceof JavaObjectWrapper wrappedObject) { Object javaObject = wrappedObject.getWrappedObject(); if (!type.isAssignableFrom(javaObject.getClass())) { throw new TypeError("Cannot convert from (" + getPythonLikeType(javaObject.getClass()) + ") to (" + getPythonLikeType(type) + ")."); } return (T) javaObject; } if (type.equals(byte.class) || type.equals(short.class) || type.equals(int.class) || type.equals(long.class) || type.equals(float.class) || type.equals(double.class) || Number.class.isAssignableFrom(type)) { if (!(object instanceof PythonNumber pythonNumber)) { throw new TypeError("Cannot convert from (" + getPythonLikeType(object.getClass()) + ") to (" + getPythonLikeType(type) + ")."); } Number value = pythonNumber.getValue(); if (type.equals(BigInteger.class) || type.equals(BigDecimal.class)) { return (T) value; } if (type.equals(byte.class) || type.equals(Byte.class)) { return (T) (Byte) value.byteValue(); } if (type.equals(short.class) || type.equals(Short.class)) { return (T) (Short) value.shortValue(); } if (type.equals(int.class) || type.equals(Integer.class)) { return (T) (Integer) value.intValue(); } if (type.equals(long.class) || type.equals(Long.class)) { return (T) (Long) value.longValue(); } if (type.equals(float.class) || type.equals(Float.class)) { return (T) (Float) value.floatValue(); } if (type.equals(double.class) || type.equals(Double.class)) { return (T) (Double) value.doubleValue(); } } if (type.equals(boolean.class) || type.equals(Boolean.class)) { if (!(object instanceof PythonBoolean pythonBoolean)) { throw new TypeError("Cannot convert from (" + getPythonLikeType(object.getClass()) + ") to (" + getPythonLikeType(type) + ")."); } return (T) (Boolean) pythonBoolean.getBooleanValue(); } if (type.equals(String.class)) { PythonString pythonString = (PythonString) object; return (T) pythonString.getValue(); } // TODO: List, Map, Set throw new TypeError( "Cannot convert from (" + getPythonLikeType(object.getClass()) + ") to (" + getPythonLikeType(type) + ")."); } /** * Loads a String and push it onto the stack * * @param name The name to load */ public static void loadName(MethodVisitor methodVisitor, String name) { methodVisitor.visitLdcInsn(name); methodVisitor.visitMethodInsn(Opcodes.INVOKESTATIC, Type.getInternalName(PythonString.class), "valueOf", Type.getMethodDescriptor(Type.getType(PythonString.class), Type.getType(PythonString.class)), false); } public static void unboxBoxedPrimitiveType(Class<?> primitiveType, MethodVisitor methodVisitor) { unboxBoxedPrimitiveType(Type.getType(primitiveType), methodVisitor); } public static void unboxBoxedPrimitiveType(Type primitiveType, MethodVisitor methodVisitor) { if (primitiveType.equals(Type.BOOLEAN_TYPE)) { methodVisitor.visitTypeInsn(Opcodes.CHECKCAST, Type.getInternalName(Boolean.class)); methodVisitor.visitMethodInsn(Opcodes.INVOKEVIRTUAL, Type.getInternalName(Boolean.class), "booleanValue", Type.getMethodDescriptor(Type.BOOLEAN_TYPE), false); } else if (primitiveType.equals(Type.BYTE_TYPE)) { methodVisitor.visitTypeInsn(Opcodes.CHECKCAST, Type.getInternalName(Byte.class)); methodVisitor.visitMethodInsn(Opcodes.INVOKEVIRTUAL, Type.getInternalName(Byte.class), "byteValue", Type.getMethodDescriptor(Type.BYTE_TYPE), false); } else if (primitiveType.equals(Type.CHAR_TYPE)) { methodVisitor.visitTypeInsn(Opcodes.CHECKCAST, Type.getInternalName(Character.class)); methodVisitor.visitMethodInsn(Opcodes.INVOKEVIRTUAL, Type.getInternalName(Character.class), "charValue", Type.getMethodDescriptor(Type.CHAR_TYPE), false); } else if (primitiveType.equals(Type.SHORT_TYPE)) { methodVisitor.visitTypeInsn(Opcodes.CHECKCAST, Type.getInternalName(Short.class)); methodVisitor.visitMethodInsn(Opcodes.INVOKEVIRTUAL, Type.getInternalName(Short.class), "shortValue", Type.getMethodDescriptor(Type.SHORT_TYPE), false); } else if (primitiveType.equals(Type.INT_TYPE)) { methodVisitor.visitTypeInsn(Opcodes.CHECKCAST, Type.getInternalName(Integer.class)); methodVisitor.visitMethodInsn(Opcodes.INVOKEVIRTUAL, Type.getInternalName(Integer.class), "intValue", Type.getMethodDescriptor(Type.INT_TYPE), false); } else if (primitiveType.equals(Type.LONG_TYPE)) { methodVisitor.visitTypeInsn(Opcodes.CHECKCAST, Type.getInternalName(Long.class)); methodVisitor.visitMethodInsn(Opcodes.INVOKEVIRTUAL, Type.getInternalName(Long.class), "longValue", Type.getMethodDescriptor(Type.LONG_TYPE), false); } else if (primitiveType.equals(Type.FLOAT_TYPE)) { methodVisitor.visitTypeInsn(Opcodes.CHECKCAST, Type.getInternalName(Float.class)); methodVisitor.visitMethodInsn(Opcodes.INVOKEVIRTUAL, Type.getInternalName(Float.class), "floatValue", Type.getMethodDescriptor(Type.FLOAT_TYPE), false); } else if (primitiveType.equals(Type.DOUBLE_TYPE)) { methodVisitor.visitTypeInsn(Opcodes.CHECKCAST, Type.getInternalName(Double.class)); methodVisitor.visitMethodInsn(Opcodes.INVOKEVIRTUAL, Type.getInternalName(Double.class), "doubleValue", Type.getMethodDescriptor(Type.DOUBLE_TYPE), false); } else { throw new IllegalStateException("Unknown primitive type %s.".formatted(primitiveType)); } } public static void boxPrimitiveType(Class<?> primitiveType, MethodVisitor methodVisitor) { boxPrimitiveType(Type.getType(primitiveType), methodVisitor); } public static void boxPrimitiveType(Type primitiveType, MethodVisitor methodVisitor) { if (primitiveType.equals(Type.BOOLEAN_TYPE)) { methodVisitor.visitMethodInsn(Opcodes.INVOKESTATIC, Type.getInternalName(Boolean.class), "valueOf", Type.getMethodDescriptor(Type.getType(Boolean.class), Type.BOOLEAN_TYPE), false); } else if (primitiveType.equals(Type.BYTE_TYPE)) { methodVisitor.visitMethodInsn(Opcodes.INVOKESTATIC, Type.getInternalName(Byte.class), "valueOf", Type.getMethodDescriptor(Type.getType(Byte.class), Type.BYTE_TYPE), false); } else if (primitiveType.equals(Type.CHAR_TYPE)) { methodVisitor.visitMethodInsn(Opcodes.INVOKESTATIC, Type.getInternalName(Character.class), "valueOf", Type.getMethodDescriptor(Type.getType(Character.class), Type.CHAR_TYPE), false); } else if (primitiveType.equals(Type.SHORT_TYPE)) { methodVisitor.visitMethodInsn(Opcodes.INVOKESTATIC, Type.getInternalName(Short.class), "valueOf", Type.getMethodDescriptor(Type.getType(Short.class), Type.SHORT_TYPE), false); } else if (primitiveType.equals(Type.INT_TYPE)) { methodVisitor.visitMethodInsn(Opcodes.INVOKESTATIC, Type.getInternalName(Integer.class), "valueOf", Type.getMethodDescriptor(Type.getType(Integer.class), Type.INT_TYPE), false); } else if (primitiveType.equals(Type.LONG_TYPE)) { methodVisitor.visitMethodInsn(Opcodes.INVOKESTATIC, Type.getInternalName(Long.class), "valueOf", Type.getMethodDescriptor(Type.getType(Long.class), Type.LONG_TYPE), false); } else if (primitiveType.equals(Type.FLOAT_TYPE)) { methodVisitor.visitMethodInsn(Opcodes.INVOKESTATIC, Type.getInternalName(Float.class), "valueOf", Type.getMethodDescriptor(Type.getType(Float.class), Type.FLOAT_TYPE), false); } else if (primitiveType.equals(Type.DOUBLE_TYPE)) { methodVisitor.visitMethodInsn(Opcodes.INVOKESTATIC, Type.getInternalName(Double.class), "valueOf", Type.getMethodDescriptor(Type.getType(Double.class), Type.DOUBLE_TYPE), false); } else { throw new IllegalStateException("Unknown primitive type %s.".formatted(primitiveType)); } } public static void loadTypeClass(Class<?> type, MethodVisitor methodVisitor) { loadTypeClass(Type.getType(type), methodVisitor); } public static void loadTypeClass(Type type, MethodVisitor methodVisitor) { if (type.equals(Type.BOOLEAN_TYPE)) { methodVisitor.visitLdcInsn(Type.getType(Boolean.class)); } else if (type.equals(Type.BYTE_TYPE)) { methodVisitor.visitLdcInsn(Type.getType(Byte.class)); } else if (type.equals(Type.CHAR_TYPE)) { methodVisitor.visitLdcInsn(Type.getType(Character.class)); } else if (type.equals(Type.SHORT_TYPE)) { methodVisitor.visitLdcInsn(Type.getType(Short.class)); } else if (type.equals(Type.INT_TYPE)) { methodVisitor.visitLdcInsn(Type.getType(Integer.class)); } else if (type.equals(Type.LONG_TYPE)) { methodVisitor.visitLdcInsn(Type.getType(Long.class)); } else if (type.equals(Type.FLOAT_TYPE)) { methodVisitor.visitLdcInsn(Type.getType(Float.class)); } else if (type.equals(Type.DOUBLE_TYPE)) { methodVisitor.visitLdcInsn(Type.getType(Double.class)); } else { methodVisitor.visitLdcInsn(type); } } private record ReturnValueOpDescriptor( String wrapperClassName, String methodName, String methodDescriptor, int opcode, boolean noConversionNeeded) { public static ReturnValueOpDescriptor noConversion() { return new ReturnValueOpDescriptor("", "", "", Opcodes.ARETURN, true); } public static ReturnValueOpDescriptor forNumeric(String methodName, String methodDescriptor, int opcode) { return new ReturnValueOpDescriptor(Type.getInternalName(Number.class), methodName, methodDescriptor, opcode, false); } } private static final Map<Type, ReturnValueOpDescriptor> numericReturnValueOpDescriptorMap = Map.of( Type.BYTE_TYPE, ReturnValueOpDescriptor.forNumeric( "byteValue", Type.getMethodDescriptor(Type.BYTE_TYPE), Opcodes.IRETURN), Type.SHORT_TYPE, ReturnValueOpDescriptor.forNumeric( "shortValue", Type.getMethodDescriptor(Type.SHORT_TYPE), Opcodes.IRETURN), Type.INT_TYPE, ReturnValueOpDescriptor.forNumeric( "intValue", Type.getMethodDescriptor(Type.INT_TYPE), Opcodes.IRETURN), Type.LONG_TYPE, ReturnValueOpDescriptor.forNumeric( "longValue", Type.getMethodDescriptor(Type.LONG_TYPE), Opcodes.LRETURN), Type.FLOAT_TYPE, ReturnValueOpDescriptor.forNumeric( "floatValue", Type.getMethodDescriptor(Type.FLOAT_TYPE), Opcodes.FRETURN), Type.DOUBLE_TYPE, ReturnValueOpDescriptor.forNumeric( "doubleValue", Type.getMethodDescriptor(Type.DOUBLE_TYPE), Opcodes.DRETURN), Type.getType(BigInteger.class), ReturnValueOpDescriptor.noConversion(), Type.getType(BigDecimal.class), ReturnValueOpDescriptor.noConversion()); /** * If {@code method} return type is not void, convert TOS into its Java equivalent and return it. * If {@code method} return type is void, immediately return. * * @param method The method that is being implemented. */ public static void returnValue(MethodVisitor methodVisitor, MethodDescriptor method, StackMetadata stackMetadata) { Type returnAsmType = method.getReturnType(); if (Type.CHAR_TYPE.equals(returnAsmType)) { throw new IllegalStateException("Unhandled case for primitive type (char)."); } if (Type.VOID_TYPE.equals(returnAsmType)) { methodVisitor.visitInsn(Opcodes.RETURN); return; } if (numericReturnValueOpDescriptorMap.containsKey(returnAsmType)) { var returnValueOpDescriptor = numericReturnValueOpDescriptorMap.get(returnAsmType); methodVisitor.visitTypeInsn(Opcodes.CHECKCAST, Type.getInternalName(PythonNumber.class)); methodVisitor.visitMethodInsn(Opcodes.INVOKEINTERFACE, Type.getInternalName(PythonNumber.class), "getValue", Type.getMethodDescriptor(Type.getType(Number.class)), true); if (returnValueOpDescriptor.noConversionNeeded) { methodVisitor.visitTypeInsn(Opcodes.CHECKCAST, returnAsmType.getInternalName()); methodVisitor.visitInsn(Opcodes.ARETURN); return; } methodVisitor.visitMethodInsn(Opcodes.INVOKEVIRTUAL, returnValueOpDescriptor.wrapperClassName, returnValueOpDescriptor.methodName, returnValueOpDescriptor.methodDescriptor, false); methodVisitor.visitInsn(returnValueOpDescriptor.opcode); return; } if (Type.BOOLEAN_TYPE.equals(returnAsmType)) { methodVisitor.visitTypeInsn(Opcodes.CHECKCAST, Type.getInternalName(PythonBoolean.class)); String wrapperClassName = Type.getInternalName(PythonBoolean.class); String methodName = "getBooleanValue"; String methodDescriptor = Type.getMethodDescriptor(Type.BOOLEAN_TYPE); int returnOpcode = Opcodes.IRETURN; methodVisitor.visitMethodInsn(Opcodes.INVOKEVIRTUAL, wrapperClassName, methodName, methodDescriptor, false); methodVisitor.visitInsn(returnOpcode); return; } try { Class<?> returnTypeClass = Class.forName(returnAsmType.getClassName(), true, BuiltinTypes.asmClassLoader); if (stackMetadata.getTOSType() == null) { throw new IllegalStateException("Cannot return a deleted or undefined value"); } Class<?> tosTypeClass = stackMetadata.getTOSType().getJavaClass(); if (returnTypeClass.isAssignableFrom(tosTypeClass)) { methodVisitor.visitTypeInsn(Opcodes.CHECKCAST, returnAsmType.getInternalName()); methodVisitor.visitInsn(Opcodes.ARETURN); return; } } catch (ClassNotFoundException e) { // Do nothing; default case is below } methodVisitor.visitLdcInsn(returnAsmType); methodVisitor.visitInsn(Opcodes.SWAP); methodVisitor.visitMethodInsn(Opcodes.INVOKESTATIC, Type.getInternalName(JavaPythonTypeConversionImplementor.class), "convertPythonObjectToJavaType", Type.getMethodDescriptor(Type.getType(Object.class), Type.getType(Class.class), Type.getType(PythonLikeObject.class)), false); methodVisitor.visitTypeInsn(Opcodes.CHECKCAST, returnAsmType.getInternalName()); methodVisitor.visitInsn(Opcodes.ARETURN); } /** * Coerce a value to a given type */ public static <T> T coerceToType(PythonLikeObject value, Class<T> type) { if (value == null) { return null; } if (type.isAssignableFrom(value.getClass())) { return (T) value; } if (value instanceof Coercible coercible) { var out = coercible.coerce(type); if (out == null) { throw new TypeError("%s cannot be coerced to %s." .formatted(value.$getType(), type)); } return out; } throw new TypeError("%s cannot be coerced to %s." .formatted(value.$getType(), type)); } /** * Convert the {@code parameterIndex} Java parameter to its Python equivalent and store it into * the corresponding Python parameter local variable slot. */ public static void copyParameter(MethodVisitor methodVisitor, LocalVariableHelper localVariableHelper, int parameterIndex) { Type parameterType = localVariableHelper.parameters[parameterIndex]; if (parameterType.getSort() != Type.OBJECT && parameterType.getSort() != Type.ARRAY) { int loadOpcode; String valueOfOwner; String valueOfDescriptor; if (Type.BOOLEAN_TYPE.equals(parameterType)) { loadOpcode = Opcodes.ILOAD; valueOfOwner = Type.getInternalName(PythonBoolean.class); valueOfDescriptor = Type.getMethodDescriptor(Type.getType(PythonBoolean.class), Type.getType(boolean.class)); } else if (Type.CHAR_TYPE.equals(parameterType)) { loadOpcode = Opcodes.ILOAD; throw new IllegalStateException("Unhandled case for primitive type (" + parameterType + ")."); } else if (Type.BYTE_TYPE.equals(parameterType)) { loadOpcode = Opcodes.ILOAD; valueOfOwner = Type.getInternalName(PythonInteger.class); valueOfDescriptor = Type.getMethodDescriptor(Type.getType(PythonInteger.class), Type.getType(byte.class)); } else if (Type.SHORT_TYPE.equals(parameterType)) { loadOpcode = Opcodes.ILOAD; valueOfOwner = Type.getInternalName(PythonInteger.class); valueOfDescriptor = Type.getMethodDescriptor(Type.getType(PythonInteger.class), Type.getType(short.class)); } else if (Type.INT_TYPE.equals(parameterType)) { loadOpcode = Opcodes.ILOAD; valueOfOwner = Type.getInternalName(PythonInteger.class); valueOfDescriptor = Type.getMethodDescriptor(Type.getType(PythonInteger.class), Type.getType(int.class)); } else if (Type.FLOAT_TYPE.equals(parameterType)) { loadOpcode = Opcodes.FLOAD; valueOfOwner = Type.getInternalName(PythonFloat.class); valueOfDescriptor = Type.getMethodDescriptor(Type.getType(PythonFloat.class), Type.getType(float.class)); } else if (Type.LONG_TYPE.equals(parameterType)) { loadOpcode = Opcodes.LLOAD; valueOfOwner = Type.getInternalName(PythonInteger.class); valueOfDescriptor = Type.getMethodDescriptor(Type.getType(PythonInteger.class), Type.getType(long.class)); } else if (Type.DOUBLE_TYPE.equals(parameterType)) { loadOpcode = Opcodes.DLOAD; valueOfOwner = Type.getInternalName(PythonFloat.class); valueOfDescriptor = Type.getMethodDescriptor(Type.getType(PythonFloat.class), Type.getType(double.class)); } else { throw new IllegalStateException("Unhandled case for primitive type (" + parameterType + ")."); } methodVisitor.visitVarInsn(loadOpcode, localVariableHelper.getParameterSlot(parameterIndex)); methodVisitor.visitMethodInsn(Opcodes.INVOKESTATIC, valueOfOwner, "valueOf", valueOfDescriptor, false); localVariableHelper.writeLocal(methodVisitor, parameterIndex); } else { try { Class<?> typeClass = Class.forName(parameterType.getClassName(), false, BuiltinTypes.asmClassLoader); if (!PythonLikeObject.class.isAssignableFrom(typeClass)) { methodVisitor.visitVarInsn(Opcodes.ALOAD, localVariableHelper.getParameterSlot(parameterIndex)); methodVisitor.visitMethodInsn(Opcodes.INVOKESTATIC, Type.getInternalName(JavaPythonTypeConversionImplementor.class), "wrapJavaObject", Type.getMethodDescriptor(Type.getType(PythonLikeObject.class), Type.getType(Object.class)), false); localVariableHelper.writeLocal(methodVisitor, parameterIndex); } else { methodVisitor.visitVarInsn(Opcodes.ALOAD, localVariableHelper.getParameterSlot(parameterIndex)); localVariableHelper.writeLocal(methodVisitor, parameterIndex); } } catch (ClassNotFoundException e) { methodVisitor.visitVarInsn(Opcodes.ALOAD, localVariableHelper.getParameterSlot(parameterIndex)); localVariableHelper.writeLocal(methodVisitor, parameterIndex); } } } }
0
java-sources/ai/timefold/solver/jpyinterpreter/1.24.0/ai/timefold/jpyinterpreter
java-sources/ai/timefold/solver/jpyinterpreter/1.24.0/ai/timefold/jpyinterpreter/implementors/JumpImplementor.java
package ai.timefold.jpyinterpreter.implementors; import java.util.Map; import ai.timefold.jpyinterpreter.FunctionMetadata; import ai.timefold.jpyinterpreter.PythonLikeObject; import ai.timefold.jpyinterpreter.PythonUnaryOperator; import ai.timefold.jpyinterpreter.StackMetadata; import ai.timefold.jpyinterpreter.types.BuiltinTypes; import ai.timefold.jpyinterpreter.types.PythonLikeType; import org.objectweb.asm.Label; import org.objectweb.asm.MethodVisitor; import org.objectweb.asm.Opcodes; import org.objectweb.asm.Type; /** * Implementations of jump opcodes */ public class JumpImplementor { /** * Set the bytecode counter to the {@code instruction} argument. */ public static void jumpAbsolute(FunctionMetadata functionMetadata, StackMetadata stackMetadata, int jumpTarget) { MethodVisitor methodVisitor = functionMetadata.methodVisitor; Map<Integer, Label> bytecodeCounterToLabelMap = functionMetadata.bytecodeCounterToLabelMap; Label jumpLocation = bytecodeCounterToLabelMap.computeIfAbsent(jumpTarget, key -> new Label()); methodVisitor.visitJumpInsn(Opcodes.GOTO, jumpLocation); } /** * Pops TOS. If TOS is true, set the bytecode counter to the {@code instruction} argument. */ public static void popAndJumpIfTrue(FunctionMetadata functionMetadata, StackMetadata stackMetadata, int jumpTarget) { MethodVisitor methodVisitor = functionMetadata.methodVisitor; Map<Integer, Label> bytecodeCounterToLabelMap = functionMetadata.bytecodeCounterToLabelMap; Label jumpLocation = bytecodeCounterToLabelMap.computeIfAbsent(jumpTarget, key -> new Label()); if (stackMetadata.getTOSType() != BuiltinTypes.BOOLEAN_TYPE) { DunderOperatorImplementor.unaryOperator(methodVisitor, PythonUnaryOperator.AS_BOOLEAN); } PythonConstantsImplementor.loadTrue(methodVisitor); methodVisitor.visitJumpInsn(Opcodes.IF_ACMPEQ, jumpLocation); } /** * Pops TOS. If TOS is false, set the bytecode counter to the {@code instruction} argument. */ public static void popAndJumpIfFalse(FunctionMetadata functionMetadata, StackMetadata stackMetadata, int jumpTarget) { MethodVisitor methodVisitor = functionMetadata.methodVisitor; Map<Integer, Label> bytecodeCounterToLabelMap = functionMetadata.bytecodeCounterToLabelMap; Label jumpLocation = bytecodeCounterToLabelMap.computeIfAbsent(jumpTarget, key -> new Label()); if (stackMetadata.getTOSType() != BuiltinTypes.BOOLEAN_TYPE) { DunderOperatorImplementor.unaryOperator(methodVisitor, PythonUnaryOperator.AS_BOOLEAN); } PythonConstantsImplementor.loadFalse(methodVisitor); methodVisitor.visitJumpInsn(Opcodes.IF_ACMPEQ, jumpLocation); } /** * Pops TOS. If TOS is not None, set the bytecode counter to {@code jumpTarget}. */ public static void popAndJumpIfIsNotNone(FunctionMetadata functionMetadata, StackMetadata stackMetadata, int jumpTarget) { MethodVisitor methodVisitor = functionMetadata.methodVisitor; Map<Integer, Label> bytecodeCounterToLabelMap = functionMetadata.bytecodeCounterToLabelMap; Label jumpLocation = bytecodeCounterToLabelMap.computeIfAbsent(jumpTarget, key -> new Label()); PythonConstantsImplementor.loadNone(methodVisitor); methodVisitor.visitJumpInsn(Opcodes.IF_ACMPNE, jumpLocation); } /** * Pops TOS. If TOS is None, set the bytecode counter to {@code jumpTarget}. */ public static void popAndJumpIfIsNone(FunctionMetadata functionMetadata, StackMetadata stackMetadata, int jumpTarget) { MethodVisitor methodVisitor = functionMetadata.methodVisitor; Map<Integer, Label> bytecodeCounterToLabelMap = functionMetadata.bytecodeCounterToLabelMap; Label jumpLocation = bytecodeCounterToLabelMap.computeIfAbsent(jumpTarget, key -> new Label()); PythonConstantsImplementor.loadNone(methodVisitor); methodVisitor.visitJumpInsn(Opcodes.IF_ACMPEQ, jumpLocation); } /** * TOS is an exception type and TOS1 is an exception. * If TOS1 is not an instance of TOS, set the bytecode counter to the * {@code instruction} argument. * Pop TOS and TOS1 off the stack. */ public static void popAndJumpIfExceptionDoesNotMatch(FunctionMetadata functionMetadata, StackMetadata stackMetadata, int jumpTarget) { MethodVisitor methodVisitor = functionMetadata.methodVisitor; Map<Integer, Label> bytecodeCounterToLabelMap = functionMetadata.bytecodeCounterToLabelMap; Label jumpLocation = bytecodeCounterToLabelMap.computeIfAbsent(jumpTarget, key -> new Label()); methodVisitor.visitTypeInsn(Opcodes.CHECKCAST, Type.getInternalName(PythonLikeType.class)); StackManipulationImplementor.swap(methodVisitor); methodVisitor.visitMethodInsn(Opcodes.INVOKEINTERFACE, Type.getInternalName(PythonLikeObject.class), "$getType", Type.getMethodDescriptor(Type.getType(PythonLikeType.class)), true); methodVisitor.visitMethodInsn(Opcodes.INVOKEVIRTUAL, Type.getInternalName(PythonLikeType.class), "isSubclassOf", Type.getMethodDescriptor(Type.BOOLEAN_TYPE, Type.getType(PythonLikeType.class)), false); methodVisitor.visitJumpInsn(Opcodes.IFEQ, jumpLocation); } /** * If TOS is true, keep TOS on the stack and set the bytecode counter to the {@code instruction} argument. * Otherwise, pop TOS. */ public static void jumpIfTrueElsePop(FunctionMetadata functionMetadata, StackMetadata stackMetadata, int jumpTarget) { MethodVisitor methodVisitor = functionMetadata.methodVisitor; Map<Integer, Label> bytecodeCounterToLabelMap = functionMetadata.bytecodeCounterToLabelMap; Label jumpLocation = bytecodeCounterToLabelMap.computeIfAbsent(jumpTarget, key -> new Label()); methodVisitor.visitInsn(Opcodes.DUP); if (stackMetadata.getTOSType() != BuiltinTypes.BOOLEAN_TYPE) { DunderOperatorImplementor.unaryOperator(methodVisitor, PythonUnaryOperator.AS_BOOLEAN); } PythonConstantsImplementor.loadTrue(methodVisitor); methodVisitor.visitJumpInsn(Opcodes.IF_ACMPEQ, jumpLocation); methodVisitor.visitInsn(Opcodes.POP); } /** * If TOS is false, keep TOS on the stack and set the bytecode counter to the {@code instruction} argument. * Otherwise, pop TOS. */ public static void jumpIfFalseElsePop(FunctionMetadata functionMetadata, StackMetadata stackMetadata, int jumpTarget) { MethodVisitor methodVisitor = functionMetadata.methodVisitor; Map<Integer, Label> bytecodeCounterToLabelMap = functionMetadata.bytecodeCounterToLabelMap; Label jumpLocation = bytecodeCounterToLabelMap.computeIfAbsent(jumpTarget, key -> new Label()); methodVisitor.visitInsn(Opcodes.DUP); if (stackMetadata.getTOSType() != BuiltinTypes.BOOLEAN_TYPE) { DunderOperatorImplementor.unaryOperator(methodVisitor, PythonUnaryOperator.AS_BOOLEAN); } PythonConstantsImplementor.loadFalse(methodVisitor); methodVisitor.visitJumpInsn(Opcodes.IF_ACMPEQ, jumpLocation); methodVisitor.visitInsn(Opcodes.POP); } }
0
java-sources/ai/timefold/solver/jpyinterpreter/1.24.0/ai/timefold/jpyinterpreter
java-sources/ai/timefold/solver/jpyinterpreter/1.24.0/ai/timefold/jpyinterpreter/implementors/KnownCallImplementor.java
package ai.timefold.jpyinterpreter.implementors; import java.util.List; import java.util.Map; import ai.timefold.jpyinterpreter.FunctionMetadata; import ai.timefold.jpyinterpreter.LocalVariableHelper; import ai.timefold.jpyinterpreter.MethodDescriptor; import ai.timefold.jpyinterpreter.PythonDefaultArgumentImplementor; import ai.timefold.jpyinterpreter.PythonFunctionSignature; import ai.timefold.jpyinterpreter.PythonLikeObject; import ai.timefold.jpyinterpreter.StackMetadata; import ai.timefold.jpyinterpreter.types.BoundPythonLikeFunction; import ai.timefold.jpyinterpreter.types.BuiltinTypes; import ai.timefold.jpyinterpreter.types.PythonLikeType; import ai.timefold.jpyinterpreter.types.PythonString; import ai.timefold.jpyinterpreter.types.collections.PythonLikeDict; import ai.timefold.jpyinterpreter.types.collections.PythonLikeTuple; import ai.timefold.jpyinterpreter.util.arguments.ArgumentSpec; import org.objectweb.asm.Label; import org.objectweb.asm.MethodVisitor; import org.objectweb.asm.Opcodes; import org.objectweb.asm.Type; /** * Implements function calls when the function being called is known. */ public class KnownCallImplementor { static void unwrapBoundMethod(PythonFunctionSignature pythonFunctionSignature, FunctionMetadata functionMetadata, StackMetadata stackMetadata, int posFromTOS) { MethodVisitor methodVisitor = functionMetadata.methodVisitor; if (pythonFunctionSignature.getMethodDescriptor().getMethodType() == MethodDescriptor.MethodType.VIRTUAL || pythonFunctionSignature.getMethodDescriptor().getMethodType() == MethodDescriptor.MethodType.INTERFACE) { StackManipulationImplementor.duplicateToTOS(functionMetadata, stackMetadata, posFromTOS); methodVisitor.visitMethodInsn(Opcodes.INVOKEVIRTUAL, Type.getInternalName(BoundPythonLikeFunction.class), "getInstance", Type.getMethodDescriptor(Type.getType(PythonLikeObject.class)), false); methodVisitor.visitTypeInsn(Opcodes.CHECKCAST, pythonFunctionSignature.getMethodDescriptor().getDeclaringClassInternalName()); StackManipulationImplementor.shiftTOSDownBy(functionMetadata, stackMetadata, posFromTOS); } } public static void callMethod(PythonFunctionSignature pythonFunctionSignature, MethodVisitor methodVisitor, LocalVariableHelper localVariableHelper, int argumentCount) { if (pythonFunctionSignature.isClassMethod()) { // Class methods will also have their type/instance on the stack, but it not in argumentCount argumentCount++; } int specPositionalArgumentCount = pythonFunctionSignature.getArgumentSpec().getAllowPositionalArgumentCount(); int missingValues = Math.max(0, specPositionalArgumentCount - argumentCount); int[] argumentLocals = new int[specPositionalArgumentCount]; int capturedExtraPositionalArgumentsLocal = localVariableHelper.newLocal(); // Create temporary variables for each argument for (int i = 0; i < argumentLocals.length; i++) { argumentLocals[i] = localVariableHelper.newLocal(); } if (pythonFunctionSignature.getArgumentSpec().hasExtraPositionalArgumentsCapture()) { CollectionImplementor.buildCollection(PythonLikeTuple.class, methodVisitor, Math.max(0, argumentCount - specPositionalArgumentCount)); localVariableHelper.writeTemp(methodVisitor, Type.getType(PythonLikeTuple.class), capturedExtraPositionalArgumentsLocal); } else if (argumentCount > specPositionalArgumentCount) { throw new IllegalStateException( "Too many positional arguments given for argument spec " + pythonFunctionSignature.getArgumentSpec()); } // Call stack is in reverse, so TOS = argument (specPositionalArgumentCount - missingValues - 1) // First store the variables into temporary local variables since we need to typecast them all for (int i = specPositionalArgumentCount - missingValues - 1; i >= 0; i--) { localVariableHelper.writeTemp(methodVisitor, Type.getType(PythonLikeObject.class), argumentLocals[i]); } if (pythonFunctionSignature.isVirtualMethod()) { // If it is a virtual method, there will be self here, which we need to cast to the declaring class methodVisitor.visitTypeInsn(Opcodes.CHECKCAST, pythonFunctionSignature.getMethodDescriptor().getDeclaringClassInternalName()); } if (pythonFunctionSignature.isClassMethod()) { // If it is a class method, argument 0 need to be converted to a type if it not a type localVariableHelper.readTemp(methodVisitor, Type.getType(PythonLikeObject.class), argumentLocals[0]); methodVisitor.visitInsn(Opcodes.DUP); Label ifIsBoundFunction = new Label(); Label doneGettingType = new Label(); methodVisitor.visitTypeInsn(Opcodes.INSTANCEOF, Type.getInternalName(BoundPythonLikeFunction.class)); methodVisitor.visitJumpInsn(Opcodes.IFNE, ifIsBoundFunction); methodVisitor.visitInsn(Opcodes.DUP); methodVisitor.visitTypeInsn(Opcodes.INSTANCEOF, Type.getInternalName(PythonLikeType.class)); methodVisitor.visitJumpInsn(Opcodes.IFNE, doneGettingType); methodVisitor.visitMethodInsn(Opcodes.INVOKEINTERFACE, Type.getInternalName(PythonLikeObject.class), "$getType", Type.getMethodDescriptor(Type.getType(PythonLikeType.class)), true); methodVisitor.visitJumpInsn(Opcodes.GOTO, doneGettingType); methodVisitor.visitLabel(ifIsBoundFunction); methodVisitor.visitTypeInsn(Opcodes.CHECKCAST, Type.getInternalName(BoundPythonLikeFunction.class)); methodVisitor.visitMethodInsn(Opcodes.INVOKEVIRTUAL, Type.getInternalName(BoundPythonLikeFunction.class), "getInstance", Type.getMethodDescriptor(Type.getType(PythonLikeObject.class)), false); methodVisitor.visitLabel(doneGettingType); localVariableHelper.writeTemp(methodVisitor, Type.getType(PythonLikeObject.class), argumentLocals[0]); } // Now load and typecheck the local variables for (int i = 0; i < Math.min(specPositionalArgumentCount, argumentCount); i++) { localVariableHelper.readTemp(methodVisitor, Type.getType(PythonLikeObject.class), argumentLocals[i]); methodVisitor.visitLdcInsn( Type.getType("L" + pythonFunctionSignature.getArgumentSpec().getArgumentTypeInternalName(i) + ";")); methodVisitor.visitMethodInsn(Opcodes.INVOKESTATIC, Type.getInternalName(JavaPythonTypeConversionImplementor.class), "coerceToType", Type.getMethodDescriptor(Type.getType(Object.class), Type.getType(PythonLikeObject.class), Type.getType(Class.class)), false); if (i == 0 && pythonFunctionSignature.isClassMethod()) { methodVisitor.visitTypeInsn(Opcodes.CHECKCAST, Type.getInternalName(PythonLikeType.class)); } else { methodVisitor.visitTypeInsn(Opcodes.CHECKCAST, pythonFunctionSignature.getArgumentSpec().getArgumentTypeInternalName(i)); } } // Load any arguments missing values int defaultOffset = pythonFunctionSignature.getArgumentSpec().getTotalArgumentCount() - pythonFunctionSignature.getDefaultArgumentList().size(); for (int i = specPositionalArgumentCount - missingValues; i < specPositionalArgumentCount; i++) { if (pythonFunctionSignature.getArgumentSpec().isArgumentNullable(i)) { methodVisitor.visitInsn(Opcodes.ACONST_NULL); } else { methodVisitor.visitFieldInsn(Opcodes.GETSTATIC, pythonFunctionSignature.getDefaultArgumentHolderClassInternalName(), PythonDefaultArgumentImplementor.getConstantName(i - defaultOffset), "L" + pythonFunctionSignature.getArgumentSpec().getArgumentTypeInternalName(i) + ";"); } } // Load *vargs and **kwargs if the function has them if (pythonFunctionSignature.getArgumentSpec().hasExtraPositionalArgumentsCapture()) { localVariableHelper.readTemp(methodVisitor, Type.getType(PythonLikeTuple.class), capturedExtraPositionalArgumentsLocal); } if (pythonFunctionSignature.getArgumentSpec().hasExtraKeywordArgumentsCapture()) { // No kwargs for call method, so just load an empty map CollectionImplementor.buildMap(PythonLikeDict.class, methodVisitor, 0); } // Call the method pythonFunctionSignature.getMethodDescriptor().callMethod(methodVisitor); // Free temporary locals for arguments for (int i = 0; i < argumentLocals.length; i++) { localVariableHelper.freeLocal(); } // Free temporary local for vargs localVariableHelper.freeLocal(); } public static void callPython311andAbove(PythonFunctionSignature pythonFunctionSignature, FunctionMetadata functionMetadata, StackMetadata stackMetadata, int argumentCount, List<String> keywordArgumentNameList) { MethodVisitor methodVisitor = functionMetadata.methodVisitor; LocalVariableHelper localVariableHelper = stackMetadata.localVariableHelper; int specTotalArgumentCount = pythonFunctionSignature.getArgumentSpec().getTotalArgumentCount(); int positionalArgumentCount = argumentCount - keywordArgumentNameList.size(); int[] argumentLocals = new int[specTotalArgumentCount]; // Create temporary variables for each argument for (int i = 0; i < argumentLocals.length; i++) { argumentLocals[i] = localVariableHelper.newLocal(); } int extraKeywordArgumentsLocal = (pythonFunctionSignature.getArgumentSpec().getExtraKeywordsArgumentIndex().isPresent()) ? argumentLocals[pythonFunctionSignature.getArgumentSpec().getExtraKeywordsArgumentIndex().get()] : -1; int extraPositionalArgumentsLocal = (pythonFunctionSignature.getArgumentSpec().getExtraPositionalsArgumentIndex().isPresent()) ? argumentLocals[pythonFunctionSignature.getArgumentSpec().getExtraPositionalsArgumentIndex().get()] : -1; // Read keyword arguments if (extraKeywordArgumentsLocal != -1) { CollectionImplementor.buildMap(PythonLikeDict.class, methodVisitor, 0); localVariableHelper.writeTemp(methodVisitor, Type.getType(PythonLikeDict.class), extraKeywordArgumentsLocal); } // Read positional arguments int positionalArgumentStart = (pythonFunctionSignature.isClassMethod()) ? 1 : 0; for (int keywordArgumentNameIndex = keywordArgumentNameList.size() - 1; keywordArgumentNameIndex >= 0; keywordArgumentNameIndex--) { // Need to iterate keyword name tuple in reverse (since last element of the tuple correspond to TOS) String keywordArgument = keywordArgumentNameList.get(keywordArgumentNameIndex); int argumentIndex = pythonFunctionSignature.getArgumentSpec().getArgumentIndex(keywordArgument); if (argumentIndex == -1) { // Unknown keyword argument; put it into the extraKeywordArguments dict localVariableHelper.readTemp(methodVisitor, Type.getType(PythonLikeDict.class), extraKeywordArgumentsLocal); methodVisitor.visitTypeInsn(Opcodes.CHECKCAST, Type.getInternalName(PythonLikeDict.class)); methodVisitor.visitInsn(Opcodes.SWAP); methodVisitor.visitLdcInsn(keywordArgument); methodVisitor.visitMethodInsn(Opcodes.INVOKESTATIC, Type.getInternalName(PythonString.class), "valueOf", Type.getMethodDescriptor(Type.getType(PythonString.class), Type.getType(String.class)), false); methodVisitor.visitInsn(Opcodes.SWAP); methodVisitor.visitMethodInsn(Opcodes.INVOKEVIRTUAL, Type.getInternalName(PythonLikeDict.class), "put", Type.getMethodDescriptor(Type.getType(PythonLikeObject.class), Type.getType(PythonLikeObject.class), Type.getType(PythonLikeObject.class)), false); } else { localVariableHelper.writeTemp(methodVisitor, Type.getType(PythonLikeObject.class), argumentLocals[argumentIndex]); } } if (extraPositionalArgumentsLocal != -1) { CollectionImplementor.buildCollection(PythonLikeTuple.class, methodVisitor, Math.max(0, positionalArgumentCount - pythonFunctionSignature.getArgumentSpec().getAllowPositionalArgumentCount() + positionalArgumentStart)); localVariableHelper.writeTemp(methodVisitor, Type.getType(PythonLikeTuple.class), extraPositionalArgumentsLocal); } for (int i = Math.min(positionalArgumentCount + positionalArgumentStart, pythonFunctionSignature.getArgumentSpec().getAllowPositionalArgumentCount()) - 1; i >= positionalArgumentStart; i--) { localVariableHelper.writeTemp(methodVisitor, Type.getType(PythonLikeObject.class), argumentLocals[i]); } // Load missing arguments with default values int defaultOffset = pythonFunctionSignature.getArgumentSpec().getTotalArgumentCount() - pythonFunctionSignature.getDefaultArgumentList().size(); for (int argumentIndex : pythonFunctionSignature.getArgumentSpec().getUnspecifiedArgumentSet( positionalArgumentCount + positionalArgumentStart, keywordArgumentNameList)) { if (pythonFunctionSignature.getArgumentSpec().isArgumentNullable(argumentIndex)) { methodVisitor.visitInsn(Opcodes.ACONST_NULL); } else { methodVisitor.visitFieldInsn(Opcodes.GETSTATIC, pythonFunctionSignature.getDefaultArgumentHolderClassInternalName(), PythonDefaultArgumentImplementor.getConstantName(argumentIndex - defaultOffset), "L" + pythonFunctionSignature.getArgumentSpec().getArgumentTypeInternalName(argumentIndex) + ";"); } localVariableHelper.writeTemp(methodVisitor, Type.getType(PythonLikeObject.class), argumentLocals[argumentIndex]); } if (pythonFunctionSignature.isVirtualMethod()) { // If it is a virtual method, there will be self here, which we need to cast to the declaring class methodVisitor.visitTypeInsn(Opcodes.CHECKCAST, pythonFunctionSignature.getMethodDescriptor().getDeclaringClassInternalName()); } if (pythonFunctionSignature.isClassMethod()) { // If it is a class method, argument 0 need to be converted to a type if it not a type methodVisitor.visitInsn(Opcodes.DUP); Label ifIsBoundFunction = new Label(); Label doneGettingType = new Label(); methodVisitor.visitTypeInsn(Opcodes.INSTANCEOF, Type.getInternalName(BoundPythonLikeFunction.class)); methodVisitor.visitJumpInsn(Opcodes.IFNE, ifIsBoundFunction); methodVisitor.visitInsn(Opcodes.DUP); methodVisitor.visitTypeInsn(Opcodes.INSTANCEOF, Type.getInternalName(PythonLikeType.class)); methodVisitor.visitJumpInsn(Opcodes.IFNE, doneGettingType); methodVisitor.visitMethodInsn(Opcodes.INVOKEINTERFACE, Type.getInternalName(PythonLikeObject.class), "$getType", Type.getMethodDescriptor(Type.getType(PythonLikeType.class)), true); methodVisitor.visitJumpInsn(Opcodes.GOTO, doneGettingType); methodVisitor.visitLabel(ifIsBoundFunction); methodVisitor.visitTypeInsn(Opcodes.CHECKCAST, Type.getInternalName(BoundPythonLikeFunction.class)); methodVisitor.visitMethodInsn(Opcodes.INVOKEVIRTUAL, Type.getInternalName(BoundPythonLikeFunction.class), "getInstance", Type.getMethodDescriptor(Type.getType(PythonLikeObject.class)), false); methodVisitor.visitLabel(doneGettingType); localVariableHelper.writeTemp(methodVisitor, Type.getType(PythonLikeObject.class), argumentLocals[0]); } // Load arguments in proper order and typecast them for (int i = 0; i < specTotalArgumentCount; i++) { localVariableHelper.readTemp(methodVisitor, Type.getType(PythonLikeObject.class), argumentLocals[i]); methodVisitor.visitLdcInsn( Type.getType("L" + pythonFunctionSignature.getArgumentSpec().getArgumentTypeInternalName(i) + ";")); methodVisitor.visitMethodInsn(Opcodes.INVOKESTATIC, Type.getInternalName(JavaPythonTypeConversionImplementor.class), "coerceToType", Type.getMethodDescriptor(Type.getType(Object.class), Type.getType(PythonLikeObject.class), Type.getType(Class.class)), false); methodVisitor.visitTypeInsn(Opcodes.CHECKCAST, pythonFunctionSignature.getArgumentSpec().getArgumentTypeInternalName(i)); } pythonFunctionSignature.getMethodDescriptor().callMethod(methodVisitor); // If it not a CLASS method, pop off the function object // CLASS method consume the function object; Static and Virtual do not if (!pythonFunctionSignature.isClassMethod()) { methodVisitor.visitInsn(Opcodes.SWAP); methodVisitor.visitInsn(Opcodes.POP); } // Pop off NULL if it on the stack if (stackMetadata.getTypeAtStackIndex(argumentCount + 1) == BuiltinTypes.NULL_TYPE) { methodVisitor.visitInsn(Opcodes.SWAP); methodVisitor.visitInsn(Opcodes.POP); } // Free temporary locals for arguments for (int i = 0; i < argumentLocals.length; i++) { localVariableHelper.freeLocal(); } } public static void callWithoutKeywords(PythonFunctionSignature pythonFunctionSignature, FunctionMetadata functionMetadata, StackMetadata stackMetadata, int argumentCount) { MethodVisitor methodVisitor = functionMetadata.methodVisitor; CollectionImplementor.buildCollection(PythonLikeTuple.class, methodVisitor, 0); callWithKeywordsAndUnwrapSelf(pythonFunctionSignature, functionMetadata, stackMetadata, argumentCount); } public static void callWithKeywordsAndUnwrapSelf(PythonFunctionSignature pythonFunctionSignature, FunctionMetadata functionMetadata, StackMetadata stackMetadata, int argumentCount) { callWithKeywords(pythonFunctionSignature, functionMetadata, stackMetadata, argumentCount); } private static void callWithKeywords(PythonFunctionSignature pythonFunctionSignature, FunctionMetadata functionMetadata, StackMetadata stackMetadata, int argumentCount) { MethodVisitor methodVisitor = functionMetadata.methodVisitor; Type[] descriptorParameterTypes = pythonFunctionSignature.getMethodDescriptor().getParameterTypes(); if (argumentCount < descriptorParameterTypes.length && pythonFunctionSignature.getDefaultArgumentHolderClassInternalName() == null) { throw new IllegalStateException( "Cannot call " + pythonFunctionSignature + " because there are not enough arguments"); } if (argumentCount > descriptorParameterTypes.length && pythonFunctionSignature.getExtraPositionalArgumentsVariableIndex().isEmpty() && pythonFunctionSignature.getExtraKeywordArgumentsVariableIndex().isEmpty()) { throw new IllegalStateException("Cannot call " + pythonFunctionSignature + " because there are too many arguments"); } unwrapBoundMethod(pythonFunctionSignature, functionMetadata, stackMetadata, argumentCount + 1); if (pythonFunctionSignature.isClassMethod()) { argumentCount++; } // TOS is a tuple of keys methodVisitor.visitTypeInsn(Opcodes.NEW, pythonFunctionSignature.getDefaultArgumentHolderClassInternalName()); methodVisitor.visitInsn(Opcodes.DUP_X1); methodVisitor.visitInsn(Opcodes.SWAP); // Stack is defaults (uninitialized), keys // Get position of last positional arg (= argumentCount - len(keys) - 1 ) methodVisitor.visitInsn(Opcodes.DUP); // dup keys methodVisitor.visitMethodInsn(Opcodes.INVOKEVIRTUAL, Type.getInternalName(PythonLikeTuple.class), "size", Type.getMethodDescriptor(Type.INT_TYPE), false); methodVisitor.visitLdcInsn(argumentCount); methodVisitor.visitInsn(Opcodes.SWAP); methodVisitor.visitInsn(Opcodes.ISUB); methodVisitor.visitInsn(Opcodes.ICONST_1); methodVisitor.visitInsn(Opcodes.ISUB); // Stack is defaults (uninitialized), keys, positional arguments methodVisitor.visitMethodInsn(Opcodes.INVOKESPECIAL, pythonFunctionSignature.getDefaultArgumentHolderClassInternalName(), "<init>", Type.getMethodDescriptor(Type.VOID_TYPE, Type.getType(PythonLikeTuple.class), Type.INT_TYPE), false); for (int i = 0; i < argumentCount; i++) { methodVisitor.visitInsn(Opcodes.DUP_X1); methodVisitor.visitInsn(Opcodes.SWAP); if (pythonFunctionSignature.isClassMethod() && i == argumentCount - 1) { methodVisitor.visitInsn(Opcodes.DUP); Label ifIsBoundFunction = new Label(); Label doneGettingType = new Label(); methodVisitor.visitTypeInsn(Opcodes.INSTANCEOF, Type.getInternalName(BoundPythonLikeFunction.class)); methodVisitor.visitJumpInsn(Opcodes.IFNE, ifIsBoundFunction); methodVisitor.visitInsn(Opcodes.DUP); methodVisitor.visitTypeInsn(Opcodes.INSTANCEOF, Type.getInternalName(PythonLikeType.class)); methodVisitor.visitJumpInsn(Opcodes.IFNE, doneGettingType); methodVisitor.visitMethodInsn(Opcodes.INVOKEINTERFACE, Type.getInternalName(PythonLikeObject.class), "$getType", Type.getMethodDescriptor(Type.getType(PythonLikeType.class)), true); methodVisitor.visitJumpInsn(Opcodes.GOTO, doneGettingType); methodVisitor.visitLabel(ifIsBoundFunction); methodVisitor.visitTypeInsn(Opcodes.CHECKCAST, Type.getInternalName(BoundPythonLikeFunction.class)); methodVisitor.visitMethodInsn(Opcodes.INVOKEVIRTUAL, Type.getInternalName(BoundPythonLikeFunction.class), "getInstance", Type.getMethodDescriptor(Type.getType(PythonLikeObject.class)), false); methodVisitor.visitLabel(doneGettingType); } methodVisitor.visitMethodInsn(Opcodes.INVOKEVIRTUAL, pythonFunctionSignature.getDefaultArgumentHolderClassInternalName(), "addArgument", Type.getMethodDescriptor(Type.VOID_TYPE, Type.getType(PythonLikeObject.class)), false); } for (int i = 0; i < descriptorParameterTypes.length; i++) { methodVisitor.visitInsn(Opcodes.DUP); methodVisitor.visitFieldInsn(Opcodes.GETFIELD, pythonFunctionSignature.getDefaultArgumentHolderClassInternalName(), PythonDefaultArgumentImplementor.getArgumentName(i), descriptorParameterTypes[i].getDescriptor()); methodVisitor.visitInsn(Opcodes.SWAP); } methodVisitor.visitInsn(Opcodes.POP); pythonFunctionSignature.getMethodDescriptor().callMethod(methodVisitor); } public static void callUnpackListAndMap(String defaultArgumentHolderClassInternalName, MethodDescriptor methodDescriptor, MethodVisitor methodVisitor) { Type[] descriptorParameterTypes = methodDescriptor.getParameterTypes(); // TOS2 is the function to call, TOS1 is positional arguments, TOS is keyword arguments if (methodDescriptor.getMethodType() == MethodDescriptor.MethodType.CLASS) { // stack is bound-method, pos, keywords StackManipulationImplementor.rotateThree(methodVisitor); // stack is keywords, bound-method, pos StackManipulationImplementor.swap(methodVisitor); // stack is keywords, pos, bound-method methodVisitor.visitInsn(Opcodes.DUP_X2); // stack is bound-method, keywords, pos, bound-method methodVisitor.visitMethodInsn(Opcodes.INVOKEVIRTUAL, Type.getInternalName(BoundPythonLikeFunction.class), "getInstance", Type.getMethodDescriptor(Type.getType(PythonLikeObject.class)), false); methodVisitor.visitTypeInsn(Opcodes.CHECKCAST, Type.getInternalName(PythonLikeType.class)); // stack is bound-method, keywords, pos, type methodVisitor.visitInsn(Opcodes.DUP2); // stack is bound-method, keywords, pos, type, pos, type methodVisitor.visitInsn(Opcodes.ICONST_0); methodVisitor.visitInsn(Opcodes.SWAP); methodVisitor.visitMethodInsn(Opcodes.INVOKEINTERFACE, Type.getInternalName(List.class), "add", Type.getMethodDescriptor(Type.VOID_TYPE, Type.INT_TYPE, Type.getType(Object.class)), true); // stack is bound-method, keywords, pos, type methodVisitor.visitInsn(Opcodes.POP); methodVisitor.visitInsn(Opcodes.SWAP); // stack is bound-method, pos, keywords } methodVisitor.visitFieldInsn(Opcodes.GETSTATIC, defaultArgumentHolderClassInternalName, PythonDefaultArgumentImplementor.ARGUMENT_SPEC_STATIC_FIELD_NAME, Type.getDescriptor(ArgumentSpec.class)); methodVisitor.visitInsn(Opcodes.DUP_X2); methodVisitor.visitInsn(Opcodes.POP); methodVisitor.visitMethodInsn(Opcodes.INVOKEVIRTUAL, Type.getInternalName(ArgumentSpec.class), "extractArgumentList", Type.getMethodDescriptor(Type.getType(List.class), Type.getType(List.class), Type.getType(Map.class)), false); // Stack is function to call, argument list // Unwrap the bound method if (methodDescriptor.getMethodType() == MethodDescriptor.MethodType.VIRTUAL || methodDescriptor.getMethodType() == MethodDescriptor.MethodType.INTERFACE) { methodVisitor.visitInsn(Opcodes.SWAP); methodVisitor.visitInsn(Opcodes.DUP_X1); methodVisitor.visitMethodInsn(Opcodes.INVOKEVIRTUAL, Type.getInternalName(BoundPythonLikeFunction.class), "getInstance", Type.getMethodDescriptor(Type.getType(PythonLikeObject.class)), false); methodVisitor.visitTypeInsn(Opcodes.CHECKCAST, methodDescriptor.getDeclaringClassInternalName()); methodVisitor.visitInsn(Opcodes.SWAP); } // Stack is method, boundedInstance?, default // Read the parameters for (int i = 0; i < descriptorParameterTypes.length; i++) { methodVisitor.visitInsn(Opcodes.DUP); methodVisitor.visitLdcInsn(i); methodVisitor.visitMethodInsn(Opcodes.INVOKEINTERFACE, Type.getInternalName(List.class), "get", Type.getMethodDescriptor(Type.getType(Object.class), Type.INT_TYPE), true); methodVisitor.visitLdcInsn(descriptorParameterTypes[i]); methodVisitor.visitMethodInsn(Opcodes.INVOKESTATIC, Type.getInternalName(JavaPythonTypeConversionImplementor.class), "coerceToType", Type.getMethodDescriptor(Type.getType(Object.class), Type.getType(PythonLikeObject.class), Type.getType(Class.class)), false); methodVisitor.visitTypeInsn(Opcodes.CHECKCAST, descriptorParameterTypes[i].getInternalName()); methodVisitor.visitInsn(Opcodes.SWAP); } methodVisitor.visitInsn(Opcodes.POP); // Stack is method, boundedInstance?, arg0, arg1, ... methodDescriptor.callMethod(methodVisitor); // Stack is method, result } }
0
java-sources/ai/timefold/solver/jpyinterpreter/1.24.0/ai/timefold/jpyinterpreter
java-sources/ai/timefold/solver/jpyinterpreter/1.24.0/ai/timefold/jpyinterpreter/implementors/ModuleImplementor.java
package ai.timefold.jpyinterpreter.implementors; import java.util.Collections; import java.util.List; import java.util.Map; import ai.timefold.jpyinterpreter.FunctionMetadata; import ai.timefold.jpyinterpreter.PythonBytecodeInstruction; import ai.timefold.jpyinterpreter.PythonBytecodeToJavaBytecodeTranslator; import ai.timefold.jpyinterpreter.PythonInterpreter; import ai.timefold.jpyinterpreter.PythonLikeObject; import ai.timefold.jpyinterpreter.StackMetadata; import ai.timefold.jpyinterpreter.types.numeric.PythonInteger; import org.objectweb.asm.Label; import org.objectweb.asm.MethodVisitor; import org.objectweb.asm.Opcodes; import org.objectweb.asm.Type; public class ModuleImplementor { /** * TOS is from_list (list or None); TOS1 is level. Imports co_names[instruction.arg] using __import__ with * the given from_list and level (using the function globals and locals). TOS and TOS1 are popped, * and the imported module is pushed. * * @see PythonInterpreter#importModule(PythonInteger, List, Map, Map, String) */ public static void importName(FunctionMetadata functionMetadata, StackMetadata stackMetadata, PythonBytecodeInstruction instruction) { MethodVisitor methodVisitor = functionMetadata.methodVisitor; // Stack is level, from_list // We need it to be interpreter, from_list, level, globals, locals, name // (to call interpreter.importModule) // check if from_list is None Label fromListSet = new Label(); methodVisitor.visitInsn(Opcodes.DUP); PythonConstantsImplementor.loadNone(methodVisitor); methodVisitor.visitJumpInsn(Opcodes.IF_ACMPNE, fromListSet); // Is None; change it to a list methodVisitor.visitInsn(Opcodes.POP); methodVisitor.visitMethodInsn(Opcodes.INVOKESTATIC, Type.getInternalName(Collections.class), "emptyList", Type.getMethodDescriptor(Type.getType(List.class)), false); // typecast from_list to List methodVisitor.visitLabel(fromListSet); methodVisitor.visitTypeInsn(Opcodes.CHECKCAST, Type.getInternalName(List.class)); methodVisitor.visitInsn(Opcodes.SWAP); // typecast level to PythonInteger methodVisitor.visitTypeInsn(Opcodes.CHECKCAST, Type.getInternalName(PythonInteger.class)); methodVisitor.visitInsn(Opcodes.SWAP); // Get the current function's interpreter methodVisitor.visitVarInsn(Opcodes.ALOAD, 0); methodVisitor.visitFieldInsn(Opcodes.GETFIELD, functionMetadata.className, PythonBytecodeToJavaBytecodeTranslator.INTERPRETER_INSTANCE_FIELD_NAME, Type.getDescriptor(PythonInterpreter.class)); // Stack is level, from_list, interpreter // Duplicate interpreter BEFORE from_list and level methodVisitor.visitInsn(Opcodes.DUP_X2); // Stack is interpreter, level, from_list, interpreter // Remove the interpreter from TOS methodVisitor.visitInsn(Opcodes.POP); // Stack is interpreter, level, from_list // Get the globals and the locals from the function methodVisitor.visitFieldInsn(Opcodes.GETSTATIC, functionMetadata.className, PythonBytecodeToJavaBytecodeTranslator.GLOBALS_MAP_STATIC_FIELD_NAME, Type.getDescriptor(Map.class)); // TODO: Create Map of local variables which is stored in a constant slot? methodVisitor.visitMethodInsn(Opcodes.INVOKESTATIC, Type.getInternalName(Collections.class), "emptyMap", Type.getMethodDescriptor(Type.getType(Map.class)), false); // Stack is interpreter, level, from_list, globals_map, locals_map // Finally, push the name of the module to load methodVisitor.visitLdcInsn(functionMetadata.pythonCompiledFunction.co_names.get(instruction.arg())); // Now call the interpreter's importModule function methodVisitor.visitMethodInsn(Opcodes.INVOKEINTERFACE, Type.getInternalName(PythonInterpreter.class), "importModule", Type.getMethodDescriptor(Type.getType(PythonLikeObject.class), Type.getType(PythonInteger.class), Type.getType(List.class), Type.getType(Map.class), Type.getType(Map.class), Type.getType(String.class)), true); } /** * TOS is a module; Push the attribute co_names[instruction.arg] from module onto the stack. TOS is NOT popped. * (i.e. after this instruction, stack is module, attribute) * * @see PythonInterpreter#importModule(PythonInteger, List, Map, Map, String) */ public static void importFrom(FunctionMetadata functionMetadata, StackMetadata stackMetadata, PythonBytecodeInstruction instruction) { MethodVisitor methodVisitor = functionMetadata.methodVisitor; // Stack is module // Duplicate module methodVisitor.visitInsn(Opcodes.DUP); // Stack is module, module // Push the attribute name to load methodVisitor.visitLdcInsn(functionMetadata.pythonCompiledFunction.co_names.get(instruction.arg())); // Stack is module, module, attribute_name // Get the attribute methodVisitor.visitMethodInsn(Opcodes.INVOKEINTERFACE, Type.getInternalName(PythonLikeObject.class), "$getAttributeOrError", Type.getMethodDescriptor(Type.getType(PythonLikeObject.class), Type.getType(String.class)), true); // Stack is module, attribute } }
0
java-sources/ai/timefold/solver/jpyinterpreter/1.24.0/ai/timefold/jpyinterpreter
java-sources/ai/timefold/solver/jpyinterpreter/1.24.0/ai/timefold/jpyinterpreter/implementors/ObjectImplementor.java
package ai.timefold.jpyinterpreter.implementors; import java.util.Optional; import ai.timefold.jpyinterpreter.FieldDescriptor; import ai.timefold.jpyinterpreter.FunctionMetadata; import ai.timefold.jpyinterpreter.LocalVariableHelper; import ai.timefold.jpyinterpreter.PythonBinaryOperator; import ai.timefold.jpyinterpreter.PythonBytecodeInstruction; import ai.timefold.jpyinterpreter.PythonLikeObject; import ai.timefold.jpyinterpreter.PythonTernaryOperator; import ai.timefold.jpyinterpreter.StackMetadata; import ai.timefold.jpyinterpreter.types.BuiltinTypes; import ai.timefold.jpyinterpreter.types.PythonLikeType; import ai.timefold.jpyinterpreter.types.PythonNone; import ai.timefold.jpyinterpreter.types.PythonString; import ai.timefold.jpyinterpreter.types.PythonSuperObject; import ai.timefold.jpyinterpreter.types.errors.AttributeError; import ai.timefold.jpyinterpreter.types.wrappers.JavaObjectWrapper; import org.objectweb.asm.Label; import org.objectweb.asm.MethodVisitor; import org.objectweb.asm.Opcodes; import org.objectweb.asm.Type; /** * Implementations of opcodes related to objects */ public class ObjectImplementor { /** * Replaces TOS with getattr(TOS, co_names[instruction.arg]) */ public static void getAttribute(FunctionMetadata functionMetadata, StackMetadata stackMetadata, int nameIndex) { var methodVisitor = functionMetadata.methodVisitor; var className = functionMetadata.className; PythonLikeType tosType = stackMetadata.getTOSType(); String name = functionMetadata.pythonCompiledFunction.co_names.get(nameIndex); Optional<FieldDescriptor> maybeFieldDescriptor = tosType.getInstanceFieldDescriptor(name); if (maybeFieldDescriptor.isPresent()) { FieldDescriptor fieldDescriptor = maybeFieldDescriptor.get(); if (fieldDescriptor.isTrueFieldDescriptor()) { methodVisitor.visitTypeInsn(Opcodes.CHECKCAST, fieldDescriptor.declaringClassInternalName()); methodVisitor.visitFieldInsn(Opcodes.GETFIELD, fieldDescriptor.declaringClassInternalName(), fieldDescriptor.javaFieldName(), fieldDescriptor.javaFieldTypeDescriptor()); // Check if field is null. If it is null, then it was deleted, so we should raise an AttributeError methodVisitor.visitInsn(Opcodes.DUP); methodVisitor.visitInsn(Opcodes.ACONST_NULL); Label ifNotNull = new Label(); methodVisitor.visitJumpInsn(Opcodes.IF_ACMPNE, ifNotNull); // Throw attribute error methodVisitor.visitTypeInsn(Opcodes.NEW, Type.getInternalName(AttributeError.class)); methodVisitor.visitInsn(Opcodes.DUP); if (fieldDescriptor.fieldPythonLikeType().isInstance(PythonNone.INSTANCE)) { methodVisitor.visitLdcInsn("'" + tosType.getTypeName() + "' object has no attribute '" + name + "'."); } else { // None cannot be assigned to the field, meaning it will delete the attribute instead methodVisitor.visitLdcInsn("'" + tosType.getTypeName() + "' object has no attribute '" + name + "'. " + "It might of been deleted because None cannot be assigned to it; either use " + "hasattr(obj, '" + name + "') or change the typing to allow None (ex: typing.Optional[" + tosType.getTypeName() + "])."); } methodVisitor.visitMethodInsn(Opcodes.INVOKESPECIAL, Type.getInternalName(AttributeError.class), "<init>", Type.getMethodDescriptor(Type.getType(void.class), Type.getType(String.class)), false); methodVisitor.visitInsn(Opcodes.ATHROW); // The attribute was not null if (fieldDescriptor.isJavaType()) { // Need to wrap the object with JavaObjectWrapper methodVisitor.visitTypeInsn(Opcodes.NEW, Type.getInternalName(JavaObjectWrapper.class)); methodVisitor.visitInsn(Opcodes.DUP_X1); methodVisitor.visitInsn(Opcodes.DUP_X1); methodVisitor.visitInsn(Opcodes.POP); methodVisitor.visitMethodInsn(Opcodes.INVOKESPECIAL, Type.getInternalName(JavaObjectWrapper.class), "<init>", Type.getMethodDescriptor(Type.VOID_TYPE, Type.getType(Object.class)), false); } methodVisitor.visitLabel(ifNotNull); } else { // It a false field descriptor, which means TOS is a type and this is a field for a method // We can call $method$__getattribute__ directly (since type do not override it), // which is more efficient then going through the full logic of __getattribute__ dunder method impl. PythonConstantsImplementor.loadName(methodVisitor, className, nameIndex); methodVisitor.visitTypeInsn(Opcodes.CHECKCAST, Type.getInternalName(PythonString.class)); methodVisitor.visitMethodInsn(Opcodes.INVOKEINTERFACE, Type.getInternalName(PythonLikeObject.class), "$method$__getattribute__", Type.getMethodDescriptor( Type.getType(PythonLikeObject.class), Type.getType(PythonString.class)), true); } } else { PythonConstantsImplementor.loadName(methodVisitor, className, nameIndex); DunderOperatorImplementor.binaryOperator(methodVisitor, stackMetadata.pushTemp(BuiltinTypes.STRING_TYPE), PythonBinaryOperator.GET_ATTRIBUTE); } } /** * Deletes co_names[instruction.arg] of TOS */ public static void deleteAttribute(FunctionMetadata functionMetadata, MethodVisitor methodVisitor, String className, StackMetadata stackMetadata, PythonBytecodeInstruction instruction) { PythonLikeType tosType = stackMetadata.getTOSType(); String name = functionMetadata.pythonCompiledFunction.co_names.get(instruction.arg()); Optional<FieldDescriptor> maybeFieldDescriptor = tosType.getInstanceFieldDescriptor(name); if (maybeFieldDescriptor.isPresent()) { FieldDescriptor fieldDescriptor = maybeFieldDescriptor.get(); methodVisitor.visitTypeInsn(Opcodes.CHECKCAST, fieldDescriptor.declaringClassInternalName()); methodVisitor.visitInsn(Opcodes.ACONST_NULL); methodVisitor.visitFieldInsn(Opcodes.PUTFIELD, fieldDescriptor.declaringClassInternalName(), fieldDescriptor.javaFieldName(), fieldDescriptor.javaFieldTypeDescriptor()); } else { PythonConstantsImplementor.loadName(methodVisitor, className, instruction.arg()); DunderOperatorImplementor.binaryOperator(methodVisitor, stackMetadata.pushTemp(BuiltinTypes.STRING_TYPE), PythonBinaryOperator.DELETE_ATTRIBUTE); // Pop off the result of __delattr__ methodVisitor.visitInsn(Opcodes.POP); } } /** * Implement TOS.name = TOS1, where name is co_names[instruction.arg]. TOS and TOS1 are popped. */ public static void setAttribute(FunctionMetadata functionMetadata, MethodVisitor methodVisitor, String className, StackMetadata stackMetadata, PythonBytecodeInstruction instruction, LocalVariableHelper localVariableHelper) { PythonLikeType tosType = stackMetadata.getTOSType(); String name = functionMetadata.pythonCompiledFunction.co_names.get(instruction.arg()); Optional<FieldDescriptor> maybeFieldDescriptor = tosType.getInstanceFieldDescriptor(name); if (maybeFieldDescriptor.isPresent()) { FieldDescriptor fieldDescriptor = maybeFieldDescriptor.get(); methodVisitor.visitTypeInsn(Opcodes.CHECKCAST, fieldDescriptor.declaringClassInternalName()); StackManipulationImplementor.swap(methodVisitor); methodVisitor.visitLdcInsn(Type.getType(fieldDescriptor.fieldPythonLikeType().getJavaTypeDescriptor())); methodVisitor.visitMethodInsn(Opcodes.INVOKESTATIC, Type.getInternalName(JavaPythonTypeConversionImplementor.class), "coerceToType", Type.getMethodDescriptor(Type.getType(Object.class), Type.getType(PythonLikeObject.class), Type.getType(Class.class)), false); methodVisitor.visitTypeInsn(Opcodes.CHECKCAST, fieldDescriptor.fieldPythonLikeType().getJavaTypeInternalName()); if (fieldDescriptor.isJavaType()) { // Need to unwrap the object methodVisitor.visitTypeInsn(Opcodes.CHECKCAST, Type.getInternalName(JavaObjectWrapper.class)); methodVisitor.visitMethodInsn(Opcodes.INVOKEVIRTUAL, Type.getInternalName(JavaObjectWrapper.class), "getWrappedObject", Type.getMethodDescriptor(Type.getType(Object.class)), false); methodVisitor.visitTypeInsn(Opcodes.CHECKCAST, Type.getType(fieldDescriptor.javaFieldTypeDescriptor()).getInternalName()); } methodVisitor.visitFieldInsn(Opcodes.PUTFIELD, fieldDescriptor.declaringClassInternalName(), fieldDescriptor.javaFieldName(), fieldDescriptor.javaFieldTypeDescriptor()); } else { StackManipulationImplementor.swap(methodVisitor); PythonConstantsImplementor.loadName(methodVisitor, className, instruction.arg()); StackManipulationImplementor.swap(methodVisitor); DunderOperatorImplementor.ternaryOperator(functionMetadata, stackMetadata.pop(2) .push(stackMetadata.getValueSourceForStackIndex(0)) .pushTemp(BuiltinTypes.STRING_TYPE) .push(stackMetadata.getValueSourceForStackIndex(1)), PythonTernaryOperator.SET_ATTRIBUTE); // Pop off the result of __setattr__ methodVisitor.visitInsn(Opcodes.POP); } } /** * Implement (super = TOS2)(TOS1, TOS).attr */ public static void getSuperAttribute(FunctionMetadata functionMetadata, StackMetadata stackMetadata, int nameIndex, boolean isLoadMethod) { var methodVisitor = functionMetadata.methodVisitor; // Stack: super, type, instance methodVisitor.visitTypeInsn(Opcodes.NEW, Type.getInternalName(PythonSuperObject.class)); methodVisitor.visitInsn(Opcodes.DUP_X2); methodVisitor.visitInsn(Opcodes.DUP_X2); methodVisitor.visitInsn(Opcodes.POP); // Stack: super, <uninit superobject>, <uninit superobject>, type, instance methodVisitor.visitInsn(Opcodes.SWAP); methodVisitor.visitTypeInsn(Opcodes.CHECKCAST, Type.getInternalName(PythonLikeType.class)); methodVisitor.visitInsn(Opcodes.SWAP); methodVisitor.visitMethodInsn(Opcodes.INVOKESPECIAL, Type.getInternalName(PythonSuperObject.class), "<init>", Type.getMethodDescriptor(Type.VOID_TYPE, Type.getType(PythonLikeType.class), Type.getType(PythonLikeObject.class))); // Stack: super, superobject ObjectImplementor.getAttribute(functionMetadata, stackMetadata.pop(2).pushTemp(BuiltinTypes.SUPER_TYPE), nameIndex); methodVisitor.visitInsn(Opcodes.SWAP); methodVisitor.visitInsn(Opcodes.POP); if (isLoadMethod) { methodVisitor.visitInsn(Opcodes.ACONST_NULL); methodVisitor.visitInsn(Opcodes.SWAP); } } }
0
java-sources/ai/timefold/solver/jpyinterpreter/1.24.0/ai/timefold/jpyinterpreter
java-sources/ai/timefold/solver/jpyinterpreter/1.24.0/ai/timefold/jpyinterpreter/implementors/PythonBuiltinOperatorImplementor.java
package ai.timefold.jpyinterpreter.implementors; import ai.timefold.jpyinterpreter.PythonBytecodeInstruction; import ai.timefold.jpyinterpreter.types.numeric.PythonBoolean; import org.objectweb.asm.Label; import org.objectweb.asm.MethodVisitor; import org.objectweb.asm.Opcodes; import org.objectweb.asm.Type; /** * Implementations of opcodes/operations that do not use dunder methods / are builtin. */ public class PythonBuiltinOperatorImplementor { /** * Replace TOS with not TOS. */ public static void performNotOnTOS(MethodVisitor methodVisitor) { methodVisitor.visitTypeInsn(Opcodes.CHECKCAST, Type.getInternalName(PythonBoolean.class)); methodVisitor.visitMethodInsn(Opcodes.INVOKEVIRTUAL, Type.getInternalName(PythonBoolean.class), "not", Type.getMethodDescriptor(Type.getType(PythonBoolean.class)), false); } /** * Perform TOS is TOS1. If {@code instruction} argument is 1, perform TOS is not TOS1 instead. */ public static void isOperator(MethodVisitor methodVisitor, PythonBytecodeInstruction instruction) { int opcode = (instruction.arg() == 0) ? Opcodes.IF_ACMPEQ : Opcodes.IF_ACMPNE; Label trueBranchLabel = new Label(); Label endLabel = new Label(); methodVisitor.visitJumpInsn(opcode, trueBranchLabel); PythonConstantsImplementor.loadFalse(methodVisitor); methodVisitor.visitJumpInsn(Opcodes.GOTO, endLabel); methodVisitor.visitLabel(trueBranchLabel); PythonConstantsImplementor.loadTrue(methodVisitor); methodVisitor.visitLabel(endLabel); } }
0
java-sources/ai/timefold/solver/jpyinterpreter/1.24.0/ai/timefold/jpyinterpreter
java-sources/ai/timefold/solver/jpyinterpreter/1.24.0/ai/timefold/jpyinterpreter/implementors/PythonConstantsImplementor.java
package ai.timefold.jpyinterpreter.implementors; import java.util.List; import ai.timefold.jpyinterpreter.PythonBytecodeToJavaBytecodeTranslator; import ai.timefold.jpyinterpreter.types.PythonNone; import ai.timefold.jpyinterpreter.types.numeric.PythonBoolean; import org.objectweb.asm.MethodVisitor; import org.objectweb.asm.Opcodes; import org.objectweb.asm.Type; /** * Implementations of loading Python constants */ public class PythonConstantsImplementor { /** * Pushes None onto the stack. The same instance is pushed on each call. */ public static void loadNone(MethodVisitor methodVisitor) { methodVisitor.visitFieldInsn(Opcodes.GETSTATIC, Type.getInternalName(PythonNone.class), "INSTANCE", Type.getDescriptor(PythonNone.class)); } /** * Pushes True onto the stack. The same instance is pushed on each call. */ public static void loadTrue(MethodVisitor methodVisitor) { methodVisitor.visitFieldInsn(Opcodes.GETSTATIC, Type.getInternalName(PythonBoolean.class), "TRUE", Type.getDescriptor(PythonBoolean.class)); } /** * Pushes False onto the stack. The same instance is pushed on each call. */ public static void loadFalse(MethodVisitor methodVisitor) { methodVisitor.visitFieldInsn(Opcodes.GETSTATIC, Type.getInternalName(PythonBoolean.class), "FALSE", Type.getDescriptor(PythonBoolean.class)); } /** * Gets the {@code constantIndex} constant from the class constant list * * @param className The class currently being defined by the methodVisitor * @param constantIndex The index of the constant to load in the class constant list */ public static void loadConstant(MethodVisitor methodVisitor, String className, int constantIndex) { methodVisitor.visitFieldInsn(Opcodes.GETSTATIC, className, PythonBytecodeToJavaBytecodeTranslator.CONSTANTS_STATIC_FIELD_NAME, Type.getDescriptor(List.class)); methodVisitor.visitLdcInsn(constantIndex); methodVisitor.visitMethodInsn(Opcodes.INVOKEINTERFACE, Type.getInternalName(List.class), "get", Type.getMethodDescriptor(Type.getType(Object.class), Type.INT_TYPE), true); } /** * Gets the {@code nameIndex} name from the class name list * * @param className The class currently being defined by the methodVisitor * @param nameIndex The index of the name to load in the class name list */ public static void loadName(MethodVisitor methodVisitor, String className, int nameIndex) { methodVisitor.visitFieldInsn(Opcodes.GETSTATIC, className, PythonBytecodeToJavaBytecodeTranslator.NAMES_STATIC_FIELD_NAME, Type.getDescriptor(List.class)); methodVisitor.visitLdcInsn(nameIndex); methodVisitor.visitMethodInsn(Opcodes.INVOKEINTERFACE, Type.getInternalName(List.class), "get", Type.getMethodDescriptor(Type.getType(Object.class), Type.INT_TYPE), true); } }
0
java-sources/ai/timefold/solver/jpyinterpreter/1.24.0/ai/timefold/jpyinterpreter
java-sources/ai/timefold/solver/jpyinterpreter/1.24.0/ai/timefold/jpyinterpreter/implementors/StackManipulationImplementor.java
package ai.timefold.jpyinterpreter.implementors; import java.util.ArrayList; import java.util.List; import ai.timefold.jpyinterpreter.ExceptionBlock; import ai.timefold.jpyinterpreter.FunctionMetadata; import ai.timefold.jpyinterpreter.LocalVariableHelper; import ai.timefold.jpyinterpreter.PythonLikeObject; import ai.timefold.jpyinterpreter.PythonVersion; import ai.timefold.jpyinterpreter.StackMetadata; import ai.timefold.jpyinterpreter.ValueSourceInfo; import org.objectweb.asm.MethodVisitor; import org.objectweb.asm.Opcodes; import org.objectweb.asm.Type; /** * Implementations of stack manipulation opcodes (rotations, pop, duplication, etc.) */ public class StackManipulationImplementor { /** * Swaps TOS and TOS1: * * (i.e. ..., TOS1, TOS -> ..., TOS, TOS1) */ public static void swap(MethodVisitor methodVisitor) { methodVisitor.visitInsn(Opcodes.SWAP); } /** * Move TOS down two places, and pushes TOS1 and TOS2 up one: * * (i.e. ..., TOS2, TOS1, TOS -> ..., TOS, TOS2, TOS1) */ public static void rotateThree(MethodVisitor methodVisitor) { methodVisitor.visitInsn(Opcodes.DUP_X2); methodVisitor.visitInsn(Opcodes.POP); } /** * Move TOS down three places, and pushes TOS1, TOS2 and TOS3 up one: * * (i.e. ..., TOS3, TOS2, TOS1, TOS -> ..., TOS, TOS3, TOS2, TOS1) */ public static void rotateFour(FunctionMetadata functionMetadata, StackMetadata stackMetadata) { MethodVisitor methodVisitor = functionMetadata.methodVisitor; LocalVariableHelper localVariableHelper = stackMetadata.localVariableHelper; int secondFromStack = localVariableHelper.newLocal(); int thirdFromStack = localVariableHelper.newLocal(); methodVisitor.visitInsn(Opcodes.DUP_X2); methodVisitor.visitInsn(Opcodes.POP); localVariableHelper.writeTemp(methodVisitor, Type.getType(stackMetadata.getTypeAtStackIndex(1).getJavaTypeDescriptor()), secondFromStack); localVariableHelper.writeTemp(methodVisitor, Type.getType(stackMetadata.getTypeAtStackIndex(2).getJavaTypeDescriptor()), thirdFromStack); methodVisitor.visitInsn(Opcodes.SWAP); localVariableHelper.readTemp(methodVisitor, Type.getType(stackMetadata.getTypeAtStackIndex(2).getJavaTypeDescriptor()), thirdFromStack); localVariableHelper.readTemp(methodVisitor, Type.getType(stackMetadata.getTypeAtStackIndex(1).getJavaTypeDescriptor()), secondFromStack); localVariableHelper.freeLocal(); localVariableHelper.freeLocal(); } /** * Pops TOS. * * (i.e. ..., TOS -> ...) */ public static void popTOS(MethodVisitor methodVisitor) { methodVisitor.visitInsn(Opcodes.POP); } /** * Duplicates TOS. * * (i.e. ..., TOS -> ..., TOS, TOS) */ public static void duplicateTOS(MethodVisitor methodVisitor) { methodVisitor.visitInsn(Opcodes.DUP); } /** * Duplicates TOS and TOS1. * * (i.e. ..., TOS1, TOS -> ..., TOS1, TOS, TOS1, TOS) */ public static void duplicateTOSAndTOS1(MethodVisitor methodVisitor) { methodVisitor.visitInsn(Opcodes.DUP2); } /** * Copies TOS[posFromTOS] to TOS, leaving other stack elements in their original place * * (i.e. ..., TOS[posFromTOS], ..., TOS2, TOS1, TOS -> ..., TOS[posFromTOS], ..., TOS2, TOS1, TOS, TOS[posFromTOS]) */ public static void duplicateToTOS(FunctionMetadata functionMetadata, StackMetadata stackMetadata, int posFromTOS) { MethodVisitor methodVisitor = functionMetadata.methodVisitor; LocalVariableHelper localVariableHelper = stackMetadata.localVariableHelper; List<Integer> localList = new ArrayList<>(posFromTOS); // Store TOS...TOS[posFromTOS - 1] into local variables for (int i = 0; i < posFromTOS; i++) { int local = localVariableHelper.newLocal(); localList.add(local); localVariableHelper.writeTemp(methodVisitor, Type.getType(stackMetadata.getTypeAtStackIndex(i).getJavaTypeDescriptor()), local); } // Duplicate TOS[posFromTOS] methodVisitor.visitInsn(Opcodes.DUP); // Restore TOS...TOS[posFromTOS - 1] from local variables, swaping the duplicated value to keep it on TOS for (int i = posFromTOS - 1; i >= 0; i--) { int local = localList.get(i); localVariableHelper.readTemp(methodVisitor, Type.getType(stackMetadata.getTypeAtStackIndex(i).getJavaTypeDescriptor()), local); methodVisitor.visitInsn(Opcodes.SWAP); localVariableHelper.freeLocal(); } } /** * Copies TOS to TOS[posFromTOS], moving other stack elements up by one * * (i.e. ..., TOS[posFromTOS], ..., TOS2, TOS1, TOS -> ..., TOS, TOS[posFromTOS] ..., TOS2, TOS1) */ public static StackMetadata shiftTOSDownBy(FunctionMetadata functionMetadata, StackMetadata stackMetadata, int posFromTOS) { MethodVisitor methodVisitor = functionMetadata.methodVisitor; LocalVariableHelper localVariableHelper = stackMetadata.localVariableHelper; List<Integer> localList = new ArrayList<>(posFromTOS + 1); if (posFromTOS == 0) { // A rotation of 0 is a no-op return stackMetadata; } // Store TOS...TOS[posFromTOS - 1] into local variables for (int i = 0; i < posFromTOS + 1; i++) { int local = localVariableHelper.newLocal(); localList.add(local); localVariableHelper.writeTemp(methodVisitor, Type.getType(stackMetadata.getTypeAtStackIndex(i).getJavaTypeDescriptor()), local); } // Copy TOS to this position localVariableHelper.readTemp(methodVisitor, Type.getType(stackMetadata.getTypeAtStackIndex(0).getJavaTypeDescriptor()), localList.get(0)); // Restore TOS[1]...TOS[posFromTOS] from local variables for (int i = posFromTOS; i > 0; i--) { int local = localList.get(i); localVariableHelper.readTemp(methodVisitor, Type.getType(stackMetadata.getTypeAtStackIndex(i).getJavaTypeDescriptor()), local); localVariableHelper.freeLocal(); } ValueSourceInfo top = stackMetadata.getTOSValueSource(); StackMetadata out = stackMetadata; out = out.pop(posFromTOS + 1); out = out.push(top); for (int i = posFromTOS; i > 0; i--) { out = out.push(stackMetadata.getValueSourceForStackIndex(i)); } return out; } /** * Swaps TOS with TOS[posFromTOS] * * (i.e. ..., TOS[posFromTOS], ..., TOS2, TOS1, TOS -> ..., TOS, ..., TOS2, TOS1, TOS[posFromTOS]) */ public static StackMetadata swapTOSWithIndex(FunctionMetadata functionMetadata, StackMetadata stackMetadata, int posFromTOS) { MethodVisitor methodVisitor = functionMetadata.methodVisitor; LocalVariableHelper localVariableHelper = stackMetadata.localVariableHelper; List<Integer> localList = new ArrayList<>(posFromTOS + 1); if (posFromTOS == 0) { // A rotation of 0 is a no-op return stackMetadata; } // Store TOS...TOS[posFromTOS - 1] into local variables for (int i = 0; i < posFromTOS + 1; i++) { int local = localVariableHelper.newLocal(); localList.add(local); localVariableHelper.writeTemp(methodVisitor, Type.getType(stackMetadata.getTypeAtStackIndex(i).getJavaTypeDescriptor()), local); } // Copy TOS to this position localVariableHelper.readTemp(methodVisitor, Type.getType(stackMetadata.getTypeAtStackIndex(0).getJavaTypeDescriptor()), localList.get(0)); // Restore TOS[1]...TOS[posFromTOS - 1] from local variables for (int i = posFromTOS - 1; i > 0; i--) { int local = localList.get(i); localVariableHelper.readTemp(methodVisitor, Type.getType(stackMetadata.getTypeAtStackIndex(i).getJavaTypeDescriptor()), local); } int local = localList.get(posFromTOS); localVariableHelper.readTemp(methodVisitor, Type.getType(stackMetadata.getTypeAtStackIndex(posFromTOS).getJavaTypeDescriptor()), local); // Free locals for (int i = posFromTOS; i > 0; i--) { localVariableHelper.freeLocal(); } return stackMetadata .set(posFromTOS, stackMetadata.getTOSValueSource()) .set(0, stackMetadata.getValueSourceForStackIndex(posFromTOS)); } public static int[] storeStack(MethodVisitor methodVisitor, StackMetadata stackMetadata) { int[] stackLocalVariables = new int[stackMetadata.getStackSize()]; for (int i = stackLocalVariables.length - 1; i >= 0; i--) { stackLocalVariables[i] = stackMetadata.localVariableHelper.newLocal(); stackMetadata.localVariableHelper.writeTemp(methodVisitor, Type.getType(stackMetadata.getTypeAtStackIndex(i).getJavaTypeDescriptor()), stackLocalVariables[i]); } for (int i = 0; i < stackLocalVariables.length; i++) { stackMetadata.localVariableHelper.readTemp(methodVisitor, Type.getType(stackMetadata.getTypeAtStackIndex(i).getJavaTypeDescriptor()), stackLocalVariables[i]); } return stackLocalVariables; } public static void restoreStack(MethodVisitor methodVisitor, StackMetadata stackMetadata, int[] stackLocalVariables) { for (int i = 0; i < stackLocalVariables.length; i++) { stackMetadata.localVariableHelper.readTemp(methodVisitor, Type.getType(stackMetadata.getTypeAtStackIndex(i).getJavaTypeDescriptor()), stackLocalVariables[i]); } } public static void storeExceptionTableStack(FunctionMetadata functionMetadata, StackMetadata stackMetadata, ExceptionBlock exceptionBlock) { MethodVisitor methodVisitor = functionMetadata.methodVisitor; LocalVariableHelper localVariableHelper = stackMetadata.localVariableHelper; int[] stackLocalVariables = new int[stackMetadata.getStackSize()]; for (int i = stackLocalVariables.length - 1; i >= 0; i--) { stackLocalVariables[i] = localVariableHelper.newLocal(); localVariableHelper.writeTemp(methodVisitor, Type.getType(stackMetadata.getTypeAtStackIndex(i).getJavaTypeDescriptor()), stackLocalVariables[i]); } methodVisitor.visitLdcInsn(exceptionBlock.getStackDepth()); methodVisitor.visitTypeInsn(Opcodes.ANEWARRAY, Type.getInternalName(PythonLikeObject.class)); for (int i = 0; i < exceptionBlock.getStackDepth(); i++) { methodVisitor.visitInsn(Opcodes.DUP); methodVisitor.visitLdcInsn(i); localVariableHelper.readTemp(methodVisitor, Type.getType(stackMetadata.getTypeAtStackIndex(i).getJavaTypeDescriptor()), stackLocalVariables[i]); methodVisitor.visitInsn(Opcodes.AASTORE); } localVariableHelper.writeExceptionTableTargetStack(methodVisitor, exceptionBlock.getTargetInstruction()); for (int i = 0; i < stackLocalVariables.length; i++) { localVariableHelper.readTemp(methodVisitor, Type.getType(stackMetadata.getTypeAtStackIndex(i).getJavaTypeDescriptor()), stackLocalVariables[i]); } for (int i = 0; i < stackLocalVariables.length; i++) { localVariableHelper.freeLocal(); } } public static void restoreExceptionTableStack(FunctionMetadata functionMetadata, StackMetadata stackMetadata, ExceptionBlock exceptionBlock) { MethodVisitor methodVisitor = functionMetadata.methodVisitor; LocalVariableHelper localVariableHelper = stackMetadata.localVariableHelper; localVariableHelper.readExceptionTableTargetStack(methodVisitor, exceptionBlock.getTargetInstruction()); for (int i = 0; i < exceptionBlock.getStackDepth(); i++) { methodVisitor.visitInsn(Opcodes.DUP); methodVisitor.visitLdcInsn(i); methodVisitor.visitInsn(Opcodes.AALOAD); if (functionMetadata.pythonCompiledFunction.pythonVersion.isBefore(PythonVersion.PYTHON_3_11) || functionMetadata.pythonCompiledFunction.pythonVersion.isAtLeast(PythonVersion.PYTHON_3_12)) { // Not a 3.11 python version methodVisitor.visitTypeInsn(Opcodes.CHECKCAST, stackMetadata.getTypeAtStackIndex(exceptionBlock.getStackDepth() - i - 1).getJavaTypeInternalName()); } else { // A 3.11 python version methodVisitor.visitTypeInsn(Opcodes.CHECKCAST, Type.getInternalName(PythonLikeObject.class)); } methodVisitor.visitInsn(Opcodes.SWAP); } methodVisitor.visitInsn(Opcodes.POP); } }
0
java-sources/ai/timefold/solver/jpyinterpreter/1.24.0/ai/timefold/jpyinterpreter
java-sources/ai/timefold/solver/jpyinterpreter/1.24.0/ai/timefold/jpyinterpreter/implementors/StringImplementor.java
package ai.timefold.jpyinterpreter.implementors; import java.util.Collections; import java.util.List; import java.util.Map; import ai.timefold.jpyinterpreter.FunctionMetadata; import ai.timefold.jpyinterpreter.PythonBytecodeInstruction; import ai.timefold.jpyinterpreter.PythonBytecodeToJavaBytecodeTranslator; import ai.timefold.jpyinterpreter.PythonInterpreter; import ai.timefold.jpyinterpreter.PythonLikeObject; import ai.timefold.jpyinterpreter.PythonUnaryOperator; import ai.timefold.jpyinterpreter.StackMetadata; import ai.timefold.jpyinterpreter.opcodes.descriptor.StringOpDescriptor; import ai.timefold.jpyinterpreter.types.PythonLikeFunction; import ai.timefold.jpyinterpreter.types.PythonString; import ai.timefold.jpyinterpreter.types.collections.PythonLikeTuple; import org.objectweb.asm.MethodVisitor; import org.objectweb.asm.Opcodes; import org.objectweb.asm.Type; public class StringImplementor { /** * Constructs a string from the top {@code itemCount} on the stack. * Basically generate the following code: * * <pre> * StringBuilder builder = new StringBuilder(); * builder.insert(0, TOS); * builder.insert(0, TOS1); * ... * builder.insert(0, TOS(itemCount - 1)); * TOS' = PythonString.valueOf(builder.toString()) * </pre> * * @param itemCount The number of items to put into collection from the stack */ public static void buildString(MethodVisitor methodVisitor, int itemCount) { methodVisitor.visitTypeInsn(Opcodes.NEW, Type.getInternalName(StringBuilder.class)); methodVisitor.visitInsn(Opcodes.DUP); methodVisitor.visitMethodInsn(Opcodes.INVOKESPECIAL, Type.getInternalName(StringBuilder.class), "<init>", Type.getMethodDescriptor(Type.VOID_TYPE), false); for (int i = 0; i < itemCount; i++) { methodVisitor.visitInsn(Opcodes.SWAP); methodVisitor.visitInsn(Opcodes.ICONST_0); methodVisitor.visitInsn(Opcodes.SWAP); methodVisitor.visitMethodInsn(Opcodes.INVOKEVIRTUAL, Type.getInternalName(StringBuilder.class), "insert", Type.getMethodDescriptor(Type.getType(StringBuilder.class), Type.INT_TYPE, Type.getType(Object.class)), false); } methodVisitor.visitMethodInsn(Opcodes.INVOKEVIRTUAL, Type.getInternalName(Object.class), "toString", Type.getMethodDescriptor(Type.getType(String.class)), false); methodVisitor.visitMethodInsn(Opcodes.INVOKESTATIC, Type.getInternalName(PythonString.class), "valueOf", Type.getMethodDescriptor(Type.getType(PythonString.class), Type.getType(String.class)), false); } /** * TOS1 is a value and TOS is an optional format string (either PythonNone or PythonString). * Depending on {@code instruction.arg}, does one of several things to TOS1 before formatting it * (as specified by {@link StringOpDescriptor#FORMAT_VALUE}: * * arg &amp; 3 == 0: Do nothing * arg &amp; 3 == 1: Call str() on value before formatting it * arg &amp; 3 == 2: Call repr() on value before formatting it * arg &amp; 3 == 3: Call ascii() on value before formatting it * * if arg &amp; 4 == 0, TOS is the value to format, so push PythonNone before calling format * if arg &amp; 4 == 4, TOS is a format string, use it in the call */ public static void formatValue(MethodVisitor methodVisitor, PythonBytecodeInstruction instruction) { if ((instruction.arg() & 4) == 0) { // No format string on stack; push None PythonConstantsImplementor.loadNone(methodVisitor); } switch (instruction.arg() & 3) { case 0 -> { // Do Nothing } case 1 -> { // Call str() StackManipulationImplementor.swap(methodVisitor); DunderOperatorImplementor.unaryOperator(methodVisitor, PythonUnaryOperator.AS_STRING); StackManipulationImplementor.swap(methodVisitor); } case 2 -> { // Call repr() StackManipulationImplementor.swap(methodVisitor); DunderOperatorImplementor.unaryOperator(methodVisitor, PythonUnaryOperator.REPRESENTATION); StackManipulationImplementor.swap(methodVisitor); } case 3 -> { // Call ascii() StackManipulationImplementor.swap(methodVisitor); // TODO: Create method that calls repr and convert non-ascii character to ascii and call it StackManipulationImplementor.swap(methodVisitor); } default -> throw new IllegalStateException("Invalid flag: %d; & did not produce a value in range 0-3: %d" .formatted(instruction.arg(), instruction.arg() & 3)); } methodVisitor.visitMethodInsn(Opcodes.INVOKEINTERFACE, Type.getInternalName(PythonLikeObject.class), "$method$__format__", Type.getMethodDescriptor(Type.getType(PythonLikeObject.class), Type.getType(PythonLikeObject.class)), true); } /** * TOS is an PythonLikeObject to be printed. Pop TOS off the stack and print it. */ public static void print(FunctionMetadata functionMetadata, StackMetadata stackMetadata) { String className = functionMetadata.className; String globalName = "print"; MethodVisitor methodVisitor = functionMetadata.methodVisitor; methodVisitor.visitVarInsn(Opcodes.ALOAD, 0); methodVisitor.visitTypeInsn(Opcodes.CHECKCAST, className); methodVisitor.visitFieldInsn(Opcodes.GETFIELD, className, PythonBytecodeToJavaBytecodeTranslator.INTERPRETER_INSTANCE_FIELD_NAME, Type.getDescriptor(PythonInterpreter.class)); methodVisitor.visitFieldInsn(Opcodes.GETSTATIC, className, PythonBytecodeToJavaBytecodeTranslator.GLOBALS_MAP_STATIC_FIELD_NAME, Type.getDescriptor(Map.class)); methodVisitor.visitLdcInsn(globalName); methodVisitor.visitMethodInsn(Opcodes.INVOKEINTERFACE, Type.getInternalName(PythonInterpreter.class), "getGlobal", Type.getMethodDescriptor(Type.getType(PythonLikeObject.class), Type.getType(Map.class), Type.getType(String.class)), true); methodVisitor.visitTypeInsn(Opcodes.CHECKCAST, Type.getInternalName(PythonLikeFunction.class)); methodVisitor.visitInsn(Opcodes.SWAP); CollectionImplementor.buildCollection(PythonLikeTuple.class, methodVisitor, 1); methodVisitor.visitMethodInsn(Opcodes.INVOKESTATIC, Type.getInternalName(Collections.class), "emptyMap", Type.getMethodDescriptor(Type.getType(Map.class)), false); methodVisitor.visitInsn(Opcodes.ACONST_NULL); methodVisitor.visitMethodInsn(Opcodes.INVOKEINTERFACE, Type.getInternalName(PythonLikeFunction.class), "$call", Type.getMethodDescriptor(Type.getType(PythonLikeObject.class), Type.getType(List.class), Type.getType(Map.class), Type.getType(PythonLikeObject.class)), true); } }
0
java-sources/ai/timefold/solver/jpyinterpreter/1.24.0/ai/timefold/jpyinterpreter
java-sources/ai/timefold/solver/jpyinterpreter/1.24.0/ai/timefold/jpyinterpreter/implementors/VariableImplementor.java
package ai.timefold.jpyinterpreter.implementors; import java.util.List; import java.util.Map; import ai.timefold.jpyinterpreter.FunctionMetadata; import ai.timefold.jpyinterpreter.LocalVariableHelper; import ai.timefold.jpyinterpreter.PythonBytecodeInstruction; import ai.timefold.jpyinterpreter.PythonBytecodeToJavaBytecodeTranslator; import ai.timefold.jpyinterpreter.PythonCompiledFunction; import ai.timefold.jpyinterpreter.PythonInterpreter; import ai.timefold.jpyinterpreter.PythonLikeObject; import ai.timefold.jpyinterpreter.PythonVersion; import ai.timefold.jpyinterpreter.StackMetadata; import ai.timefold.jpyinterpreter.opcodes.descriptor.VariableOpDescriptor; import ai.timefold.jpyinterpreter.types.PythonCell; import ai.timefold.jpyinterpreter.types.PythonLikeType; import ai.timefold.jpyinterpreter.types.collections.PythonLikeTuple; import org.objectweb.asm.MethodVisitor; import org.objectweb.asm.Opcodes; import org.objectweb.asm.Type; /** * Implementations of local variable manipulation opcodes. * See https://tenthousandmeters.com/blog/python-behind-the-scenes-5-how-variables-are-implemented-in-cpython/ * for a detailed explanation of the differences between LOAD_FAST, LOAD_GLOBAL, LOAD_DEREF, etc. */ public class VariableImplementor { /** * Loads the local variable or parameter indicated by the {@code instruction} argument onto the stack. */ public static void loadLocalVariable(MethodVisitor methodVisitor, PythonBytecodeInstruction instruction, LocalVariableHelper localVariableHelper) { localVariableHelper.readLocal(methodVisitor, instruction.arg()); } /** * Stores TOS into the local variable or parameter indicated by the {@code instruction} argument. */ public static void storeInLocalVariable(MethodVisitor methodVisitor, PythonBytecodeInstruction instruction, LocalVariableHelper localVariableHelper) { localVariableHelper.writeLocal(methodVisitor, instruction.arg()); } /** * Deletes the global variable or parameter indicated by the {@code instruction} argument. */ public static void deleteGlobalVariable(MethodVisitor methodVisitor, String className, PythonCompiledFunction pythonCompiledFunction, PythonBytecodeInstruction instruction) { String globalName = pythonCompiledFunction.co_names.get(instruction.arg()); methodVisitor.visitVarInsn(Opcodes.ALOAD, 0); methodVisitor.visitTypeInsn(Opcodes.CHECKCAST, className); methodVisitor.visitFieldInsn(Opcodes.GETFIELD, className, PythonBytecodeToJavaBytecodeTranslator.INTERPRETER_INSTANCE_FIELD_NAME, Type.getDescriptor(PythonInterpreter.class)); methodVisitor.visitFieldInsn(Opcodes.GETSTATIC, className, PythonBytecodeToJavaBytecodeTranslator.GLOBALS_MAP_STATIC_FIELD_NAME, Type.getDescriptor(Map.class)); methodVisitor.visitLdcInsn(globalName); methodVisitor.visitMethodInsn(Opcodes.INVOKEINTERFACE, Type.getInternalName(PythonInterpreter.class), "deleteGlobal", Type.getMethodDescriptor(Type.VOID_TYPE, Type.getType(Map.class), Type.getType(String.class)), true); } /** * Loads the global variable or parameter indicated by the {@code instruction} argument onto the stack. */ public static void loadGlobalVariable(FunctionMetadata functionMetadata, StackMetadata stackMetadata, int globalIndex, PythonLikeType globalType) { PythonCompiledFunction pythonCompiledFunction = functionMetadata.pythonCompiledFunction; MethodVisitor methodVisitor = functionMetadata.methodVisitor; String className = functionMetadata.className; String globalName = pythonCompiledFunction.co_names.get(globalIndex); methodVisitor.visitVarInsn(Opcodes.ALOAD, 0); methodVisitor.visitTypeInsn(Opcodes.CHECKCAST, className); methodVisitor.visitFieldInsn(Opcodes.GETFIELD, className, PythonBytecodeToJavaBytecodeTranslator.INTERPRETER_INSTANCE_FIELD_NAME, Type.getDescriptor(PythonInterpreter.class)); methodVisitor.visitFieldInsn(Opcodes.GETSTATIC, className, PythonBytecodeToJavaBytecodeTranslator.GLOBALS_MAP_STATIC_FIELD_NAME, Type.getDescriptor(Map.class)); methodVisitor.visitLdcInsn(globalName); methodVisitor.visitMethodInsn(Opcodes.INVOKEINTERFACE, Type.getInternalName(PythonInterpreter.class), "getGlobal", Type.getMethodDescriptor(Type.getType(PythonLikeObject.class), Type.getType(Map.class), Type.getType(String.class)), true); methodVisitor.visitTypeInsn(Opcodes.CHECKCAST, globalType.getJavaTypeInternalName()); } /** * Stores TOS into the global variable or parameter indicated by the {@code instruction} argument. */ public static void storeInGlobalVariable(MethodVisitor methodVisitor, String className, PythonCompiledFunction pythonCompiledFunction, PythonBytecodeInstruction instruction) { String globalName = pythonCompiledFunction.co_names.get(instruction.arg()); methodVisitor.visitVarInsn(Opcodes.ALOAD, 0); methodVisitor.visitTypeInsn(Opcodes.CHECKCAST, className); methodVisitor.visitFieldInsn(Opcodes.GETFIELD, className, PythonBytecodeToJavaBytecodeTranslator.INTERPRETER_INSTANCE_FIELD_NAME, Type.getDescriptor(PythonInterpreter.class)); StackManipulationImplementor.swap(methodVisitor); methodVisitor.visitFieldInsn(Opcodes.GETSTATIC, className, PythonBytecodeToJavaBytecodeTranslator.GLOBALS_MAP_STATIC_FIELD_NAME, Type.getDescriptor(Map.class)); StackManipulationImplementor.swap(methodVisitor); methodVisitor.visitLdcInsn(globalName); StackManipulationImplementor.swap(methodVisitor); methodVisitor.visitMethodInsn(Opcodes.INVOKEINTERFACE, Type.getInternalName(PythonInterpreter.class), "setGlobal", Type.getMethodDescriptor(Type.VOID_TYPE, Type.getType(Map.class), Type.getType(String.class), Type.getType(PythonLikeObject.class)), true); } /** * Deletes the local variable or parameter indicated by the {@code instruction} argument. */ public static void deleteLocalVariable(MethodVisitor methodVisitor, PythonBytecodeInstruction instruction, LocalVariableHelper localVariableHelper) { // Deleting is implemented as setting the value to null methodVisitor.visitInsn(Opcodes.ACONST_NULL); localVariableHelper.writeLocal(methodVisitor, instruction.arg()); } public static int getCellIndex(FunctionMetadata functionMetadata, int instructionArg) { if (functionMetadata.pythonCompiledFunction.pythonVersion.isAtLeast(PythonVersion.PYTHON_3_11)) { // free variables are offset by co_varnames.size(), bound variables are not if (instructionArg >= functionMetadata.pythonCompiledFunction.co_cellvars.size()) { // it a free variable return instructionArg - functionMetadata.pythonCompiledFunction.co_varnames.size(); } return instructionArg; // it a bound variable } else { return instructionArg; // Python 3.10 and below, we don't need to do anything } } /** * Loads the cell indicated by the {@code instruction} argument onto the stack. * This is used by {@link VariableOpDescriptor#LOAD_CLOSURE} when creating a closure * for a dependent function. */ public static void createCell(MethodVisitor methodVisitor, LocalVariableHelper localVariableHelper, int cellIndex) { methodVisitor.visitTypeInsn(Opcodes.NEW, Type.getInternalName(PythonCell.class)); methodVisitor.visitInsn(Opcodes.DUP); methodVisitor.visitMethodInsn(Opcodes.INVOKESPECIAL, Type.getInternalName(PythonCell.class), "<init>", Type.getMethodDescriptor(Type.VOID_TYPE), false); methodVisitor.visitInsn(Opcodes.DUP); localVariableHelper.readCellInitialValue(methodVisitor, cellIndex); methodVisitor.visitTypeInsn(Opcodes.CHECKCAST, Type.getInternalName(PythonLikeObject.class)); methodVisitor.visitFieldInsn(Opcodes.PUTFIELD, Type.getInternalName(PythonCell.class), "cellValue", Type.getDescriptor(PythonLikeObject.class)); localVariableHelper.writeCell(methodVisitor, cellIndex); } /** * Moves the {@code cellIndex} free variable (stored in the * {@link PythonBytecodeToJavaBytecodeTranslator#CELLS_INSTANCE_FIELD_NAME} field * to its corresponding local variable. */ public static void setupFreeVariableCell(MethodVisitor methodVisitor, String internalClassName, LocalVariableHelper localVariableHelper, int cellIndex) { methodVisitor.visitVarInsn(Opcodes.ALOAD, 0); methodVisitor.visitFieldInsn(Opcodes.GETFIELD, internalClassName, PythonBytecodeToJavaBytecodeTranslator.CELLS_INSTANCE_FIELD_NAME, Type.getDescriptor(PythonLikeTuple.class)); methodVisitor.visitLdcInsn(cellIndex); methodVisitor.visitMethodInsn(Opcodes.INVOKEINTERFACE, Type.getInternalName(List.class), "get", Type.getMethodDescriptor(Type.getType(Object.class), Type.getType(int.class)), true); methodVisitor.visitTypeInsn(Opcodes.CHECKCAST, Type.getInternalName(PythonCell.class)); localVariableHelper.writeFreeCell(methodVisitor, cellIndex); } /** * Loads the cell indicated by the {@code instruction} argument onto the stack. * This is used by {@link VariableOpDescriptor#LOAD_CLOSURE} when creating a closure * for a dependent function. */ public static void loadCell(FunctionMetadata functionMetadata, StackMetadata stackMetadata, int cellIndex) { MethodVisitor methodVisitor = functionMetadata.methodVisitor; LocalVariableHelper localVariableHelper = stackMetadata.localVariableHelper; localVariableHelper.readCell(methodVisitor, cellIndex); } /** * Loads the cell variable/free variable indicated by the {@code instruction} argument onto the stack. * (which is an {@link PythonCell}, so it can see changes from the parent function). */ public static void loadCellVariable(FunctionMetadata functionMetadata, StackMetadata stackMetadata, int cellIndex) { MethodVisitor methodVisitor = functionMetadata.methodVisitor; loadCell(functionMetadata, stackMetadata, cellIndex); methodVisitor.visitFieldInsn(Opcodes.GETFIELD, Type.getInternalName(PythonCell.class), "cellValue", Type.getDescriptor(PythonLikeObject.class)); } /** * Stores TOS into the cell variable or parameter indicated by the {@code instruction} argument * (which is an {@link PythonCell}, so changes in the parent function affect the variable in dependent functions). */ public static void storeInCellVariable(FunctionMetadata functionMetadata, StackMetadata stackMetadata, int cellIndex) { MethodVisitor methodVisitor = functionMetadata.methodVisitor; loadCell(functionMetadata, stackMetadata, cellIndex); methodVisitor.visitInsn(Opcodes.SWAP); methodVisitor.visitFieldInsn(Opcodes.PUTFIELD, Type.getInternalName(PythonCell.class), "cellValue", Type.getDescriptor(PythonLikeObject.class)); } /** * Deletes the cell variable or parameter indicated by the {@code instruction} argument * (which is an {@link PythonCell}, so changes in the parent function affect the variable in dependent functions). */ public static void deleteCellVariable(FunctionMetadata functionMetadata, StackMetadata stackMetadata, int cellIndex) { MethodVisitor methodVisitor = functionMetadata.methodVisitor; // Deleting is implemented as setting the value to null loadCell(functionMetadata, stackMetadata, cellIndex); methodVisitor.visitInsn(Opcodes.ACONST_NULL); methodVisitor.visitFieldInsn(Opcodes.PUTFIELD, Type.getInternalName(PythonCell.class), "cellValue", Type.getDescriptor(PythonLikeObject.class)); } }
0
java-sources/ai/timefold/solver/jpyinterpreter/1.24.0/ai/timefold/jpyinterpreter
java-sources/ai/timefold/solver/jpyinterpreter/1.24.0/ai/timefold/jpyinterpreter/opcodes/AbstractOpcode.java
package ai.timefold.jpyinterpreter.opcodes; import java.util.HashMap; import java.util.List; import java.util.Map; import ai.timefold.jpyinterpreter.FunctionMetadata; import ai.timefold.jpyinterpreter.PythonBytecodeInstruction; import ai.timefold.jpyinterpreter.StackMetadata; import ai.timefold.jpyinterpreter.opcodes.descriptor.OpcodeDescriptor; public abstract class AbstractOpcode implements Opcode { protected PythonBytecodeInstruction instruction; private static final Map<String, OpcodeDescriptor> opcodeNameToInstructionMap = getOpcodeNameToInstructionMap(); private static Map<String, OpcodeDescriptor> getOpcodeNameToInstructionMap() { Map<String, OpcodeDescriptor> out = new HashMap<>(); for (Class<?> subclass : OpcodeDescriptor.class.getPermittedSubclasses()) { if (!subclass.isEnum()) { throw new IllegalStateException("%s is a subclass of %s and is not an enum." .formatted(subclass, OpcodeDescriptor.class.getSimpleName())); } @SuppressWarnings("unchecked") Class<? extends Enum<?>> enumSubclass = (Class<? extends Enum<?>>) subclass; for (Enum<?> constant : enumSubclass.getEnumConstants()) { String name = constant.name(); if (out.containsKey(name)) { throw new IllegalStateException("Duplicate identifier %s present in both %s and %s." .formatted(name, out.get(name).getClass(), enumSubclass)); } out.put(name, (OpcodeDescriptor) constant); } } return out; } public AbstractOpcode(PythonBytecodeInstruction instruction) { this.instruction = instruction; } public PythonBytecodeInstruction getInstruction() { return instruction; } @Override public int getBytecodeIndex() { return instruction.offset(); } @Override public boolean isJumpTarget() { return instruction.isJumpTarget(); } @Override public List<StackMetadata> getStackMetadataAfterInstructionForBranches(FunctionMetadata functionMetadata, StackMetadata stackMetadata) { return List.of(getStackMetadataAfterInstruction(functionMetadata, stackMetadata)); } protected abstract StackMetadata getStackMetadataAfterInstruction(FunctionMetadata functionMetadata, StackMetadata stackMetadata); public static OpcodeDescriptor lookupInstruction(String name) { OpcodeDescriptor out = opcodeNameToInstructionMap.get(name); if (out == null) { throw new IllegalArgumentException("Invalid opcode identifier %s.".formatted(name)); } return out; } @Override public String toString() { return instruction.toString(); } }
0
java-sources/ai/timefold/solver/jpyinterpreter/1.24.0/ai/timefold/jpyinterpreter
java-sources/ai/timefold/solver/jpyinterpreter/1.24.0/ai/timefold/jpyinterpreter/opcodes/Opcode.java
package ai.timefold.jpyinterpreter.opcodes; import java.util.List; import ai.timefold.jpyinterpreter.FunctionMetadata; import ai.timefold.jpyinterpreter.PythonBytecodeInstruction; import ai.timefold.jpyinterpreter.PythonVersion; import ai.timefold.jpyinterpreter.StackMetadata; public interface Opcode { /** * Return the bytecode index of the instruction, which can be used * to identify the instruction as the target of a jump. * * @return The bytecode index of the instruction, which is defined * as the number of instructions before it in the instruction * listing. */ int getBytecodeIndex(); /** * Return the possible next bytecode index after this instruction is executed. * The default simply return [getBytecodeIndex() + 1], but is * typically overwritten in jump instructions. * * @return the possible next bytecode index after this instruction is executed */ default List<Integer> getPossibleNextBytecodeIndexList() { return List.of(getBytecodeIndex() + 1); } /** * Return a list of {@link StackMetadata} corresponding to each branch returned by * {@link #getPossibleNextBytecodeIndexList()}. * * @param functionMetadata Metadata about the function being compiled. * @param stackMetadata the StackMetadata just before this instruction is executed. * @return a new List, the same size as {@link #getPossibleNextBytecodeIndexList()}, * containing the StackMetadata after this instruction is executed for the given branch * in {@link #getPossibleNextBytecodeIndexList()}. */ List<StackMetadata> getStackMetadataAfterInstructionForBranches(FunctionMetadata functionMetadata, StackMetadata stackMetadata); /** * Implements the opcode. * * @param functionMetadata Metadata about the function being compiled. * @param stackMetadata Metadata about the state of the stack when this instruction is executed. */ void implement(FunctionMetadata functionMetadata, StackMetadata stackMetadata); /** * @return true if this opcode the target of a jump */ boolean isJumpTarget(); /** * @return true if this opcode is a forced jump (i.e. goto) */ default boolean isForcedJump() { return false; } static Opcode lookupOpcodeForInstruction(PythonBytecodeInstruction instruction, PythonVersion pythonVersion) { return AbstractOpcode.lookupInstruction(instruction.opname()) .getVersionMapping() .getOpcodeForVersion(instruction, pythonVersion); } }
0
java-sources/ai/timefold/solver/jpyinterpreter/1.24.0/ai/timefold/jpyinterpreter
java-sources/ai/timefold/solver/jpyinterpreter/1.24.0/ai/timefold/jpyinterpreter/opcodes/OpcodeWithoutSource.java
package ai.timefold.jpyinterpreter.opcodes; import java.util.List; import ai.timefold.jpyinterpreter.FunctionMetadata; import ai.timefold.jpyinterpreter.StackMetadata; public class OpcodeWithoutSource implements Opcode { @Override public int getBytecodeIndex() { throw new UnsupportedOperationException(); } @Override public List<StackMetadata> getStackMetadataAfterInstructionForBranches(FunctionMetadata functionMetadata, StackMetadata stackMetadata) { throw new UnsupportedOperationException(); } @Override public void implement(FunctionMetadata functionMetadata, StackMetadata stackMetadata) { throw new UnsupportedOperationException(); } @Override public boolean isJumpTarget() { throw new UnsupportedOperationException(); } @Override public boolean equals(Object other) { if (other == null) { return false; } return other.getClass() == getClass(); } @Override public int hashCode() { return getClass().hashCode(); } }
0
java-sources/ai/timefold/solver/jpyinterpreter/1.24.0/ai/timefold/jpyinterpreter
java-sources/ai/timefold/solver/jpyinterpreter/1.24.0/ai/timefold/jpyinterpreter/opcodes/SelfOpcodeWithoutSource.java
package ai.timefold.jpyinterpreter.opcodes; import java.util.List; import ai.timefold.jpyinterpreter.FunctionMetadata; import ai.timefold.jpyinterpreter.StackMetadata; public class SelfOpcodeWithoutSource implements Opcode { @Override public int getBytecodeIndex() { throw new UnsupportedOperationException(); } @Override public List<StackMetadata> getStackMetadataAfterInstructionForBranches(FunctionMetadata functionMetadata, StackMetadata stackMetadata) { throw new UnsupportedOperationException(); } @Override public void implement(FunctionMetadata functionMetadata, StackMetadata stackMetadata) { throw new UnsupportedOperationException(); } @Override public boolean isJumpTarget() { throw new UnsupportedOperationException(); } }
0
java-sources/ai/timefold/solver/jpyinterpreter/1.24.0/ai/timefold/jpyinterpreter/opcodes
java-sources/ai/timefold/solver/jpyinterpreter/1.24.0/ai/timefold/jpyinterpreter/opcodes/collection/BuildConstantKeyMapOpcode.java
package ai.timefold.jpyinterpreter.opcodes.collection; import ai.timefold.jpyinterpreter.FunctionMetadata; import ai.timefold.jpyinterpreter.PythonBytecodeInstruction; import ai.timefold.jpyinterpreter.StackMetadata; import ai.timefold.jpyinterpreter.ValueSourceInfo; import ai.timefold.jpyinterpreter.implementors.CollectionImplementor; import ai.timefold.jpyinterpreter.opcodes.AbstractOpcode; import ai.timefold.jpyinterpreter.types.BuiltinTypes; import ai.timefold.jpyinterpreter.types.collections.PythonLikeDict; public class BuildConstantKeyMapOpcode extends AbstractOpcode { public BuildConstantKeyMapOpcode(PythonBytecodeInstruction instruction) { super(instruction); } @Override protected StackMetadata getStackMetadataAfterInstruction(FunctionMetadata functionMetadata, StackMetadata stackMetadata) { return stackMetadata.pop(instruction.arg() + 1).push(ValueSourceInfo.of(this, BuiltinTypes.DICT_TYPE, stackMetadata.getValueSourcesUpToStackIndex(instruction.arg() + 1))); } @Override public void implement(FunctionMetadata functionMetadata, StackMetadata stackMetadata) { CollectionImplementor.buildConstKeysMap(PythonLikeDict.class, functionMetadata.methodVisitor, instruction.arg()); } }
0
java-sources/ai/timefold/solver/jpyinterpreter/1.24.0/ai/timefold/jpyinterpreter/opcodes
java-sources/ai/timefold/solver/jpyinterpreter/1.24.0/ai/timefold/jpyinterpreter/opcodes/collection/BuildListOpcode.java
package ai.timefold.jpyinterpreter.opcodes.collection; import ai.timefold.jpyinterpreter.FunctionMetadata; import ai.timefold.jpyinterpreter.PythonBytecodeInstruction; import ai.timefold.jpyinterpreter.StackMetadata; import ai.timefold.jpyinterpreter.ValueSourceInfo; import ai.timefold.jpyinterpreter.implementors.CollectionImplementor; import ai.timefold.jpyinterpreter.opcodes.AbstractOpcode; import ai.timefold.jpyinterpreter.types.BuiltinTypes; import ai.timefold.jpyinterpreter.types.collections.PythonLikeList; public class BuildListOpcode extends AbstractOpcode { public BuildListOpcode(PythonBytecodeInstruction instruction) { super(instruction); } @Override protected StackMetadata getStackMetadataAfterInstruction(FunctionMetadata functionMetadata, StackMetadata stackMetadata) { return stackMetadata.pop(instruction.arg()).push(ValueSourceInfo.of(this, BuiltinTypes.LIST_TYPE, stackMetadata.getValueSourcesUpToStackIndex(instruction.arg()))); } @Override public void implement(FunctionMetadata functionMetadata, StackMetadata stackMetadata) { CollectionImplementor.buildCollection(PythonLikeList.class, functionMetadata.methodVisitor, instruction.arg()); } }
0
java-sources/ai/timefold/solver/jpyinterpreter/1.24.0/ai/timefold/jpyinterpreter/opcodes
java-sources/ai/timefold/solver/jpyinterpreter/1.24.0/ai/timefold/jpyinterpreter/opcodes/collection/BuildMapOpcode.java
package ai.timefold.jpyinterpreter.opcodes.collection; import ai.timefold.jpyinterpreter.FunctionMetadata; import ai.timefold.jpyinterpreter.PythonBytecodeInstruction; import ai.timefold.jpyinterpreter.StackMetadata; import ai.timefold.jpyinterpreter.ValueSourceInfo; import ai.timefold.jpyinterpreter.implementors.CollectionImplementor; import ai.timefold.jpyinterpreter.opcodes.AbstractOpcode; import ai.timefold.jpyinterpreter.types.BuiltinTypes; import ai.timefold.jpyinterpreter.types.collections.PythonLikeDict; public class BuildMapOpcode extends AbstractOpcode { public BuildMapOpcode(PythonBytecodeInstruction instruction) { super(instruction); } @Override protected StackMetadata getStackMetadataAfterInstruction(FunctionMetadata functionMetadata, StackMetadata stackMetadata) { return stackMetadata.pop(2 * instruction.arg()).push(ValueSourceInfo.of(this, BuiltinTypes.DICT_TYPE, stackMetadata.getValueSourcesUpToStackIndex(2 * instruction.arg()))); } @Override public void implement(FunctionMetadata functionMetadata, StackMetadata stackMetadata) { CollectionImplementor.buildMap(PythonLikeDict.class, functionMetadata.methodVisitor, instruction.arg()); } }
0
java-sources/ai/timefold/solver/jpyinterpreter/1.24.0/ai/timefold/jpyinterpreter/opcodes
java-sources/ai/timefold/solver/jpyinterpreter/1.24.0/ai/timefold/jpyinterpreter/opcodes/collection/BuildSetOpcode.java
package ai.timefold.jpyinterpreter.opcodes.collection; import ai.timefold.jpyinterpreter.FunctionMetadata; import ai.timefold.jpyinterpreter.PythonBytecodeInstruction; import ai.timefold.jpyinterpreter.StackMetadata; import ai.timefold.jpyinterpreter.ValueSourceInfo; import ai.timefold.jpyinterpreter.implementors.CollectionImplementor; import ai.timefold.jpyinterpreter.opcodes.AbstractOpcode; import ai.timefold.jpyinterpreter.types.BuiltinTypes; import ai.timefold.jpyinterpreter.types.collections.PythonLikeSet; public class BuildSetOpcode extends AbstractOpcode { public BuildSetOpcode(PythonBytecodeInstruction instruction) { super(instruction); } @Override protected StackMetadata getStackMetadataAfterInstruction(FunctionMetadata functionMetadata, StackMetadata stackMetadata) { return stackMetadata.pop(instruction.arg()).push(ValueSourceInfo.of(this, BuiltinTypes.SET_TYPE, stackMetadata.getValueSourcesUpToStackIndex(instruction.arg()))); } @Override public void implement(FunctionMetadata functionMetadata, StackMetadata stackMetadata) { // TODO: either modify reverseAdd for PythonLikeSet so it replaces already encountered elements // or store the top count items in local variables and do it in forward order. CollectionImplementor.buildCollection(PythonLikeSet.class, functionMetadata.methodVisitor, instruction.arg()); } }
0
java-sources/ai/timefold/solver/jpyinterpreter/1.24.0/ai/timefold/jpyinterpreter/opcodes
java-sources/ai/timefold/solver/jpyinterpreter/1.24.0/ai/timefold/jpyinterpreter/opcodes/collection/BuildSliceOpcode.java
package ai.timefold.jpyinterpreter.opcodes.collection; import ai.timefold.jpyinterpreter.FunctionMetadata; import ai.timefold.jpyinterpreter.PythonBytecodeInstruction; import ai.timefold.jpyinterpreter.StackMetadata; import ai.timefold.jpyinterpreter.ValueSourceInfo; import ai.timefold.jpyinterpreter.implementors.CollectionImplementor; import ai.timefold.jpyinterpreter.opcodes.AbstractOpcode; import ai.timefold.jpyinterpreter.types.PythonSlice; public class BuildSliceOpcode extends AbstractOpcode { public BuildSliceOpcode(PythonBytecodeInstruction instruction) { super(instruction); } @Override protected StackMetadata getStackMetadataAfterInstruction(FunctionMetadata functionMetadata, StackMetadata stackMetadata) { return stackMetadata.pop(instruction.arg()).push(ValueSourceInfo.of(this, PythonSlice.SLICE_TYPE, stackMetadata.getValueSourcesUpToStackIndex(instruction.arg()))); } @Override public void implement(FunctionMetadata functionMetadata, StackMetadata stackMetadata) { CollectionImplementor.buildSlice(functionMetadata, stackMetadata, instruction.arg()); } }
0
java-sources/ai/timefold/solver/jpyinterpreter/1.24.0/ai/timefold/jpyinterpreter/opcodes
java-sources/ai/timefold/solver/jpyinterpreter/1.24.0/ai/timefold/jpyinterpreter/opcodes/collection/BuildTupleOpcode.java
package ai.timefold.jpyinterpreter.opcodes.collection; import ai.timefold.jpyinterpreter.FunctionMetadata; import ai.timefold.jpyinterpreter.PythonBytecodeInstruction; import ai.timefold.jpyinterpreter.StackMetadata; import ai.timefold.jpyinterpreter.ValueSourceInfo; import ai.timefold.jpyinterpreter.implementors.CollectionImplementor; import ai.timefold.jpyinterpreter.opcodes.AbstractOpcode; import ai.timefold.jpyinterpreter.types.BuiltinTypes; import ai.timefold.jpyinterpreter.types.collections.PythonLikeTuple; public class BuildTupleOpcode extends AbstractOpcode { public BuildTupleOpcode(PythonBytecodeInstruction instruction) { super(instruction); } @Override protected StackMetadata getStackMetadataAfterInstruction(FunctionMetadata functionMetadata, StackMetadata stackMetadata) { return stackMetadata.pop(instruction.arg()).push(ValueSourceInfo.of(this, BuiltinTypes.TUPLE_TYPE, stackMetadata.getValueSourcesUpToStackIndex(instruction.arg()))); } @Override public void implement(FunctionMetadata functionMetadata, StackMetadata stackMetadata) { CollectionImplementor.buildCollection(PythonLikeTuple.class, functionMetadata.methodVisitor, instruction.arg()); } }
0
java-sources/ai/timefold/solver/jpyinterpreter/1.24.0/ai/timefold/jpyinterpreter/opcodes
java-sources/ai/timefold/solver/jpyinterpreter/1.24.0/ai/timefold/jpyinterpreter/opcodes/collection/CollectionAddAllOpcode.java
package ai.timefold.jpyinterpreter.opcodes.collection; import ai.timefold.jpyinterpreter.FunctionMetadata; import ai.timefold.jpyinterpreter.PythonBytecodeInstruction; import ai.timefold.jpyinterpreter.StackMetadata; import ai.timefold.jpyinterpreter.implementors.CollectionImplementor; import ai.timefold.jpyinterpreter.opcodes.AbstractOpcode; public class CollectionAddAllOpcode extends AbstractOpcode { public CollectionAddAllOpcode(PythonBytecodeInstruction instruction) { super(instruction); } @Override protected StackMetadata getStackMetadataAfterInstruction(FunctionMetadata functionMetadata, StackMetadata stackMetadata) { return stackMetadata.pop(); } @Override public void implement(FunctionMetadata functionMetadata, StackMetadata stackMetadata) { CollectionImplementor.collectionAddAll(functionMetadata, stackMetadata, instruction); } }
0
java-sources/ai/timefold/solver/jpyinterpreter/1.24.0/ai/timefold/jpyinterpreter/opcodes
java-sources/ai/timefold/solver/jpyinterpreter/1.24.0/ai/timefold/jpyinterpreter/opcodes/collection/CollectionAddOpcode.java
package ai.timefold.jpyinterpreter.opcodes.collection; import ai.timefold.jpyinterpreter.FunctionMetadata; import ai.timefold.jpyinterpreter.PythonBytecodeInstruction; import ai.timefold.jpyinterpreter.StackMetadata; import ai.timefold.jpyinterpreter.implementors.CollectionImplementor; import ai.timefold.jpyinterpreter.opcodes.AbstractOpcode; public class CollectionAddOpcode extends AbstractOpcode { public CollectionAddOpcode(PythonBytecodeInstruction instruction) { super(instruction); } @Override protected StackMetadata getStackMetadataAfterInstruction(FunctionMetadata functionMetadata, StackMetadata stackMetadata) { return stackMetadata.pop(); } @Override public void implement(FunctionMetadata functionMetadata, StackMetadata stackMetadata) { CollectionImplementor.collectionAdd(functionMetadata, stackMetadata, instruction); } }
0
java-sources/ai/timefold/solver/jpyinterpreter/1.24.0/ai/timefold/jpyinterpreter/opcodes
java-sources/ai/timefold/solver/jpyinterpreter/1.24.0/ai/timefold/jpyinterpreter/opcodes/collection/ContainsOpcode.java
package ai.timefold.jpyinterpreter.opcodes.collection; import ai.timefold.jpyinterpreter.FunctionMetadata; import ai.timefold.jpyinterpreter.PythonBytecodeInstruction; import ai.timefold.jpyinterpreter.StackMetadata; import ai.timefold.jpyinterpreter.ValueSourceInfo; import ai.timefold.jpyinterpreter.implementors.CollectionImplementor; import ai.timefold.jpyinterpreter.opcodes.AbstractOpcode; import ai.timefold.jpyinterpreter.types.BuiltinTypes; public class ContainsOpcode extends AbstractOpcode { public ContainsOpcode(PythonBytecodeInstruction instruction) { super(instruction); } @Override protected StackMetadata getStackMetadataAfterInstruction(FunctionMetadata functionMetadata, StackMetadata stackMetadata) { return stackMetadata.pop(2).push(ValueSourceInfo.of(this, BuiltinTypes.BOOLEAN_TYPE, stackMetadata.getValueSourcesUpToStackIndex(2))); } @Override public void implement(FunctionMetadata functionMetadata, StackMetadata stackMetadata) { CollectionImplementor.containsOperator(functionMetadata.methodVisitor, stackMetadata, instruction); } }
0
java-sources/ai/timefold/solver/jpyinterpreter/1.24.0/ai/timefold/jpyinterpreter/opcodes
java-sources/ai/timefold/solver/jpyinterpreter/1.24.0/ai/timefold/jpyinterpreter/opcodes/collection/DeleteItemOpcode.java
package ai.timefold.jpyinterpreter.opcodes.collection; import ai.timefold.jpyinterpreter.FunctionMetadata; import ai.timefold.jpyinterpreter.PythonBinaryOperator; import ai.timefold.jpyinterpreter.PythonBytecodeInstruction; import ai.timefold.jpyinterpreter.StackMetadata; import ai.timefold.jpyinterpreter.implementors.DunderOperatorImplementor; import ai.timefold.jpyinterpreter.opcodes.AbstractOpcode; import org.objectweb.asm.Opcodes; public class DeleteItemOpcode extends AbstractOpcode { public DeleteItemOpcode(PythonBytecodeInstruction instruction) { super(instruction); } @Override protected StackMetadata getStackMetadataAfterInstruction(FunctionMetadata functionMetadata, StackMetadata stackMetadata) { return stackMetadata.pop(2); } @Override public void implement(FunctionMetadata functionMetadata, StackMetadata stackMetadata) { DunderOperatorImplementor.binaryOperator(functionMetadata.methodVisitor, stackMetadata, PythonBinaryOperator.DELETE_ITEM); functionMetadata.methodVisitor.visitInsn(Opcodes.POP); // DELETE_ITEM ignore results of delete function } }
0
java-sources/ai/timefold/solver/jpyinterpreter/1.24.0/ai/timefold/jpyinterpreter/opcodes
java-sources/ai/timefold/solver/jpyinterpreter/1.24.0/ai/timefold/jpyinterpreter/opcodes/collection/GetIterOpcode.java
package ai.timefold.jpyinterpreter.opcodes.collection; import ai.timefold.jpyinterpreter.FunctionMetadata; import ai.timefold.jpyinterpreter.PythonBytecodeInstruction; import ai.timefold.jpyinterpreter.PythonUnaryOperator; import ai.timefold.jpyinterpreter.StackMetadata; import ai.timefold.jpyinterpreter.ValueSourceInfo; import ai.timefold.jpyinterpreter.implementors.DunderOperatorImplementor; import ai.timefold.jpyinterpreter.opcodes.AbstractOpcode; import ai.timefold.jpyinterpreter.types.BuiltinTypes; public class GetIterOpcode extends AbstractOpcode { public GetIterOpcode(PythonBytecodeInstruction instruction) { super(instruction); } @Override protected StackMetadata getStackMetadataAfterInstruction(FunctionMetadata functionMetadata, StackMetadata stackMetadata) { return stackMetadata.pop().push(ValueSourceInfo.of(this, BuiltinTypes.ITERATOR_TYPE, stackMetadata.getValueSourcesUpToStackIndex(1))); } @Override public void implement(FunctionMetadata functionMetadata, StackMetadata stackMetadata) { DunderOperatorImplementor.unaryOperator(functionMetadata.methodVisitor, PythonUnaryOperator.ITERATOR); } }
0
java-sources/ai/timefold/solver/jpyinterpreter/1.24.0/ai/timefold/jpyinterpreter/opcodes
java-sources/ai/timefold/solver/jpyinterpreter/1.24.0/ai/timefold/jpyinterpreter/opcodes/collection/ListToTupleOpcode.java
package ai.timefold.jpyinterpreter.opcodes.collection; import ai.timefold.jpyinterpreter.FunctionMetadata; import ai.timefold.jpyinterpreter.PythonBytecodeInstruction; import ai.timefold.jpyinterpreter.StackMetadata; import ai.timefold.jpyinterpreter.ValueSourceInfo; import ai.timefold.jpyinterpreter.implementors.CollectionImplementor; import ai.timefold.jpyinterpreter.opcodes.AbstractOpcode; import ai.timefold.jpyinterpreter.types.BuiltinTypes; public class ListToTupleOpcode extends AbstractOpcode { public ListToTupleOpcode(PythonBytecodeInstruction instruction) { super(instruction); } @Override protected StackMetadata getStackMetadataAfterInstruction(FunctionMetadata functionMetadata, StackMetadata stackMetadata) { return stackMetadata.pop().push(ValueSourceInfo.of(this, BuiltinTypes.LIST_TYPE, stackMetadata.getValueSourcesUpToStackIndex(1))); } @Override public void implement(FunctionMetadata functionMetadata, StackMetadata stackMetadata) { CollectionImplementor.convertListToTuple(functionMetadata.methodVisitor); } }
0
java-sources/ai/timefold/solver/jpyinterpreter/1.24.0/ai/timefold/jpyinterpreter/opcodes
java-sources/ai/timefold/solver/jpyinterpreter/1.24.0/ai/timefold/jpyinterpreter/opcodes/collection/MapMergeOpcode.java
package ai.timefold.jpyinterpreter.opcodes.collection; import ai.timefold.jpyinterpreter.FunctionMetadata; import ai.timefold.jpyinterpreter.PythonBytecodeInstruction; import ai.timefold.jpyinterpreter.StackMetadata; import ai.timefold.jpyinterpreter.implementors.CollectionImplementor; import ai.timefold.jpyinterpreter.opcodes.AbstractOpcode; public class MapMergeOpcode extends AbstractOpcode { public MapMergeOpcode(PythonBytecodeInstruction instruction) { super(instruction); } @Override protected StackMetadata getStackMetadataAfterInstruction(FunctionMetadata functionMetadata, StackMetadata stackMetadata) { return stackMetadata.pop(); } @Override public void implement(FunctionMetadata functionMetadata, StackMetadata stackMetadata) { CollectionImplementor.mapPutAllOnlyIfAllNewElseThrow(functionMetadata, stackMetadata, instruction); } }
0
java-sources/ai/timefold/solver/jpyinterpreter/1.24.0/ai/timefold/jpyinterpreter/opcodes
java-sources/ai/timefold/solver/jpyinterpreter/1.24.0/ai/timefold/jpyinterpreter/opcodes/collection/MapPutAllOpcode.java
package ai.timefold.jpyinterpreter.opcodes.collection; import ai.timefold.jpyinterpreter.FunctionMetadata; import ai.timefold.jpyinterpreter.PythonBytecodeInstruction; import ai.timefold.jpyinterpreter.StackMetadata; import ai.timefold.jpyinterpreter.implementors.CollectionImplementor; import ai.timefold.jpyinterpreter.opcodes.AbstractOpcode; public class MapPutAllOpcode extends AbstractOpcode { public MapPutAllOpcode(PythonBytecodeInstruction instruction) { super(instruction); } @Override protected StackMetadata getStackMetadataAfterInstruction(FunctionMetadata functionMetadata, StackMetadata stackMetadata) { return stackMetadata.pop(); } @Override public void implement(FunctionMetadata functionMetadata, StackMetadata stackMetadata) { CollectionImplementor.mapPutAllOnlyIfAllNewElseThrow(functionMetadata, stackMetadata, instruction); } }
0
java-sources/ai/timefold/solver/jpyinterpreter/1.24.0/ai/timefold/jpyinterpreter/opcodes
java-sources/ai/timefold/solver/jpyinterpreter/1.24.0/ai/timefold/jpyinterpreter/opcodes/collection/MapPutOpcode.java
package ai.timefold.jpyinterpreter.opcodes.collection; import ai.timefold.jpyinterpreter.FunctionMetadata; import ai.timefold.jpyinterpreter.PythonBytecodeInstruction; import ai.timefold.jpyinterpreter.StackMetadata; import ai.timefold.jpyinterpreter.implementors.CollectionImplementor; import ai.timefold.jpyinterpreter.opcodes.AbstractOpcode; public class MapPutOpcode extends AbstractOpcode { public MapPutOpcode(PythonBytecodeInstruction instruction) { super(instruction); } @Override protected StackMetadata getStackMetadataAfterInstruction(FunctionMetadata functionMetadata, StackMetadata stackMetadata) { return stackMetadata.pop(2); } @Override public void implement(FunctionMetadata functionMetadata, StackMetadata stackMetadata) { CollectionImplementor.mapPut(functionMetadata, stackMetadata, instruction); } }
0
java-sources/ai/timefold/solver/jpyinterpreter/1.24.0/ai/timefold/jpyinterpreter/opcodes
java-sources/ai/timefold/solver/jpyinterpreter/1.24.0/ai/timefold/jpyinterpreter/opcodes/collection/SetItemOpcode.java
package ai.timefold.jpyinterpreter.opcodes.collection; import ai.timefold.jpyinterpreter.FunctionMetadata; import ai.timefold.jpyinterpreter.PythonBytecodeInstruction; import ai.timefold.jpyinterpreter.StackMetadata; import ai.timefold.jpyinterpreter.implementors.CollectionImplementor; import ai.timefold.jpyinterpreter.opcodes.AbstractOpcode; public class SetItemOpcode extends AbstractOpcode { public SetItemOpcode(PythonBytecodeInstruction instruction) { super(instruction); } @Override protected StackMetadata getStackMetadataAfterInstruction(FunctionMetadata functionMetadata, StackMetadata stackMetadata) { return stackMetadata.pop(3); } @Override public void implement(FunctionMetadata functionMetadata, StackMetadata stackMetadata) { CollectionImplementor.setItem(functionMetadata, stackMetadata); } }
0
java-sources/ai/timefold/solver/jpyinterpreter/1.24.0/ai/timefold/jpyinterpreter/opcodes
java-sources/ai/timefold/solver/jpyinterpreter/1.24.0/ai/timefold/jpyinterpreter/opcodes/collection/UnpackSequenceOpcode.java
package ai.timefold.jpyinterpreter.opcodes.collection; import ai.timefold.jpyinterpreter.FunctionMetadata; import ai.timefold.jpyinterpreter.PythonBytecodeInstruction; import ai.timefold.jpyinterpreter.StackMetadata; import ai.timefold.jpyinterpreter.ValueSourceInfo; import ai.timefold.jpyinterpreter.implementors.CollectionImplementor; import ai.timefold.jpyinterpreter.opcodes.AbstractOpcode; import ai.timefold.jpyinterpreter.types.BuiltinTypes; public class UnpackSequenceOpcode extends AbstractOpcode { public UnpackSequenceOpcode(PythonBytecodeInstruction instruction) { super(instruction); } @Override protected StackMetadata getStackMetadataAfterInstruction(FunctionMetadata functionMetadata, StackMetadata stackMetadata) { StackMetadata newStackMetadata = stackMetadata.pop(); for (int i = 0; i < instruction.arg(); i++) { newStackMetadata = newStackMetadata.push(ValueSourceInfo.of(this, BuiltinTypes.BASE_TYPE, stackMetadata.getValueSourcesUpToStackIndex(1))); } return newStackMetadata; } @Override public void implement(FunctionMetadata functionMetadata, StackMetadata stackMetadata) { CollectionImplementor.unpackSequence(functionMetadata.methodVisitor, instruction.arg(), stackMetadata.localVariableHelper); } }
0
java-sources/ai/timefold/solver/jpyinterpreter/1.24.0/ai/timefold/jpyinterpreter/opcodes
java-sources/ai/timefold/solver/jpyinterpreter/1.24.0/ai/timefold/jpyinterpreter/opcodes/collection/UnpackSequenceWithTailOpcode.java
package ai.timefold.jpyinterpreter.opcodes.collection; import ai.timefold.jpyinterpreter.FunctionMetadata; import ai.timefold.jpyinterpreter.PythonBytecodeInstruction; import ai.timefold.jpyinterpreter.StackMetadata; import ai.timefold.jpyinterpreter.ValueSourceInfo; import ai.timefold.jpyinterpreter.implementors.CollectionImplementor; import ai.timefold.jpyinterpreter.opcodes.AbstractOpcode; import ai.timefold.jpyinterpreter.types.BuiltinTypes; public class UnpackSequenceWithTailOpcode extends AbstractOpcode { public UnpackSequenceWithTailOpcode(PythonBytecodeInstruction instruction) { super(instruction); } @Override protected StackMetadata getStackMetadataAfterInstruction(FunctionMetadata functionMetadata, StackMetadata stackMetadata) { // TODO: Correctly handle when high byte is set StackMetadata newStackMetadata = stackMetadata.pop(); newStackMetadata = newStackMetadata .push(ValueSourceInfo.of(this, BuiltinTypes.LIST_TYPE, stackMetadata.getValueSourcesUpToStackIndex(1))); for (int i = 0; i < instruction.arg(); i++) { newStackMetadata = newStackMetadata.push(ValueSourceInfo.of(this, BuiltinTypes.BASE_TYPE, stackMetadata.getValueSourcesUpToStackIndex(1))); } return newStackMetadata; } @Override public void implement(FunctionMetadata functionMetadata, StackMetadata stackMetadata) { CollectionImplementor.unpackSequenceWithTail(functionMetadata.methodVisitor, instruction.arg(), stackMetadata.localVariableHelper); } }
0
java-sources/ai/timefold/solver/jpyinterpreter/1.24.0/ai/timefold/jpyinterpreter/opcodes
java-sources/ai/timefold/solver/jpyinterpreter/1.24.0/ai/timefold/jpyinterpreter/opcodes/controlflow/AbstractControlFlowOpcode.java
package ai.timefold.jpyinterpreter.opcodes.controlflow; import ai.timefold.jpyinterpreter.PythonBytecodeInstruction; import ai.timefold.jpyinterpreter.opcodes.Opcode; public abstract class AbstractControlFlowOpcode implements Opcode { protected PythonBytecodeInstruction instruction; public AbstractControlFlowOpcode(PythonBytecodeInstruction instruction) { this.instruction = instruction; } @Override public boolean isJumpTarget() { return instruction.isJumpTarget(); } @Override public int getBytecodeIndex() { return instruction.offset(); } @Override public String toString() { return instruction.toString(); } }
0
java-sources/ai/timefold/solver/jpyinterpreter/1.24.0/ai/timefold/jpyinterpreter/opcodes
java-sources/ai/timefold/solver/jpyinterpreter/1.24.0/ai/timefold/jpyinterpreter/opcodes/controlflow/ForIterOpcode.java
package ai.timefold.jpyinterpreter.opcodes.controlflow; import java.util.List; import ai.timefold.jpyinterpreter.FunctionMetadata; import ai.timefold.jpyinterpreter.PythonBytecodeInstruction; import ai.timefold.jpyinterpreter.StackMetadata; import ai.timefold.jpyinterpreter.ValueSourceInfo; import ai.timefold.jpyinterpreter.implementors.CollectionImplementor; import ai.timefold.jpyinterpreter.types.BuiltinTypes; public class ForIterOpcode extends AbstractControlFlowOpcode { int jumpTarget; public ForIterOpcode(PythonBytecodeInstruction instruction, int jumpTarget) { super(instruction); this.jumpTarget = jumpTarget; } @Override public List<Integer> getPossibleNextBytecodeIndexList() { return List.of( getBytecodeIndex() + 1, jumpTarget); } @Override public List<StackMetadata> getStackMetadataAfterInstructionForBranches(FunctionMetadata functionMetadata, StackMetadata stackMetadata) { return List.of(stackMetadata.push(ValueSourceInfo.of(this, BuiltinTypes.BASE_TYPE, stackMetadata.getValueSourcesUpToStackIndex(1))), stackMetadata.pop()); } @Override public void implement(FunctionMetadata functionMetadata, StackMetadata stackMetadata) { CollectionImplementor.iterateIterator(functionMetadata.methodVisitor, jumpTarget, stackMetadata, functionMetadata); } }
0
java-sources/ai/timefold/solver/jpyinterpreter/1.24.0/ai/timefold/jpyinterpreter/opcodes
java-sources/ai/timefold/solver/jpyinterpreter/1.24.0/ai/timefold/jpyinterpreter/opcodes/controlflow/JumpAbsoluteOpcode.java
package ai.timefold.jpyinterpreter.opcodes.controlflow; import java.util.List; import ai.timefold.jpyinterpreter.FunctionMetadata; import ai.timefold.jpyinterpreter.PythonBytecodeInstruction; import ai.timefold.jpyinterpreter.StackMetadata; import ai.timefold.jpyinterpreter.implementors.JumpImplementor; public class JumpAbsoluteOpcode extends AbstractControlFlowOpcode { int jumpTarget; public JumpAbsoluteOpcode(PythonBytecodeInstruction instruction, int jumpTarget) { super(instruction); this.jumpTarget = jumpTarget; } @Override public List<Integer> getPossibleNextBytecodeIndexList() { return List.of(jumpTarget); } @Override public List<StackMetadata> getStackMetadataAfterInstructionForBranches(FunctionMetadata functionMetadata, StackMetadata stackMetadata) { return List.of(stackMetadata.copy()); } @Override public void implement(FunctionMetadata functionMetadata, StackMetadata stackMetadata) { JumpImplementor.jumpAbsolute(functionMetadata, stackMetadata, jumpTarget); } @Override public boolean isForcedJump() { return true; } }
0
java-sources/ai/timefold/solver/jpyinterpreter/1.24.0/ai/timefold/jpyinterpreter/opcodes
java-sources/ai/timefold/solver/jpyinterpreter/1.24.0/ai/timefold/jpyinterpreter/opcodes/controlflow/JumpIfFalseOrPopOpcode.java
package ai.timefold.jpyinterpreter.opcodes.controlflow; import java.util.List; import ai.timefold.jpyinterpreter.FunctionMetadata; import ai.timefold.jpyinterpreter.PythonBytecodeInstruction; import ai.timefold.jpyinterpreter.StackMetadata; import ai.timefold.jpyinterpreter.implementors.JumpImplementor; public class JumpIfFalseOrPopOpcode extends AbstractControlFlowOpcode { int jumpTarget; public JumpIfFalseOrPopOpcode(PythonBytecodeInstruction instruction, int jumpTarget) { super(instruction); this.jumpTarget = jumpTarget; } @Override public List<Integer> getPossibleNextBytecodeIndexList() { return List.of( getBytecodeIndex() + 1, jumpTarget); } @Override public List<StackMetadata> getStackMetadataAfterInstructionForBranches(FunctionMetadata functionMetadata, StackMetadata stackMetadata) { return List.of(stackMetadata.pop(), stackMetadata.copy()); } @Override public void implement(FunctionMetadata functionMetadata, StackMetadata stackMetadata) { JumpImplementor.jumpIfFalseElsePop(functionMetadata, stackMetadata, jumpTarget); } }
0
java-sources/ai/timefold/solver/jpyinterpreter/1.24.0/ai/timefold/jpyinterpreter/opcodes
java-sources/ai/timefold/solver/jpyinterpreter/1.24.0/ai/timefold/jpyinterpreter/opcodes/controlflow/JumpIfNotExcMatchOpcode.java
package ai.timefold.jpyinterpreter.opcodes.controlflow; import java.util.List; import ai.timefold.jpyinterpreter.FunctionMetadata; import ai.timefold.jpyinterpreter.PythonBytecodeInstruction; import ai.timefold.jpyinterpreter.StackMetadata; import ai.timefold.jpyinterpreter.implementors.JumpImplementor; public class JumpIfNotExcMatchOpcode extends AbstractControlFlowOpcode { int jumpTarget; public JumpIfNotExcMatchOpcode(PythonBytecodeInstruction instruction, int jumpTarget) { super(instruction); this.jumpTarget = jumpTarget; } @Override public List<Integer> getPossibleNextBytecodeIndexList() { return List.of( getBytecodeIndex() + 1, jumpTarget); } @Override public List<StackMetadata> getStackMetadataAfterInstructionForBranches(FunctionMetadata functionMetadata, StackMetadata stackMetadata) { return List.of(stackMetadata.pop(2), stackMetadata.pop(2)); } @Override public void implement(FunctionMetadata functionMetadata, StackMetadata stackMetadata) { JumpImplementor.popAndJumpIfExceptionDoesNotMatch(functionMetadata, stackMetadata, jumpTarget); } }
0
java-sources/ai/timefold/solver/jpyinterpreter/1.24.0/ai/timefold/jpyinterpreter/opcodes
java-sources/ai/timefold/solver/jpyinterpreter/1.24.0/ai/timefold/jpyinterpreter/opcodes/controlflow/JumpIfTrueOrPopOpcode.java
package ai.timefold.jpyinterpreter.opcodes.controlflow; import java.util.List; import ai.timefold.jpyinterpreter.FunctionMetadata; import ai.timefold.jpyinterpreter.PythonBytecodeInstruction; import ai.timefold.jpyinterpreter.StackMetadata; import ai.timefold.jpyinterpreter.implementors.JumpImplementor; public class JumpIfTrueOrPopOpcode extends AbstractControlFlowOpcode { int jumpTarget; public JumpIfTrueOrPopOpcode(PythonBytecodeInstruction instruction, int jumpTarget) { super(instruction); this.jumpTarget = jumpTarget; } @Override public List<Integer> getPossibleNextBytecodeIndexList() { return List.of( getBytecodeIndex() + 1, jumpTarget); } @Override public List<StackMetadata> getStackMetadataAfterInstructionForBranches(FunctionMetadata functionMetadata, StackMetadata stackMetadata) { return List.of(stackMetadata.pop(), stackMetadata.copy()); } @Override public void implement(FunctionMetadata functionMetadata, StackMetadata stackMetadata) { JumpImplementor.jumpIfTrueElsePop(functionMetadata, stackMetadata, jumpTarget); } }
0
java-sources/ai/timefold/solver/jpyinterpreter/1.24.0/ai/timefold/jpyinterpreter/opcodes
java-sources/ai/timefold/solver/jpyinterpreter/1.24.0/ai/timefold/jpyinterpreter/opcodes/controlflow/PopJumpIfFalseOpcode.java
package ai.timefold.jpyinterpreter.opcodes.controlflow; import java.util.List; import ai.timefold.jpyinterpreter.FunctionMetadata; import ai.timefold.jpyinterpreter.PythonBytecodeInstruction; import ai.timefold.jpyinterpreter.StackMetadata; import ai.timefold.jpyinterpreter.implementors.JumpImplementor; public class PopJumpIfFalseOpcode extends AbstractControlFlowOpcode { int jumpTarget; public PopJumpIfFalseOpcode(PythonBytecodeInstruction instruction, int jumpTarget) { super(instruction); this.jumpTarget = jumpTarget; } @Override public List<Integer> getPossibleNextBytecodeIndexList() { return List.of( getBytecodeIndex() + 1, jumpTarget); } @Override public List<StackMetadata> getStackMetadataAfterInstructionForBranches(FunctionMetadata functionMetadata, StackMetadata stackMetadata) { return List.of(stackMetadata.pop(), stackMetadata.pop()); } @Override public void implement(FunctionMetadata functionMetadata, StackMetadata stackMetadata) { JumpImplementor.popAndJumpIfFalse(functionMetadata, stackMetadata, jumpTarget); } }
0
java-sources/ai/timefold/solver/jpyinterpreter/1.24.0/ai/timefold/jpyinterpreter/opcodes
java-sources/ai/timefold/solver/jpyinterpreter/1.24.0/ai/timefold/jpyinterpreter/opcodes/controlflow/PopJumpIfIsNoneOpcode.java
package ai.timefold.jpyinterpreter.opcodes.controlflow; import java.util.List; import ai.timefold.jpyinterpreter.FunctionMetadata; import ai.timefold.jpyinterpreter.PythonBytecodeInstruction; import ai.timefold.jpyinterpreter.StackMetadata; import ai.timefold.jpyinterpreter.implementors.JumpImplementor; public class PopJumpIfIsNoneOpcode extends AbstractControlFlowOpcode { int jumpTarget; public PopJumpIfIsNoneOpcode(PythonBytecodeInstruction instruction, int jumpTarget) { super(instruction); this.jumpTarget = jumpTarget; } @Override public List<Integer> getPossibleNextBytecodeIndexList() { return List.of( getBytecodeIndex() + 1, jumpTarget); } @Override public List<StackMetadata> getStackMetadataAfterInstructionForBranches(FunctionMetadata functionMetadata, StackMetadata stackMetadata) { return List.of(stackMetadata.pop(), stackMetadata.pop()); } @Override public void implement(FunctionMetadata functionMetadata, StackMetadata stackMetadata) { JumpImplementor.popAndJumpIfIsNone(functionMetadata, stackMetadata, jumpTarget); } }
0
java-sources/ai/timefold/solver/jpyinterpreter/1.24.0/ai/timefold/jpyinterpreter/opcodes
java-sources/ai/timefold/solver/jpyinterpreter/1.24.0/ai/timefold/jpyinterpreter/opcodes/controlflow/PopJumpIfIsNotNoneOpcode.java
package ai.timefold.jpyinterpreter.opcodes.controlflow; import java.util.List; import ai.timefold.jpyinterpreter.FunctionMetadata; import ai.timefold.jpyinterpreter.PythonBytecodeInstruction; import ai.timefold.jpyinterpreter.StackMetadata; import ai.timefold.jpyinterpreter.implementors.JumpImplementor; public class PopJumpIfIsNotNoneOpcode extends AbstractControlFlowOpcode { int jumpTarget; public PopJumpIfIsNotNoneOpcode(PythonBytecodeInstruction instruction, int jumpTarget) { super(instruction); this.jumpTarget = jumpTarget; } @Override public List<Integer> getPossibleNextBytecodeIndexList() { return List.of( getBytecodeIndex() + 1, jumpTarget); } @Override public List<StackMetadata> getStackMetadataAfterInstructionForBranches(FunctionMetadata functionMetadata, StackMetadata stackMetadata) { return List.of(stackMetadata.pop(), stackMetadata.pop()); } @Override public void implement(FunctionMetadata functionMetadata, StackMetadata stackMetadata) { JumpImplementor.popAndJumpIfIsNotNone(functionMetadata, stackMetadata, jumpTarget); } }
0
java-sources/ai/timefold/solver/jpyinterpreter/1.24.0/ai/timefold/jpyinterpreter/opcodes
java-sources/ai/timefold/solver/jpyinterpreter/1.24.0/ai/timefold/jpyinterpreter/opcodes/controlflow/PopJumpIfTrueOpcode.java
package ai.timefold.jpyinterpreter.opcodes.controlflow; import java.util.List; import ai.timefold.jpyinterpreter.FunctionMetadata; import ai.timefold.jpyinterpreter.PythonBytecodeInstruction; import ai.timefold.jpyinterpreter.StackMetadata; import ai.timefold.jpyinterpreter.implementors.JumpImplementor; public class PopJumpIfTrueOpcode extends AbstractControlFlowOpcode { int jumpTarget; public PopJumpIfTrueOpcode(PythonBytecodeInstruction instruction, int jumpTarget) { super(instruction); this.jumpTarget = jumpTarget; } @Override public List<Integer> getPossibleNextBytecodeIndexList() { return List.of( getBytecodeIndex() + 1, jumpTarget); } @Override public List<StackMetadata> getStackMetadataAfterInstructionForBranches(FunctionMetadata functionMetadata, StackMetadata stackMetadata) { return List.of(stackMetadata.pop(), stackMetadata.pop()); } @Override public void implement(FunctionMetadata functionMetadata, StackMetadata stackMetadata) { JumpImplementor.popAndJumpIfTrue(functionMetadata, stackMetadata, jumpTarget); } }
0
java-sources/ai/timefold/solver/jpyinterpreter/1.24.0/ai/timefold/jpyinterpreter/opcodes
java-sources/ai/timefold/solver/jpyinterpreter/1.24.0/ai/timefold/jpyinterpreter/opcodes/controlflow/ReturnConstantValueOpcode.java
package ai.timefold.jpyinterpreter.opcodes.controlflow; import java.util.Collections; import java.util.List; import ai.timefold.jpyinterpreter.FunctionMetadata; import ai.timefold.jpyinterpreter.PythonBytecodeInstruction; import ai.timefold.jpyinterpreter.PythonCompiledFunction; import ai.timefold.jpyinterpreter.PythonFunctionType; import ai.timefold.jpyinterpreter.PythonLikeObject; import ai.timefold.jpyinterpreter.StackMetadata; import ai.timefold.jpyinterpreter.implementors.GeneratorImplementor; import ai.timefold.jpyinterpreter.implementors.JavaPythonTypeConversionImplementor; import ai.timefold.jpyinterpreter.implementors.PythonConstantsImplementor; import ai.timefold.jpyinterpreter.types.PythonLikeType; public class ReturnConstantValueOpcode extends AbstractControlFlowOpcode { public ReturnConstantValueOpcode(PythonBytecodeInstruction instruction) { super(instruction); } @Override public List<Integer> getPossibleNextBytecodeIndexList() { return Collections.emptyList(); } @Override public List<StackMetadata> getStackMetadataAfterInstructionForBranches(FunctionMetadata functionMetadata, StackMetadata stackMetadata) { return Collections.emptyList(); } @Override public boolean isForcedJump() { return true; } public PythonLikeObject getConstant(PythonCompiledFunction function) { return function.co_constants.get(instruction.arg()); } @Override public void implement(FunctionMetadata functionMetadata, StackMetadata stackMetadata) { PythonLikeObject constant = getConstant(functionMetadata.pythonCompiledFunction); PythonLikeType constantType = constant.$getGenericType(); if (functionMetadata.functionType == PythonFunctionType.GENERATOR) { PythonConstantsImplementor.loadConstant(functionMetadata.methodVisitor, functionMetadata.className, instruction.arg()); GeneratorImplementor.endGenerator(functionMetadata, stackMetadata.pushTemp(constantType)); } else { PythonConstantsImplementor.loadConstant(functionMetadata.methodVisitor, functionMetadata.className, instruction.arg()); JavaPythonTypeConversionImplementor.returnValue(functionMetadata.methodVisitor, functionMetadata.method, stackMetadata.pushTemp(constantType)); } } }
0
java-sources/ai/timefold/solver/jpyinterpreter/1.24.0/ai/timefold/jpyinterpreter/opcodes
java-sources/ai/timefold/solver/jpyinterpreter/1.24.0/ai/timefold/jpyinterpreter/opcodes/controlflow/ReturnValueOpcode.java
package ai.timefold.jpyinterpreter.opcodes.controlflow; import java.util.Collections; import java.util.List; import ai.timefold.jpyinterpreter.FunctionMetadata; import ai.timefold.jpyinterpreter.PythonBytecodeInstruction; import ai.timefold.jpyinterpreter.PythonFunctionType; import ai.timefold.jpyinterpreter.StackMetadata; import ai.timefold.jpyinterpreter.implementors.GeneratorImplementor; import ai.timefold.jpyinterpreter.implementors.JavaPythonTypeConversionImplementor; public class ReturnValueOpcode extends AbstractControlFlowOpcode { public ReturnValueOpcode(PythonBytecodeInstruction instruction) { super(instruction); } @Override public List<Integer> getPossibleNextBytecodeIndexList() { return Collections.emptyList(); } @Override public List<StackMetadata> getStackMetadataAfterInstructionForBranches(FunctionMetadata functionMetadata, StackMetadata stackMetadata) { return Collections.emptyList(); } @Override public boolean isForcedJump() { return true; } @Override public void implement(FunctionMetadata functionMetadata, StackMetadata stackMetadata) { if (functionMetadata.functionType == PythonFunctionType.GENERATOR) { GeneratorImplementor.endGenerator(functionMetadata, stackMetadata); } else { JavaPythonTypeConversionImplementor.returnValue(functionMetadata.methodVisitor, functionMetadata.method, stackMetadata); } } }
0
java-sources/ai/timefold/solver/jpyinterpreter/1.24.0/ai/timefold/jpyinterpreter/opcodes
java-sources/ai/timefold/solver/jpyinterpreter/1.24.0/ai/timefold/jpyinterpreter/opcodes/descriptor/AsyncOpDescriptor.java
package ai.timefold.jpyinterpreter.opcodes.descriptor; public enum AsyncOpDescriptor implements OpcodeDescriptor { /** * Implements TOS = get_awaitable(TOS), where get_awaitable(o) returns o if o is a coroutine object or a generator * object with the CO_ITERABLE_COROUTINE flag, or resolves o.__await__. */ GET_AWAITABLE, /** * Implements TOS = TOS.__aiter__(). */ GET_AITER, /** * Implements PUSH(get_awaitable(TOS.__anext__())). See {@link #GET_AWAITABLE} for details about get_awaitable */ GET_ANEXT, /** * Terminates an async for loop. Handles an exception raised when awaiting a next item. If TOS is StopAsyncIteration * pop 7 values from the stack and restore the exception state using the second three of them. Otherwise re-raise the * exception using the three values from the stack. An exception handler block is removed from the block stack. */ END_ASYNC_FOR, /** * Resolves __aenter__ and __aexit__ from the object on top of the stack. * Pushes __aexit__ and result of __aenter__() to the stack. */ BEFORE_ASYNC_WITH, /** * Creates a new frame object. */ SETUP_ASYNC_WITH; @Override public VersionMapping getVersionMapping() { // TODO return VersionMapping.unimplemented(); } }
0
java-sources/ai/timefold/solver/jpyinterpreter/1.24.0/ai/timefold/jpyinterpreter/opcodes
java-sources/ai/timefold/solver/jpyinterpreter/1.24.0/ai/timefold/jpyinterpreter/opcodes/descriptor/CollectionOpDescriptor.java
package ai.timefold.jpyinterpreter.opcodes.descriptor; import java.util.function.Function; import ai.timefold.jpyinterpreter.PythonBytecodeInstruction; import ai.timefold.jpyinterpreter.opcodes.Opcode; import ai.timefold.jpyinterpreter.opcodes.collection.BuildConstantKeyMapOpcode; import ai.timefold.jpyinterpreter.opcodes.collection.BuildListOpcode; import ai.timefold.jpyinterpreter.opcodes.collection.BuildMapOpcode; import ai.timefold.jpyinterpreter.opcodes.collection.BuildSetOpcode; import ai.timefold.jpyinterpreter.opcodes.collection.BuildSliceOpcode; import ai.timefold.jpyinterpreter.opcodes.collection.BuildTupleOpcode; import ai.timefold.jpyinterpreter.opcodes.collection.CollectionAddAllOpcode; import ai.timefold.jpyinterpreter.opcodes.collection.CollectionAddOpcode; import ai.timefold.jpyinterpreter.opcodes.collection.ContainsOpcode; import ai.timefold.jpyinterpreter.opcodes.collection.DeleteItemOpcode; import ai.timefold.jpyinterpreter.opcodes.collection.GetIterOpcode; import ai.timefold.jpyinterpreter.opcodes.collection.ListToTupleOpcode; import ai.timefold.jpyinterpreter.opcodes.collection.MapMergeOpcode; import ai.timefold.jpyinterpreter.opcodes.collection.MapPutAllOpcode; import ai.timefold.jpyinterpreter.opcodes.collection.MapPutOpcode; import ai.timefold.jpyinterpreter.opcodes.collection.SetItemOpcode; import ai.timefold.jpyinterpreter.opcodes.collection.UnpackSequenceOpcode; import ai.timefold.jpyinterpreter.opcodes.collection.UnpackSequenceWithTailOpcode; public enum CollectionOpDescriptor implements OpcodeDescriptor { /** * Implements TOS = iter(TOS). */ GET_ITER(GetIterOpcode::new), /** * Implements TOS1[TOS] = TOS2. */ STORE_SUBSCR(SetItemOpcode::new), /** * Implements del TOS1[TOS]. */ DELETE_SUBSCR(DeleteItemOpcode::new), CONTAINS_OP(ContainsOpcode::new), UNPACK_SEQUENCE(UnpackSequenceOpcode::new), UNPACK_EX(UnpackSequenceWithTailOpcode::new), // ************************************************** // Collection Construction Operations // ************************************************** BUILD_SLICE(BuildSliceOpcode::new), BUILD_TUPLE(BuildTupleOpcode::new), BUILD_LIST(BuildListOpcode::new), BUILD_SET(BuildSetOpcode::new), BUILD_MAP(BuildMapOpcode::new), BUILD_CONST_KEY_MAP(BuildConstantKeyMapOpcode::new), // ************************************************** // Collection Edit Operations // ************************************************** LIST_TO_TUPLE(ListToTupleOpcode::new), /** * Calls set.add(TOS1[-i], TOS). Used to implement set comprehensions. * <p> * The added value is popped off, the container object remains on the stack so that it is available for further * iterations of the loop. */ SET_ADD(CollectionAddOpcode::new), /** * Calls list.append(TOS1[-i], TOS). Used to implement list comprehensions. * <p> * The added value is popped off, the container object remains on the stack so that it is available for further * iterations of the loop. */ LIST_APPEND(CollectionAddOpcode::new), /** * Calls dict.__setitem__(TOS1[-i], TOS1, TOS). Used to implement dict comprehensions. * <p> * The key/value pair is popped off, the container object remains on the stack so that it is available for further * iterations of the loop. */ MAP_ADD(MapPutOpcode::new), LIST_EXTEND(CollectionAddAllOpcode::new), SET_UPDATE(CollectionAddAllOpcode::new), DICT_UPDATE(MapPutAllOpcode::new), DICT_MERGE(MapMergeOpcode::new); final VersionMapping versionLookup; CollectionOpDescriptor(Function<PythonBytecodeInstruction, Opcode> instructionToOpcode) { this.versionLookup = VersionMapping.constantMapping(instructionToOpcode); } @Override public VersionMapping getVersionMapping() { return versionLookup; } }
0
java-sources/ai/timefold/solver/jpyinterpreter/1.24.0/ai/timefold/jpyinterpreter/opcodes
java-sources/ai/timefold/solver/jpyinterpreter/1.24.0/ai/timefold/jpyinterpreter/opcodes/descriptor/ControlOpDescriptor.java
package ai.timefold.jpyinterpreter.opcodes.descriptor; import java.util.function.BiFunction; import java.util.function.Function; import java.util.function.ToIntBiFunction; import ai.timefold.jpyinterpreter.PythonBytecodeInstruction; import ai.timefold.jpyinterpreter.PythonVersion; import ai.timefold.jpyinterpreter.opcodes.Opcode; import ai.timefold.jpyinterpreter.opcodes.controlflow.ForIterOpcode; import ai.timefold.jpyinterpreter.opcodes.controlflow.JumpAbsoluteOpcode; import ai.timefold.jpyinterpreter.opcodes.controlflow.JumpIfFalseOrPopOpcode; import ai.timefold.jpyinterpreter.opcodes.controlflow.JumpIfNotExcMatchOpcode; import ai.timefold.jpyinterpreter.opcodes.controlflow.JumpIfTrueOrPopOpcode; import ai.timefold.jpyinterpreter.opcodes.controlflow.PopJumpIfFalseOpcode; import ai.timefold.jpyinterpreter.opcodes.controlflow.PopJumpIfIsNoneOpcode; import ai.timefold.jpyinterpreter.opcodes.controlflow.PopJumpIfIsNotNoneOpcode; import ai.timefold.jpyinterpreter.opcodes.controlflow.PopJumpIfTrueOpcode; import ai.timefold.jpyinterpreter.opcodes.controlflow.ReturnConstantValueOpcode; import ai.timefold.jpyinterpreter.opcodes.controlflow.ReturnValueOpcode; import ai.timefold.jpyinterpreter.opcodes.meta.NopOpcode; import ai.timefold.jpyinterpreter.util.JumpUtils; public enum ControlOpDescriptor implements OpcodeDescriptor { /** * Returns with TOS to the caller of the function. */ RETURN_VALUE(ReturnValueOpcode::new), RETURN_CONST(ReturnConstantValueOpcode::new), JUMP_FORWARD(JumpAbsoluteOpcode::new, JumpUtils::getRelativeTarget), JUMP_BACKWARD(JumpAbsoluteOpcode::new, JumpUtils::getBackwardRelativeTarget), JUMP_BACKWARD_NO_INTERRUPT(JumpAbsoluteOpcode::new, JumpUtils::getBackwardRelativeTarget), POP_JUMP_IF_TRUE(PopJumpIfTrueOpcode::new, JumpUtils::getAbsoluteTarget), POP_JUMP_FORWARD_IF_TRUE(PopJumpIfTrueOpcode::new, JumpUtils::getRelativeTarget), POP_JUMP_BACKWARD_IF_TRUE(PopJumpIfTrueOpcode::new, JumpUtils::getBackwardRelativeTarget), POP_JUMP_IF_FALSE(PopJumpIfFalseOpcode::new, JumpUtils::getAbsoluteTarget), POP_JUMP_FORWARD_IF_FALSE(PopJumpIfFalseOpcode::new, JumpUtils::getRelativeTarget), POP_JUMP_BACKWARD_IF_FALSE(PopJumpIfFalseOpcode::new, JumpUtils::getBackwardRelativeTarget), POP_JUMP_IF_NONE(PopJumpIfIsNoneOpcode::new, JumpUtils::getRelativeTarget), POP_JUMP_IF_NOT_NONE(PopJumpIfIsNotNoneOpcode::new, JumpUtils::getRelativeTarget), POP_JUMP_FORWARD_IF_NONE(PopJumpIfIsNoneOpcode::new, JumpUtils::getRelativeTarget), POP_JUMP_BACKWARD_IF_NONE(PopJumpIfIsNoneOpcode::new, JumpUtils::getBackwardRelativeTarget), POP_JUMP_FORWARD_IF_NOT_NONE(PopJumpIfIsNotNoneOpcode::new, JumpUtils::getRelativeTarget), POP_JUMP_BACKWARD_IF_NOT_NONE(PopJumpIfIsNotNoneOpcode::new, JumpUtils::getBackwardRelativeTarget), JUMP_IF_NOT_EXC_MATCH(JumpIfNotExcMatchOpcode::new, JumpUtils::getAbsoluteTarget), JUMP_IF_TRUE_OR_POP(new VersionMapping() .mapWithLabels(PythonVersion.MINIMUM_PYTHON_VERSION, JumpIfTrueOrPopOpcode::new, JumpUtils::getAbsoluteTarget) .mapWithLabels(PythonVersion.PYTHON_3_11, JumpIfTrueOrPopOpcode::new, JumpUtils::getRelativeTarget)), JUMP_IF_FALSE_OR_POP(new VersionMapping() .mapWithLabels(PythonVersion.MINIMUM_PYTHON_VERSION, JumpIfFalseOrPopOpcode::new, JumpUtils::getAbsoluteTarget) .mapWithLabels(PythonVersion.PYTHON_3_11, JumpIfFalseOrPopOpcode::new, JumpUtils::getRelativeTarget)), JUMP_ABSOLUTE(JumpAbsoluteOpcode::new, JumpUtils::getAbsoluteTarget), FOR_ITER(ForIterOpcode::new, JumpUtils::getRelativeTarget), END_FOR(NopOpcode::new); final VersionMapping versionLookup; ControlOpDescriptor(Function<PythonBytecodeInstruction, Opcode> opcodeFunction) { this.versionLookup = VersionMapping.constantMapping(opcodeFunction); } ControlOpDescriptor(BiFunction<PythonBytecodeInstruction, Integer, Opcode> opcodeFunction, ToIntBiFunction<PythonBytecodeInstruction, PythonVersion> labelFunction) { this.versionLookup = VersionMapping.constantMapping((instruction, version) -> opcodeFunction.apply(instruction, labelFunction.applyAsInt(instruction, version))); } ControlOpDescriptor(VersionMapping versionLookup) { this.versionLookup = versionLookup; } @Override public VersionMapping getVersionMapping() { return versionLookup; } }
0
java-sources/ai/timefold/solver/jpyinterpreter/1.24.0/ai/timefold/jpyinterpreter/opcodes
java-sources/ai/timefold/solver/jpyinterpreter/1.24.0/ai/timefold/jpyinterpreter/opcodes/descriptor/DunderOpDescriptor.java
package ai.timefold.jpyinterpreter.opcodes.descriptor; import java.util.function.Function; import ai.timefold.jpyinterpreter.PythonBinaryOperator; import ai.timefold.jpyinterpreter.PythonBytecodeInstruction; import ai.timefold.jpyinterpreter.PythonUnaryOperator; import ai.timefold.jpyinterpreter.opcodes.Opcode; import ai.timefold.jpyinterpreter.opcodes.dunder.BinaryDunderOpcode; import ai.timefold.jpyinterpreter.opcodes.dunder.CompareOpcode; import ai.timefold.jpyinterpreter.opcodes.dunder.GetSliceOpcode; import ai.timefold.jpyinterpreter.opcodes.dunder.NotOpcode; import ai.timefold.jpyinterpreter.opcodes.dunder.StoreSliceOpcode; import ai.timefold.jpyinterpreter.opcodes.dunder.UniDunerOpcode; public enum DunderOpDescriptor implements OpcodeDescriptor { COMPARE_OP(CompareOpcode::new), /** * Implements TOS = not TOS. */ UNARY_NOT(NotOpcode::new), /** * Implements any binary op. Its argument represent the arg to implement, which * may or may not be inplace. */ BINARY_OP(PythonBinaryOperator::getBinaryOpcode), /** * Implements TOS = +TOS. */ UNARY_POSITIVE(PythonUnaryOperator.POSITIVE), /** * Implements TOS = -TOS. */ UNARY_NEGATIVE(PythonUnaryOperator.NEGATIVE), /** * Implements TOS = ~TOS. */ UNARY_INVERT(PythonUnaryOperator.INVERT), /** * Implements TOS = TOS1 ** TOS. */ BINARY_POWER(PythonBinaryOperator.POWER), /** * Implements TOS = TOS1 * TOS. */ BINARY_MULTIPLY(PythonBinaryOperator.MULTIPLY), /** * Implements TOS = TOS1 @ TOS. */ BINARY_MATRIX_MULTIPLY(PythonBinaryOperator.MATRIX_MULTIPLY), /** * Implements TOS = TOS1 // TOS. */ BINARY_FLOOR_DIVIDE(PythonBinaryOperator.FLOOR_DIVIDE), /** * Implements TOS = TOS1 / TOS. */ BINARY_TRUE_DIVIDE(PythonBinaryOperator.TRUE_DIVIDE), /** * Implements TOS = TOS1 % TOS. */ BINARY_MODULO(PythonBinaryOperator.MODULO), /** * Implements TOS = TOS1 + TOS. */ BINARY_ADD(PythonBinaryOperator.ADD), /** * Implements TOS = TOS1 - TOS. */ BINARY_SUBTRACT(PythonBinaryOperator.SUBTRACT), /** * Implements TOS = TOS1[TOS]. */ BINARY_SUBSCR(PythonBinaryOperator.GET_ITEM), /** * Implements TOS = TOS2[TOS1:TOS] */ BINARY_SLICE(GetSliceOpcode::new), /** * Implements TOS2[TOS1:TOS] = TOS3 */ STORE_SLICE(StoreSliceOpcode::new), /** * Implements TOS = TOS1 &lt;&lt; TOS. */ BINARY_LSHIFT(PythonBinaryOperator.LSHIFT), /** * Implements TOS = TOS1 &gt;&gt; TOS. */ BINARY_RSHIFT(PythonBinaryOperator.RSHIFT), /** * Implements TOS = TOS1 &amp; TOS. */ BINARY_AND(PythonBinaryOperator.AND), /** * Implements TOS = TOS1 ^ TOS. */ BINARY_XOR(PythonBinaryOperator.XOR), /** * Implements TOS = TOS1 | TOS. */ BINARY_OR(PythonBinaryOperator.OR), // ************************************************** // In-place Dunder Operations // ************************************************** /** * Implements in-place TOS = TOS1 ** TOS. */ INPLACE_POWER(PythonBinaryOperator.INPLACE_POWER), /** * Implements in-place TOS = TOS1 * TOS. */ INPLACE_MULTIPLY(PythonBinaryOperator.INPLACE_MULTIPLY), /** * Implements in-place TOS = TOS1 @ TOS. */ INPLACE_MATRIX_MULTIPLY(PythonBinaryOperator.INPLACE_MATRIX_MULTIPLY), /** * Implements in-place TOS = TOS1 // TOS. */ INPLACE_FLOOR_DIVIDE(PythonBinaryOperator.INPLACE_FLOOR_DIVIDE), /** * Implements in-place TOS = TOS1 / TOS. */ INPLACE_TRUE_DIVIDE(PythonBinaryOperator.INPLACE_TRUE_DIVIDE), /** * Implements in-place TOS = TOS1 % TOS. */ INPLACE_MODULO(PythonBinaryOperator.INPLACE_MODULO), /** * Implements in-place TOS = TOS1 + TOS. */ INPLACE_ADD(PythonBinaryOperator.INPLACE_ADD), /** * Implements in-place TOS = TOS1 - TOS. */ INPLACE_SUBTRACT(PythonBinaryOperator.INPLACE_SUBTRACT), /** * Implements in-place TOS = TOS1 &lt;&lt; TOS. */ INPLACE_LSHIFT(PythonBinaryOperator.INPLACE_LSHIFT), /** * Implements in-place TOS = TOS1 &gt;&gt; TOS. */ INPLACE_RSHIFT(PythonBinaryOperator.INPLACE_RSHIFT), /** * Implements in-place TOS = TOS1 &amp; TOS. */ INPLACE_AND(PythonBinaryOperator.INPLACE_AND), /** * Implements in-place TOS = TOS1 ^ TOS. */ INPLACE_XOR(PythonBinaryOperator.INPLACE_XOR), /** * Implements in-place TOS = TOS1 | TOS. */ INPLACE_OR(PythonBinaryOperator.INPLACE_OR); final VersionMapping versionLookup; DunderOpDescriptor(Function<PythonBytecodeInstruction, Opcode> opcodeFunction) { this.versionLookup = VersionMapping.constantMapping(opcodeFunction); } DunderOpDescriptor(PythonUnaryOperator binaryOperator) { this((instruction) -> new UniDunerOpcode(instruction, binaryOperator)); } DunderOpDescriptor(PythonBinaryOperator binaryOperator) { this((instruction) -> new BinaryDunderOpcode(instruction, binaryOperator)); } @Override public VersionMapping getVersionMapping() { return versionLookup; } }
0
java-sources/ai/timefold/solver/jpyinterpreter/1.24.0/ai/timefold/jpyinterpreter/opcodes
java-sources/ai/timefold/solver/jpyinterpreter/1.24.0/ai/timefold/jpyinterpreter/opcodes/descriptor/ExceptionOpDescriptor.java
package ai.timefold.jpyinterpreter.opcodes.descriptor; import java.util.function.BiFunction; import java.util.function.Function; import java.util.function.ToIntBiFunction; import ai.timefold.jpyinterpreter.PythonBytecodeInstruction; import ai.timefold.jpyinterpreter.PythonVersion; import ai.timefold.jpyinterpreter.opcodes.Opcode; import ai.timefold.jpyinterpreter.opcodes.exceptions.BeforeWithOpcode; import ai.timefold.jpyinterpreter.opcodes.exceptions.CheckExcMatchOpcode; import ai.timefold.jpyinterpreter.opcodes.exceptions.CleanupThrowOpcode; import ai.timefold.jpyinterpreter.opcodes.exceptions.LoadAssertionErrorOpcode; import ai.timefold.jpyinterpreter.opcodes.exceptions.PopBlockOpcode; import ai.timefold.jpyinterpreter.opcodes.exceptions.PopExceptOpcode; import ai.timefold.jpyinterpreter.opcodes.exceptions.PushExcInfoOpcode; import ai.timefold.jpyinterpreter.opcodes.exceptions.RaiseVarargsOpcode; import ai.timefold.jpyinterpreter.opcodes.exceptions.ReraiseOpcode; import ai.timefold.jpyinterpreter.opcodes.exceptions.SetupFinallyOpcode; import ai.timefold.jpyinterpreter.opcodes.exceptions.SetupWithOpcode; import ai.timefold.jpyinterpreter.opcodes.exceptions.WithExceptStartOpcode; import ai.timefold.jpyinterpreter.util.JumpUtils; public enum ExceptionOpDescriptor implements OpcodeDescriptor { /** * Pushes AssertionError onto the stack. Used by the assert statement. */ LOAD_ASSERTION_ERROR(LoadAssertionErrorOpcode::new), /** * Removes one block from the block stack. Per frame, there is a stack of blocks, * denoting try statements, and such. */ POP_BLOCK(PopBlockOpcode::new), /** * Removes one block from the block stack. The popped block must be an exception handler block, as implicitly created * when entering an except handler. In addition to popping extraneous values from the frame stack, the last three * popped values are used to restore the exception state. */ POP_EXCEPT(PopExceptOpcode::new), /** * Re-raises the exception currently on top of the stack. */ RERAISE(ReraiseOpcode::new), /** * Performs exception matching for except. Tests whether the TOS1 is an exception matching TOS. * Pops TOS and pushes the boolean result of the test. */ CHECK_EXC_MATCH(CheckExcMatchOpcode::new), /** * Pops a value from the stack. Pushes the current exception to the top of the stack. * Pushes the value originally popped back to the stack. Used in exception handlers. */ PUSH_EXC_INFO(PushExcInfoOpcode::new), RAISE_VARARGS(RaiseVarargsOpcode::new), /** * Calls the function in position 7 on the stack with the top three items on the stack as arguments. Used to implement * the call context_manager.__exit__(*exc_info()) when an exception has occurred in a with statement. */ WITH_EXCEPT_START(WithExceptStartOpcode::new), SETUP_FINALLY(SetupFinallyOpcode::new, JumpUtils::getRelativeTarget), BEFORE_WITH(BeforeWithOpcode::new), SETUP_WITH(SetupWithOpcode::new, JumpUtils::getRelativeTarget), CLEANUP_THROW(CleanupThrowOpcode::new); final VersionMapping versionLookup; ExceptionOpDescriptor(Function<PythonBytecodeInstruction, Opcode> opcodeFunction) { this.versionLookup = VersionMapping.constantMapping(opcodeFunction); } ExceptionOpDescriptor(BiFunction<PythonBytecodeInstruction, Integer, Opcode> opcodeFunction, ToIntBiFunction<PythonBytecodeInstruction, PythonVersion> jumpFunction) { this.versionLookup = VersionMapping.constantMapping((instruction, pythonVersion) -> opcodeFunction.apply(instruction, jumpFunction.applyAsInt(instruction, pythonVersion))); } @Override public VersionMapping getVersionMapping() { return versionLookup; } }
0
java-sources/ai/timefold/solver/jpyinterpreter/1.24.0/ai/timefold/jpyinterpreter/opcodes
java-sources/ai/timefold/solver/jpyinterpreter/1.24.0/ai/timefold/jpyinterpreter/opcodes/descriptor/FunctionOpDescriptor.java
package ai.timefold.jpyinterpreter.opcodes.descriptor; import java.util.function.Function; import ai.timefold.jpyinterpreter.PythonBytecodeInstruction; import ai.timefold.jpyinterpreter.opcodes.Opcode; import ai.timefold.jpyinterpreter.opcodes.function.CallFunctionKeywordOpcode; import ai.timefold.jpyinterpreter.opcodes.function.CallFunctionOpcode; import ai.timefold.jpyinterpreter.opcodes.function.CallFunctionUnpackOpcode; import ai.timefold.jpyinterpreter.opcodes.function.CallMethodOpcode; import ai.timefold.jpyinterpreter.opcodes.function.CallOpcode; import ai.timefold.jpyinterpreter.opcodes.function.LoadMethodOpcode; import ai.timefold.jpyinterpreter.opcodes.function.MakeFunctionOpcode; import ai.timefold.jpyinterpreter.opcodes.function.PushNullOpcode; import ai.timefold.jpyinterpreter.opcodes.function.SetCallKeywordNameTupleOpcode; public enum FunctionOpDescriptor implements OpcodeDescriptor { PUSH_NULL(PushNullOpcode::new), KW_NAMES(SetCallKeywordNameTupleOpcode::new), CALL(CallOpcode::new), CALL_FUNCTION(CallFunctionOpcode::new), CALL_FUNCTION_KW(CallFunctionKeywordOpcode::new), CALL_FUNCTION_EX(CallFunctionUnpackOpcode::new), LOAD_METHOD(LoadMethodOpcode::new), CALL_METHOD(CallMethodOpcode::new), MAKE_FUNCTION(MakeFunctionOpcode::new); final VersionMapping versionLookup; FunctionOpDescriptor(Function<PythonBytecodeInstruction, Opcode> opcodeFunction) { this.versionLookup = VersionMapping.constantMapping(opcodeFunction); } @Override public VersionMapping getVersionMapping() { return versionLookup; } }
0
java-sources/ai/timefold/solver/jpyinterpreter/1.24.0/ai/timefold/jpyinterpreter/opcodes
java-sources/ai/timefold/solver/jpyinterpreter/1.24.0/ai/timefold/jpyinterpreter/opcodes/descriptor/GeneratorOpDescriptor.java
package ai.timefold.jpyinterpreter.opcodes.descriptor; import java.util.function.BiFunction; import java.util.function.Function; import java.util.function.ToIntBiFunction; import ai.timefold.jpyinterpreter.PythonBytecodeInstruction; import ai.timefold.jpyinterpreter.PythonVersion; import ai.timefold.jpyinterpreter.opcodes.Opcode; import ai.timefold.jpyinterpreter.opcodes.generator.GeneratorStartOpcode; import ai.timefold.jpyinterpreter.opcodes.generator.GetYieldFromIterOpcode; import ai.timefold.jpyinterpreter.opcodes.generator.ResumeOpcode; import ai.timefold.jpyinterpreter.opcodes.generator.SendOpcode; import ai.timefold.jpyinterpreter.opcodes.generator.YieldFromOpcode; import ai.timefold.jpyinterpreter.opcodes.generator.YieldValueOpcode; import ai.timefold.jpyinterpreter.opcodes.meta.NopOpcode; import ai.timefold.jpyinterpreter.opcodes.meta.ReturnGeneratorOpcode; import ai.timefold.jpyinterpreter.util.JumpUtils; public enum GeneratorOpDescriptor implements OpcodeDescriptor { /** * Another do nothing code. Performs internal tracing, debugging and optimization checks in CPython */ RESUME(ResumeOpcode::new), /** * Pops TOS and yields it from a generator. */ YIELD_VALUE(YieldValueOpcode::new), /** * Pops TOS and delegates to it as a subiterator from a generator. */ YIELD_FROM(YieldFromOpcode::new), /** * If TOS is a generator iterator or coroutine object it is left as is. * Otherwise, implements TOS = iter(TOS). */ GET_YIELD_FROM_ITER(GetYieldFromIterOpcode::new), /** * Pops TOS. The kind operand corresponds to the type of generator or coroutine. * The legal kinds are 0 for generator, 1 for coroutine, and 2 for async generator. */ GEN_START(GeneratorStartOpcode::new), /** * TOS1 is a subgenerator, TOS is a value. Calls TOS1.send(TOS) if self.thrownValue is null. * Otherwise, set self.thrownValue to null and call TOS1.throwValue(TOS) instead. TOS is replaced by the subgenerator * yielded value; TOS1 remains. When the subgenerator is exhausted, jump forward by its argument. */ SEND(SendOpcode::new, JumpUtils::getRelativeTarget), END_SEND(NopOpcode::new), /** * Create a generator, coroutine, or async generator from the current frame. * Clear the current frame and return the newly created generator. A no-op for us, since we detect if * the code represent a generator (and if so, generate a wrapper function for it that act like * RETURN_GENERATOR) before interpreting it */ RETURN_GENERATOR(ReturnGeneratorOpcode::new); final VersionMapping versionLookup; GeneratorOpDescriptor(Function<PythonBytecodeInstruction, Opcode> opcodeFunction) { this.versionLookup = VersionMapping.constantMapping(opcodeFunction); } GeneratorOpDescriptor(BiFunction<PythonBytecodeInstruction, Integer, Opcode> opcodeConstructor, ToIntBiFunction<PythonBytecodeInstruction, PythonVersion> labelFunction) { this.versionLookup = VersionMapping.constantMapping( (instruction, pythonVersion) -> opcodeConstructor.apply( instruction, labelFunction.applyAsInt(instruction, pythonVersion))); } @Override public VersionMapping getVersionMapping() { return versionLookup; } }
0
java-sources/ai/timefold/solver/jpyinterpreter/1.24.0/ai/timefold/jpyinterpreter/opcodes
java-sources/ai/timefold/solver/jpyinterpreter/1.24.0/ai/timefold/jpyinterpreter/opcodes/descriptor/MetaOpDescriptor.java
package ai.timefold.jpyinterpreter.opcodes.descriptor; import java.util.function.Function; import ai.timefold.jpyinterpreter.PythonBytecodeInstruction; import ai.timefold.jpyinterpreter.opcodes.Opcode; import ai.timefold.jpyinterpreter.opcodes.meta.NopOpcode; import ai.timefold.jpyinterpreter.opcodes.meta.UnaryIntrinsicFunction; public enum MetaOpDescriptor implements OpcodeDescriptor { /** * Do nothing code. Used as a placeholder by the bytecode optimizer. */ NOP(NopOpcode::new), /** * A no-op code used by CPython to hold arbitrary data for JIT. */ CACHE(NopOpcode::new), /** * Prefixes {@link FunctionOpDescriptor#CALL}. * Logically this is a no op. * It exists to enable effective specialization of calls. argc is the number of arguments as described in CALL. */ PRECALL(NopOpcode::new), MAKE_CELL(NopOpcode::new), COPY_FREE_VARS(NopOpcode::new), CALL_INTRINSIC_1(UnaryIntrinsicFunction::lookup), // TODO EXTENDED_ARG(ignored -> { throw new UnsupportedOperationException("EXTENDED_ARG"); }), /** * Pushes builtins.__build_class__() onto the stack. * It is later called by CALL_FUNCTION to construct a class. */ LOAD_BUILD_CLASS(ignored -> { throw new UnsupportedOperationException("LOAD_BUILD_CLASS"); }), /** * Checks whether __annotations__ is defined in locals(), if not it is set up to an empty dict. This opcode is only * emitted if a class or module body contains variable annotations statically. * TODO: Properly implement this */ SETUP_ANNOTATIONS(NopOpcode::new); private final VersionMapping versionLookup; MetaOpDescriptor(Function<PythonBytecodeInstruction, Opcode> opcodeFunction) { this.versionLookup = VersionMapping.constantMapping(opcodeFunction); } @Override public VersionMapping getVersionMapping() { return versionLookup; } }
0
java-sources/ai/timefold/solver/jpyinterpreter/1.24.0/ai/timefold/jpyinterpreter/opcodes
java-sources/ai/timefold/solver/jpyinterpreter/1.24.0/ai/timefold/jpyinterpreter/opcodes/descriptor/ModuleOpDescriptor.java
package ai.timefold.jpyinterpreter.opcodes.descriptor; import java.util.function.Function; import ai.timefold.jpyinterpreter.PythonBytecodeInstruction; import ai.timefold.jpyinterpreter.opcodes.Opcode; import ai.timefold.jpyinterpreter.opcodes.module.ImportFromOpcode; import ai.timefold.jpyinterpreter.opcodes.module.ImportNameOpcode; public enum ModuleOpDescriptor implements OpcodeDescriptor { IMPORT_NAME(ImportNameOpcode::new), IMPORT_FROM(ImportFromOpcode::new), /** * Loads all symbols not starting with '_' directly from the module TOS to the local namespace. The module is popped * after * loading all names. This opcode implements from module import *. */ IMPORT_STAR(instruction -> { // From https://docs.python.org/3/reference/simple_stmts.html#the-import-statement , // Import * is only allowed at the module level and as such WILL never appear // in functions. throw new UnsupportedOperationException( "Impossible state/invalid bytecode: import * only allowed at module level"); }); final VersionMapping versionLookup; ModuleOpDescriptor(Function<PythonBytecodeInstruction, Opcode> opcodeFunction) { this.versionLookup = VersionMapping.constantMapping(opcodeFunction); } @Override public VersionMapping getVersionMapping() { return versionLookup; } }
0
java-sources/ai/timefold/solver/jpyinterpreter/1.24.0/ai/timefold/jpyinterpreter/opcodes
java-sources/ai/timefold/solver/jpyinterpreter/1.24.0/ai/timefold/jpyinterpreter/opcodes/descriptor/ObjectOpDescriptor.java
package ai.timefold.jpyinterpreter.opcodes.descriptor; import java.util.function.Function; import ai.timefold.jpyinterpreter.PythonBytecodeInstruction; import ai.timefold.jpyinterpreter.PythonVersion; import ai.timefold.jpyinterpreter.opcodes.Opcode; import ai.timefold.jpyinterpreter.opcodes.function.LoadMethodOpcode; import ai.timefold.jpyinterpreter.opcodes.object.DeleteAttrOpcode; import ai.timefold.jpyinterpreter.opcodes.object.IsOpcode; import ai.timefold.jpyinterpreter.opcodes.object.LoadAttrOpcode; import ai.timefold.jpyinterpreter.opcodes.object.LoadSuperAttrOpcode; import ai.timefold.jpyinterpreter.opcodes.object.StoreAttrOpcode; public enum ObjectOpDescriptor implements OpcodeDescriptor { IS_OP(IsOpcode::new), LOAD_ATTR(new VersionMapping() .map(PythonVersion.MINIMUM_PYTHON_VERSION, LoadAttrOpcode::new) .map(PythonVersion.PYTHON_3_12, instruction -> ((instruction.arg() & 1) == 1) ? new LoadMethodOpcode(instruction.withArg(instruction.arg() >> 1)) : new LoadAttrOpcode(instruction.withArg(instruction.arg() >> 1)))), LOAD_SUPER_ATTR(LoadSuperAttrOpcode::new), STORE_ATTR(StoreAttrOpcode::new), DELETE_ATTR(DeleteAttrOpcode::new); final VersionMapping versionLookup; ObjectOpDescriptor(Function<PythonBytecodeInstruction, Opcode> opcodeFunction) { this(VersionMapping.constantMapping(opcodeFunction)); } ObjectOpDescriptor(VersionMapping versionLookup) { this.versionLookup = versionLookup; } @Override public VersionMapping getVersionMapping() { return versionLookup; } }
0
java-sources/ai/timefold/solver/jpyinterpreter/1.24.0/ai/timefold/jpyinterpreter/opcodes
java-sources/ai/timefold/solver/jpyinterpreter/1.24.0/ai/timefold/jpyinterpreter/opcodes/descriptor/OpcodeDescriptor.java
package ai.timefold.jpyinterpreter.opcodes.descriptor; public sealed interface OpcodeDescriptor permits AsyncOpDescriptor, CollectionOpDescriptor, ControlOpDescriptor, DunderOpDescriptor, ExceptionOpDescriptor, FunctionOpDescriptor, GeneratorOpDescriptor, MetaOpDescriptor, ModuleOpDescriptor, ObjectOpDescriptor, StackOpDescriptor, StringOpDescriptor, VariableOpDescriptor { String name(); VersionMapping getVersionMapping(); }
0
java-sources/ai/timefold/solver/jpyinterpreter/1.24.0/ai/timefold/jpyinterpreter/opcodes
java-sources/ai/timefold/solver/jpyinterpreter/1.24.0/ai/timefold/jpyinterpreter/opcodes/descriptor/StackOpDescriptor.java
package ai.timefold.jpyinterpreter.opcodes.descriptor; import java.util.function.Function; import ai.timefold.jpyinterpreter.PythonBytecodeInstruction; import ai.timefold.jpyinterpreter.opcodes.Opcode; import ai.timefold.jpyinterpreter.opcodes.stack.CopyOpcode; import ai.timefold.jpyinterpreter.opcodes.stack.DupOpcode; import ai.timefold.jpyinterpreter.opcodes.stack.DupTwoOpcode; import ai.timefold.jpyinterpreter.opcodes.stack.PopOpcode; import ai.timefold.jpyinterpreter.opcodes.stack.RotateFourOpcode; import ai.timefold.jpyinterpreter.opcodes.stack.RotateThreeOpcode; import ai.timefold.jpyinterpreter.opcodes.stack.RotateTwoOpcode; import ai.timefold.jpyinterpreter.opcodes.stack.SwapOpcode; public enum StackOpDescriptor implements OpcodeDescriptor { /** * Removes the top-of-stack (TOS) item. */ POP_TOP(PopOpcode::new), /** * Swaps the two top-most stack items. */ ROT_TWO(RotateTwoOpcode::new), /** * Lifts second and third stack item one position up, moves top down to position three. */ ROT_THREE(RotateThreeOpcode::new), /** * Lifts second, third and fourth stack items one position up, moves top down to position four. */ ROT_FOUR(RotateFourOpcode::new), /** * Push the i-th item to the top of the stack. The item is not removed from its original location. * Uses 1-based indexing (TOS is 1, TOS1 is 2, ...) instead of 0-based indexing. */ COPY(CopyOpcode::new), /** * Swap TOS with the item at position i. Uses 1-based indexing (TOS is 1, TOS1 is 2, ...) instead of 0-based indexing. */ SWAP(SwapOpcode::new), /** * Duplicates the reference on top of the stack. */ DUP_TOP(DupOpcode::new), /** * Duplicates the two references on top of the stack, leaving them in the same order. */ DUP_TOP_TWO(DupTwoOpcode::new); final VersionMapping versionLookup; StackOpDescriptor(Function<PythonBytecodeInstruction, Opcode> opcodeFunction) { this.versionLookup = VersionMapping.constantMapping(opcodeFunction); } @Override public VersionMapping getVersionMapping() { return versionLookup; } }
0
java-sources/ai/timefold/solver/jpyinterpreter/1.24.0/ai/timefold/jpyinterpreter/opcodes
java-sources/ai/timefold/solver/jpyinterpreter/1.24.0/ai/timefold/jpyinterpreter/opcodes/descriptor/StringOpDescriptor.java
package ai.timefold.jpyinterpreter.opcodes.descriptor; import java.util.function.Function; import ai.timefold.jpyinterpreter.PythonBytecodeInstruction; import ai.timefold.jpyinterpreter.opcodes.Opcode; import ai.timefold.jpyinterpreter.opcodes.string.BuildStringOpcode; import ai.timefold.jpyinterpreter.opcodes.string.FormatValueOpcode; import ai.timefold.jpyinterpreter.opcodes.string.PrintExprOpcode; public enum StringOpDescriptor implements OpcodeDescriptor { /** * Implements the expression statement for the interactive mode. TOS is removed from the stack and printed. * In non-interactive mode, an expression statement is terminated with POP_TOP. */ PRINT_EXPR(PrintExprOpcode::new), FORMAT_VALUE(FormatValueOpcode::new), BUILD_STRING(BuildStringOpcode::new); final VersionMapping versionLookup; StringOpDescriptor(Function<PythonBytecodeInstruction, Opcode> opcodeFunction) { this.versionLookup = VersionMapping.constantMapping(opcodeFunction); } @Override public VersionMapping getVersionMapping() { return versionLookup; } }
0
java-sources/ai/timefold/solver/jpyinterpreter/1.24.0/ai/timefold/jpyinterpreter/opcodes
java-sources/ai/timefold/solver/jpyinterpreter/1.24.0/ai/timefold/jpyinterpreter/opcodes/descriptor/VariableOpDescriptor.java
package ai.timefold.jpyinterpreter.opcodes.descriptor; import java.util.function.Function; import ai.timefold.jpyinterpreter.PythonBytecodeInstruction; import ai.timefold.jpyinterpreter.opcodes.Opcode; import ai.timefold.jpyinterpreter.opcodes.variable.DeleteDerefOpcode; import ai.timefold.jpyinterpreter.opcodes.variable.DeleteFastOpcode; import ai.timefold.jpyinterpreter.opcodes.variable.DeleteGlobalOpcode; import ai.timefold.jpyinterpreter.opcodes.variable.LoadClosureOpcode; import ai.timefold.jpyinterpreter.opcodes.variable.LoadConstantOpcode; import ai.timefold.jpyinterpreter.opcodes.variable.LoadDerefOpcode; import ai.timefold.jpyinterpreter.opcodes.variable.LoadFastAndClearOpcode; import ai.timefold.jpyinterpreter.opcodes.variable.LoadFastOpcode; import ai.timefold.jpyinterpreter.opcodes.variable.LoadGlobalOpcode; import ai.timefold.jpyinterpreter.opcodes.variable.StoreDerefOpcode; import ai.timefold.jpyinterpreter.opcodes.variable.StoreFastOpcode; import ai.timefold.jpyinterpreter.opcodes.variable.StoreGlobalOpcode; public enum VariableOpDescriptor implements OpcodeDescriptor { LOAD_CONST(LoadConstantOpcode::new), LOAD_NAME(VersionMapping.unimplemented()), //TODO STORE_NAME(VersionMapping.unimplemented()), //TODO DELETE_NAME(VersionMapping.unimplemented()), //TODO LOAD_GLOBAL(LoadGlobalOpcode::new), STORE_GLOBAL(StoreGlobalOpcode::new), DELETE_GLOBAL(DeleteGlobalOpcode::new), // TODO: Implement unbound local variable checks LOAD_FAST(LoadFastOpcode::new), // This is LOAD_FAST but do an unbound variable check LOAD_FAST_CHECK(LoadFastOpcode::new), LOAD_FAST_AND_CLEAR(LoadFastAndClearOpcode::new), STORE_FAST(StoreFastOpcode::new), DELETE_FAST(DeleteFastOpcode::new), LOAD_CLOSURE(LoadClosureOpcode::new), LOAD_DEREF(LoadDerefOpcode::new), STORE_DEREF(StoreDerefOpcode::new), DELETE_DEREF(DeleteDerefOpcode::new), LOAD_CLASSDEREF(VersionMapping.unimplemented()); final VersionMapping versionLookup; VariableOpDescriptor(Function<PythonBytecodeInstruction, Opcode> opcodeFunction) { this(VersionMapping.constantMapping(opcodeFunction)); } VariableOpDescriptor(VersionMapping lookup) { this.versionLookup = lookup; } @Override public VersionMapping getVersionMapping() { return versionLookup; } }
0
java-sources/ai/timefold/solver/jpyinterpreter/1.24.0/ai/timefold/jpyinterpreter/opcodes
java-sources/ai/timefold/solver/jpyinterpreter/1.24.0/ai/timefold/jpyinterpreter/opcodes/descriptor/VersionMapping.java
package ai.timefold.jpyinterpreter.opcodes.descriptor; import java.util.NavigableMap; import java.util.Objects; import java.util.TreeMap; import java.util.function.BiFunction; import java.util.function.Function; import java.util.function.ToIntBiFunction; import ai.timefold.jpyinterpreter.PythonBytecodeInstruction; import ai.timefold.jpyinterpreter.PythonVersion; import ai.timefold.jpyinterpreter.opcodes.Opcode; public final class VersionMapping { private final NavigableMap<PythonVersion, BiFunction<PythonBytecodeInstruction, PythonVersion, Opcode>> versionToMappingMap; public VersionMapping() { this.versionToMappingMap = new TreeMap<>(); } private VersionMapping( NavigableMap<PythonVersion, BiFunction<PythonBytecodeInstruction, PythonVersion, Opcode>> versionToMappingMap) { this.versionToMappingMap = versionToMappingMap; } public static VersionMapping unimplemented() { return new VersionMapping(); } public static VersionMapping constantMapping(Function<PythonBytecodeInstruction, Opcode> mapper) { return new VersionMapping() .map(PythonVersion.MINIMUM_PYTHON_VERSION, Objects.requireNonNull(mapper)); } public static VersionMapping constantMapping(BiFunction<PythonBytecodeInstruction, PythonVersion, Opcode> mapper) { return new VersionMapping() .map(PythonVersion.MINIMUM_PYTHON_VERSION, Objects.requireNonNull(mapper)); } public VersionMapping map(PythonVersion version, Function<PythonBytecodeInstruction, Opcode> mapper) { var mapCopy = new TreeMap<>(versionToMappingMap); mapCopy.put(version, (instruction, ignored) -> mapper.apply(instruction)); return new VersionMapping(mapCopy); } public VersionMapping map(PythonVersion version, BiFunction<PythonBytecodeInstruction, PythonVersion, Opcode> mapper) { var mapCopy = new TreeMap<>(versionToMappingMap); mapCopy.put(version, mapper); return new VersionMapping(mapCopy); } public VersionMapping mapWithLabels(PythonVersion version, BiFunction<PythonBytecodeInstruction, Integer, Opcode> mapper, ToIntBiFunction<PythonBytecodeInstruction, PythonVersion> labelMapper) { var mapCopy = new TreeMap<>(versionToMappingMap); mapCopy.put(version, (instruction, actualVersion) -> mapper.apply(instruction, labelMapper.applyAsInt(instruction, actualVersion))); return new VersionMapping(mapCopy); } public Opcode getOpcodeForVersion(PythonBytecodeInstruction instruction, PythonVersion pythonVersion) { var mappingForVersion = versionToMappingMap.floorEntry(pythonVersion); if (mappingForVersion == null) { throw new UnsupportedOperationException( "Could not find implementation for Opcode %s for Python version %s (instruction %s)" .formatted(instruction.opname(), pythonVersion, instruction)); } return mappingForVersion.getValue().apply(instruction, pythonVersion); } }
0
java-sources/ai/timefold/solver/jpyinterpreter/1.24.0/ai/timefold/jpyinterpreter/opcodes
java-sources/ai/timefold/solver/jpyinterpreter/1.24.0/ai/timefold/jpyinterpreter/opcodes/dunder/BinaryDunderOpcode.java
package ai.timefold.jpyinterpreter.opcodes.dunder; import java.util.Optional; import ai.timefold.jpyinterpreter.FunctionMetadata; import ai.timefold.jpyinterpreter.PythonBinaryOperator; import ai.timefold.jpyinterpreter.PythonBytecodeInstruction; import ai.timefold.jpyinterpreter.PythonFunctionSignature; import ai.timefold.jpyinterpreter.StackMetadata; import ai.timefold.jpyinterpreter.ValueSourceInfo; import ai.timefold.jpyinterpreter.implementors.DunderOperatorImplementor; import ai.timefold.jpyinterpreter.opcodes.AbstractOpcode; import ai.timefold.jpyinterpreter.types.BuiltinTypes; import ai.timefold.jpyinterpreter.types.PythonKnownFunctionType; import ai.timefold.jpyinterpreter.types.PythonLikeType; public class BinaryDunderOpcode extends AbstractOpcode { final PythonBinaryOperator operator; public BinaryDunderOpcode(PythonBytecodeInstruction instruction, PythonBinaryOperator operator) { super(instruction); this.operator = operator; } @Override public StackMetadata getStackMetadataAfterInstruction(FunctionMetadata functionMetadata, StackMetadata stackMetadata) { PythonLikeType leftOperand = Optional.ofNullable(stackMetadata.getTypeAtStackIndex(1)).orElse(BuiltinTypes.BASE_TYPE); PythonLikeType rightOperand = Optional.ofNullable(stackMetadata.getTypeAtStackIndex(0)).orElse(BuiltinTypes.BASE_TYPE); Optional<PythonKnownFunctionType> maybeKnownFunctionType = leftOperand.getMethodType(operator.getDunderMethod()); if (maybeKnownFunctionType.isPresent()) { PythonKnownFunctionType knownFunctionType = maybeKnownFunctionType.get(); Optional<PythonFunctionSignature> maybeFunctionSignature = knownFunctionType.getFunctionForParameters(rightOperand); if (maybeFunctionSignature.isPresent()) { PythonFunctionSignature functionSignature = maybeFunctionSignature.get(); return stackMetadata.pop().pop().push(ValueSourceInfo.of(this, functionSignature.getReturnType(), stackMetadata.getValueSourcesUpToStackIndex(2))); } } // TODO: Right dunder method return stackMetadata.pop().pop() .push(ValueSourceInfo.of(this, BuiltinTypes.BASE_TYPE, stackMetadata.getValueSourcesUpToStackIndex(2))); } @Override public void implement(FunctionMetadata functionMetadata, StackMetadata stackMetadata) { DunderOperatorImplementor.binaryOperator(functionMetadata.methodVisitor, stackMetadata, operator); } }
0
java-sources/ai/timefold/solver/jpyinterpreter/1.24.0/ai/timefold/jpyinterpreter/opcodes
java-sources/ai/timefold/solver/jpyinterpreter/1.24.0/ai/timefold/jpyinterpreter/opcodes/dunder/CompareOpcode.java
package ai.timefold.jpyinterpreter.opcodes.dunder; import ai.timefold.jpyinterpreter.CompareOp; import ai.timefold.jpyinterpreter.FunctionMetadata; import ai.timefold.jpyinterpreter.PythonBytecodeInstruction; import ai.timefold.jpyinterpreter.StackMetadata; import ai.timefold.jpyinterpreter.ValueSourceInfo; import ai.timefold.jpyinterpreter.implementors.DunderOperatorImplementor; import ai.timefold.jpyinterpreter.opcodes.AbstractOpcode; import ai.timefold.jpyinterpreter.types.BuiltinTypes; public class CompareOpcode extends AbstractOpcode { public CompareOpcode(PythonBytecodeInstruction instruction) { super(instruction); } @Override public StackMetadata getStackMetadataAfterInstruction(FunctionMetadata functionMetadata, StackMetadata stackMetadata) { return stackMetadata.pop(2).push(ValueSourceInfo.of(this, BuiltinTypes.BOOLEAN_TYPE, stackMetadata.getValueSourcesUpToStackIndex(2))); } @Override public void implement(FunctionMetadata functionMetadata, StackMetadata stackMetadata) { DunderOperatorImplementor.compareValues(functionMetadata.methodVisitor, stackMetadata, CompareOp.getOp(instruction.argRepr())); } }
0
java-sources/ai/timefold/solver/jpyinterpreter/1.24.0/ai/timefold/jpyinterpreter/opcodes
java-sources/ai/timefold/solver/jpyinterpreter/1.24.0/ai/timefold/jpyinterpreter/opcodes/dunder/GetSliceOpcode.java
package ai.timefold.jpyinterpreter.opcodes.dunder; import ai.timefold.jpyinterpreter.FunctionMetadata; import ai.timefold.jpyinterpreter.PythonBytecodeInstruction; import ai.timefold.jpyinterpreter.StackMetadata; import ai.timefold.jpyinterpreter.ValueSourceInfo; import ai.timefold.jpyinterpreter.implementors.DunderOperatorImplementor; import ai.timefold.jpyinterpreter.opcodes.AbstractOpcode; import ai.timefold.jpyinterpreter.types.BuiltinTypes; public class GetSliceOpcode extends AbstractOpcode { public GetSliceOpcode(PythonBytecodeInstruction instruction) { super(instruction); } @Override protected StackMetadata getStackMetadataAfterInstruction(FunctionMetadata functionMetadata, StackMetadata stackMetadata) { // TODO: Type the result return stackMetadata.pop(3) .push(ValueSourceInfo.of(this, BuiltinTypes.BASE_TYPE, stackMetadata.getValueSourcesUpToStackIndex(3))); } @Override public void implement(FunctionMetadata functionMetadata, StackMetadata stackMetadata) { DunderOperatorImplementor.getSlice(functionMetadata, stackMetadata); } }
0
java-sources/ai/timefold/solver/jpyinterpreter/1.24.0/ai/timefold/jpyinterpreter/opcodes
java-sources/ai/timefold/solver/jpyinterpreter/1.24.0/ai/timefold/jpyinterpreter/opcodes/dunder/NotOpcode.java
package ai.timefold.jpyinterpreter.opcodes.dunder; import ai.timefold.jpyinterpreter.FunctionMetadata; import ai.timefold.jpyinterpreter.PythonBytecodeInstruction; import ai.timefold.jpyinterpreter.PythonUnaryOperator; import ai.timefold.jpyinterpreter.StackMetadata; import ai.timefold.jpyinterpreter.ValueSourceInfo; import ai.timefold.jpyinterpreter.implementors.DunderOperatorImplementor; import ai.timefold.jpyinterpreter.implementors.PythonBuiltinOperatorImplementor; import ai.timefold.jpyinterpreter.opcodes.AbstractOpcode; import ai.timefold.jpyinterpreter.types.BuiltinTypes; public class NotOpcode extends AbstractOpcode { public NotOpcode(PythonBytecodeInstruction instruction) { super(instruction); } @Override public StackMetadata getStackMetadataAfterInstruction(FunctionMetadata functionMetadata, StackMetadata stackMetadata) { return stackMetadata.pop().push(ValueSourceInfo.of(this, BuiltinTypes.BOOLEAN_TYPE, stackMetadata.getValueSourcesUpToStackIndex(1))); } @Override public void implement(FunctionMetadata functionMetadata, StackMetadata stackMetadata) { DunderOperatorImplementor.unaryOperator(functionMetadata.methodVisitor, stackMetadata, PythonUnaryOperator.AS_BOOLEAN); PythonBuiltinOperatorImplementor.performNotOnTOS(functionMetadata.methodVisitor); } }
0
java-sources/ai/timefold/solver/jpyinterpreter/1.24.0/ai/timefold/jpyinterpreter/opcodes
java-sources/ai/timefold/solver/jpyinterpreter/1.24.0/ai/timefold/jpyinterpreter/opcodes/dunder/StoreSliceOpcode.java
package ai.timefold.jpyinterpreter.opcodes.dunder; import ai.timefold.jpyinterpreter.FunctionMetadata; import ai.timefold.jpyinterpreter.PythonBytecodeInstruction; import ai.timefold.jpyinterpreter.StackMetadata; import ai.timefold.jpyinterpreter.implementors.DunderOperatorImplementor; import ai.timefold.jpyinterpreter.opcodes.AbstractOpcode; public class StoreSliceOpcode extends AbstractOpcode { public StoreSliceOpcode(PythonBytecodeInstruction instruction) { super(instruction); } @Override protected StackMetadata getStackMetadataAfterInstruction(FunctionMetadata functionMetadata, StackMetadata stackMetadata) { return stackMetadata.pop(4); } @Override public void implement(FunctionMetadata functionMetadata, StackMetadata stackMetadata) { DunderOperatorImplementor.storeSlice(functionMetadata, stackMetadata); } }
0
java-sources/ai/timefold/solver/jpyinterpreter/1.24.0/ai/timefold/jpyinterpreter/opcodes
java-sources/ai/timefold/solver/jpyinterpreter/1.24.0/ai/timefold/jpyinterpreter/opcodes/dunder/TernaryDunderOpcode.java
package ai.timefold.jpyinterpreter.opcodes.dunder; public class TernaryDunderOpcode { }
0
java-sources/ai/timefold/solver/jpyinterpreter/1.24.0/ai/timefold/jpyinterpreter/opcodes
java-sources/ai/timefold/solver/jpyinterpreter/1.24.0/ai/timefold/jpyinterpreter/opcodes/dunder/UniDunerOpcode.java
package ai.timefold.jpyinterpreter.opcodes.dunder; import java.util.Optional; import ai.timefold.jpyinterpreter.FunctionMetadata; import ai.timefold.jpyinterpreter.PythonBytecodeInstruction; import ai.timefold.jpyinterpreter.PythonFunctionSignature; import ai.timefold.jpyinterpreter.PythonUnaryOperator; import ai.timefold.jpyinterpreter.StackMetadata; import ai.timefold.jpyinterpreter.ValueSourceInfo; import ai.timefold.jpyinterpreter.implementors.DunderOperatorImplementor; import ai.timefold.jpyinterpreter.opcodes.AbstractOpcode; import ai.timefold.jpyinterpreter.types.BuiltinTypes; import ai.timefold.jpyinterpreter.types.PythonKnownFunctionType; import ai.timefold.jpyinterpreter.types.PythonLikeType; public class UniDunerOpcode extends AbstractOpcode { final PythonUnaryOperator operator; public UniDunerOpcode(PythonBytecodeInstruction instruction, PythonUnaryOperator operator) { super(instruction); this.operator = operator; } @Override public StackMetadata getStackMetadataAfterInstruction(FunctionMetadata functionMetadata, StackMetadata stackMetadata) { PythonLikeType operand = Optional.ofNullable(stackMetadata.getTOSType()).orElse(BuiltinTypes.BASE_TYPE); Optional<PythonKnownFunctionType> maybeKnownFunctionType = operand.getMethodType(operator.getDunderMethod()); if (maybeKnownFunctionType.isPresent()) { PythonKnownFunctionType knownFunctionType = maybeKnownFunctionType.get(); Optional<PythonFunctionSignature> maybeFunctionSignature = knownFunctionType.getFunctionForParameters(); if (maybeFunctionSignature.isPresent()) { PythonFunctionSignature functionSignature = maybeFunctionSignature.get(); return stackMetadata.pop().push(ValueSourceInfo.of(this, functionSignature.getReturnType(), stackMetadata.getValueSourcesUpToStackIndex(1))); } } return stackMetadata.pop() .push(ValueSourceInfo.of(this, BuiltinTypes.BASE_TYPE, stackMetadata.getValueSourcesUpToStackIndex(1))); } @Override public void implement(FunctionMetadata functionMetadata, StackMetadata stackMetadata) { DunderOperatorImplementor.unaryOperator(functionMetadata.methodVisitor, stackMetadata, operator); } }
0
java-sources/ai/timefold/solver/jpyinterpreter/1.24.0/ai/timefold/jpyinterpreter/opcodes
java-sources/ai/timefold/solver/jpyinterpreter/1.24.0/ai/timefold/jpyinterpreter/opcodes/exceptions/BeforeWithOpcode.java
package ai.timefold.jpyinterpreter.opcodes.exceptions; import ai.timefold.jpyinterpreter.FunctionMetadata; import ai.timefold.jpyinterpreter.PythonBytecodeInstruction; import ai.timefold.jpyinterpreter.StackMetadata; import ai.timefold.jpyinterpreter.ValueSourceInfo; import ai.timefold.jpyinterpreter.implementors.ExceptionImplementor; import ai.timefold.jpyinterpreter.opcodes.AbstractOpcode; import ai.timefold.jpyinterpreter.types.BuiltinTypes; import ai.timefold.jpyinterpreter.types.PythonLikeFunction; public class BeforeWithOpcode extends AbstractOpcode { public BeforeWithOpcode(PythonBytecodeInstruction instruction) { super(instruction); } @Override protected StackMetadata getStackMetadataAfterInstruction(FunctionMetadata functionMetadata, StackMetadata stackMetadata) { return stackMetadata .pop() .push(ValueSourceInfo.of(this, PythonLikeFunction.getFunctionType(), stackMetadata.getTOSValueSource())) .push(ValueSourceInfo.of(this, BuiltinTypes.BASE_TYPE, stackMetadata.getTOSValueSource())); } @Override public void implement(FunctionMetadata functionMetadata, StackMetadata stackMetadata) { ExceptionImplementor.beforeWith(functionMetadata, stackMetadata); } }
0
java-sources/ai/timefold/solver/jpyinterpreter/1.24.0/ai/timefold/jpyinterpreter/opcodes
java-sources/ai/timefold/solver/jpyinterpreter/1.24.0/ai/timefold/jpyinterpreter/opcodes/exceptions/CheckExcMatchOpcode.java
package ai.timefold.jpyinterpreter.opcodes.exceptions; import ai.timefold.jpyinterpreter.FunctionMetadata; import ai.timefold.jpyinterpreter.PythonBytecodeInstruction; import ai.timefold.jpyinterpreter.StackMetadata; import ai.timefold.jpyinterpreter.ValueSourceInfo; import ai.timefold.jpyinterpreter.implementors.ExceptionImplementor; import ai.timefold.jpyinterpreter.opcodes.AbstractOpcode; import ai.timefold.jpyinterpreter.types.BuiltinTypes; public class CheckExcMatchOpcode extends AbstractOpcode { public CheckExcMatchOpcode(PythonBytecodeInstruction instruction) { super(instruction); } @Override protected StackMetadata getStackMetadataAfterInstruction(FunctionMetadata functionMetadata, StackMetadata stackMetadata) { return stackMetadata .pop() .push(ValueSourceInfo.of(this, BuiltinTypes.BOOLEAN_TYPE, stackMetadata.getValueSourcesUpToStackIndex(2))); } @Override public void implement(FunctionMetadata functionMetadata, StackMetadata stackMetadata) { ExceptionImplementor.checkExcMatch(functionMetadata, stackMetadata); } }
0
java-sources/ai/timefold/solver/jpyinterpreter/1.24.0/ai/timefold/jpyinterpreter/opcodes
java-sources/ai/timefold/solver/jpyinterpreter/1.24.0/ai/timefold/jpyinterpreter/opcodes/exceptions/CleanupThrowOpcode.java
package ai.timefold.jpyinterpreter.opcodes.exceptions; import ai.timefold.jpyinterpreter.FunctionMetadata; import ai.timefold.jpyinterpreter.PythonBytecodeInstruction; import ai.timefold.jpyinterpreter.StackMetadata; import ai.timefold.jpyinterpreter.ValueSourceInfo; import ai.timefold.jpyinterpreter.implementors.ExceptionImplementor; import ai.timefold.jpyinterpreter.opcodes.AbstractOpcode; import ai.timefold.jpyinterpreter.types.BuiltinTypes; import org.objectweb.asm.Opcodes; public class CleanupThrowOpcode extends AbstractOpcode { public CleanupThrowOpcode(PythonBytecodeInstruction instruction) { super(instruction); } @Override protected StackMetadata getStackMetadataAfterInstruction(FunctionMetadata functionMetadata, StackMetadata stackMetadata) { return stackMetadata.pop(3).push(ValueSourceInfo.of(this, BuiltinTypes.BASE_TYPE, stackMetadata.getTOSValueSource())); } @Override public void implement(FunctionMetadata functionMetadata, StackMetadata stackMetadata) { ExceptionImplementor.getValueFromStopIterationOrReraise(functionMetadata, stackMetadata); var methodVisitor = functionMetadata.methodVisitor; methodVisitor.visitInsn(Opcodes.DUP_X2); methodVisitor.visitInsn(Opcodes.POP2); } }
0
java-sources/ai/timefold/solver/jpyinterpreter/1.24.0/ai/timefold/jpyinterpreter/opcodes
java-sources/ai/timefold/solver/jpyinterpreter/1.24.0/ai/timefold/jpyinterpreter/opcodes/exceptions/LoadAssertionErrorOpcode.java
package ai.timefold.jpyinterpreter.opcodes.exceptions; import ai.timefold.jpyinterpreter.FunctionMetadata; import ai.timefold.jpyinterpreter.PythonBytecodeInstruction; import ai.timefold.jpyinterpreter.StackMetadata; import ai.timefold.jpyinterpreter.ValueSourceInfo; import ai.timefold.jpyinterpreter.implementors.ExceptionImplementor; import ai.timefold.jpyinterpreter.opcodes.AbstractOpcode; import ai.timefold.jpyinterpreter.types.errors.PythonAssertionError; public class LoadAssertionErrorOpcode extends AbstractOpcode { public LoadAssertionErrorOpcode(PythonBytecodeInstruction instruction) { super(instruction); } @Override protected StackMetadata getStackMetadataAfterInstruction(FunctionMetadata functionMetadata, StackMetadata stackMetadata) { return stackMetadata.push(ValueSourceInfo.of(this, PythonAssertionError.ASSERTION_ERROR_TYPE)); } @Override public void implement(FunctionMetadata functionMetadata, StackMetadata stackMetadata) { ExceptionImplementor.createAssertionError(functionMetadata.methodVisitor); } }
0
java-sources/ai/timefold/solver/jpyinterpreter/1.24.0/ai/timefold/jpyinterpreter/opcodes
java-sources/ai/timefold/solver/jpyinterpreter/1.24.0/ai/timefold/jpyinterpreter/opcodes/exceptions/PopBlockOpcode.java
package ai.timefold.jpyinterpreter.opcodes.exceptions; import ai.timefold.jpyinterpreter.FunctionMetadata; import ai.timefold.jpyinterpreter.PythonBytecodeInstruction; import ai.timefold.jpyinterpreter.StackMetadata; import ai.timefold.jpyinterpreter.opcodes.AbstractOpcode; public class PopBlockOpcode extends AbstractOpcode { public PopBlockOpcode(PythonBytecodeInstruction instruction) { super(instruction); } @Override protected StackMetadata getStackMetadataAfterInstruction(FunctionMetadata functionMetadata, StackMetadata stackMetadata) { return stackMetadata.copy(); } @Override public void implement(FunctionMetadata functionMetadata, StackMetadata stackMetadata) { // Pop block has a stack effect of 0 (does nothing); ASM take care of popping blocks for us via computeFrames } }
0
java-sources/ai/timefold/solver/jpyinterpreter/1.24.0/ai/timefold/jpyinterpreter/opcodes
java-sources/ai/timefold/solver/jpyinterpreter/1.24.0/ai/timefold/jpyinterpreter/opcodes/exceptions/PopExceptOpcode.java
package ai.timefold.jpyinterpreter.opcodes.exceptions; import ai.timefold.jpyinterpreter.FunctionMetadata; import ai.timefold.jpyinterpreter.PythonBytecodeInstruction; import ai.timefold.jpyinterpreter.PythonVersion; import ai.timefold.jpyinterpreter.StackMetadata; import ai.timefold.jpyinterpreter.implementors.ExceptionImplementor; import ai.timefold.jpyinterpreter.opcodes.AbstractOpcode; public class PopExceptOpcode extends AbstractOpcode { public PopExceptOpcode(PythonBytecodeInstruction instruction) { super(instruction); } @Override protected StackMetadata getStackMetadataAfterInstruction(FunctionMetadata functionMetadata, StackMetadata stackMetadata) { if (functionMetadata.pythonCompiledFunction.pythonVersion.isAtLeast(PythonVersion.PYTHON_3_11)) { return stackMetadata.pop(1); } else { return stackMetadata.pop(3); } } @Override public void implement(FunctionMetadata functionMetadata, StackMetadata stackMetadata) { ExceptionImplementor.startExceptOrFinally(functionMetadata, stackMetadata); } }
0
java-sources/ai/timefold/solver/jpyinterpreter/1.24.0/ai/timefold/jpyinterpreter/opcodes
java-sources/ai/timefold/solver/jpyinterpreter/1.24.0/ai/timefold/jpyinterpreter/opcodes/exceptions/PushExcInfoOpcode.java
package ai.timefold.jpyinterpreter.opcodes.exceptions; import ai.timefold.jpyinterpreter.FunctionMetadata; import ai.timefold.jpyinterpreter.PythonBytecodeInstruction; import ai.timefold.jpyinterpreter.StackMetadata; import ai.timefold.jpyinterpreter.ValueSourceInfo; import ai.timefold.jpyinterpreter.implementors.ExceptionImplementor; import ai.timefold.jpyinterpreter.opcodes.AbstractOpcode; import ai.timefold.jpyinterpreter.types.errors.PythonBaseException; public class PushExcInfoOpcode extends AbstractOpcode { public PushExcInfoOpcode(PythonBytecodeInstruction instruction) { super(instruction); } @Override protected StackMetadata getStackMetadataAfterInstruction(FunctionMetadata functionMetadata, StackMetadata stackMetadata) { return stackMetadata .pop() .push(ValueSourceInfo.of(this, PythonBaseException.BASE_EXCEPTION_TYPE)) .push(stackMetadata.getTOSValueSource()); } @Override public void implement(FunctionMetadata functionMetadata, StackMetadata stackMetadata) { ExceptionImplementor.pushExcInfo(functionMetadata, stackMetadata); } }
0
java-sources/ai/timefold/solver/jpyinterpreter/1.24.0/ai/timefold/jpyinterpreter/opcodes
java-sources/ai/timefold/solver/jpyinterpreter/1.24.0/ai/timefold/jpyinterpreter/opcodes/exceptions/RaiseVarargsOpcode.java
package ai.timefold.jpyinterpreter.opcodes.exceptions; import java.util.Collections; import java.util.List; import ai.timefold.jpyinterpreter.FunctionMetadata; import ai.timefold.jpyinterpreter.PythonBytecodeInstruction; import ai.timefold.jpyinterpreter.StackMetadata; import ai.timefold.jpyinterpreter.implementors.ExceptionImplementor; import ai.timefold.jpyinterpreter.opcodes.controlflow.AbstractControlFlowOpcode; public class RaiseVarargsOpcode extends AbstractControlFlowOpcode { public RaiseVarargsOpcode(PythonBytecodeInstruction instruction) { super(instruction); } @Override public List<Integer> getPossibleNextBytecodeIndexList() { return Collections.emptyList(); } @Override public List<StackMetadata> getStackMetadataAfterInstructionForBranches(FunctionMetadata functionMetadata, StackMetadata stackMetadata) { return Collections.emptyList(); } @Override public boolean isForcedJump() { return true; } @Override public void implement(FunctionMetadata functionMetadata, StackMetadata stackMetadata) { ExceptionImplementor.raiseWithOptionalExceptionAndCause(functionMetadata.methodVisitor, instruction, stackMetadata.localVariableHelper); } }
0
java-sources/ai/timefold/solver/jpyinterpreter/1.24.0/ai/timefold/jpyinterpreter/opcodes
java-sources/ai/timefold/solver/jpyinterpreter/1.24.0/ai/timefold/jpyinterpreter/opcodes/exceptions/ReraiseOpcode.java
package ai.timefold.jpyinterpreter.opcodes.exceptions; import java.util.Collections; import java.util.List; import ai.timefold.jpyinterpreter.FunctionMetadata; import ai.timefold.jpyinterpreter.PythonBytecodeInstruction; import ai.timefold.jpyinterpreter.StackMetadata; import ai.timefold.jpyinterpreter.implementors.ExceptionImplementor; import ai.timefold.jpyinterpreter.opcodes.controlflow.AbstractControlFlowOpcode; public class ReraiseOpcode extends AbstractControlFlowOpcode { public ReraiseOpcode(PythonBytecodeInstruction instruction) { super(instruction); } @Override public List<Integer> getPossibleNextBytecodeIndexList() { return Collections.emptyList(); } @Override public List<StackMetadata> getStackMetadataAfterInstructionForBranches(FunctionMetadata functionMetadata, StackMetadata stackMetadata) { return Collections.emptyList(); } @Override public boolean isForcedJump() { return true; } @Override public void implement(FunctionMetadata functionMetadata, StackMetadata stackMetadata) { ExceptionImplementor.reraise(functionMetadata.methodVisitor); } }
0
java-sources/ai/timefold/solver/jpyinterpreter/1.24.0/ai/timefold/jpyinterpreter/opcodes
java-sources/ai/timefold/solver/jpyinterpreter/1.24.0/ai/timefold/jpyinterpreter/opcodes/exceptions/SetupFinallyOpcode.java
package ai.timefold.jpyinterpreter.opcodes.exceptions; import java.util.ArrayList; import java.util.List; import ai.timefold.jpyinterpreter.FunctionMetadata; import ai.timefold.jpyinterpreter.PythonBytecodeInstruction; import ai.timefold.jpyinterpreter.StackMetadata; import ai.timefold.jpyinterpreter.implementors.ExceptionImplementor; import ai.timefold.jpyinterpreter.opcodes.controlflow.AbstractControlFlowOpcode; import ai.timefold.jpyinterpreter.types.BuiltinTypes; import ai.timefold.jpyinterpreter.types.errors.PythonBaseException; import ai.timefold.jpyinterpreter.types.errors.PythonTraceback; public class SetupFinallyOpcode extends AbstractControlFlowOpcode { int jumpTarget; public SetupFinallyOpcode(PythonBytecodeInstruction instruction, int jumpTarget) { super(instruction); this.jumpTarget = jumpTarget; } @Override public List<Integer> getPossibleNextBytecodeIndexList() { return List.of(getBytecodeIndex() + 1, jumpTarget); } @Override public List<StackMetadata> getStackMetadataAfterInstructionForBranches(FunctionMetadata functionMetadata, StackMetadata stackMetadata) { return List.of(stackMetadata.copy(), stackMetadata.copy() .pushTemp(BuiltinTypes.NONE_TYPE) .pushTemp(BuiltinTypes.INT_TYPE) .pushTemp(BuiltinTypes.NONE_TYPE) .pushTemp(PythonTraceback.TRACEBACK_TYPE) .pushTemp(PythonBaseException.BASE_EXCEPTION_TYPE) .pushTemp(PythonBaseException.BASE_EXCEPTION_TYPE)); } @Override public void implement(FunctionMetadata functionMetadata, StackMetadata stackMetadata) { ExceptionImplementor.createTryFinallyBlock(functionMetadata, stackMetadata, jumpTarget, functionMetadata.bytecodeCounterToLabelMap, (bytecodeIndex, runnable) -> { functionMetadata.bytecodeCounterToCodeArgumenterList .computeIfAbsent(bytecodeIndex, key -> new ArrayList<>()).add(runnable); }); } }
0
java-sources/ai/timefold/solver/jpyinterpreter/1.24.0/ai/timefold/jpyinterpreter/opcodes
java-sources/ai/timefold/solver/jpyinterpreter/1.24.0/ai/timefold/jpyinterpreter/opcodes/exceptions/SetupWithOpcode.java
package ai.timefold.jpyinterpreter.opcodes.exceptions; import java.util.List; import ai.timefold.jpyinterpreter.FunctionMetadata; import ai.timefold.jpyinterpreter.PythonBytecodeInstruction; import ai.timefold.jpyinterpreter.StackMetadata; import ai.timefold.jpyinterpreter.ValueSourceInfo; import ai.timefold.jpyinterpreter.implementors.ExceptionImplementor; import ai.timefold.jpyinterpreter.opcodes.controlflow.AbstractControlFlowOpcode; import ai.timefold.jpyinterpreter.types.BuiltinTypes; import ai.timefold.jpyinterpreter.types.PythonLikeFunction; import ai.timefold.jpyinterpreter.types.errors.PythonBaseException; import ai.timefold.jpyinterpreter.types.errors.PythonTraceback; public class SetupWithOpcode extends AbstractControlFlowOpcode { int jumpTarget; public SetupWithOpcode(PythonBytecodeInstruction instruction, int jumpTarget) { super(instruction); this.jumpTarget = jumpTarget; } @Override public List<Integer> getPossibleNextBytecodeIndexList() { return List.of( getBytecodeIndex() + 1, jumpTarget); } @Override public List<StackMetadata> getStackMetadataAfterInstructionForBranches(FunctionMetadata functionMetadata, StackMetadata stackMetadata) { return List.of( stackMetadata .pop() .push(ValueSourceInfo.of(this, PythonLikeFunction.getFunctionType(), stackMetadata.getTOSValueSource())) .push(ValueSourceInfo.of(this, BuiltinTypes.BASE_TYPE, stackMetadata.getTOSValueSource())), stackMetadata .pop() .push(ValueSourceInfo.of(this, PythonLikeFunction.getFunctionType(), stackMetadata.getTOSValueSource())) .pushTemp(BuiltinTypes.NONE_TYPE) .pushTemp(BuiltinTypes.INT_TYPE) .pushTemp(BuiltinTypes.NONE_TYPE) .pushTemp(PythonTraceback.TRACEBACK_TYPE) .pushTemp(PythonBaseException.BASE_EXCEPTION_TYPE) .pushTemp(BuiltinTypes.TYPE_TYPE)); } @Override public void implement(FunctionMetadata functionMetadata, StackMetadata stackMetadata) { ExceptionImplementor.setupWith(jumpTarget, functionMetadata, stackMetadata); } }
0
java-sources/ai/timefold/solver/jpyinterpreter/1.24.0/ai/timefold/jpyinterpreter/opcodes
java-sources/ai/timefold/solver/jpyinterpreter/1.24.0/ai/timefold/jpyinterpreter/opcodes/exceptions/WithExceptStartOpcode.java
package ai.timefold.jpyinterpreter.opcodes.exceptions; import ai.timefold.jpyinterpreter.FunctionMetadata; import ai.timefold.jpyinterpreter.PythonBytecodeInstruction; import ai.timefold.jpyinterpreter.PythonVersion; import ai.timefold.jpyinterpreter.StackMetadata; import ai.timefold.jpyinterpreter.ValueSourceInfo; import ai.timefold.jpyinterpreter.implementors.ExceptionImplementor; import ai.timefold.jpyinterpreter.opcodes.AbstractOpcode; import ai.timefold.jpyinterpreter.types.BuiltinTypes; public class WithExceptStartOpcode extends AbstractOpcode { public WithExceptStartOpcode(PythonBytecodeInstruction instruction) { super(instruction); } @Override protected StackMetadata getStackMetadataAfterInstruction(FunctionMetadata functionMetadata, StackMetadata stackMetadata) { if (functionMetadata.pythonCompiledFunction.pythonVersion.isAtLeast(PythonVersion.PYTHON_3_11)) { return stackMetadata .push(ValueSourceInfo.of(this, BuiltinTypes.BASE_TYPE, stackMetadata.getValueSourceForStackIndex(1))); } return stackMetadata .push(ValueSourceInfo.of(this, BuiltinTypes.BASE_TYPE, stackMetadata.getValueSourceForStackIndex(6))); } @Override public void implement(FunctionMetadata functionMetadata, StackMetadata stackMetadata) { ExceptionImplementor.handleExceptionInWith(functionMetadata, stackMetadata); } }
0
java-sources/ai/timefold/solver/jpyinterpreter/1.24.0/ai/timefold/jpyinterpreter/opcodes
java-sources/ai/timefold/solver/jpyinterpreter/1.24.0/ai/timefold/jpyinterpreter/opcodes/function/CallFunctionKeywordOpcode.java
package ai.timefold.jpyinterpreter.opcodes.function; import ai.timefold.jpyinterpreter.FunctionMetadata; import ai.timefold.jpyinterpreter.PythonBytecodeInstruction; import ai.timefold.jpyinterpreter.StackMetadata; import ai.timefold.jpyinterpreter.ValueSourceInfo; import ai.timefold.jpyinterpreter.implementors.FunctionImplementor; import ai.timefold.jpyinterpreter.opcodes.AbstractOpcode; import ai.timefold.jpyinterpreter.types.BuiltinTypes; import ai.timefold.jpyinterpreter.types.PythonKnownFunctionType; import ai.timefold.jpyinterpreter.types.PythonLikeGenericType; import ai.timefold.jpyinterpreter.types.PythonLikeType; public class CallFunctionKeywordOpcode extends AbstractOpcode { public CallFunctionKeywordOpcode(PythonBytecodeInstruction instruction) { super(instruction); } @Override protected StackMetadata getStackMetadataAfterInstruction(FunctionMetadata functionMetadata, StackMetadata stackMetadata) { PythonLikeType functionType = stackMetadata.getTypeAtStackIndex(instruction.arg() + 1); if (functionType instanceof PythonLikeGenericType) { functionType = ((PythonLikeGenericType) functionType).getOrigin().getConstructorType().orElse(null); } if (functionType instanceof PythonKnownFunctionType) { PythonKnownFunctionType knownFunctionType = (PythonKnownFunctionType) functionType; return knownFunctionType.getDefaultFunctionSignature() .map(functionSignature -> stackMetadata.pop(instruction.arg() + 2).push(ValueSourceInfo.of(this, functionSignature.getReturnType(), stackMetadata.getValueSourcesUpToStackIndex(instruction.arg() + 2)))) .orElseGet(() -> stackMetadata.pop(instruction.arg() + 2) .push(ValueSourceInfo.of(this, BuiltinTypes.BASE_TYPE, stackMetadata.getValueSourcesUpToStackIndex(instruction.arg() + 2)))); } return stackMetadata.pop(instruction.arg() + 2).push(ValueSourceInfo.of(this, BuiltinTypes.BASE_TYPE, stackMetadata.getValueSourcesUpToStackIndex(instruction.arg() + 2))); } @Override public void implement(FunctionMetadata functionMetadata, StackMetadata stackMetadata) { FunctionImplementor.callFunctionWithKeywords(functionMetadata, stackMetadata, functionMetadata.methodVisitor, instruction); } }
0
java-sources/ai/timefold/solver/jpyinterpreter/1.24.0/ai/timefold/jpyinterpreter/opcodes
java-sources/ai/timefold/solver/jpyinterpreter/1.24.0/ai/timefold/jpyinterpreter/opcodes/function/CallFunctionOpcode.java
package ai.timefold.jpyinterpreter.opcodes.function; import ai.timefold.jpyinterpreter.FunctionMetadata; import ai.timefold.jpyinterpreter.PythonBytecodeInstruction; import ai.timefold.jpyinterpreter.StackMetadata; import ai.timefold.jpyinterpreter.ValueSourceInfo; import ai.timefold.jpyinterpreter.implementors.FunctionImplementor; import ai.timefold.jpyinterpreter.opcodes.AbstractOpcode; import ai.timefold.jpyinterpreter.types.BuiltinTypes; import ai.timefold.jpyinterpreter.types.PythonKnownFunctionType; import ai.timefold.jpyinterpreter.types.PythonLikeGenericType; import ai.timefold.jpyinterpreter.types.PythonLikeType; public class CallFunctionOpcode extends AbstractOpcode { public CallFunctionOpcode(PythonBytecodeInstruction instruction) { super(instruction); } @Override protected StackMetadata getStackMetadataAfterInstruction(FunctionMetadata functionMetadata, StackMetadata stackMetadata) { PythonLikeType functionType = stackMetadata.getTypeAtStackIndex(instruction.arg()); if (functionType instanceof PythonLikeGenericType) { functionType = ((PythonLikeGenericType) functionType).getOrigin().getConstructorType().orElse(null); } if (functionType instanceof PythonKnownFunctionType) { PythonKnownFunctionType knownFunctionType = (PythonKnownFunctionType) functionType; return knownFunctionType.getDefaultFunctionSignature() .map(functionSignature -> stackMetadata.pop(instruction.arg() + 1).push(ValueSourceInfo.of(this, functionSignature.getReturnType(), stackMetadata.getValueSourcesUpToStackIndex(instruction.arg() + 1)))) .orElseGet(() -> stackMetadata.pop(instruction.arg() + 1) .push(ValueSourceInfo.of(this, BuiltinTypes.BASE_TYPE, stackMetadata.getValueSourcesUpToStackIndex(instruction.arg() + 1)))); } return stackMetadata.pop(instruction.arg() + 1).push(ValueSourceInfo.of(this, BuiltinTypes.BASE_TYPE, stackMetadata.getValueSourcesUpToStackIndex(instruction.arg() + 1))); } @Override public void implement(FunctionMetadata functionMetadata, StackMetadata stackMetadata) { FunctionImplementor.callFunction(functionMetadata, stackMetadata, functionMetadata.methodVisitor, instruction); } }
0
java-sources/ai/timefold/solver/jpyinterpreter/1.24.0/ai/timefold/jpyinterpreter/opcodes
java-sources/ai/timefold/solver/jpyinterpreter/1.24.0/ai/timefold/jpyinterpreter/opcodes/function/CallFunctionUnpackOpcode.java
package ai.timefold.jpyinterpreter.opcodes.function; import ai.timefold.jpyinterpreter.FunctionMetadata; import ai.timefold.jpyinterpreter.PythonBytecodeInstruction; import ai.timefold.jpyinterpreter.PythonVersion; import ai.timefold.jpyinterpreter.StackMetadata; import ai.timefold.jpyinterpreter.ValueSourceInfo; import ai.timefold.jpyinterpreter.implementors.FunctionImplementor; import ai.timefold.jpyinterpreter.opcodes.AbstractOpcode; import ai.timefold.jpyinterpreter.types.BuiltinTypes; public class CallFunctionUnpackOpcode extends AbstractOpcode { public CallFunctionUnpackOpcode(PythonBytecodeInstruction instruction) { super(instruction); } @Override protected StackMetadata getStackMetadataAfterInstruction(FunctionMetadata functionMetadata, StackMetadata stackMetadata) { if (functionMetadata.pythonCompiledFunction.pythonVersion.isBefore(PythonVersion.PYTHON_3_11)) { if ((instruction.arg() & 1) == 1) { // Stack is callable, iterable, map return stackMetadata.pop(3).push(ValueSourceInfo.of(this, BuiltinTypes.BASE_TYPE, stackMetadata.getValueSourcesUpToStackIndex(3))); } else { // Stack is callable, iterable return stackMetadata.pop(2).push(ValueSourceInfo.of(this, BuiltinTypes.BASE_TYPE, stackMetadata.getValueSourcesUpToStackIndex(2))); } } else { if ((instruction.arg() & 1) == 1) { // Stack is null, callable, iterable, map return stackMetadata.pop(4).push(ValueSourceInfo.of(this, BuiltinTypes.BASE_TYPE, stackMetadata.getValueSourcesUpToStackIndex(3))); } else { // Stack is null, callable, iterable return stackMetadata.pop(3).push(ValueSourceInfo.of(this, BuiltinTypes.BASE_TYPE, stackMetadata.getValueSourcesUpToStackIndex(2))); } } } @Override public void implement(FunctionMetadata functionMetadata, StackMetadata stackMetadata) { FunctionImplementor.callFunctionUnpack(functionMetadata, stackMetadata, instruction); } }