index
int64
repo_id
string
file_path
string
content
string
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/CallMethodOpcode.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.PythonLikeType; public class CallMethodOpcode extends AbstractOpcode { public CallMethodOpcode(PythonBytecodeInstruction instruction) { super(instruction); } @Override protected StackMetadata getStackMetadataAfterInstruction(FunctionMetadata functionMetadata, StackMetadata stackMetadata) { 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); } return knownFunctionType.getFunctionForParameters(parameterTypes) .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.callMethod(functionMetadata, stackMetadata, 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/function/CallOpcode.java
package ai.timefold.jpyinterpreter.opcodes.function; import java.util.Collections; import java.util.List; import java.util.stream.Collectors; 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 CallOpcode extends AbstractOpcode { public CallOpcode(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; List<String> keywordArgumentNameList = stackMetadata.getCallKeywordNameList(); List<PythonLikeType> callStackParameterTypes = stackMetadata.getValueSourcesUpToStackIndex(instruction.arg()) .stream().map(ValueSourceInfo::getValueType).collect(Collectors.toList()); return knownFunctionType.getFunctionForParameters(instruction.arg() - keywordArgumentNameList.size(), keywordArgumentNameList, callStackParameterTypes) .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)))) .setCallKeywordNameList(Collections.emptyList()); } functionType = stackMetadata.getTypeAtStackIndex(instruction.arg()); 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(instruction.arg()) .stream().map(ValueSourceInfo::getValueType).collect(Collectors.toList()); return knownFunctionType.getFunctionForParameters(instruction.arg() - keywordArgumentNameList.size(), keywordArgumentNameList, callStackParameterTypes) .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)))) .setCallKeywordNameList(Collections.emptyList()); } return stackMetadata.pop(instruction.arg() + 2).push(ValueSourceInfo.of(this, BuiltinTypes.BASE_TYPE, stackMetadata.getValueSourcesUpToStackIndex(instruction.arg() + 2))) .setCallKeywordNameList(Collections.emptyList()); } @Override public void implement(FunctionMetadata functionMetadata, StackMetadata stackMetadata) { FunctionImplementor.call(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/function/LoadMethodOpcode.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.PythonLikeFunction; import ai.timefold.jpyinterpreter.types.PythonLikeGenericType; import ai.timefold.jpyinterpreter.types.PythonLikeType; public class LoadMethodOpcode extends AbstractOpcode { public LoadMethodOpcode(PythonBytecodeInstruction instruction) { super(instruction); } @Override protected StackMetadata getStackMetadataAfterInstruction(FunctionMetadata functionMetadata, StackMetadata stackMetadata) { PythonLikeType stackTosType = stackMetadata.getTOSType(); PythonLikeType tosType; if (stackTosType instanceof PythonLikeGenericType) { tosType = ((PythonLikeGenericType) stackTosType).getOrigin(); } else { tosType = stackTosType; } return tosType.getMethodType(functionMetadata.pythonCompiledFunction.co_names.get(instruction.arg())) .map(knownFunction -> stackMetadata.pop() .push(ValueSourceInfo.of(this, knownFunction, stackMetadata.getValueSourcesUpToStackIndex(1))) .push(ValueSourceInfo.of(this, tosType, stackMetadata.getValueSourcesUpToStackIndex(1))) // TOS, since we know the function exists ) .orElseGet(() -> stackMetadata.pop() .push(ValueSourceInfo.of(this, PythonLikeFunction.getFunctionType(), stackMetadata.getValueSourcesUpToStackIndex(1))) .push(ValueSourceInfo.of(this, BuiltinTypes.NULL_TYPE, stackMetadata.getValueSourcesUpToStackIndex(1)))); // either TOS or NULL } @Override public void implement(FunctionMetadata functionMetadata, StackMetadata stackMetadata) { FunctionImplementor.loadMethod(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/function/MakeFunctionOpcode.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.PythonLikeFunction; public class MakeFunctionOpcode extends AbstractOpcode { public MakeFunctionOpcode(PythonBytecodeInstruction instruction) { super(instruction); } @Override protected StackMetadata getStackMetadataAfterInstruction(FunctionMetadata functionMetadata, StackMetadata stackMetadata) { int stackElements = (functionMetadata.pythonCompiledFunction.pythonVersion.isAtLeast(PythonVersion.PYTHON_3_11)) ? 1 : 2; return stackMetadata.pop(stackElements + Integer.bitCount(instruction.arg())) .push(ValueSourceInfo.of(this, PythonLikeFunction.getFunctionType(), stackMetadata.getValueSourcesUpToStackIndex(stackElements + Integer.bitCount(instruction.arg())))); } @Override public void implement(FunctionMetadata functionMetadata, StackMetadata stackMetadata) { FunctionImplementor.createFunction(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/function/PushNullOpcode.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.opcodes.AbstractOpcode; import ai.timefold.jpyinterpreter.types.BuiltinTypes; import org.objectweb.asm.Opcodes; public class PushNullOpcode extends AbstractOpcode { public PushNullOpcode(PythonBytecodeInstruction instruction) { super(instruction); } @Override public StackMetadata getStackMetadataAfterInstruction(FunctionMetadata functionMetadata, StackMetadata stackMetadata) { return stackMetadata.push(ValueSourceInfo.of(this, BuiltinTypes.BASE_TYPE)); } @Override public void implement(FunctionMetadata functionMetadata, StackMetadata stackMetadata) { functionMetadata.methodVisitor.visitInsn(Opcodes.ACONST_NULL); } }
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/SetCallKeywordNameTupleOpcode.java
package ai.timefold.jpyinterpreter.opcodes.function; import java.util.List; import java.util.stream.Collectors; import ai.timefold.jpyinterpreter.FunctionMetadata; import ai.timefold.jpyinterpreter.PythonBytecodeInstruction; import ai.timefold.jpyinterpreter.StackMetadata; import ai.timefold.jpyinterpreter.implementors.FunctionImplementor; import ai.timefold.jpyinterpreter.opcodes.AbstractOpcode; import ai.timefold.jpyinterpreter.types.PythonString; public class SetCallKeywordNameTupleOpcode extends AbstractOpcode { public SetCallKeywordNameTupleOpcode(PythonBytecodeInstruction instruction) { super(instruction); } @Override public StackMetadata getStackMetadataAfterInstruction(FunctionMetadata functionMetadata, StackMetadata stackMetadata) { return stackMetadata.setCallKeywordNameList( ((List<PythonString>) functionMetadata.pythonCompiledFunction.co_constants.get(instruction.arg())) .stream().map(PythonString::getValue).collect(Collectors.toList())); } @Override public void implement(FunctionMetadata functionMetadata, StackMetadata stackMetadata) { FunctionImplementor.setCallKeywordNameTuple(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/generator/GeneratorStartOpcode.java
package ai.timefold.jpyinterpreter.opcodes.generator; import ai.timefold.jpyinterpreter.FunctionMetadata; import ai.timefold.jpyinterpreter.PythonBytecodeInstruction; import ai.timefold.jpyinterpreter.StackMetadata; import ai.timefold.jpyinterpreter.implementors.GeneratorImplementor; import ai.timefold.jpyinterpreter.opcodes.AbstractOpcode; public class GeneratorStartOpcode extends AbstractOpcode { public GeneratorStartOpcode(PythonBytecodeInstruction instruction) { super(instruction); } @Override protected StackMetadata getStackMetadataAfterInstruction(FunctionMetadata functionMetadata, StackMetadata stackMetadata) { return stackMetadata; } @Override public void implement(FunctionMetadata functionMetadata, StackMetadata stackMetadata) { GeneratorImplementor.generatorStart(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/generator/GetYieldFromIterOpcode.java
package ai.timefold.jpyinterpreter.opcodes.generator; 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.GeneratorImplementor; import ai.timefold.jpyinterpreter.opcodes.AbstractOpcode; import ai.timefold.jpyinterpreter.types.BuiltinTypes; public class GetYieldFromIterOpcode extends AbstractOpcode { public GetYieldFromIterOpcode(PythonBytecodeInstruction instruction) { super(instruction); } @Override protected StackMetadata getStackMetadataAfterInstruction(FunctionMetadata functionMetadata, StackMetadata stackMetadata) { return stackMetadata.pop().push(ValueSourceInfo.of(this, BuiltinTypes.BASE_TYPE)); } @Override public void implement(FunctionMetadata functionMetadata, StackMetadata stackMetadata) { GeneratorImplementor.getYieldFromIter(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/generator/ResumeOpcode.java
package ai.timefold.jpyinterpreter.opcodes.generator; import ai.timefold.jpyinterpreter.FunctionMetadata; import ai.timefold.jpyinterpreter.PythonBytecodeInstruction; import ai.timefold.jpyinterpreter.StackMetadata; import ai.timefold.jpyinterpreter.opcodes.AbstractOpcode; import org.objectweb.asm.Opcodes; public class ResumeOpcode extends AbstractOpcode { public ResumeOpcode(PythonBytecodeInstruction instruction) { super(instruction); } public static ResumeType getResumeType(int arg) { switch (arg) { case 0: return ResumeType.START; case 1: return ResumeType.YIELD; case 2: return ResumeType.YIELD_FROM; case 3: return ResumeType.AWAIT; default: throw new IllegalArgumentException("Invalid RESUME opcode argument: " + arg); } } public ResumeType getResumeType() { return getResumeType(instruction.arg()); } @Override public StackMetadata getStackMetadataAfterInstruction(FunctionMetadata functionMetadata, StackMetadata stackMetadata) { return stackMetadata.copy(); } @Override public void implement(FunctionMetadata functionMetadata, StackMetadata stackMetadata) { functionMetadata.methodVisitor.visitInsn(Opcodes.NOP); } public enum ResumeType { START, YIELD, YIELD_FROM, AWAIT } }
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/generator/SendOpcode.java
package ai.timefold.jpyinterpreter.opcodes.generator; 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.GeneratorImplementor; import ai.timefold.jpyinterpreter.opcodes.controlflow.AbstractControlFlowOpcode; import ai.timefold.jpyinterpreter.types.BuiltinTypes; public class SendOpcode extends AbstractControlFlowOpcode { int jumpTarget; public SendOpcode(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, BuiltinTypes.BASE_TYPE, stackMetadata.getValueSourcesUpToStackIndex(2))), stackMetadata.pop()); } @Override public void implement(FunctionMetadata functionMetadata, StackMetadata stackMetadata) { GeneratorImplementor.progressSubgenerator(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/generator/StopIteratorErrorOpcode.java
package ai.timefold.jpyinterpreter.opcodes.generator; 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 StopIteratorErrorOpcode extends AbstractOpcode { public StopIteratorErrorOpcode(PythonBytecodeInstruction instruction) { super(instruction); } @Override protected StackMetadata getStackMetadataAfterInstruction(FunctionMetadata functionMetadata, StackMetadata stackMetadata) { return stackMetadata.pop().push(ValueSourceInfo.of(this, BuiltinTypes.BASE_TYPE, stackMetadata.getTOSValueSource())); } @Override public void implement(FunctionMetadata functionMetadata, StackMetadata stackMetadata) { ExceptionImplementor.getValueFromStopIterationOrReraise(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/generator/YieldFromOpcode.java
package ai.timefold.jpyinterpreter.opcodes.generator; 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.GeneratorImplementor; import ai.timefold.jpyinterpreter.opcodes.AbstractOpcode; import ai.timefold.jpyinterpreter.types.BuiltinTypes; public class YieldFromOpcode extends AbstractOpcode { public YieldFromOpcode(PythonBytecodeInstruction instruction) { super(instruction); } @Override protected StackMetadata getStackMetadataAfterInstruction(FunctionMetadata functionMetadata, StackMetadata stackMetadata) { return stackMetadata.pop(2).push(ValueSourceInfo.of(this, BuiltinTypes.BASE_TYPE)); } @Override public void implement(FunctionMetadata functionMetadata, StackMetadata stackMetadata) { GeneratorImplementor.yieldFrom(instruction, 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/generator/YieldValueOpcode.java
package ai.timefold.jpyinterpreter.opcodes.generator; 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.GeneratorImplementor; import ai.timefold.jpyinterpreter.opcodes.AbstractOpcode; import ai.timefold.jpyinterpreter.types.BuiltinTypes; public class YieldValueOpcode extends AbstractOpcode { public YieldValueOpcode(PythonBytecodeInstruction instruction) { super(instruction); } @Override protected StackMetadata getStackMetadataAfterInstruction(FunctionMetadata functionMetadata, StackMetadata stackMetadata) { return stackMetadata.pop().push(ValueSourceInfo.of(this, BuiltinTypes.BASE_TYPE)); } @Override public void implement(FunctionMetadata functionMetadata, StackMetadata stackMetadata) { GeneratorImplementor.yieldValue(instruction, 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/meta/NopOpcode.java
package ai.timefold.jpyinterpreter.opcodes.meta; import ai.timefold.jpyinterpreter.FunctionMetadata; import ai.timefold.jpyinterpreter.PythonBytecodeInstruction; import ai.timefold.jpyinterpreter.StackMetadata; import ai.timefold.jpyinterpreter.opcodes.AbstractOpcode; import org.objectweb.asm.Opcodes; public class NopOpcode extends AbstractOpcode { public NopOpcode(PythonBytecodeInstruction instruction) { super(instruction); } @Override public StackMetadata getStackMetadataAfterInstruction(FunctionMetadata functionMetadata, StackMetadata stackMetadata) { return stackMetadata.copy(); } @Override public void implement(FunctionMetadata functionMetadata, StackMetadata stackMetadata) { functionMetadata.methodVisitor.visitInsn(Opcodes.NOP); } }
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/meta/ReturnGeneratorOpcode.java
package ai.timefold.jpyinterpreter.opcodes.meta; import ai.timefold.jpyinterpreter.FunctionMetadata; import ai.timefold.jpyinterpreter.PythonBytecodeInstruction; import ai.timefold.jpyinterpreter.StackMetadata; import ai.timefold.jpyinterpreter.ValueSourceInfo; import ai.timefold.jpyinterpreter.opcodes.AbstractOpcode; import ai.timefold.jpyinterpreter.types.BuiltinTypes; import org.objectweb.asm.Opcodes; public class ReturnGeneratorOpcode extends AbstractOpcode { public ReturnGeneratorOpcode(PythonBytecodeInstruction instruction) { super(instruction); } @Override public StackMetadata getStackMetadataAfterInstruction(FunctionMetadata functionMetadata, StackMetadata stackMetadata) { // Although this opcode does nothing, it is followed by a POP_TOP, which need something to pop return stackMetadata.push(ValueSourceInfo.of(this, BuiltinTypes.BASE_TYPE)); } @Override public void implement(FunctionMetadata functionMetadata, StackMetadata stackMetadata) { functionMetadata.methodVisitor.visitInsn(Opcodes.ACONST_NULL); } }
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/meta/UnaryIntrinsicFunction.java
package ai.timefold.jpyinterpreter.opcodes.meta; import java.util.function.Function; import ai.timefold.jpyinterpreter.PythonBytecodeInstruction; import ai.timefold.jpyinterpreter.PythonUnaryOperator; import ai.timefold.jpyinterpreter.opcodes.Opcode; import ai.timefold.jpyinterpreter.opcodes.collection.ListToTupleOpcode; import ai.timefold.jpyinterpreter.opcodes.dunder.UniDunerOpcode; import ai.timefold.jpyinterpreter.opcodes.generator.StopIteratorErrorOpcode; public enum UnaryIntrinsicFunction { INTRINSIC_1_INVALID(ignored -> { throw new UnsupportedOperationException("INTRINSIC_1_INVALID"); }), INTRINSIC_PRINT(ignored -> { throw new UnsupportedOperationException("INTRINSIC_PRINT"); }), INTRINSIC_IMPORT_STAR(ignored -> { throw new UnsupportedOperationException("INTRINSIC_IMPORT_STAR"); }), INTRINSIC_STOPITERATION_ERROR(StopIteratorErrorOpcode::new), INTRINSIC_ASYNC_GEN_WRAP(ignored -> { throw new UnsupportedOperationException("INTRINSIC_ASYNC_GEN_WRAP"); }), INTRINSIC_UNARY_POSITIVE(instruction -> new UniDunerOpcode(instruction, PythonUnaryOperator.POSITIVE)), INTRINSIC_LIST_TO_TUPLE(ListToTupleOpcode::new), INTRINSIC_TYPEVAR(ignored -> { throw new UnsupportedOperationException("INTRINSIC_TYPEVAR"); }), INTRINSIC_PARAMSPEC(ignored -> { throw new UnsupportedOperationException("INTRINSIC_PARAMSPEC"); }), INTRINSIC_TYPEVARTUPLE(ignored -> { throw new UnsupportedOperationException("INTRINSIC_TYPEVARTUPLE"); }), INTRINSIC_SUBSCRIPT_GENERIC(ignored -> { throw new UnsupportedOperationException("INTRINSIC_SUBSCRIPT_GENERIC"); }), INTRINSIC_TYPEALIAS(ignored -> { throw new UnsupportedOperationException("INTRINSIC_TYPEALIAS"); }); final Function<PythonBytecodeInstruction, Opcode> opcodeFunction; UnaryIntrinsicFunction(Function<PythonBytecodeInstruction, Opcode> opcodeFunction) { this.opcodeFunction = opcodeFunction; } public Opcode getOpcode(PythonBytecodeInstruction instruction) { return opcodeFunction.apply(instruction); } public static Opcode lookup(PythonBytecodeInstruction instruction) { return UnaryIntrinsicFunction.valueOf(instruction.argRepr()).getOpcode(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/module/ImportFromOpcode.java
package ai.timefold.jpyinterpreter.opcodes.module; 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.ModuleImplementor; import ai.timefold.jpyinterpreter.opcodes.AbstractOpcode; import ai.timefold.jpyinterpreter.types.BuiltinTypes; public class ImportFromOpcode extends AbstractOpcode { public ImportFromOpcode(PythonBytecodeInstruction instruction) { super(instruction); } @Override protected StackMetadata getStackMetadataAfterInstruction(FunctionMetadata functionMetadata, StackMetadata stackMetadata) { return stackMetadata.push(ValueSourceInfo.of(this, BuiltinTypes.BASE_TYPE, stackMetadata.getTOSValueSource())); } @Override public void implement(FunctionMetadata functionMetadata, StackMetadata stackMetadata) { ModuleImplementor.importFrom(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/module/ImportNameOpcode.java
package ai.timefold.jpyinterpreter.opcodes.module; 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.ModuleImplementor; import ai.timefold.jpyinterpreter.opcodes.AbstractOpcode; import ai.timefold.jpyinterpreter.types.BuiltinTypes; public class ImportNameOpcode extends AbstractOpcode { public ImportNameOpcode(PythonBytecodeInstruction instruction) { super(instruction); } @Override protected StackMetadata getStackMetadataAfterInstruction(FunctionMetadata functionMetadata, StackMetadata stackMetadata) { return stackMetadata.pop(2) .push(ValueSourceInfo.of(this, BuiltinTypes.BASE_TYPE, stackMetadata.getValueSourcesUpToStackIndex(2))); } @Override public void implement(FunctionMetadata functionMetadata, StackMetadata stackMetadata) { ModuleImplementor.importName(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/object/DeleteAttrOpcode.java
package ai.timefold.jpyinterpreter.opcodes.object; import ai.timefold.jpyinterpreter.FunctionMetadata; import ai.timefold.jpyinterpreter.PythonBytecodeInstruction; import ai.timefold.jpyinterpreter.StackMetadata; import ai.timefold.jpyinterpreter.implementors.ObjectImplementor; import ai.timefold.jpyinterpreter.opcodes.AbstractOpcode; public class DeleteAttrOpcode extends AbstractOpcode { public DeleteAttrOpcode(PythonBytecodeInstruction instruction) { super(instruction); } @Override protected StackMetadata getStackMetadataAfterInstruction(FunctionMetadata functionMetadata, StackMetadata stackMetadata) { return stackMetadata.pop(1); } @Override public void implement(FunctionMetadata functionMetadata, StackMetadata stackMetadata) { ObjectImplementor.deleteAttribute(functionMetadata, functionMetadata.methodVisitor, functionMetadata.className, 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/object/IsOpcode.java
package ai.timefold.jpyinterpreter.opcodes.object; 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.PythonBuiltinOperatorImplementor; import ai.timefold.jpyinterpreter.opcodes.AbstractOpcode; import ai.timefold.jpyinterpreter.types.BuiltinTypes; public class IsOpcode extends AbstractOpcode { public IsOpcode(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) { PythonBuiltinOperatorImplementor.isOperator(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/object/LoadAttrOpcode.java
package ai.timefold.jpyinterpreter.opcodes.object; 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.ObjectImplementor; import ai.timefold.jpyinterpreter.opcodes.AbstractOpcode; import ai.timefold.jpyinterpreter.types.BuiltinTypes; import ai.timefold.jpyinterpreter.types.PythonLikeType; public class LoadAttrOpcode extends AbstractOpcode { public LoadAttrOpcode(PythonBytecodeInstruction instruction) { super(instruction); } @Override protected StackMetadata getStackMetadataAfterInstruction(FunctionMetadata functionMetadata, StackMetadata stackMetadata) { PythonLikeType tosType = stackMetadata.getTOSType(); int arg = instruction.arg(); return tosType.getInstanceFieldDescriptor(functionMetadata.pythonCompiledFunction.co_names.get(arg)) .map(fieldDescriptor -> stackMetadata.pop() .push(ValueSourceInfo.of(this, fieldDescriptor.fieldPythonLikeType(), stackMetadata.getValueSourcesUpToStackIndex(1)))) .orElseGet(() -> stackMetadata.pop().push(ValueSourceInfo.of(this, BuiltinTypes.BASE_TYPE, stackMetadata.getValueSourcesUpToStackIndex(1)))); } @Override public void implement(FunctionMetadata functionMetadata, StackMetadata stackMetadata) { ObjectImplementor.getAttribute(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/object/LoadSuperAttrOpcode.java
package ai.timefold.jpyinterpreter.opcodes.object; 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.ObjectImplementor; import ai.timefold.jpyinterpreter.opcodes.AbstractOpcode; import ai.timefold.jpyinterpreter.types.BuiltinTypes; public class LoadSuperAttrOpcode extends AbstractOpcode { final int nameIndex; final boolean isLoadMethod; final boolean isTwoArgSuper; public LoadSuperAttrOpcode(PythonBytecodeInstruction instruction) { super(instruction); nameIndex = instruction.arg() >> 2; isLoadMethod = (instruction.arg() & 1) == 1; isTwoArgSuper = (instruction.arg() & 2) == 2; } @Override protected StackMetadata getStackMetadataAfterInstruction(FunctionMetadata functionMetadata, StackMetadata stackMetadata) { if (isLoadMethod) { // Pop 3, Push None and Method return stackMetadata.pop(3) .push(ValueSourceInfo.of(this, BuiltinTypes.BASE_TYPE, stackMetadata.getValueSourcesUpToStackIndex(3))) .push(ValueSourceInfo.of(this, BuiltinTypes.BASE_TYPE, stackMetadata.getValueSourcesUpToStackIndex(3))); } else { // Pop 3, Push Attribute return stackMetadata.pop(3) .push(ValueSourceInfo.of(this, BuiltinTypes.BASE_TYPE, stackMetadata.getValueSourcesUpToStackIndex(3))); } } @Override public void implement(FunctionMetadata functionMetadata, StackMetadata stackMetadata) { ObjectImplementor.getSuperAttribute(functionMetadata, stackMetadata, nameIndex, isLoadMethod); } }
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/object/StoreAttrOpcode.java
package ai.timefold.jpyinterpreter.opcodes.object; import ai.timefold.jpyinterpreter.FunctionMetadata; import ai.timefold.jpyinterpreter.PythonBytecodeInstruction; import ai.timefold.jpyinterpreter.StackMetadata; import ai.timefold.jpyinterpreter.implementors.ObjectImplementor; import ai.timefold.jpyinterpreter.opcodes.AbstractOpcode; public class StoreAttrOpcode extends AbstractOpcode { public StoreAttrOpcode(PythonBytecodeInstruction instruction) { super(instruction); } @Override protected StackMetadata getStackMetadataAfterInstruction(FunctionMetadata functionMetadata, StackMetadata stackMetadata) { return stackMetadata.pop(2); } @Override public void implement(FunctionMetadata functionMetadata, StackMetadata stackMetadata) { ObjectImplementor.setAttribute(functionMetadata, functionMetadata.methodVisitor, functionMetadata.className, stackMetadata, 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/stack/CopyOpcode.java
package ai.timefold.jpyinterpreter.opcodes.stack; import ai.timefold.jpyinterpreter.FunctionMetadata; import ai.timefold.jpyinterpreter.PythonBytecodeInstruction; import ai.timefold.jpyinterpreter.StackMetadata; import ai.timefold.jpyinterpreter.implementors.StackManipulationImplementor; import ai.timefold.jpyinterpreter.opcodes.AbstractOpcode; public class CopyOpcode extends AbstractOpcode { public CopyOpcode(PythonBytecodeInstruction instruction) { super(instruction); } @Override public StackMetadata getStackMetadataAfterInstruction(FunctionMetadata functionMetadata, StackMetadata stackMetadata) { return stackMetadata.push(stackMetadata.getValueSourceForStackIndex(instruction.arg() - 1)); } @Override public void implement(FunctionMetadata functionMetadata, StackMetadata stackMetadata) { StackManipulationImplementor.duplicateToTOS(functionMetadata, stackMetadata, instruction.arg() - 1); } }
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/stack/DupOpcode.java
package ai.timefold.jpyinterpreter.opcodes.stack; import ai.timefold.jpyinterpreter.FunctionMetadata; import ai.timefold.jpyinterpreter.PythonBytecodeInstruction; import ai.timefold.jpyinterpreter.StackMetadata; import ai.timefold.jpyinterpreter.implementors.StackManipulationImplementor; import ai.timefold.jpyinterpreter.opcodes.AbstractOpcode; public class DupOpcode extends AbstractOpcode { public DupOpcode(PythonBytecodeInstruction instruction) { super(instruction); } @Override public StackMetadata getStackMetadataAfterInstruction(FunctionMetadata functionMetadata, StackMetadata stackMetadata) { return stackMetadata.push(stackMetadata.getTOSValueSource()); } @Override public void implement(FunctionMetadata functionMetadata, StackMetadata stackMetadata) { StackManipulationImplementor.duplicateTOS(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/stack/DupTwoOpcode.java
package ai.timefold.jpyinterpreter.opcodes.stack; import ai.timefold.jpyinterpreter.FunctionMetadata; import ai.timefold.jpyinterpreter.PythonBytecodeInstruction; import ai.timefold.jpyinterpreter.StackMetadata; import ai.timefold.jpyinterpreter.implementors.StackManipulationImplementor; import ai.timefold.jpyinterpreter.opcodes.AbstractOpcode; public class DupTwoOpcode extends AbstractOpcode { public DupTwoOpcode(PythonBytecodeInstruction instruction) { super(instruction); } @Override public StackMetadata getStackMetadataAfterInstruction(FunctionMetadata functionMetadata, StackMetadata stackTypesBeforeInstruction) { return stackTypesBeforeInstruction .push(stackTypesBeforeInstruction.getValueSourceForStackIndex(1)) .push(stackTypesBeforeInstruction.getValueSourceForStackIndex(0)); } @Override public void implement(FunctionMetadata functionMetadata, StackMetadata stackMetadata) { StackManipulationImplementor.duplicateTOSAndTOS1(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/stack/PopOpcode.java
package ai.timefold.jpyinterpreter.opcodes.stack; import ai.timefold.jpyinterpreter.FunctionMetadata; import ai.timefold.jpyinterpreter.PythonBytecodeInstruction; import ai.timefold.jpyinterpreter.StackMetadata; import ai.timefold.jpyinterpreter.implementors.StackManipulationImplementor; import ai.timefold.jpyinterpreter.opcodes.AbstractOpcode; public class PopOpcode extends AbstractOpcode { public PopOpcode(PythonBytecodeInstruction instruction) { super(instruction); } @Override public StackMetadata getStackMetadataAfterInstruction(FunctionMetadata functionMetadata, StackMetadata stackMetadata) { return stackMetadata.pop(); } @Override public void implement(FunctionMetadata functionMetadata, StackMetadata stackMetadata) { StackManipulationImplementor.popTOS(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/stack/RotateFourOpcode.java
package ai.timefold.jpyinterpreter.opcodes.stack; import ai.timefold.jpyinterpreter.FunctionMetadata; import ai.timefold.jpyinterpreter.PythonBytecodeInstruction; import ai.timefold.jpyinterpreter.StackMetadata; import ai.timefold.jpyinterpreter.implementors.StackManipulationImplementor; import ai.timefold.jpyinterpreter.opcodes.AbstractOpcode; public class RotateFourOpcode extends AbstractOpcode { public RotateFourOpcode(PythonBytecodeInstruction instruction) { super(instruction); } @Override public StackMetadata getStackMetadataAfterInstruction(FunctionMetadata functionMetadata, StackMetadata stackMetadata) { return stackMetadata .pop() .pop() .pop() .pop() .push(stackMetadata.getValueSourceForStackIndex(0)) .push(stackMetadata.getValueSourceForStackIndex(3)) .push(stackMetadata.getValueSourceForStackIndex(2)) .push(stackMetadata.getValueSourceForStackIndex(1)); } @Override public void implement(FunctionMetadata functionMetadata, StackMetadata stackMetadata) { StackManipulationImplementor.rotateFour(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/stack/RotateThreeOpcode.java
package ai.timefold.jpyinterpreter.opcodes.stack; import ai.timefold.jpyinterpreter.FunctionMetadata; import ai.timefold.jpyinterpreter.PythonBytecodeInstruction; import ai.timefold.jpyinterpreter.StackMetadata; import ai.timefold.jpyinterpreter.implementors.StackManipulationImplementor; import ai.timefold.jpyinterpreter.opcodes.AbstractOpcode; public class RotateThreeOpcode extends AbstractOpcode { public RotateThreeOpcode(PythonBytecodeInstruction instruction) { super(instruction); } @Override public StackMetadata getStackMetadataAfterInstruction(FunctionMetadata functionMetadata, StackMetadata stackMetadata) { return stackMetadata .pop() .pop() .pop() .push(stackMetadata.getValueSourceForStackIndex(0)) .push(stackMetadata.getValueSourceForStackIndex(2)) .push(stackMetadata.getValueSourceForStackIndex(1)); } @Override public void implement(FunctionMetadata functionMetadata, StackMetadata stackMetadata) { StackManipulationImplementor.rotateThree(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/stack/RotateTwoOpcode.java
package ai.timefold.jpyinterpreter.opcodes.stack; import ai.timefold.jpyinterpreter.FunctionMetadata; import ai.timefold.jpyinterpreter.PythonBytecodeInstruction; import ai.timefold.jpyinterpreter.StackMetadata; import ai.timefold.jpyinterpreter.implementors.StackManipulationImplementor; import ai.timefold.jpyinterpreter.opcodes.AbstractOpcode; public class RotateTwoOpcode extends AbstractOpcode { public RotateTwoOpcode(PythonBytecodeInstruction instruction) { super(instruction); } @Override public StackMetadata getStackMetadataAfterInstruction(FunctionMetadata functionMetadata, StackMetadata stackMetadata) { return stackMetadata .pop() .pop() .push(stackMetadata.getValueSourceForStackIndex(0)) .push(stackMetadata.getValueSourceForStackIndex(1)); } @Override public void implement(FunctionMetadata functionMetadata, StackMetadata stackMetadata) { StackManipulationImplementor.swap(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/stack/SwapOpcode.java
package ai.timefold.jpyinterpreter.opcodes.stack; import ai.timefold.jpyinterpreter.FunctionMetadata; import ai.timefold.jpyinterpreter.PythonBytecodeInstruction; import ai.timefold.jpyinterpreter.StackMetadata; import ai.timefold.jpyinterpreter.implementors.StackManipulationImplementor; import ai.timefold.jpyinterpreter.opcodes.AbstractOpcode; public class SwapOpcode extends AbstractOpcode { public SwapOpcode(PythonBytecodeInstruction instruction) { super(instruction); } @Override public StackMetadata getStackMetadataAfterInstruction(FunctionMetadata functionMetadata, StackMetadata stackMetadata) { return stackMetadata .set(instruction.arg() - 1, stackMetadata.getTOSValueSource()) .set(0, stackMetadata.getValueSourceForStackIndex(instruction.arg() - 1)); } @Override public void implement(FunctionMetadata functionMetadata, StackMetadata stackMetadata) { StackManipulationImplementor.swapTOSWithIndex(functionMetadata, stackMetadata, instruction.arg() - 1); } }
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/string/BuildStringOpcode.java
package ai.timefold.jpyinterpreter.opcodes.string; 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.StringImplementor; import ai.timefold.jpyinterpreter.opcodes.AbstractOpcode; import ai.timefold.jpyinterpreter.types.BuiltinTypes; public class BuildStringOpcode extends AbstractOpcode { public BuildStringOpcode(PythonBytecodeInstruction instruction) { super(instruction); } @Override public StackMetadata getStackMetadataAfterInstruction(FunctionMetadata functionMetadata, StackMetadata stackMetadata) { return stackMetadata.pop(instruction.arg()).push( ValueSourceInfo.of(this, BuiltinTypes.STRING_TYPE, stackMetadata.getValueSourcesUpToStackIndex(instruction.arg()))); } @Override public void implement(FunctionMetadata functionMetadata, StackMetadata stackMetadata) { StringImplementor.buildString(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/string/FormatValueOpcode.java
package ai.timefold.jpyinterpreter.opcodes.string; 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.StringImplementor; import ai.timefold.jpyinterpreter.opcodes.AbstractOpcode; import ai.timefold.jpyinterpreter.types.BuiltinTypes; public class FormatValueOpcode extends AbstractOpcode { public FormatValueOpcode(PythonBytecodeInstruction instruction) { super(instruction); } @Override public StackMetadata getStackMetadataAfterInstruction(FunctionMetadata functionMetadata, StackMetadata stackMetadata) { if ((instruction.arg() & 4) == 4) { // There is a format argument above the value return stackMetadata.pop(2) .push(ValueSourceInfo.of(this, BuiltinTypes.STRING_TYPE, stackMetadata.getValueSourcesUpToStackIndex(2))); } else { // There is no format argument above the value return stackMetadata.pop() .push(ValueSourceInfo.of(this, BuiltinTypes.STRING_TYPE, stackMetadata.getValueSourcesUpToStackIndex(1))); } } @Override public void implement(FunctionMetadata functionMetadata, StackMetadata stackMetadata) { StringImplementor.formatValue(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/string/PrintExprOpcode.java
package ai.timefold.jpyinterpreter.opcodes.string; import ai.timefold.jpyinterpreter.FunctionMetadata; import ai.timefold.jpyinterpreter.PythonBytecodeInstruction; import ai.timefold.jpyinterpreter.StackMetadata; import ai.timefold.jpyinterpreter.implementors.StringImplementor; import ai.timefold.jpyinterpreter.opcodes.AbstractOpcode; public class PrintExprOpcode extends AbstractOpcode { public PrintExprOpcode(PythonBytecodeInstruction instruction) { super(instruction); } @Override public StackMetadata getStackMetadataAfterInstruction(FunctionMetadata functionMetadata, StackMetadata stackMetadata) { return stackMetadata.pop(); } @Override public void implement(FunctionMetadata functionMetadata, StackMetadata stackMetadata) { StringImplementor.print(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/variable/DeleteDerefOpcode.java
package ai.timefold.jpyinterpreter.opcodes.variable; import ai.timefold.jpyinterpreter.FunctionMetadata; import ai.timefold.jpyinterpreter.PythonBytecodeInstruction; import ai.timefold.jpyinterpreter.StackMetadata; import ai.timefold.jpyinterpreter.implementors.VariableImplementor; import ai.timefold.jpyinterpreter.opcodes.AbstractOpcode; public class DeleteDerefOpcode extends AbstractOpcode { public DeleteDerefOpcode(PythonBytecodeInstruction instruction) { super(instruction); } @Override protected StackMetadata getStackMetadataAfterInstruction(FunctionMetadata functionMetadata, StackMetadata stackMetadata) { return stackMetadata.setCellVariableValueSource(VariableImplementor.getCellIndex(functionMetadata, instruction.arg()), null); } @Override public void implement(FunctionMetadata functionMetadata, StackMetadata stackMetadata) { VariableImplementor.deleteCellVariable(functionMetadata, stackMetadata, VariableImplementor.getCellIndex(functionMetadata, 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/variable/DeleteFastOpcode.java
package ai.timefold.jpyinterpreter.opcodes.variable; import ai.timefold.jpyinterpreter.FunctionMetadata; import ai.timefold.jpyinterpreter.PythonBytecodeInstruction; import ai.timefold.jpyinterpreter.StackMetadata; import ai.timefold.jpyinterpreter.implementors.VariableImplementor; import ai.timefold.jpyinterpreter.opcodes.AbstractOpcode; public class DeleteFastOpcode extends AbstractOpcode { public DeleteFastOpcode(PythonBytecodeInstruction instruction) { super(instruction); } @Override protected StackMetadata getStackMetadataAfterInstruction(FunctionMetadata functionMetadata, StackMetadata stackMetadata) { return stackMetadata.setLocalVariableValueSource(instruction.arg(), null); } @Override public void implement(FunctionMetadata functionMetadata, StackMetadata stackMetadata) { VariableImplementor.deleteLocalVariable(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/variable/DeleteGlobalOpcode.java
package ai.timefold.jpyinterpreter.opcodes.variable; import ai.timefold.jpyinterpreter.FunctionMetadata; import ai.timefold.jpyinterpreter.PythonBytecodeInstruction; import ai.timefold.jpyinterpreter.StackMetadata; import ai.timefold.jpyinterpreter.implementors.VariableImplementor; import ai.timefold.jpyinterpreter.opcodes.AbstractOpcode; public class DeleteGlobalOpcode extends AbstractOpcode { public DeleteGlobalOpcode(PythonBytecodeInstruction instruction) { super(instruction); } @Override protected StackMetadata getStackMetadataAfterInstruction(FunctionMetadata functionMetadata, StackMetadata stackMetadata) { return stackMetadata.copy(); } @Override public void implement(FunctionMetadata functionMetadata, StackMetadata stackMetadata) { VariableImplementor.deleteGlobalVariable(functionMetadata.methodVisitor, functionMetadata.className, functionMetadata.pythonCompiledFunction, 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/variable/LoadClosureOpcode.java
package ai.timefold.jpyinterpreter.opcodes.variable; 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.VariableImplementor; import ai.timefold.jpyinterpreter.opcodes.AbstractOpcode; import ai.timefold.jpyinterpreter.types.PythonCell; public class LoadClosureOpcode extends AbstractOpcode { public LoadClosureOpcode(PythonBytecodeInstruction instruction) { super(instruction); } @Override protected StackMetadata getStackMetadataAfterInstruction(FunctionMetadata functionMetadata, StackMetadata stackMetadata) { return stackMetadata.push(ValueSourceInfo.of(this, PythonCell.CELL_TYPE)); } @Override public void implement(FunctionMetadata functionMetadata, StackMetadata stackMetadata) { VariableImplementor.loadCell(functionMetadata, stackMetadata, VariableImplementor.getCellIndex(functionMetadata, 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/variable/LoadConstantOpcode.java
package ai.timefold.jpyinterpreter.opcodes.variable; import ai.timefold.jpyinterpreter.FunctionMetadata; import ai.timefold.jpyinterpreter.PythonBytecodeInstruction; import ai.timefold.jpyinterpreter.PythonLikeObject; import ai.timefold.jpyinterpreter.StackMetadata; import ai.timefold.jpyinterpreter.ValueSourceInfo; import ai.timefold.jpyinterpreter.implementors.PythonConstantsImplementor; import ai.timefold.jpyinterpreter.opcodes.AbstractOpcode; import ai.timefold.jpyinterpreter.types.PythonLikeType; import org.objectweb.asm.Opcodes; public class LoadConstantOpcode extends AbstractOpcode { public LoadConstantOpcode(PythonBytecodeInstruction instruction) { super(instruction); } @Override protected StackMetadata getStackMetadataAfterInstruction(FunctionMetadata functionMetadata, StackMetadata stackMetadata) { PythonLikeObject constant = functionMetadata.pythonCompiledFunction.co_constants.get(instruction.arg()); PythonLikeType constantType = constant.$getGenericType(); return stackMetadata.push(ValueSourceInfo.of(this, constantType)); } @Override public void implement(FunctionMetadata functionMetadata, StackMetadata stackMetadata) { PythonLikeObject constant = functionMetadata.pythonCompiledFunction.co_constants.get(instruction.arg()); PythonLikeType constantType = constant.$getGenericType(); PythonConstantsImplementor.loadConstant(functionMetadata.methodVisitor, functionMetadata.className, instruction.arg()); functionMetadata.methodVisitor.visitTypeInsn(Opcodes.CHECKCAST, constantType.getJavaTypeInternalName()); } }
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/variable/LoadDerefOpcode.java
package ai.timefold.jpyinterpreter.opcodes.variable; import ai.timefold.jpyinterpreter.FunctionMetadata; import ai.timefold.jpyinterpreter.PythonBytecodeInstruction; import ai.timefold.jpyinterpreter.StackMetadata; import ai.timefold.jpyinterpreter.implementors.VariableImplementor; import ai.timefold.jpyinterpreter.opcodes.AbstractOpcode; public class LoadDerefOpcode extends AbstractOpcode { public LoadDerefOpcode(PythonBytecodeInstruction instruction) { super(instruction); } @Override protected StackMetadata getStackMetadataAfterInstruction(FunctionMetadata functionMetadata, StackMetadata stackMetadata) { return stackMetadata.push( stackMetadata .getCellVariableValueSource(VariableImplementor.getCellIndex(functionMetadata, instruction.arg()))); } @Override public void implement(FunctionMetadata functionMetadata, StackMetadata stackMetadata) { VariableImplementor.loadCellVariable(functionMetadata, stackMetadata, VariableImplementor.getCellIndex(functionMetadata, 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/variable/LoadFastAndClearOpcode.java
package ai.timefold.jpyinterpreter.opcodes.variable; import ai.timefold.jpyinterpreter.FunctionMetadata; import ai.timefold.jpyinterpreter.PythonBytecodeInstruction; import ai.timefold.jpyinterpreter.StackMetadata; import ai.timefold.jpyinterpreter.implementors.VariableImplementor; import ai.timefold.jpyinterpreter.opcodes.AbstractOpcode; public class LoadFastAndClearOpcode extends AbstractOpcode { public LoadFastAndClearOpcode(PythonBytecodeInstruction instruction) { super(instruction); } @Override protected StackMetadata getStackMetadataAfterInstruction(FunctionMetadata functionMetadata, StackMetadata stackMetadata) { return stackMetadata.push(stackMetadata.getLocalVariableValueSource(instruction.arg())); } @Override public void implement(FunctionMetadata functionMetadata, StackMetadata stackMetadata) { VariableImplementor.loadLocalVariable(functionMetadata.methodVisitor, instruction, stackMetadata.localVariableHelper); VariableImplementor.deleteLocalVariable(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/variable/LoadFastOpcode.java
package ai.timefold.jpyinterpreter.opcodes.variable; import ai.timefold.jpyinterpreter.FunctionMetadata; import ai.timefold.jpyinterpreter.PythonBytecodeInstruction; import ai.timefold.jpyinterpreter.StackMetadata; import ai.timefold.jpyinterpreter.implementors.VariableImplementor; import ai.timefold.jpyinterpreter.opcodes.AbstractOpcode; public class LoadFastOpcode extends AbstractOpcode { public LoadFastOpcode(PythonBytecodeInstruction instruction) { super(instruction); } @Override protected StackMetadata getStackMetadataAfterInstruction(FunctionMetadata functionMetadata, StackMetadata stackMetadata) { return stackMetadata.push(stackMetadata.getLocalVariableValueSource(instruction.arg())); } @Override public void implement(FunctionMetadata functionMetadata, StackMetadata stackMetadata) { VariableImplementor.loadLocalVariable(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/variable/LoadGlobalOpcode.java
package ai.timefold.jpyinterpreter.opcodes.variable; import ai.timefold.jpyinterpreter.FunctionMetadata; import ai.timefold.jpyinterpreter.PythonBytecodeInstruction; import ai.timefold.jpyinterpreter.PythonLikeObject; import ai.timefold.jpyinterpreter.PythonVersion; import ai.timefold.jpyinterpreter.StackMetadata; import ai.timefold.jpyinterpreter.ValueSourceInfo; import ai.timefold.jpyinterpreter.implementors.VariableImplementor; import ai.timefold.jpyinterpreter.opcodes.AbstractOpcode; import ai.timefold.jpyinterpreter.types.BuiltinTypes; import ai.timefold.jpyinterpreter.types.wrappers.CPythonType; import ai.timefold.jpyinterpreter.types.wrappers.PythonObjectWrapper; import org.objectweb.asm.Opcodes; public class LoadGlobalOpcode extends AbstractOpcode { public LoadGlobalOpcode(PythonBytecodeInstruction instruction) { super(instruction); } private int getGlobalIndex(FunctionMetadata functionMetadata) { return (functionMetadata.pythonCompiledFunction.pythonVersion.compareTo(PythonVersion.PYTHON_3_11) >= 0) ? instruction.arg() >> 1 : instruction.arg(); } private boolean pushNullBeforeGlobal(FunctionMetadata functionMetadata) { return functionMetadata.pythonCompiledFunction.pythonVersion.compareTo(PythonVersion.PYTHON_3_11) >= 0 && ((instruction.arg() & 1) == 1); } private PythonLikeObject getGlobal(FunctionMetadata functionMetadata) { return functionMetadata.pythonCompiledFunction.globalsMap .get(functionMetadata.pythonCompiledFunction.co_names.get(getGlobalIndex(functionMetadata))); } @Override protected StackMetadata getStackMetadataAfterInstruction(FunctionMetadata functionMetadata, StackMetadata stackMetadata) { boolean pushNull = pushNullBeforeGlobal(functionMetadata); PythonLikeObject global = getGlobal(functionMetadata); if (pushNull) { if (global != null) { return stackMetadata .push(ValueSourceInfo.of(this, BuiltinTypes.NULL_TYPE)) .push(ValueSourceInfo.of(this, global.$getGenericType())); } else { return stackMetadata .push(ValueSourceInfo.of(this, BuiltinTypes.NULL_TYPE)) .push(ValueSourceInfo.of(this, BuiltinTypes.BASE_TYPE)); } } else { if (global != null) { return stackMetadata .push(ValueSourceInfo.of(this, global.$getGenericType())); } else { return stackMetadata .push(ValueSourceInfo.of(this, BuiltinTypes.BASE_TYPE)); } } } @Override public void implement(FunctionMetadata functionMetadata, StackMetadata stackMetadata) { int globalIndex = getGlobalIndex(functionMetadata); boolean pushNull = pushNullBeforeGlobal(functionMetadata); PythonLikeObject global = getGlobal(functionMetadata); if (global instanceof CPythonType || global instanceof PythonObjectWrapper) { // TODO: note native objects are used somewhere } if (pushNull) { functionMetadata.methodVisitor.visitInsn(Opcodes.ACONST_NULL); } VariableImplementor.loadGlobalVariable(functionMetadata, stackMetadata, globalIndex, (global != null) ? global.$getGenericType() : BuiltinTypes.BASE_TYPE); } }
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/variable/StoreDerefOpcode.java
package ai.timefold.jpyinterpreter.opcodes.variable; import ai.timefold.jpyinterpreter.FunctionMetadata; import ai.timefold.jpyinterpreter.PythonBytecodeInstruction; import ai.timefold.jpyinterpreter.StackMetadata; import ai.timefold.jpyinterpreter.implementors.VariableImplementor; import ai.timefold.jpyinterpreter.opcodes.AbstractOpcode; public class StoreDerefOpcode extends AbstractOpcode { public StoreDerefOpcode(PythonBytecodeInstruction instruction) { super(instruction); } @Override protected StackMetadata getStackMetadataAfterInstruction(FunctionMetadata functionMetadata, StackMetadata stackMetadata) { return stackMetadata.pop().setCellVariableValueSource( VariableImplementor.getCellIndex(functionMetadata, instruction.arg()), stackMetadata.getTOSValueSource()); } @Override public void implement(FunctionMetadata functionMetadata, StackMetadata stackMetadata) { VariableImplementor.storeInCellVariable(functionMetadata, stackMetadata, VariableImplementor.getCellIndex(functionMetadata, 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/variable/StoreFastOpcode.java
package ai.timefold.jpyinterpreter.opcodes.variable; import ai.timefold.jpyinterpreter.FunctionMetadata; import ai.timefold.jpyinterpreter.PythonBytecodeInstruction; import ai.timefold.jpyinterpreter.StackMetadata; import ai.timefold.jpyinterpreter.implementors.VariableImplementor; import ai.timefold.jpyinterpreter.opcodes.AbstractOpcode; public class StoreFastOpcode extends AbstractOpcode { public StoreFastOpcode(PythonBytecodeInstruction instruction) { super(instruction); } @Override protected StackMetadata getStackMetadataAfterInstruction(FunctionMetadata functionMetadata, StackMetadata stackMetadata) { return stackMetadata.pop().setLocalVariableValueSource(instruction.arg(), stackMetadata.getTOSValueSource()); } @Override public void implement(FunctionMetadata functionMetadata, StackMetadata stackMetadata) { VariableImplementor.storeInLocalVariable(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/variable/StoreGlobalOpcode.java
package ai.timefold.jpyinterpreter.opcodes.variable; import ai.timefold.jpyinterpreter.FunctionMetadata; import ai.timefold.jpyinterpreter.PythonBytecodeInstruction; import ai.timefold.jpyinterpreter.StackMetadata; import ai.timefold.jpyinterpreter.implementors.VariableImplementor; import ai.timefold.jpyinterpreter.opcodes.AbstractOpcode; public class StoreGlobalOpcode extends AbstractOpcode { public StoreGlobalOpcode(PythonBytecodeInstruction instruction) { super(instruction); } @Override protected StackMetadata getStackMetadataAfterInstruction(FunctionMetadata functionMetadata, StackMetadata stackMetadata) { return stackMetadata.pop(); } @Override public void implement(FunctionMetadata functionMetadata, StackMetadata stackMetadata) { VariableImplementor.storeInGlobalVariable(functionMetadata.methodVisitor, functionMetadata.className, functionMetadata.pythonCompiledFunction, instruction); } }
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/test/TestdataExtendedInterface.java
package ai.timefold.jpyinterpreter.test; import ai.timefold.jpyinterpreter.types.PythonString; import ai.timefold.jpyinterpreter.types.numeric.PythonInteger; /** * Not a real interface; in main sources instead of test sources * so a Python test can use it. */ public interface TestdataExtendedInterface { PythonString stringMethod(PythonString name); PythonInteger intMethod(PythonInteger value); static String getString(TestdataExtendedInterface instance, String name) { return instance.stringMethod(PythonString.valueOf(name)).value; } static int getInt(TestdataExtendedInterface instance, int value) { return instance.intMethod(PythonInteger.valueOf(value)).value.intValue(); } }
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/types/AbstractPythonLikeObject.java
package ai.timefold.jpyinterpreter.types; import java.util.HashMap; import java.util.Map; import ai.timefold.jpyinterpreter.PythonLikeObject; import ai.timefold.jpyinterpreter.types.errors.AttributeError; public abstract class AbstractPythonLikeObject implements PythonLikeObject { public static final PythonLikeType OBJECT_TYPE = new PythonLikeType("object", AbstractPythonLikeObject.class); private final PythonLikeType __type__; private final Map<String, PythonLikeObject> __dir__; public AbstractPythonLikeObject(PythonLikeType __type__) { this(__type__, new HashMap<>()); } public AbstractPythonLikeObject(PythonLikeType __type__, Map<String, PythonLikeObject> __dir__) { this.__type__ = __type__; this.__dir__ = __dir__; } @Override public PythonLikeObject $getAttributeOrNull(String attributeName) { return __dir__.get(attributeName); } @Override public void $setAttribute(String attributeName, PythonLikeObject value) { __dir__.put(attributeName, value); } @Override public void $deleteAttribute(String attributeName) { // TODO: Descriptors: https://docs.python.org/3/howto/descriptor.html if (!__dir__.containsKey(attributeName)) { throw new AttributeError("'" + $getType().getTypeName() + "' object has no attribute '" + attributeName + "'"); } __dir__.remove(attributeName); } @Override public PythonLikeType $getType() { return __type__; } public void setAttribute(String attributeName, PythonLikeObject value) { __dir__.put(attributeName, value); } public Map<String, PythonLikeObject> getExtraAttributeMap() { return __dir__; } @Override public String toString() { return $method$__str__().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/types/BoundPythonLikeFunction.java
package ai.timefold.jpyinterpreter.types; import java.util.ArrayList; import java.util.List; import java.util.Map; import ai.timefold.jpyinterpreter.PythonLikeObject; public class BoundPythonLikeFunction implements PythonLikeFunction { private final PythonLikeObject instance; private final PythonLikeFunction function; public BoundPythonLikeFunction(PythonLikeObject instance, PythonLikeFunction function) { this.instance = instance; this.function = function; } public static BoundPythonLikeFunction boundToTypeOfObject(PythonLikeObject instance, PythonLikeFunction function) { if (instance instanceof PythonLikeType) { return new BoundPythonLikeFunction(instance, function); } else { return new BoundPythonLikeFunction(instance.$getType(), function); } } public PythonLikeObject getInstance() { return instance; } @Override public PythonLikeObject $call(List<PythonLikeObject> positionalArguments, Map<PythonString, PythonLikeObject> namedArguments, PythonLikeObject callerInstance) { ArrayList<PythonLikeObject> actualPositionalArgs = new ArrayList<>(positionalArguments.size() + 1); actualPositionalArgs.add(instance); actualPositionalArgs.addAll(positionalArguments); return function.$call(actualPositionalArgs, namedArguments, 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/types/BuiltinTypes.java
package ai.timefold.jpyinterpreter.types; import java.lang.reflect.Field; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import ai.timefold.jpyinterpreter.PythonBytecodeToJavaBytecodeTranslator; import ai.timefold.jpyinterpreter.PythonLikeObject; import ai.timefold.jpyinterpreter.PythonOverloadImplementor; import ai.timefold.jpyinterpreter.PythonTernaryOperator; import ai.timefold.jpyinterpreter.builtins.FunctionBuiltinOperations; import ai.timefold.jpyinterpreter.builtins.GlobalBuiltins; 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.collections.view.DictItemView; import ai.timefold.jpyinterpreter.types.collections.view.DictKeyView; import ai.timefold.jpyinterpreter.types.collections.view.DictValueView; import ai.timefold.jpyinterpreter.types.numeric.PythonBoolean; import ai.timefold.jpyinterpreter.types.numeric.PythonComplex; 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.JavaMethodReference; public class BuiltinTypes { public static final PythonLikeType NULL_TYPE = new PythonLikeType("NULL", PythonLikeObject.class, Collections.emptyList()); public static final PythonLikeType BASE_TYPE = new PythonLikeType("base-object", PythonLikeObject.class, Collections.emptyList()); public static final PythonLikeType TYPE_TYPE = new PythonLikeType("type", PythonLikeType.class, List.of(BASE_TYPE)); public static final PythonLikeType SUPER_TYPE = new PythonLikeType("super", PythonSuperObject.class, List.of(BASE_TYPE)); public static final PythonLikeType MODULE_TYPE = new PythonLikeType("module", PythonModule.class, List.of(BASE_TYPE)); public static final PythonLikeType FUNCTION_TYPE = new PythonLikeType("function", PythonLikeFunction.class, List.of(BASE_TYPE)); public static final PythonLikeType CLASS_FUNCTION_TYPE = new PythonLikeType("classmethod", PythonLikeFunction.class, List.of(BASE_TYPE)); public static final PythonLikeType STATIC_FUNCTION_TYPE = new PythonLikeType("staticmethod", PythonLikeFunction.class, List.of(BASE_TYPE)); public static final PythonLikeType METHOD_TYPE = new PythonLikeType("method", PythonLikeFunction.class, List.of(BASE_TYPE)); public static final PythonLikeType GENERATOR_TYPE = new PythonLikeType("generator", PythonGenerator.class, List.of(BASE_TYPE)); public static final PythonLikeType CODE_TYPE = new PythonLikeType("code", PythonCode.class, List.of(BASE_TYPE)); public static final PythonLikeType CELL_TYPE = new PythonLikeType("cell", PythonCell.class, List.of(BASE_TYPE)); public static final PythonLikeType NONE_TYPE = new PythonLikeType("NoneType", PythonNone.class, List.of(BASE_TYPE)); public static final PythonLikeType NOT_IMPLEMENTED_TYPE = new PythonLikeType("NotImplementedType", NotImplemented.class, List.of(BASE_TYPE)); public static final PythonLikeType ELLIPSIS_TYPE = new PythonLikeType("EllipsisType", Ellipsis.class, List.of(BASE_TYPE)); public static final PythonLikeType NUMBER_TYPE = new PythonLikeType("number", PythonNumber.class, List.of(BASE_TYPE)); public static final PythonLikeType INT_TYPE = new PythonLikeType("int", PythonInteger.class, List.of(NUMBER_TYPE)); public static final PythonLikeType BOOLEAN_TYPE = new PythonLikeType("bool", PythonBoolean.class, List.of(INT_TYPE)); public static final PythonLikeType FLOAT_TYPE = new PythonLikeType("float", PythonFloat.class, List.of(NUMBER_TYPE)); public final static PythonLikeType COMPLEX_TYPE = new PythonLikeType("complex", PythonComplex.class, List.of(NUMBER_TYPE)); public final static PythonLikeType DECIMAL_TYPE = new PythonLikeType("Decimal", PythonDecimal.class, List.of(NUMBER_TYPE)); public static final PythonLikeType STRING_TYPE = new PythonLikeType("str", PythonString.class, List.of(BASE_TYPE)); public static final PythonLikeType BYTES_TYPE = new PythonLikeType("bytes", PythonBytes.class, List.of(BASE_TYPE)); public static final PythonLikeType BYTE_ARRAY_TYPE = new PythonLikeType("bytearray", PythonByteArray.class, List.of(BASE_TYPE)); public static final PythonLikeType ITERATOR_TYPE = new PythonLikeType("iterator", PythonIterator.class, List.of(BASE_TYPE)); public static final PythonLikeType DICT_TYPE = new PythonLikeType("dict", PythonLikeDict.class, List.of(BASE_TYPE)); public static final PythonLikeType DICT_ITEM_VIEW_TYPE = new PythonLikeType("dict_items", DictItemView.class, List.of(BASE_TYPE)); public static final PythonLikeType DICT_KEY_VIEW_TYPE = new PythonLikeType("dict_keys", DictKeyView.class, List.of(BASE_TYPE)); public static final PythonLikeType DICT_VALUE_VIEW_TYPE = new PythonLikeType("dict_values", DictValueView.class, List.of(BASE_TYPE)); public static final PythonLikeType SET_TYPE = new PythonLikeType("set", PythonLikeSet.class, List.of(BASE_TYPE)); public static final PythonLikeType FROZEN_SET_TYPE = new PythonLikeType("frozenset", PythonLikeFrozenSet.class, List.of(BASE_TYPE)); public static final PythonLikeType TUPLE_TYPE = new PythonLikeType("tuple", PythonLikeTuple.class, List.of(BASE_TYPE)); public static final PythonLikeType LIST_TYPE = new PythonLikeType("list", PythonLikeList.class, List.of(BASE_TYPE)); public static final PythonLikeType RANGE_TYPE = new PythonLikeType("range", PythonRange.class, List.of(BASE_TYPE)); public static final PythonLikeType SLICE_TYPE = new PythonLikeType("slice", PythonSlice.class, List.of(BASE_TYPE)); /** * The ASM generated bytecode. Used by * asmClassLoader to create the Java versions of Python methods */ public static final Map<String, byte[]> classNameToBytecode = new HashMap<>(); /** * A custom classloader that looks for the class in * classNameToBytecode */ public static ClassLoader asmClassLoader = new ClassLoader() { // getName() is an abstract method in Java 11 but not in Java 8 public String getName() { return "JPyInterpreter Python Bytecode ClassLoader"; } @Override public Class<?> findClass(String name) throws ClassNotFoundException { if (classNameToBytecode.containsKey(name)) { // Gizmo generated class byte[] byteCode = classNameToBytecode.get(name); return defineClass(name, byteCode, 0, byteCode.length); } else { // Not a Gizmo generated class; load from parent class loader return PythonBytecodeToJavaBytecodeTranslator.class.getClassLoader().loadClass(name); } } }; static { PythonOverloadImplementor.deferDispatchesFor(PythonLikeType::registerBaseType); PythonOverloadImplementor.deferDispatchesFor(PythonLikeType::registerTypeType); try { FUNCTION_TYPE.__dir__.put(PythonTernaryOperator.GET.dunderMethod, new JavaMethodReference( FunctionBuiltinOperations.class.getMethod("bindFunctionToInstance", PythonLikeFunction.class, PythonLikeObject.class, PythonLikeType.class), Map.of("self", 0, "obj", 1, "objtype", 2))); CLASS_FUNCTION_TYPE.__dir__.put(PythonTernaryOperator.GET.dunderMethod, new JavaMethodReference( FunctionBuiltinOperations.class.getMethod("bindFunctionToType", PythonLikeFunction.class, PythonLikeObject.class, PythonLikeType.class), Map.of("self", 0, "obj", 1, "objtype", 2))); } catch (NoSuchMethodException e) { throw new IllegalStateException(e); } for (Field field : BuiltinTypes.class.getFields()) { try { if (!field.getType().equals(PythonLikeType.class)) { continue; } PythonLikeType pythonLikeType = (PythonLikeType) field.get(null); Class<?> javaClass = pythonLikeType.getJavaClass(); Class.forName(javaClass.getName(), true, javaClass.getClassLoader()); } catch (IllegalAccessException | ClassNotFoundException e) { throw new IllegalStateException(e); } } GlobalBuiltins.loadBuiltinConstants(); } public static void load() { } // Class should not be initated; only holds static constants private BuiltinTypes() { } }
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/types/CPythonBackedPythonLikeObject.java
package ai.timefold.jpyinterpreter.types; import java.util.HashMap; import java.util.List; import java.util.Map; import ai.timefold.jpyinterpreter.CPythonBackedPythonInterpreter; import ai.timefold.jpyinterpreter.PythonInterpreter; import ai.timefold.jpyinterpreter.PythonLikeObject; import ai.timefold.jpyinterpreter.types.numeric.PythonInteger; import ai.timefold.jpyinterpreter.types.wrappers.OpaquePythonReference; public class CPythonBackedPythonLikeObject extends AbstractPythonLikeObject implements PythonLikeFunction { public static final PythonLikeType CPYTHON_BACKED_OBJECT_TYPE = new PythonLikeType("object", CPythonBackedPythonLikeObject.class); private final PythonInterpreter interpreter; public OpaquePythonReference $cpythonReference; public PythonInteger $cpythonId; public Map<Number, PythonLikeObject> $instanceMap; public CPythonBackedPythonLikeObject(PythonInterpreter interpreter, PythonLikeType __type__) { this(interpreter, __type__, (OpaquePythonReference) null); } public CPythonBackedPythonLikeObject(PythonInterpreter interpreter, PythonLikeType __type__, Map<String, PythonLikeObject> __dir__) { this(interpreter, __type__, __dir__, null); } public CPythonBackedPythonLikeObject(PythonInterpreter interpreter, PythonLikeType __type__, OpaquePythonReference reference) { super(__type__); this.interpreter = interpreter; this.$cpythonReference = reference; $instanceMap = new HashMap<>(); } public CPythonBackedPythonLikeObject(PythonInterpreter interpreter, PythonLikeType __type__, Map<String, PythonLikeObject> __dir__, OpaquePythonReference reference) { super(__type__, __dir__); this.interpreter = interpreter; this.$cpythonReference = reference; $instanceMap = new HashMap<>(); } public OpaquePythonReference $getCPythonReference() { return $cpythonReference; } public void $setCPythonReference(OpaquePythonReference pythonReference) { interpreter.setPythonReference(this, pythonReference); } public PythonInteger $getCPythonId() { return $cpythonId; } public Map<Number, PythonLikeObject> $getInstanceMap() { return $instanceMap; } public void $setInstanceMap(Map<Number, PythonLikeObject> $instanceMap) { this.$instanceMap = $instanceMap; } public boolean $shouldCreateNewInstance() { return !interpreter.hasValidPythonReference(this); } public void $readFieldsFromCPythonReference() { } public void $writeFieldsToCPythonReference(OpaquePythonReference cloneMap) { for (var attributeEntry : getExtraAttributeMap().entrySet()) { CPythonBackedPythonInterpreter.setAttributeOnPythonReference($cpythonReference, cloneMap, attributeEntry.getKey(), attributeEntry.getValue()); } } @Override public PythonLikeObject $call(List<PythonLikeObject> positionalArguments, Map<PythonString, PythonLikeObject> namedArguments, PythonLikeObject callerInstance) { return PythonNone.INSTANCE; } }
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/types/Coercible.java
package ai.timefold.jpyinterpreter.types; public interface Coercible { <T> T coerce(Class<T> targetType); }
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/types/Ellipsis.java
package ai.timefold.jpyinterpreter.types; import ai.timefold.jpyinterpreter.builtins.GlobalBuiltins; import ai.timefold.solver.core.impl.domain.solution.cloner.PlanningImmutable; public class Ellipsis extends AbstractPythonLikeObject implements PlanningImmutable { public static final Ellipsis INSTANCE; public static final PythonLikeType ELLIPSIS_TYPE = new PythonLikeType("EllipsisType", Ellipsis.class); public static final PythonLikeType $TYPE = ELLIPSIS_TYPE; static { INSTANCE = new Ellipsis(); GlobalBuiltins.addBuiltinConstant("Ellipsis", INSTANCE); } private Ellipsis() { super(ELLIPSIS_TYPE); } @Override public PythonString $method$__str__() { return PythonString.valueOf(toString()); } @Override public String toString() { return "NotImplemented"; } }
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/types/GeneratedFunctionMethodReference.java
package ai.timefold.jpyinterpreter.types; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.List; import java.util.Map; import ai.timefold.jpyinterpreter.PythonLikeObject; public class GeneratedFunctionMethodReference implements PythonLikeFunction { private final Object instance; private final Method method; private final Map<String, Integer> parameterNameToIndexMap; private final PythonLikeType type; public GeneratedFunctionMethodReference(Object instance, Method method, Map<String, Integer> parameterNameToIndexMap, PythonLikeType type) { this.instance = instance; this.method = method; this.parameterNameToIndexMap = parameterNameToIndexMap; this.type = type; } @Override public PythonLikeObject $call(List<PythonLikeObject> positionalArguments, Map<PythonString, PythonLikeObject> namedArguments, PythonLikeObject callerInstance) { Object[] args = unwrapPrimitiveArguments(positionalArguments, namedArguments); try { return (PythonLikeObject) method.invoke(instance, args); } catch (IllegalAccessException e) { throw new IllegalStateException("Method (" + method + ") is not accessible.", e); } catch (InvocationTargetException e) { throw new RuntimeException(e); } } private Object[] unwrapPrimitiveArguments(List<PythonLikeObject> positionalArguments, Map<PythonString, PythonLikeObject> namedArguments) { namedArguments = (namedArguments != null) ? namedArguments : Map.of(); Object[] out = new Object[method.getParameterCount()]; for (int i = 0; i < positionalArguments.size(); i++) { PythonLikeObject argument = positionalArguments.get(i); out[i] = argument; } for (PythonString key : namedArguments.keySet()) { int index = parameterNameToIndexMap.get(key.value); PythonLikeObject argument = namedArguments.get(key); out[index] = argument; } return out; } @Override public PythonLikeType $getType() { return type; } }
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/types/NotImplemented.java
package ai.timefold.jpyinterpreter.types; import ai.timefold.jpyinterpreter.builtins.GlobalBuiltins; public class NotImplemented extends AbstractPythonLikeObject { public static final NotImplemented INSTANCE; public static final PythonLikeType NOT_IMPLEMENTED_TYPE = new PythonLikeType("NotImplementedType", NotImplemented.class); public static final PythonLikeType $TYPE = NOT_IMPLEMENTED_TYPE; static { INSTANCE = new NotImplemented(); GlobalBuiltins.addBuiltinConstant("NotImplemented", INSTANCE); } private NotImplemented() { super(NOT_IMPLEMENTED_TYPE); } @Override public PythonString $method$__str__() { return PythonString.valueOf(toString()); } @Override public String toString() { return "NotImplemented"; } }
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/types/PythonByteArray.java
package ai.timefold.jpyinterpreter.types; import java.io.ByteArrayOutputStream; import java.math.BigInteger; import java.nio.ByteBuffer; import java.nio.charset.CharacterCodingException; import java.nio.charset.Charset; import java.nio.charset.CodingErrorAction; import java.nio.charset.StandardCharsets; import java.util.Arrays; import java.util.BitSet; import java.util.stream.Collectors; import java.util.stream.IntStream; import ai.timefold.jpyinterpreter.PythonBinaryOperator; import ai.timefold.jpyinterpreter.PythonLikeObject; import ai.timefold.jpyinterpreter.PythonOverloadImplementor; import ai.timefold.jpyinterpreter.PythonTernaryOperator; import ai.timefold.jpyinterpreter.PythonUnaryOperator; import ai.timefold.jpyinterpreter.builtins.UnaryDunderBuiltin; 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.PythonLikeList; import ai.timefold.jpyinterpreter.types.collections.PythonLikeTuple; import ai.timefold.jpyinterpreter.types.errors.TypeError; import ai.timefold.jpyinterpreter.types.errors.ValueError; import ai.timefold.jpyinterpreter.types.errors.lookup.IndexError; import ai.timefold.jpyinterpreter.types.errors.unicode.UnicodeDecodeError; import ai.timefold.jpyinterpreter.types.numeric.PythonBoolean; import ai.timefold.jpyinterpreter.types.numeric.PythonInteger; import ai.timefold.jpyinterpreter.util.ByteCharSequence; import ai.timefold.jpyinterpreter.util.StringFormatter; public class PythonByteArray extends AbstractPythonLikeObject implements PythonBytesLikeObject { private static final PythonByteArray ASCII_SPACE = new PythonByteArray(new byte[] { ' ' }); private static final BitSet ASCII_WHITESPACE_BITSET = asBitSet(new PythonByteArray( new byte[] { ' ', '\t', '\n', '\r', 0x0b, '\f' })); static { PythonOverloadImplementor.deferDispatchesFor(PythonByteArray::registerMethods); } private static PythonLikeType registerMethods() throws NoSuchMethodException { BuiltinTypes.BYTE_ARRAY_TYPE.setConstructor(((positionalArguments, namedArguments, callerInstance) -> { if (positionalArguments.isEmpty()) { return new PythonByteArray(); } else if (positionalArguments.size() == 1) { PythonLikeObject arg = positionalArguments.get(0); if (arg instanceof PythonInteger) { return new PythonByteArray(new byte[((PythonInteger) arg).value.intValueExact()]); } else { PythonIterator<?> iterator = (PythonIterator<?>) UnaryDunderBuiltin.ITERATOR.invoke(arg); ByteArrayOutputStream out = new ByteArrayOutputStream(); byte[] toWrite = new byte[1]; while (iterator.hasNext()) { PythonLikeObject item = iterator.nextPythonItem(); if (!(item instanceof PythonInteger)) { throw new ValueError("bytearray argument 1 must be an int or an iterable of int"); } toWrite[0] = ((PythonInteger) item).asByte(); out.writeBytes(toWrite); } return new PythonByteArray(out.toByteArray()); } } else { throw new ValueError("bytearray takes 0 or 1 arguments, not " + positionalArguments.size()); } })); // Unary BuiltinTypes.BYTE_ARRAY_TYPE.addUnaryMethod(PythonUnaryOperator.REPRESENTATION, PythonByteArray.class.getMethod("repr")); BuiltinTypes.BYTE_ARRAY_TYPE.addUnaryMethod(PythonUnaryOperator.AS_STRING, PythonByteArray.class.getMethod("asString")); BuiltinTypes.BYTE_ARRAY_TYPE.addUnaryMethod(PythonUnaryOperator.ITERATOR, PythonByteArray.class.getMethod("getIterator")); BuiltinTypes.BYTE_ARRAY_TYPE.addUnaryMethod(PythonUnaryOperator.LENGTH, PythonByteArray.class.getMethod("getLength")); // Binary BuiltinTypes.BYTE_ARRAY_TYPE.addBinaryMethod(PythonBinaryOperator.GET_ITEM, PythonByteArray.class.getMethod("getCharAt", PythonInteger.class)); BuiltinTypes.BYTE_ARRAY_TYPE.addBinaryMethod(PythonBinaryOperator.GET_ITEM, PythonByteArray.class.getMethod("getSubsequence", PythonSlice.class)); BuiltinTypes.BYTE_ARRAY_TYPE.addBinaryMethod(PythonBinaryOperator.DELETE_ITEM, PythonByteArray.class.getMethod("deleteIndex", PythonInteger.class)); BuiltinTypes.BYTE_ARRAY_TYPE.addBinaryMethod(PythonBinaryOperator.DELETE_ITEM, PythonByteArray.class.getMethod("deleteSlice", PythonSlice.class)); BuiltinTypes.BYTE_ARRAY_TYPE.addBinaryMethod(PythonBinaryOperator.CONTAINS, PythonByteArray.class.getMethod("containsSubsequence", PythonByteArray.class)); BuiltinTypes.BYTE_ARRAY_TYPE.addBinaryMethod(PythonBinaryOperator.ADD, PythonByteArray.class.getMethod("concat", PythonByteArray.class)); BuiltinTypes.BYTE_ARRAY_TYPE.addBinaryMethod(PythonBinaryOperator.INPLACE_ADD, PythonByteArray.class.getMethod("inplaceAdd", PythonLikeObject.class)); BuiltinTypes.BYTE_ARRAY_TYPE.addBinaryMethod(PythonBinaryOperator.MULTIPLY, PythonByteArray.class.getMethod("repeat", PythonInteger.class)); BuiltinTypes.BYTE_ARRAY_TYPE.addBinaryMethod(PythonBinaryOperator.INPLACE_MULTIPLY, PythonByteArray.class.getMethod("inplaceRepeat", PythonInteger.class)); BuiltinTypes.BYTE_ARRAY_TYPE.addBinaryMethod(PythonBinaryOperator.MODULO, PythonByteArray.class.getMethod("interpolate", PythonLikeObject.class)); BuiltinTypes.BYTE_ARRAY_TYPE.addBinaryMethod(PythonBinaryOperator.MODULO, PythonByteArray.class.getMethod("interpolate", PythonLikeTuple.class)); BuiltinTypes.BYTE_ARRAY_TYPE.addBinaryMethod(PythonBinaryOperator.MODULO, PythonByteArray.class.getMethod("interpolate", PythonLikeDict.class)); // Ternary BuiltinTypes.BYTE_ARRAY_TYPE.addTernaryMethod(PythonTernaryOperator.SET_ITEM, PythonByteArray.class.getMethod("setByte", PythonInteger.class, PythonInteger.class)); BuiltinTypes.BYTE_ARRAY_TYPE.addTernaryMethod(PythonTernaryOperator.SET_ITEM, PythonByteArray.class.getMethod("setSlice", PythonSlice.class, PythonLikeObject.class)); // Other BuiltinTypes.BYTE_ARRAY_TYPE.addMethod("append", PythonByteArray.class.getMethod("appendByte", PythonInteger.class)); BuiltinTypes.BYTE_ARRAY_TYPE.addMethod("clear", PythonByteArray.class.getMethod("clear")); BuiltinTypes.BYTE_ARRAY_TYPE.addMethod("copy", PythonByteArray.class.getMethod("copy")); BuiltinTypes.BYTE_ARRAY_TYPE.addMethod("extend", PythonByteArray.class.getMethod("extend", PythonLikeObject.class)); BuiltinTypes.BYTE_ARRAY_TYPE.addMethod("insert", PythonByteArray.class.getMethod("insert", PythonInteger.class, PythonInteger.class)); BuiltinTypes.BYTE_ARRAY_TYPE.addMethod("pop", PythonByteArray.class.getMethod("pop")); BuiltinTypes.BYTE_ARRAY_TYPE.addMethod("pop", PythonByteArray.class.getMethod("pop", PythonInteger.class)); BuiltinTypes.BYTE_ARRAY_TYPE.addMethod("remove", PythonByteArray.class.getMethod("remove", PythonInteger.class)); BuiltinTypes.BYTE_ARRAY_TYPE.addMethod("reverse", PythonByteArray.class.getMethod("reverse")); BuiltinTypes.BYTE_ARRAY_TYPE.addMethod("capitalize", PythonByteArray.class.getMethod("capitalize")); BuiltinTypes.BYTE_ARRAY_TYPE.addMethod("center", PythonByteArray.class.getMethod("center", PythonInteger.class)); BuiltinTypes.BYTE_ARRAY_TYPE.addMethod("center", PythonByteArray.class.getMethod("center", PythonInteger.class, PythonByteArray.class)); BuiltinTypes.BYTE_ARRAY_TYPE.addMethod("count", PythonByteArray.class.getMethod("count", PythonInteger.class)); BuiltinTypes.BYTE_ARRAY_TYPE.addMethod("count", PythonByteArray.class.getMethod("count", PythonInteger.class, PythonInteger.class)); BuiltinTypes.BYTE_ARRAY_TYPE.addMethod("count", PythonByteArray.class.getMethod("count", PythonInteger.class, PythonInteger.class, PythonInteger.class)); BuiltinTypes.BYTE_ARRAY_TYPE.addMethod("count", PythonByteArray.class.getMethod("count", PythonByteArray.class)); BuiltinTypes.BYTE_ARRAY_TYPE.addMethod("count", PythonByteArray.class.getMethod("count", PythonByteArray.class, PythonInteger.class)); BuiltinTypes.BYTE_ARRAY_TYPE.addMethod("count", PythonByteArray.class.getMethod("count", PythonByteArray.class, PythonInteger.class, PythonInteger.class)); // TODO: decode BuiltinTypes.BYTE_ARRAY_TYPE.addMethod("endswith", PythonByteArray.class.getMethod("endsWith", PythonByteArray.class)); BuiltinTypes.BYTE_ARRAY_TYPE.addMethod("endswith", PythonByteArray.class.getMethod("endsWith", PythonLikeTuple.class)); BuiltinTypes.BYTE_ARRAY_TYPE.addMethod("endswith", PythonByteArray.class.getMethod("endsWith", PythonByteArray.class, PythonInteger.class)); BuiltinTypes.BYTE_ARRAY_TYPE.addMethod("endswith", PythonByteArray.class.getMethod("endsWith", PythonLikeTuple.class, PythonInteger.class)); BuiltinTypes.BYTE_ARRAY_TYPE.addMethod("endswith", PythonByteArray.class.getMethod("endsWith", PythonByteArray.class, PythonInteger.class, PythonInteger.class)); BuiltinTypes.BYTE_ARRAY_TYPE.addMethod("endswith", PythonByteArray.class.getMethod("endsWith", PythonLikeTuple.class, PythonInteger.class, PythonInteger.class)); BuiltinTypes.BYTE_ARRAY_TYPE.addMethod("expandtabs", PythonByteArray.class.getMethod("expandTabs")); BuiltinTypes.BYTE_ARRAY_TYPE.addMethod("expandtabs", PythonByteArray.class.getMethod("expandTabs", PythonInteger.class)); BuiltinTypes.BYTE_ARRAY_TYPE.addMethod("find", PythonByteArray.class.getMethod("find", PythonByteArray.class)); BuiltinTypes.BYTE_ARRAY_TYPE.addMethod("find", PythonByteArray.class.getMethod("find", PythonInteger.class)); BuiltinTypes.BYTE_ARRAY_TYPE.addMethod("find", PythonByteArray.class.getMethod("find", PythonByteArray.class, PythonInteger.class)); BuiltinTypes.BYTE_ARRAY_TYPE.addMethod("find", PythonByteArray.class.getMethod("find", PythonInteger.class, PythonInteger.class)); BuiltinTypes.BYTE_ARRAY_TYPE.addMethod("find", PythonByteArray.class.getMethod("find", PythonByteArray.class, PythonInteger.class, PythonInteger.class)); BuiltinTypes.BYTE_ARRAY_TYPE.addMethod("find", PythonByteArray.class.getMethod("find", PythonInteger.class, PythonInteger.class, PythonInteger.class)); BuiltinTypes.BYTE_ARRAY_TYPE.addMethod("index", PythonByteArray.class.getMethod("index", PythonByteArray.class)); BuiltinTypes.BYTE_ARRAY_TYPE.addMethod("index", PythonByteArray.class.getMethod("index", PythonInteger.class)); BuiltinTypes.BYTE_ARRAY_TYPE.addMethod("index", PythonByteArray.class.getMethod("index", PythonByteArray.class, PythonInteger.class)); BuiltinTypes.BYTE_ARRAY_TYPE.addMethod("index", PythonByteArray.class.getMethod("index", PythonInteger.class, PythonInteger.class)); BuiltinTypes.BYTE_ARRAY_TYPE.addMethod("index", PythonByteArray.class.getMethod("index", PythonByteArray.class, PythonInteger.class, PythonInteger.class)); BuiltinTypes.BYTE_ARRAY_TYPE.addMethod("index", PythonByteArray.class.getMethod("index", PythonInteger.class, PythonInteger.class, PythonInteger.class)); BuiltinTypes.BYTE_ARRAY_TYPE.addMethod("isalnum", PythonByteArray.class.getMethod("isAlphaNumeric")); BuiltinTypes.BYTE_ARRAY_TYPE.addMethod("isalpha", PythonByteArray.class.getMethod("isAlpha")); BuiltinTypes.BYTE_ARRAY_TYPE.addMethod("isascii", PythonByteArray.class.getMethod("isAscii")); BuiltinTypes.BYTE_ARRAY_TYPE.addMethod("isdigit", PythonByteArray.class.getMethod("isDigit")); BuiltinTypes.BYTE_ARRAY_TYPE.addMethod("islower", PythonByteArray.class.getMethod("isLower")); BuiltinTypes.BYTE_ARRAY_TYPE.addMethod("isspace", PythonByteArray.class.getMethod("isSpace")); BuiltinTypes.BYTE_ARRAY_TYPE.addMethod("istitle", PythonByteArray.class.getMethod("isTitle")); BuiltinTypes.BYTE_ARRAY_TYPE.addMethod("isupper", PythonByteArray.class.getMethod("isUpper")); BuiltinTypes.BYTE_ARRAY_TYPE.addMethod("join", PythonByteArray.class.getMethod("join", PythonLikeObject.class)); BuiltinTypes.BYTE_ARRAY_TYPE.addMethod("ljust", PythonByteArray.class.getMethod("leftJustify", PythonInteger.class)); BuiltinTypes.BYTE_ARRAY_TYPE.addMethod("ljust", PythonByteArray.class.getMethod("leftJustify", PythonInteger.class, PythonByteArray.class)); BuiltinTypes.BYTE_ARRAY_TYPE.addMethod("lower", PythonByteArray.class.getMethod("lower")); BuiltinTypes.BYTE_ARRAY_TYPE.addMethod("lstrip", PythonByteArray.class.getMethod("leftStrip")); BuiltinTypes.BYTE_ARRAY_TYPE.addMethod("lstrip", PythonByteArray.class.getMethod("leftStrip", PythonNone.class)); BuiltinTypes.BYTE_ARRAY_TYPE.addMethod("lstrip", PythonByteArray.class.getMethod("leftStrip", PythonByteArray.class)); // TODO: maketrans BuiltinTypes.BYTE_ARRAY_TYPE.addMethod("partition", PythonByteArray.class.getMethod("partition", PythonByteArray.class)); BuiltinTypes.BYTE_ARRAY_TYPE.addMethod("removeprefix", PythonByteArray.class.getMethod("removePrefix", PythonByteArray.class)); BuiltinTypes.BYTE_ARRAY_TYPE.addMethod("removesuffix", PythonByteArray.class.getMethod("removeSuffix", PythonByteArray.class)); BuiltinTypes.BYTE_ARRAY_TYPE.addMethod("replace", PythonByteArray.class.getMethod("replace", PythonByteArray.class, PythonByteArray.class)); BuiltinTypes.BYTE_ARRAY_TYPE.addMethod("replace", PythonByteArray.class.getMethod("replace", PythonByteArray.class, PythonByteArray.class, PythonInteger.class)); BuiltinTypes.BYTE_ARRAY_TYPE.addMethod("rfind", PythonByteArray.class.getMethod("rightFind", PythonByteArray.class)); BuiltinTypes.BYTE_ARRAY_TYPE.addMethod("rfind", PythonByteArray.class.getMethod("rightFind", PythonInteger.class)); BuiltinTypes.BYTE_ARRAY_TYPE.addMethod("rfind", PythonByteArray.class.getMethod("rightFind", PythonByteArray.class, PythonInteger.class)); BuiltinTypes.BYTE_ARRAY_TYPE.addMethod("rfind", PythonByteArray.class.getMethod("rightFind", PythonInteger.class, PythonInteger.class)); BuiltinTypes.BYTE_ARRAY_TYPE.addMethod("rfind", PythonByteArray.class.getMethod("rightFind", PythonByteArray.class, PythonInteger.class, PythonInteger.class)); BuiltinTypes.BYTE_ARRAY_TYPE.addMethod("rfind", PythonByteArray.class.getMethod("rightFind", PythonInteger.class, PythonInteger.class, PythonInteger.class)); BuiltinTypes.BYTE_ARRAY_TYPE.addMethod("rindex", PythonByteArray.class.getMethod("rightIndex", PythonByteArray.class)); BuiltinTypes.BYTE_ARRAY_TYPE.addMethod("rindex", PythonByteArray.class.getMethod("rightIndex", PythonInteger.class)); BuiltinTypes.BYTE_ARRAY_TYPE.addMethod("rindex", PythonByteArray.class.getMethod("rightIndex", PythonByteArray.class, PythonInteger.class)); BuiltinTypes.BYTE_ARRAY_TYPE.addMethod("rindex", PythonByteArray.class.getMethod("rightIndex", PythonInteger.class, PythonInteger.class)); BuiltinTypes.BYTE_ARRAY_TYPE.addMethod("rindex", PythonByteArray.class.getMethod("rightIndex", PythonByteArray.class, PythonInteger.class, PythonInteger.class)); BuiltinTypes.BYTE_ARRAY_TYPE.addMethod("rindex", PythonByteArray.class.getMethod("rightIndex", PythonInteger.class, PythonInteger.class, PythonInteger.class)); BuiltinTypes.BYTE_ARRAY_TYPE.addMethod("rjust", PythonByteArray.class.getMethod("rightJustify", PythonInteger.class)); BuiltinTypes.BYTE_ARRAY_TYPE.addMethod("rjust", PythonByteArray.class.getMethod("rightJustify", PythonInteger.class, PythonByteArray.class)); BuiltinTypes.BYTE_ARRAY_TYPE.addMethod("rpartition", PythonByteArray.class.getMethod("rightPartition", PythonByteArray.class)); BuiltinTypes.BYTE_ARRAY_TYPE.addMethod("rsplit", PythonByteArray.class.getMethod("rightSplit")); BuiltinTypes.BYTE_ARRAY_TYPE.addMethod("rsplit", PythonByteArray.class.getMethod("rightSplit", PythonNone.class)); BuiltinTypes.BYTE_ARRAY_TYPE.addMethod("rsplit", PythonByteArray.class.getMethod("rightSplit", PythonByteArray.class)); BuiltinTypes.BYTE_ARRAY_TYPE.addMethod("rsplit", PythonByteArray.class.getMethod("rightSplit", PythonNone.class, PythonInteger.class)); BuiltinTypes.BYTE_ARRAY_TYPE.addMethod("rsplit", PythonByteArray.class.getMethod("rightSplit", PythonByteArray.class, PythonInteger.class)); BuiltinTypes.BYTE_ARRAY_TYPE.addMethod("rstrip", PythonByteArray.class.getMethod("rightStrip")); BuiltinTypes.BYTE_ARRAY_TYPE.addMethod("rstrip", PythonByteArray.class.getMethod("rightStrip", PythonNone.class)); BuiltinTypes.BYTE_ARRAY_TYPE.addMethod("rstrip", PythonByteArray.class.getMethod("rightStrip", PythonByteArray.class)); BuiltinTypes.BYTE_ARRAY_TYPE.addMethod("split", PythonByteArray.class.getMethod("split")); BuiltinTypes.BYTE_ARRAY_TYPE.addMethod("split", PythonByteArray.class.getMethod("split", PythonNone.class)); BuiltinTypes.BYTE_ARRAY_TYPE.addMethod("split", PythonByteArray.class.getMethod("split", PythonByteArray.class)); BuiltinTypes.BYTE_ARRAY_TYPE.addMethod("split", PythonByteArray.class.getMethod("split", PythonNone.class, PythonInteger.class)); BuiltinTypes.BYTE_ARRAY_TYPE.addMethod("split", PythonByteArray.class.getMethod("split", PythonByteArray.class, PythonInteger.class)); BuiltinTypes.BYTE_ARRAY_TYPE.addMethod("splitlines", PythonByteArray.class.getMethod("splitLines")); BuiltinTypes.BYTE_ARRAY_TYPE.addMethod("splitlines", PythonByteArray.class.getMethod("splitLines", PythonBoolean.class)); BuiltinTypes.BYTE_ARRAY_TYPE.addMethod("startswith", PythonByteArray.class.getMethod("startsWith", PythonByteArray.class)); BuiltinTypes.BYTE_ARRAY_TYPE.addMethod("startswith", PythonByteArray.class.getMethod("startsWith", PythonLikeTuple.class)); BuiltinTypes.BYTE_ARRAY_TYPE.addMethod("startswith", PythonByteArray.class.getMethod("startsWith", PythonByteArray.class, PythonInteger.class)); BuiltinTypes.BYTE_ARRAY_TYPE.addMethod("startswith", PythonByteArray.class.getMethod("startsWith", PythonLikeTuple.class, PythonInteger.class)); BuiltinTypes.BYTE_ARRAY_TYPE.addMethod("startswith", PythonByteArray.class.getMethod("startsWith", PythonByteArray.class, PythonInteger.class, PythonInteger.class)); BuiltinTypes.BYTE_ARRAY_TYPE.addMethod("startswith", PythonByteArray.class.getMethod("startsWith", PythonLikeTuple.class, PythonInteger.class, PythonInteger.class)); BuiltinTypes.BYTE_ARRAY_TYPE.addMethod("strip", PythonByteArray.class.getMethod("strip")); BuiltinTypes.BYTE_ARRAY_TYPE.addMethod("strip", PythonByteArray.class.getMethod("strip", PythonNone.class)); BuiltinTypes.BYTE_ARRAY_TYPE.addMethod("strip", PythonByteArray.class.getMethod("strip", PythonByteArray.class)); BuiltinTypes.BYTE_ARRAY_TYPE.addMethod("swapcase", PythonByteArray.class.getMethod("swapCase")); BuiltinTypes.BYTE_ARRAY_TYPE.addMethod("title", PythonByteArray.class.getMethod("title")); BuiltinTypes.BYTE_ARRAY_TYPE.addMethod("translate", PythonByteArray.class.getMethod("translate", PythonBytes.class)); BuiltinTypes.BYTE_ARRAY_TYPE.addMethod("translate", PythonByteArray.class.getMethod("translate", PythonByteArray.class)); BuiltinTypes.BYTE_ARRAY_TYPE.addMethod("upper", PythonByteArray.class.getMethod("upper")); BuiltinTypes.BYTE_ARRAY_TYPE.addMethod("zfill", PythonByteArray.class.getMethod("zfill", PythonInteger.class)); return BuiltinTypes.BYTE_ARRAY_TYPE; } public ByteBuffer valueBuffer; public PythonByteArray() { super(BuiltinTypes.BYTE_ARRAY_TYPE); this.valueBuffer = ByteBuffer.allocate(4096); valueBuffer.limit(0); } public PythonByteArray(byte[] data) { super(BuiltinTypes.BYTE_ARRAY_TYPE); this.valueBuffer = ByteBuffer.allocate(data.length); valueBuffer.put(data); valueBuffer.position(0); } public PythonByteArray(ByteBuffer valueBuffer) { super(BuiltinTypes.BYTE_ARRAY_TYPE); this.valueBuffer = valueBuffer; } @Override public ByteBuffer asByteBuffer() { return valueBuffer.duplicate().asReadOnlyBuffer(); } public final ByteCharSequence asCharSequence() { return new ByteCharSequence(valueBuffer.array(), 0, valueBuffer.limit()); } public final PythonString asAsciiString() { return PythonString.valueOf(asCharSequence().toString()); } public static PythonByteArray fromIntTuple(PythonLikeTuple tuple) { byte[] out = new byte[tuple.size()]; IntStream.range(0, tuple.size()).forEach(index -> out[index] = ((PythonInteger) tuple.get(index)).asByte()); return new PythonByteArray(out); } public final PythonLikeTuple asIntTuple() { return IntStream.range(0, valueBuffer.limit()) .mapToObj(index -> PythonBytes.BYTE_TO_INT[Byte.toUnsignedInt(valueBuffer.get(index))]) .collect(Collectors.toCollection(PythonLikeTuple::new)); } private static BitSet asBitSet(PythonByteArray bytesInBitSet) { BitSet out = new BitSet(); for (int i = 0; i < bytesInBitSet.valueBuffer.limit(); i++) { out.set(bytesInBitSet.valueBuffer.get(i) & 0xFF); } return out; } public PythonInteger getLength() { return PythonInteger.valueOf(valueBuffer.limit()); } public PythonInteger getCharAt(PythonInteger position) { int index = PythonSlice.asIntIndexForLength(position, valueBuffer.limit()); if (index >= valueBuffer.limit()) { throw new IndexError("position " + position + " larger than bytes length " + valueBuffer.limit()); } else if (index < 0) { throw new IndexError("position " + position + " is less than 0"); } return PythonBytes.BYTE_TO_INT[Byte.toUnsignedInt(valueBuffer.get(index))]; } public PythonByteArray getSubsequence(PythonSlice slice) { int length = valueBuffer.limit(); int start = slice.getStartIndex(length); int stop = slice.getStopIndex(length); int step = slice.getStrideLength(); if (step == 1) { if (stop <= start) { return new PythonByteArray(new byte[] {}); } else { return new PythonByteArray(Arrays.copyOfRange(valueBuffer.array(), start, stop)); } } else { byte[] out = new byte[slice.getSliceSize(length)]; slice.iterate(length, (index, iteration) -> { out[iteration] = valueBuffer.get(index); }); return new PythonByteArray(out); } } public PythonBoolean containsSubsequence(PythonByteArray subsequence) { if (subsequence.valueBuffer.limit() == 0) { return PythonBoolean.TRUE; } if (subsequence.valueBuffer.limit() > valueBuffer.limit()) { return PythonBoolean.FALSE; } for (int i = 0; i <= valueBuffer.limit() - subsequence.valueBuffer.limit(); i++) { if (Arrays.equals(valueBuffer.array(), i, i + subsequence.valueBuffer.limit(), subsequence.valueBuffer.array(), 0, subsequence.valueBuffer.limit())) { return PythonBoolean.TRUE; } } return PythonBoolean.FALSE; } public PythonByteArray concat(PythonByteArray other) { if (valueBuffer.limit() == 0) { return new PythonByteArray(other.valueBuffer.duplicate()); } else if (other.valueBuffer.limit() == 0) { return new PythonByteArray(valueBuffer.duplicate()); } else { byte[] out = new byte[valueBuffer.limit() + other.valueBuffer.limit()]; System.arraycopy(valueBuffer.array(), 0, out, 0, valueBuffer.limit()); System.arraycopy(other.valueBuffer.array(), 0, out, valueBuffer.limit(), other.valueBuffer.limit()); return new PythonByteArray(out); } } public PythonByteArray repeat(PythonInteger times) { int timesAsInt = times.value.intValueExact(); if (timesAsInt <= 0) { return new PythonByteArray(new byte[] {}); } byte[] out = new byte[valueBuffer.limit() * timesAsInt]; for (int i = 0; i < timesAsInt; i++) { System.arraycopy(valueBuffer.array(), 0, out, i * valueBuffer.limit(), valueBuffer.limit()); } return new PythonByteArray(out); } public DelegatePythonIterator<PythonInteger> getIterator() { return new DelegatePythonIterator<>(IntStream.range(0, valueBuffer.limit()) .mapToObj(index -> PythonBytes.BYTE_TO_INT[Byte.toUnsignedInt(valueBuffer.get(index))]) .iterator()); } public PythonInteger countByte(byte query, int start, int end) { int count = 0; for (int i = start; i < end; i++) { if (valueBuffer.get(i) == query) { count++; } } return PythonInteger.valueOf(count); } public PythonInteger count(PythonInteger byteAsInt) { byte query = byteAsInt.asByte(); return countByte(query, 0, valueBuffer.limit()); } public PythonInteger count(PythonInteger byteAsInt, PythonInteger start) { byte query = byteAsInt.asByte(); int startAsInt = PythonSlice.asValidStartIntIndexForLength(start, valueBuffer.limit()); return countByte(query, startAsInt, valueBuffer.limit()); } public PythonInteger count(PythonInteger byteAsInt, PythonInteger start, PythonInteger end) { byte query = byteAsInt.asByte(); int startAsInt = PythonSlice.asValidStartIntIndexForLength(start, valueBuffer.limit()); int endAsInt = PythonSlice.asValidEndIntIndexForLength(end, valueBuffer.limit()); return countByte(query, startAsInt, endAsInt); } private PythonInteger countSubsequence(byte[] query, int from, int to) { int count = 0; if ((to - from) == 0 || query.length > (to - from)) { return PythonInteger.ZERO; } if (query.length == 0) { return PythonInteger.valueOf((to - from) + 1); } for (int i = from; i <= to - query.length; i++) { if (Arrays.equals(valueBuffer.array(), i, i + query.length, query, 0, query.length)) { count++; i += query.length - 1; } } return PythonInteger.valueOf(count); } public PythonInteger count(PythonByteArray bytes) { return countSubsequence(bytes.valueBuffer.array(), 0, valueBuffer.limit()); } public PythonInteger count(PythonByteArray bytes, PythonInteger start) { int startAsInt = PythonSlice.asValidStartIntIndexForLength(start, valueBuffer.limit()); return countSubsequence(bytes.valueBuffer.array(), startAsInt, valueBuffer.limit()); } public PythonInteger count(PythonByteArray bytes, PythonInteger start, PythonInteger end) { int startAsInt = PythonSlice.asValidStartIntIndexForLength(start, valueBuffer.limit()); int endAsInt = PythonSlice.asValidEndIntIndexForLength(end, valueBuffer.limit()); return countSubsequence(bytes.valueBuffer.array(), startAsInt, endAsInt); } private static byte[] getBytes(PythonLikeObject iterable) { if (iterable instanceof PythonBytes) { return ((PythonBytes) iterable).value; } else if (iterable instanceof PythonByteArray) { return ((PythonByteArray) iterable).asByteArray(); } else { PythonIterator<?> iterator = (PythonIterator<?>) UnaryDunderBuiltin.ITERATOR.invoke(iterable); ByteArrayOutputStream out = new ByteArrayOutputStream(); while (iterator.hasNext()) { PythonLikeObject next = iterator.nextPythonItem(); byte[] byteWrapper = new byte[1]; if (!(next instanceof PythonInteger)) { throw new TypeError("'" + next.$getType().getTypeName() + "' object cannot be interpreted as an integer"); } byteWrapper[0] = ((PythonInteger) next).asByte(); out.writeBytes(byteWrapper); } return out.toByteArray(); } } private void ensureCapacity(int minimumCapacity) { int oldCapacity = valueBuffer.capacity(); if (oldCapacity >= minimumCapacity) { return; } int newCapacity = Math.max(oldCapacity + (oldCapacity >> 1), minimumCapacity); ByteBuffer newValueBuffer = ByteBuffer.allocate(newCapacity); System.arraycopy(valueBuffer.array(), 0, newValueBuffer.array(), 0, valueBuffer.limit()); newValueBuffer.limit(valueBuffer.limit()); this.valueBuffer = newValueBuffer; } private void insertExtraBytesAt(int position, int extraBytes) { System.arraycopy(valueBuffer.array(), position, valueBuffer.array(), position + extraBytes, valueBuffer.limit() - position); valueBuffer.limit(valueBuffer.limit() + extraBytes); } private void removeBytesStartingAt(int position, int removedBytes) { System.arraycopy(valueBuffer.array(), position + removedBytes, valueBuffer.array(), position, valueBuffer.limit() - position - removedBytes); valueBuffer.limit(valueBuffer.limit() - removedBytes); } public PythonNone setByte(PythonInteger index, PythonInteger item) { int indexAsInt = PythonSlice.asIntIndexForLength(index, valueBuffer.limit()); if (indexAsInt < 0 || indexAsInt >= valueBuffer.limit()) { throw new IndexError("bytearray index out of range"); } valueBuffer.put(indexAsInt, item.asByte()); return PythonNone.INSTANCE; } public PythonNone setSlice(PythonSlice slice, PythonLikeObject iterable) { byte[] iterableBytes = getBytes(iterable); if (slice.getStrideLength() == 1) { int sizeDifference = iterableBytes.length - slice.getSliceSize(valueBuffer.limit()); if (sizeDifference == 0) { valueBuffer.position(slice.getStartIndex(valueBuffer.limit())); valueBuffer.put(iterableBytes); } else if (sizeDifference > 0) { // inserted extra bytes int oldLimit = valueBuffer.limit(); ensureCapacity(valueBuffer.capacity() + sizeDifference); insertExtraBytesAt(slice.getStopIndex(oldLimit), sizeDifference); System.arraycopy(iterableBytes, 0, valueBuffer.array(), slice.getStartIndex(oldLimit), iterableBytes.length); } else { // removed some bytes int oldLimit = valueBuffer.limit(); removeBytesStartingAt(slice.getStopIndex(oldLimit) + sizeDifference, -sizeDifference); System.arraycopy(iterableBytes, 0, valueBuffer.array(), slice.getStartIndex(oldLimit), iterableBytes.length); } } else { if (iterableBytes.length == 0) { deleteSlice(slice); } else { if (iterableBytes.length != slice.getSliceSize(valueBuffer.limit())) { throw new ValueError( "attempt to assign bytes of size " + iterableBytes.length + " to extended slice of size " + slice.getSliceSize(valueBuffer.limit())); } slice.iterate(valueBuffer.limit(), (index, step) -> { valueBuffer.put(index, iterableBytes[step]); }); } } return PythonNone.INSTANCE; } public PythonNone deleteIndex(PythonInteger index) { int indexAsInt = PythonSlice.asIntIndexForLength(index, valueBuffer.limit()); removeBytesStartingAt(indexAsInt, 1); return PythonNone.INSTANCE; } public PythonNone deleteSlice(PythonSlice deletedSlice) { if (deletedSlice.getStrideLength() == 1) { removeBytesStartingAt(deletedSlice.getStartIndex(valueBuffer.limit()), deletedSlice.getSliceSize(valueBuffer.limit())); } else { if (deletedSlice.getStrideLength() > 0) { deletedSlice.iterate(valueBuffer.limit(), (index, step) -> { removeBytesStartingAt(index - step, 1); }); } else { deletedSlice.iterate(valueBuffer.limit(), (index, step) -> { removeBytesStartingAt(index, 1); }); } } return PythonNone.INSTANCE; } public PythonNone appendByte(PythonInteger addedByte) { byte toAdd = addedByte.asByte(); ensureCapacity(valueBuffer.limit() + 1); valueBuffer.limit(valueBuffer.limit() + 1); valueBuffer.position(valueBuffer.limit() - 1); valueBuffer.put(toAdd); return PythonNone.INSTANCE; } public PythonNone clear() { valueBuffer.limit(0); return PythonNone.INSTANCE; } public PythonByteArray copy() { byte[] copiedData = asByteArray(); return new PythonByteArray(copiedData); } public PythonNone extend(PythonLikeObject iterable) { byte[] data = getBytes(iterable); ensureCapacity(valueBuffer.limit() + data.length); int oldLimit = valueBuffer.limit(); valueBuffer.limit(valueBuffer.limit() + data.length); valueBuffer.position(oldLimit); valueBuffer.put(data); return PythonNone.INSTANCE; } public PythonByteArray inplaceAdd(PythonLikeObject iterable) { extend(iterable); return this; } public PythonByteArray inplaceRepeat(PythonLikeObject indexable) { return inplaceRepeat((PythonInteger) UnaryDunderBuiltin.INDEX.invoke(indexable)); } public PythonByteArray inplaceRepeat(PythonInteger index) { int indexAsInt = index.value.intValueExact(); if (indexAsInt <= 0) { clear(); return this; } else if (indexAsInt == 1) { return this; } else { ensureCapacity(valueBuffer.limit() * indexAsInt); int oldLimit = valueBuffer.limit(); valueBuffer.limit(oldLimit * indexAsInt); for (int i = 1; i < indexAsInt; i++) { System.arraycopy(valueBuffer.array(), 0, valueBuffer.array(), i * oldLimit, oldLimit); } return this; } } public PythonNone insert(PythonInteger index, PythonInteger value) { byte toInsert = value.asByte(); ensureCapacity(valueBuffer.limit() + 1); int indexAsInt = PythonSlice.asIntIndexForLength(index, valueBuffer.limit()); if (indexAsInt < 0) { indexAsInt = 0; } if (indexAsInt > valueBuffer.limit()) { indexAsInt = valueBuffer.limit(); } insertExtraBytesAt(indexAsInt, 1); valueBuffer.position(indexAsInt); valueBuffer.put(toInsert); return PythonNone.INSTANCE; } public PythonInteger pop() { if (valueBuffer.limit() == 0) { throw new IndexError("pop from empty bytearray"); } PythonInteger out = PythonBytes.BYTE_TO_INT[Byte.toUnsignedInt(valueBuffer.get(valueBuffer.limit() - 1))]; valueBuffer.limit(valueBuffer.limit() - 1); return out; } public PythonInteger pop(PythonInteger index) { int indexAsInt = PythonSlice.asIntIndexForLength(index, valueBuffer.limit()); if (valueBuffer.limit() == 0) { throw new IndexError("pop from empty bytearray"); } if (indexAsInt < 0 || indexAsInt > valueBuffer.limit()) { throw new IndexError("index out of range for bytearray"); } PythonInteger out = PythonBytes.BYTE_TO_INT[Byte.toUnsignedInt(valueBuffer.get(indexAsInt))]; removeBytesStartingAt(indexAsInt, 1); return out; } public PythonNone remove(PythonInteger item) { byte queryByte = item.asByte(); for (int i = 0; i < valueBuffer.limit(); i++) { if (valueBuffer.get(i) == queryByte) { removeBytesStartingAt(i, 1); return PythonNone.INSTANCE; } } throw new ValueError("Subsequence not found"); } public PythonNone reverse() { int limit = valueBuffer.limit(); byte[] data = valueBuffer.array(); for (int i = 0; i < limit >> 1; i++) { byte temp = data[i]; data[i] = data[data.length - i - 1]; data[data.length - i - 1] = temp; } return PythonNone.INSTANCE; } public boolean hasPrefix(ByteBuffer prefixBytes, int start, int end) { if (prefixBytes.limit() > end - start) { return false; } return Arrays.equals(valueBuffer.array(), start, start + prefixBytes.limit(), prefixBytes.array(), 0, prefixBytes.limit()); } public boolean hasSuffix(ByteBuffer suffixBytes, int start, int end) { if (suffixBytes.limit() > end - start) { return false; } return Arrays.equals(valueBuffer.array(), end - suffixBytes.limit(), end, suffixBytes.array(), 0, suffixBytes.limit()); } public PythonByteArray removePrefix(PythonByteArray prefix) { return hasPrefix(prefix.valueBuffer, 0, valueBuffer.limit()) ? new PythonByteArray(Arrays.copyOfRange(valueBuffer.array(), prefix.valueBuffer.limit(), valueBuffer.limit())) : this; } public PythonByteArray removeSuffix(PythonByteArray suffix) { return hasSuffix(suffix.valueBuffer, 0, valueBuffer.limit()) ? new PythonByteArray( Arrays.copyOfRange(valueBuffer.array(), 0, valueBuffer.limit() - suffix.valueBuffer.limit())) : this; } public PythonString decode() { try { return PythonString.valueOf(StandardCharsets.UTF_8.newDecoder() .onMalformedInput(CodingErrorAction.REPORT) .decode(valueBuffer).toString()); } catch (CharacterCodingException e) { throw new UnicodeDecodeError(e.getMessage()); } } public PythonString decode(PythonString charset) { try { return PythonString.valueOf(Charset.forName(charset.value).newDecoder() .onMalformedInput(CodingErrorAction.REPORT) .decode(valueBuffer).toString()); } catch (CharacterCodingException e) { throw new UnicodeDecodeError(e.getMessage()); } } public PythonString decode(PythonString charset, PythonString errorActionString) { CodingErrorAction errorAction; switch (errorActionString.value) { case "strict": errorAction = CodingErrorAction.REPORT; break; case "ignore": errorAction = CodingErrorAction.IGNORE; break; case "replace": errorAction = CodingErrorAction.REPLACE; break; default: throw new ValueError(errorActionString.repr() + " is not a valid value for errors. Possible values are: " + "\"strict\", \"ignore\", \"replace\"."); } try { return PythonString.valueOf(Charset.forName(charset.value).newDecoder() .onMalformedInput(errorAction) .decode(valueBuffer).toString()); } catch (CharacterCodingException e) { throw new UnicodeDecodeError(e.getMessage()); } } public PythonBoolean endsWith(PythonByteArray suffix) { return PythonBoolean.valueOf(hasSuffix(suffix.valueBuffer, 0, valueBuffer.limit())); } public PythonBoolean endsWith(PythonByteArray suffix, PythonInteger start) { int startAsInt = PythonSlice.asValidStartIntIndexForLength(start, valueBuffer.limit()); return PythonBoolean.valueOf(hasSuffix(suffix.valueBuffer, startAsInt, valueBuffer.limit())); } public PythonBoolean endsWith(PythonByteArray suffix, PythonInteger start, PythonInteger end) { int startAsInt = PythonSlice.asValidStartIntIndexForLength(start, valueBuffer.limit()); int endAsInt = PythonSlice.asValidEndIntIndexForLength(end, valueBuffer.limit()); return PythonBoolean.valueOf(hasSuffix(suffix.valueBuffer, startAsInt, endAsInt)); } public PythonBoolean endsWith(PythonLikeTuple<PythonByteArray> suffixes) { for (PythonByteArray suffix : suffixes) { if (hasSuffix(suffix.valueBuffer, 0, valueBuffer.limit())) { return PythonBoolean.TRUE; } } return PythonBoolean.FALSE; } public PythonBoolean endsWith(PythonLikeTuple<PythonByteArray> suffixes, PythonInteger start) { int startAsInt = PythonSlice.asValidStartIntIndexForLength(start, valueBuffer.limit()); for (PythonByteArray suffix : suffixes) { if (hasSuffix(suffix.valueBuffer, startAsInt, valueBuffer.limit())) { return PythonBoolean.TRUE; } } return PythonBoolean.FALSE; } public PythonBoolean endsWith(PythonLikeTuple<PythonByteArray> suffixes, PythonInteger start, PythonInteger end) { int startAsInt = PythonSlice.asValidStartIntIndexForLength(start, valueBuffer.limit()); int endAsInt = PythonSlice.asValidEndIntIndexForLength(end, valueBuffer.limit()); for (PythonByteArray suffix : suffixes) { if (hasSuffix(suffix.valueBuffer, startAsInt, endAsInt)) { return PythonBoolean.TRUE; } } return PythonBoolean.FALSE; } private PythonInteger find(PythonInteger query, int start, int end) { byte queryByte = query.asByte(); for (int i = start; i < end; i++) { if (valueBuffer.get(i) == queryByte) { return PythonInteger.valueOf(i); } } return PythonInteger.valueOf(-1); } private PythonInteger index(PythonInteger query, int start, int end) { byte queryByte = query.asByte(); for (int i = start; i < end; i++) { if (valueBuffer.get(i) == queryByte) { return PythonInteger.valueOf(i); } } throw new ValueError("Subsequence not found"); } public PythonInteger find(PythonInteger query) { return find(query, 0, valueBuffer.limit()); } public PythonInteger find(PythonInteger query, PythonInteger start) { int startAsInt = PythonSlice.asValidStartIntIndexForLength(start, valueBuffer.limit()); return find(query, startAsInt, valueBuffer.limit()); } public PythonInteger find(PythonInteger query, PythonInteger start, PythonInteger end) { int startAsInt = PythonSlice.asValidStartIntIndexForLength(start, valueBuffer.limit()); int endAsInt = PythonSlice.asValidEndIntIndexForLength(end, valueBuffer.limit()); return find(query, startAsInt, endAsInt); } public PythonInteger index(PythonInteger query) { return index(query, 0, valueBuffer.limit()); } public PythonInteger index(PythonInteger query, PythonInteger start) { int startAsInt = PythonSlice.asValidStartIntIndexForLength(start, valueBuffer.limit()); return index(query, startAsInt, valueBuffer.limit()); } public PythonInteger index(PythonInteger query, PythonInteger start, PythonInteger end) { int startAsInt = PythonSlice.asValidStartIntIndexForLength(start, valueBuffer.limit()); int endAsInt = PythonSlice.asValidEndIntIndexForLength(end, valueBuffer.limit()); return index(query, startAsInt, endAsInt); } private PythonInteger find(PythonBytesLikeObject query, int start, int end) { byte[] queryBytes = query.asByteArray(); if (queryBytes.length == 0) { return (valueBuffer.limit() > 0) ? PythonInteger.ZERO : PythonInteger.valueOf(-1); } for (int i = start; i <= end - queryBytes.length; i++) { if (Arrays.equals(valueBuffer.array(), i, i + queryBytes.length, queryBytes, 0, queryBytes.length)) { return PythonInteger.valueOf(i); } } return PythonInteger.valueOf(-1); } private PythonInteger index(PythonBytesLikeObject query, int start, int end) { byte[] queryBytes = query.asByteArray(); if (queryBytes.length == 0) { if (valueBuffer.limit() > 0) { return PythonInteger.ZERO; } else { throw new ValueError("Subsequence not found"); } } for (int i = start; i <= end - queryBytes.length; i++) { if (Arrays.equals(valueBuffer.array(), i, i + queryBytes.length, queryBytes, 0, queryBytes.length)) { return PythonInteger.valueOf(i); } } throw new ValueError("Subsequence not found"); } public PythonInteger find(PythonByteArray query) { return find(query, 0, valueBuffer.limit()); } public PythonInteger find(PythonByteArray query, PythonInteger start) { int startAsInt = PythonSlice.asValidStartIntIndexForLength(start, valueBuffer.limit()); return find(query, startAsInt, valueBuffer.limit()); } public PythonInteger find(PythonByteArray query, PythonInteger start, PythonInteger end) { int startAsInt = PythonSlice.asValidStartIntIndexForLength(start, valueBuffer.limit()); int endAsInt = PythonSlice.asValidEndIntIndexForLength(end, valueBuffer.limit()); return find(query, startAsInt, endAsInt); } public PythonInteger index(PythonByteArray query) { return index(query, 0, valueBuffer.limit()); } public PythonInteger index(PythonByteArray query, PythonInteger start) { int startAsInt = PythonSlice.asValidStartIntIndexForLength(start, valueBuffer.limit()); return index(query, startAsInt, valueBuffer.limit()); } public PythonInteger index(PythonByteArray query, PythonInteger start, PythonInteger end) { int startAsInt = PythonSlice.asValidStartIntIndexForLength(start, valueBuffer.limit()); int endAsInt = PythonSlice.asValidEndIntIndexForLength(end, valueBuffer.limit()); return index(query, startAsInt, endAsInt); } public PythonByteArray interpolate(PythonLikeObject object) { if (object instanceof PythonLikeTuple) { return interpolate((PythonLikeTuple) object); } else if (object instanceof PythonLikeDict) { return interpolate((PythonLikeDict) object); } else { return interpolate(PythonLikeTuple.fromItems(object)); } } public PythonByteArray interpolate(PythonLikeTuple tuple) { return PythonString.valueOf(StringFormatter.printfInterpolate(asCharSequence(), tuple, StringFormatter.PrintfStringType.BYTES)).asAsciiByteArray(); } public PythonByteArray interpolate(PythonLikeDict dict) { return PythonString.valueOf(StringFormatter.printfInterpolate(asCharSequence(), dict, StringFormatter.PrintfStringType.BYTES)).asAsciiByteArray(); } public PythonByteArray join(PythonLikeObject iterable) { PythonIterator<?> iterator = (PythonIterator<?>) UnaryDunderBuiltin.ITERATOR.invoke(iterable); ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); while (iterator.hasNext()) { PythonLikeObject item = iterator.nextPythonItem(); if (!(item instanceof PythonBytesLikeObject)) { throw new TypeError("type " + item.$getType() + " is not a bytes-like type"); } outputStream.writeBytes(((PythonBytesLikeObject) item).asByteArray()); if (iterator.hasNext()) { outputStream.write(valueBuffer.array(), 0, valueBuffer.limit()); } } return new PythonByteArray(outputStream.toByteArray()); } private PythonLikeTuple partition(PythonBytesLikeObject sep, int start, int end) { byte[] sepBytes = sep.asByteArray(); for (int i = start; i < end - sepBytes.length; i++) { int j = 0; for (; j < sepBytes.length; j++) { if (valueBuffer.get(i + j) != sepBytes[j]) { break; } } if (j == sepBytes.length) { return PythonLikeTuple.fromItems( new PythonByteArray(Arrays.copyOfRange(valueBuffer.array(), 0, i)), sep, new PythonByteArray( Arrays.copyOfRange(valueBuffer.array(), i + sepBytes.length, valueBuffer.limit()))); } } return PythonLikeTuple.fromItems( this, new PythonByteArray(new byte[] {}), new PythonByteArray(new byte[] {})); } public PythonLikeTuple partition(PythonByteArray sep) { return partition(sep, 0, valueBuffer.limit()); } public PythonLikeTuple partition(PythonByteArray sep, PythonInteger start) { int startAsInt = PythonSlice.asValidStartIntIndexForLength(start, valueBuffer.limit()); return partition(sep, startAsInt, valueBuffer.limit()); } public PythonLikeTuple partition(PythonByteArray sep, PythonInteger start, PythonInteger end) { int startAsInt = PythonSlice.asValidStartIntIndexForLength(start, valueBuffer.limit()); int endAsInt = PythonSlice.asValidStartIntIndexForLength(end, valueBuffer.limit()); return partition(sep, startAsInt, endAsInt); } public PythonByteArray replace(PythonBytesLikeObject old, PythonBytesLikeObject replacement) { byte[] oldBytes = old.asByteArray(); byte[] replacementBytes = replacement.asByteArray(); ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); int lastReplacementEnd = 0; for (int i = 0; i < valueBuffer.limit() - oldBytes.length; i++) { if (!Arrays.equals(valueBuffer.array(), i, i + oldBytes.length, oldBytes, 0, oldBytes.length)) { continue; } outputStream.write(valueBuffer.array(), lastReplacementEnd, i - lastReplacementEnd); outputStream.writeBytes(replacementBytes); i += oldBytes.length; lastReplacementEnd = i; } outputStream.write(valueBuffer.array(), lastReplacementEnd, valueBuffer.limit() - lastReplacementEnd); return new PythonByteArray(outputStream.toByteArray()); } public PythonByteArray replace(PythonBytesLikeObject old, PythonBytesLikeObject replacement, BigInteger count) { byte[] oldBytes = old.asByteArray(); byte[] replacementBytes = replacement.asByteArray(); ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); int lastReplacementEnd = 0; for (int i = 0; i < valueBuffer.limit() - oldBytes.length; i++) { if (count.compareTo(BigInteger.ZERO) == 0) { break; } if (!Arrays.equals(valueBuffer.array(), i, i + oldBytes.length, oldBytes, 0, oldBytes.length)) { continue; } outputStream.write(valueBuffer.array(), lastReplacementEnd, i - lastReplacementEnd); outputStream.writeBytes(replacementBytes); i += oldBytes.length; lastReplacementEnd = i; count = count.subtract(BigInteger.ONE); } outputStream.write(valueBuffer.array(), lastReplacementEnd, valueBuffer.limit() - lastReplacementEnd); return new PythonByteArray(outputStream.toByteArray()); } public PythonByteArray replace(PythonByteArray old, PythonByteArray replacement) { return replace((PythonBytesLikeObject) old, replacement); } public PythonByteArray replace(PythonByteArray old, PythonByteArray replacement, PythonInteger count) { return replace(old, replacement, count.value); } private PythonInteger rightFind(PythonInteger query, int start, int end) { byte queryByte = query.asByte(); for (int i = end - 1; i >= start; i--) { if (valueBuffer.get(i) == queryByte) { return PythonInteger.valueOf(i); } } return PythonInteger.valueOf(-1); } private PythonInteger rightIndex(PythonInteger query, int start, int end) { byte queryByte = query.asByte(); for (int i = end - 1; i >= start; i--) { if (valueBuffer.get(i) == queryByte) { return PythonInteger.valueOf(i); } } throw new ValueError("Subsequence not found"); } public PythonInteger rightFind(PythonInteger query) { return rightFind(query, 0, valueBuffer.limit()); } public PythonInteger rightFind(PythonInteger query, PythonInteger start) { int startAsInt = PythonSlice.asValidStartIntIndexForLength(start, valueBuffer.limit()); return rightFind(query, startAsInt, valueBuffer.limit()); } public PythonInteger rightFind(PythonInteger query, PythonInteger start, PythonInteger end) { int startAsInt = PythonSlice.asValidStartIntIndexForLength(start, valueBuffer.limit()); int endAsInt = PythonSlice.asValidEndIntIndexForLength(end, valueBuffer.limit()); return rightFind(query, startAsInt, endAsInt); } public PythonInteger rightIndex(PythonInteger query) { return rightIndex(query, 0, valueBuffer.limit()); } public PythonInteger rightIndex(PythonInteger query, PythonInteger start) { int startAsInt = PythonSlice.asValidStartIntIndexForLength(start, valueBuffer.limit()); return rightIndex(query, startAsInt, valueBuffer.limit()); } public PythonInteger rightIndex(PythonInteger query, PythonInteger start, PythonInteger end) { int startAsInt = PythonSlice.asValidStartIntIndexForLength(start, valueBuffer.limit()); int endAsInt = PythonSlice.asValidEndIntIndexForLength(end, valueBuffer.limit()); return rightIndex(query, startAsInt, endAsInt); } private PythonInteger rightFind(PythonBytesLikeObject query, int start, int end) { byte[] queryBytes = query.asByteArray(); for (int i = end - queryBytes.length; i >= start; i--) { int j = 0; for (; j < queryBytes.length; j++) { if (valueBuffer.get(i + j) != queryBytes[j]) { break; } } if (j == queryBytes.length) { return PythonInteger.valueOf(i); } } return PythonInteger.valueOf(-1); } private PythonInteger rightIndex(PythonBytesLikeObject query, int start, int end) { byte[] queryBytes = query.asByteArray(); for (int i = end - queryBytes.length; i >= start; i--) { int j = 0; for (; j < queryBytes.length; j++) { if (valueBuffer.get(i + j) != queryBytes[j]) { break; } } if (j == queryBytes.length) { return PythonInteger.valueOf(i); } } throw new ValueError("Subsequence not found"); } public PythonInteger rightFind(PythonByteArray query) { return rightFind(query, 0, valueBuffer.limit()); } public PythonInteger rightFind(PythonByteArray query, PythonInteger start) { int startAsInt = PythonSlice.asValidStartIntIndexForLength(start, valueBuffer.limit()); return rightFind(query, startAsInt, valueBuffer.limit()); } public PythonInteger rightFind(PythonByteArray query, PythonInteger start, PythonInteger end) { int startAsInt = PythonSlice.asValidStartIntIndexForLength(start, valueBuffer.limit()); int endAsInt = PythonSlice.asValidEndIntIndexForLength(end, valueBuffer.limit()); return rightFind(query, startAsInt, endAsInt); } public PythonInteger rightIndex(PythonByteArray query) { return rightIndex(query, 0, valueBuffer.limit()); } public PythonInteger rightIndex(PythonByteArray query, PythonInteger start) { int startAsInt = PythonSlice.asValidStartIntIndexForLength(start, valueBuffer.limit()); return rightIndex(query, startAsInt, valueBuffer.limit()); } public PythonInteger rightIndex(PythonByteArray query, PythonInteger start, PythonInteger end) { int startAsInt = PythonSlice.asValidStartIntIndexForLength(start, valueBuffer.limit()); int endAsInt = PythonSlice.asValidEndIntIndexForLength(end, valueBuffer.limit()); return rightIndex(query, startAsInt, endAsInt); } private PythonLikeTuple rightPartition(PythonBytesLikeObject sep, int start, int end) { byte[] sepBytes = sep.asByteArray(); for (int i = end - sepBytes.length; i >= start; i--) { if (!Arrays.equals(valueBuffer.array(), i, i + sepBytes.length, sepBytes, 0, sepBytes.length)) { continue; } return PythonLikeTuple.fromItems( new PythonByteArray(Arrays.copyOfRange(valueBuffer.array(), 0, i)), sep, new PythonByteArray(Arrays.copyOfRange(valueBuffer.array(), i + sepBytes.length, valueBuffer.limit()))); } return PythonLikeTuple.fromItems( new PythonByteArray(new byte[] {}), new PythonByteArray(new byte[] {}), this); } public PythonLikeTuple rightPartition(PythonByteArray sep) { return rightPartition(sep, 0, valueBuffer.limit()); } public PythonBoolean startsWith(PythonByteArray prefix) { return PythonBoolean.valueOf(hasPrefix(prefix.valueBuffer, 0, valueBuffer.limit())); } public PythonBoolean startsWith(PythonByteArray prefix, PythonInteger start) { int startAsInt = PythonSlice.asValidStartIntIndexForLength(start, valueBuffer.limit()); return PythonBoolean.valueOf(hasPrefix(prefix.valueBuffer, startAsInt, valueBuffer.limit())); } public PythonBoolean startsWith(PythonByteArray prefix, PythonInteger start, PythonInteger end) { int startAsInt = PythonSlice.asValidStartIntIndexForLength(start, valueBuffer.limit()); int endAsInt = PythonSlice.asValidEndIntIndexForLength(end, valueBuffer.limit()); return PythonBoolean.valueOf(hasPrefix(prefix.valueBuffer, startAsInt, endAsInt)); } public PythonBoolean startsWith(PythonLikeTuple<PythonByteArray> prefixes) { for (PythonByteArray prefix : prefixes) { if (hasPrefix(prefix.valueBuffer, 0, valueBuffer.limit())) { return PythonBoolean.TRUE; } } return PythonBoolean.FALSE; } public PythonBoolean startsWith(PythonLikeTuple<PythonByteArray> prefixes, PythonInteger start) { int startAsInt = PythonSlice.asValidStartIntIndexForLength(start, valueBuffer.limit()); for (PythonByteArray prefix : prefixes) { if (hasPrefix(prefix.valueBuffer, startAsInt, valueBuffer.limit())) { return PythonBoolean.TRUE; } } return PythonBoolean.FALSE; } public PythonBoolean startsWith(PythonLikeTuple<PythonByteArray> prefixes, PythonInteger start, PythonInteger end) { int startAsInt = PythonSlice.asValidStartIntIndexForLength(start, valueBuffer.limit()); int endAsInt = PythonSlice.asValidEndIntIndexForLength(end, valueBuffer.limit()); for (PythonByteArray prefix : prefixes) { if (hasPrefix(prefix.valueBuffer, startAsInt, endAsInt)) { return PythonBoolean.TRUE; } } return PythonBoolean.FALSE; } public PythonByteArray translate(PythonBytes table) { byte[] tableBytes = table.value; if (tableBytes.length != 256) { throw new ValueError("translate table must be a bytes object of length 256"); } byte[] out = new byte[valueBuffer.limit()]; for (int i = 0; i < valueBuffer.limit(); i++) { out[i] = tableBytes[valueBuffer.get(i) & 0xFF]; } return new PythonByteArray(out); } public PythonByteArray translate(PythonByteArray table) { if (table.valueBuffer.limit() != 256) { throw new ValueError("translate table must be a bytes object of length 256"); } byte[] out = new byte[valueBuffer.limit()]; for (int i = 0; i < valueBuffer.limit(); i++) { out[i] = table.valueBuffer.get(valueBuffer.get(i) & 0xFF); } return new PythonByteArray(out); } public PythonByteArray translate(PythonNone table) { return this; } public PythonByteArray translate(PythonBytes table, PythonByteArray delete) { byte[] tableBytes = table.value; if (tableBytes.length != 256) { throw new ValueError("translate table must be a bytes object of length 256"); } ByteArrayOutputStream out = new ByteArrayOutputStream(valueBuffer.limit()); BitSet removedSet = asBitSet(delete); for (int i = 0; i < valueBuffer.limit(); i++) { byte b = valueBuffer.get(i); if (!removedSet.get(b & 0xFF)) { out.write(tableBytes, b & 0xFF, 1); } } return new PythonByteArray(out.toByteArray()); } public PythonByteArray translate(PythonNone table, PythonByteArray delete) { ByteArrayOutputStream out = new ByteArrayOutputStream(valueBuffer.limit()); BitSet removedSet = asBitSet(delete); for (int i = 0; i < valueBuffer.limit(); i++) { if (!removedSet.get(valueBuffer.get(i) & 0xFF)) { out.write(valueBuffer.array(), i, 1); } } return new PythonByteArray(out.toByteArray()); } public PythonByteArray translate(PythonByteArray table, PythonByteArray delete) { if (table.valueBuffer.limit() != 256) { throw new ValueError("translate table must be a bytes object of length 256"); } ByteArrayOutputStream out = new ByteArrayOutputStream(valueBuffer.limit()); BitSet removedSet = asBitSet(delete); for (int i = 0; i < valueBuffer.limit(); i++) { byte b = valueBuffer.get(i); if (!removedSet.get(b & 0xFF)) { out.write(table.valueBuffer.array(), b & 0xFF, 1); } } return new PythonByteArray(out.toByteArray()); } public PythonByteArray center(PythonInteger fillWidth) { return center(fillWidth, ASCII_SPACE); } public PythonByteArray center(PythonInteger fillWidth, PythonByteArray fillCharacter) { if (fillCharacter.valueBuffer.limit() != 1) { throw new TypeError("center() argument 2 must be a byte string of length 1"); } int widthAsInt = fillWidth.value.intValueExact(); if (widthAsInt <= valueBuffer.limit()) { return this; } int extraWidth = widthAsInt - valueBuffer.limit(); int rightPadding = extraWidth / 2; // left padding get extra character if extraWidth is odd int leftPadding = rightPadding + (extraWidth & 1); // x & 1 == x % 2 byte[] out = new byte[widthAsInt]; Arrays.fill(out, 0, leftPadding, fillCharacter.valueBuffer.get(0)); System.arraycopy(valueBuffer.array(), 0, out, leftPadding, valueBuffer.limit()); Arrays.fill(out, leftPadding + valueBuffer.limit(), widthAsInt, fillCharacter.valueBuffer.get(0)); return new PythonByteArray(out); } public PythonByteArray leftJustify(PythonInteger fillWidth) { return leftJustify(fillWidth, ASCII_SPACE); } public PythonByteArray leftJustify(PythonInteger fillWidth, PythonByteArray fillCharacter) { if (fillCharacter.valueBuffer.limit() != 1) { throw new TypeError("ljust() argument 2 must be a byte string of length 1"); } int widthAsInt = fillWidth.value.intValueExact(); if (widthAsInt <= valueBuffer.limit()) { return this; } byte[] out = new byte[widthAsInt]; System.arraycopy(valueBuffer.array(), 0, out, 0, valueBuffer.limit()); Arrays.fill(out, valueBuffer.limit(), widthAsInt, fillCharacter.valueBuffer.get(0)); return new PythonByteArray(out); } public PythonByteArray rightJustify(PythonInteger fillWidth) { return rightJustify(fillWidth, ASCII_SPACE); } public PythonByteArray rightJustify(PythonInteger fillWidth, PythonByteArray fillCharacter) { if (fillCharacter.valueBuffer.limit() != 1) { throw new TypeError("rjust() argument 2 must be a byte string of length 1"); } int widthAsInt = fillWidth.value.intValueExact(); if (widthAsInt <= valueBuffer.limit()) { return this; } int extraWidth = widthAsInt - valueBuffer.limit(); byte[] out = new byte[widthAsInt]; Arrays.fill(out, 0, extraWidth, fillCharacter.valueBuffer.get(0)); System.arraycopy(valueBuffer.array(), 0, out, extraWidth, valueBuffer.limit()); return new PythonByteArray(out); } public PythonByteArray strip() { return strip(ASCII_SPACE); } public PythonByteArray strip(PythonNone ignored) { return strip(); } public PythonByteArray strip(PythonByteArray bytesToStrip) { BitSet toStrip = asBitSet(bytesToStrip); int start = 0; int end = valueBuffer.limit() - 1; while (start < valueBuffer.limit() && toStrip.get(valueBuffer.get(start) & 0xFF)) { start++; } while (end >= start && toStrip.get(valueBuffer.get(end) & 0xFF)) { end--; } if (end < start) { return new PythonByteArray(new byte[] {}); } return new PythonByteArray(Arrays.copyOfRange(valueBuffer.array(), start, end + 1)); } public PythonByteArray leftStrip() { return leftStrip(ASCII_SPACE); } public PythonByteArray leftStrip(PythonNone ignored) { return leftStrip(); } public PythonByteArray leftStrip(PythonByteArray bytesToStrip) { BitSet toStrip = asBitSet(bytesToStrip); int start = 0; while (start < valueBuffer.limit() && toStrip.get(valueBuffer.get(start) & 0xFF)) { start++; } if (start == valueBuffer.limit()) { return new PythonByteArray(new byte[] {}); } return new PythonByteArray(Arrays.copyOfRange(valueBuffer.array(), start, valueBuffer.limit())); } public PythonByteArray rightStrip() { return rightStrip(ASCII_SPACE); } public PythonByteArray rightStrip(PythonNone ignored) { return rightStrip(); } public PythonByteArray rightStrip(PythonByteArray bytesToStrip) { BitSet toStrip = asBitSet(bytesToStrip); int end = valueBuffer.limit() - 1; while (end >= 0 && toStrip.get(valueBuffer.get(end) & 0xFF)) { end--; } if (end < 0) { return new PythonByteArray(new byte[] {}); } return new PythonByteArray(Arrays.copyOfRange(valueBuffer.array(), 0, end + 1)); } public PythonLikeList<PythonByteArray> split() { PythonLikeList<PythonByteArray> out = new PythonLikeList<>(); int start = 0; int end = valueBuffer.limit(); while (end > 0 && ASCII_WHITESPACE_BITSET.get(valueBuffer.get(end - 1) & 0xFF)) { end--; } while (start < end && ASCII_WHITESPACE_BITSET.get(valueBuffer.get(start) & 0xFF)) { start++; } if (start == end) { return out; } int lastEnd = start; while (start < end - 1) { while (start < end - 1 && !ASCII_WHITESPACE_BITSET.get(valueBuffer.get(start) & 0xFF)) { start++; } if (start != end - 1) { out.add(new PythonByteArray(Arrays.copyOfRange(valueBuffer.array(), lastEnd, start))); lastEnd = start + 1; start = lastEnd; } } if (lastEnd != end) { out.add(new PythonByteArray(Arrays.copyOfRange(valueBuffer.array(), lastEnd, end))); } return out; } public PythonLikeList<PythonByteArray> split(PythonNone ignored) { return split(); } public PythonLikeList<PythonByteArray> split(PythonByteArray seperator) { PythonLikeList<PythonByteArray> out = new PythonLikeList<>(); int start = 0; int end = valueBuffer.limit(); int lastEnd = start; while (start < end - seperator.valueBuffer.limit()) { while (start < end - seperator.valueBuffer.limit() && !Arrays.equals(valueBuffer.array(), start, start + seperator.valueBuffer.limit(), seperator.valueBuffer.array(), 0, seperator.valueBuffer.limit())) { start++; } if (start != end - seperator.valueBuffer.limit()) { out.add(new PythonByteArray(Arrays.copyOfRange(valueBuffer.array(), lastEnd, start))); lastEnd = start + seperator.valueBuffer.limit(); start = lastEnd; } } if (Arrays.equals(valueBuffer.array(), start, start + seperator.valueBuffer.limit(), seperator.valueBuffer.array(), 0, seperator.valueBuffer.limit())) { out.add(new PythonByteArray(Arrays.copyOfRange(valueBuffer.array(), lastEnd, start))); lastEnd = start + seperator.valueBuffer.limit(); } out.add(new PythonByteArray(Arrays.copyOfRange(valueBuffer.array(), lastEnd, end))); return out; } public PythonLikeList<PythonByteArray> split(PythonByteArray seperator, PythonInteger maxSplits) { if (maxSplits.equals(new PythonInteger(-1))) { return split(seperator); } PythonLikeList<PythonByteArray> out = new PythonLikeList<>(); int start = 0; int end = valueBuffer.limit(); int lastEnd = start; while (start < end - seperator.valueBuffer.limit() && maxSplits.compareTo(PythonInteger.ONE) >= 0) { while (start < end - seperator.valueBuffer.limit() && !Arrays.equals(valueBuffer.array(), start, start + seperator.valueBuffer.limit(), seperator.valueBuffer.array(), 0, seperator.valueBuffer.limit())) { start++; } if (start != end - seperator.valueBuffer.limit()) { out.add(new PythonByteArray(Arrays.copyOfRange(valueBuffer.array(), lastEnd, start))); lastEnd = start + seperator.valueBuffer.limit(); start = lastEnd; maxSplits = maxSplits.subtract(PythonInteger.ONE); } } if (maxSplits.compareTo(PythonInteger.ONE) >= 0 && Arrays.equals(valueBuffer.array(), start, start + seperator.valueBuffer.limit(), seperator.valueBuffer.array(), 0, seperator.valueBuffer.limit())) { out.add(new PythonByteArray(Arrays.copyOfRange(valueBuffer.array(), lastEnd, start))); lastEnd = start + seperator.valueBuffer.limit(); } out.add(new PythonByteArray(Arrays.copyOfRange(valueBuffer.array(), lastEnd, end))); return out; } public PythonLikeList<PythonByteArray> split(PythonNone seperator, PythonInteger maxSplits) { if (maxSplits.equals(new PythonInteger(-1))) { return split(seperator); } PythonLikeList<PythonByteArray> out = new PythonLikeList<>(); int start = 0; int end = valueBuffer.limit(); while (end > 0 && ASCII_WHITESPACE_BITSET.get(valueBuffer.get(end - 1) & 0xFF)) { end--; } while (start < end && ASCII_WHITESPACE_BITSET.get(valueBuffer.get(start) & 0xFF)) { start++; } if (start == end) { return out; } int lastEnd = start; while (start < end - 1 && maxSplits.compareTo(PythonInteger.ONE) >= 0) { while (start < end - 1 && !ASCII_WHITESPACE_BITSET.get(valueBuffer.get(start) & 0xFF)) { start++; } if (start != end - 1) { out.add(new PythonByteArray(Arrays.copyOfRange(valueBuffer.array(), lastEnd, start))); lastEnd = start + 1; start = lastEnd; maxSplits = maxSplits.subtract(PythonInteger.ONE); } } if (lastEnd != end) { out.add(new PythonByteArray(Arrays.copyOfRange(valueBuffer.array(), lastEnd, end))); } return out; } public PythonLikeList<PythonByteArray> rightSplit() { return split(); } public PythonLikeList<PythonByteArray> rightSplit(PythonNone ignored) { return rightSplit(); } public PythonLikeList<PythonByteArray> rightSplit(PythonByteArray seperator) { return split(seperator); } private static byte[] reverseInplace(byte[] array) { for (int i = 0; i < array.length >> 1; i++) { byte temp = array[i]; array[i] = array[array.length - i - 1]; array[array.length - i - 1] = temp; } return array; } public PythonLikeList<PythonByteArray> rightSplit(PythonByteArray seperator, PythonInteger maxSplits) { if (maxSplits.equals(new PythonInteger(-1))) { return split(seperator); } PythonLikeList<PythonByteArray> out = new PythonLikeList<>(); byte[] reversedValue = reverseInplace(valueBuffer.array().clone()); byte[] reversedSep = reverseInplace(seperator.valueBuffer.array().clone()); int start = 0; int end = reversedValue.length; int lastEnd = start; while (start < end - reversedSep.length && maxSplits.compareTo(PythonInteger.ONE) >= 0) { while (start < end - reversedSep.length && !Arrays.equals(reversedValue, start, start + reversedSep.length, reversedSep, 0, reversedSep.length)) { start++; } if (start != end - reversedSep.length) { out.add(new PythonByteArray(reverseInplace(Arrays.copyOfRange(reversedValue, lastEnd, start)))); lastEnd = start + reversedSep.length; start = lastEnd; maxSplits = maxSplits.subtract(PythonInteger.ONE); } } if (maxSplits.compareTo(PythonInteger.ONE) >= 0 && Arrays.equals(reversedValue, start, start + reversedSep.length, reversedSep, 0, reversedSep.length)) { out.add(new PythonByteArray(reverseInplace(Arrays.copyOfRange(reversedValue, lastEnd, start)))); lastEnd = start + seperator.valueBuffer.limit(); } out.add(new PythonByteArray(reverseInplace(Arrays.copyOfRange(reversedValue, lastEnd, end)))); out.reverse(); return out; } public PythonLikeList<PythonByteArray> rightSplit(PythonNone seperator, PythonInteger maxSplits) { if (maxSplits.equals(new PythonInteger(-1))) { return split(seperator); } PythonLikeList<PythonByteArray> out = new PythonLikeList<>(); byte[] reversedValue = reverseInplace(Arrays.copyOfRange(valueBuffer.array(), 0, valueBuffer.limit())); int start = 0; int end = valueBuffer.limit(); while (end > 0 && ASCII_WHITESPACE_BITSET.get(valueBuffer.get(end - 1) & 0xFF)) { end--; } while (start < end && ASCII_WHITESPACE_BITSET.get(valueBuffer.get(start) & 0xFF)) { start++; } if (start == end) { return out; } int lastEnd = start; while (start < end - 1 && maxSplits.compareTo(PythonInteger.ONE) >= 0) { while (start < end - 1 && !ASCII_WHITESPACE_BITSET.get(reversedValue[start] & 0xFF)) { start++; } if (start != end - 1) { out.add(new PythonByteArray(reverseInplace(Arrays.copyOfRange(reversedValue, lastEnd, start)))); lastEnd = start + 1; start = lastEnd; maxSplits = maxSplits.subtract(PythonInteger.ONE); } } if (lastEnd != end) { out.add(new PythonByteArray(reverseInplace(Arrays.copyOfRange(reversedValue, lastEnd, end)))); } out.reverse(); return out; } public PythonByteArray capitalize() { var asString = asAsciiString(); if (asString.value.isEmpty()) { return asString.asAsciiByteArray(); } var tail = PythonString.valueOf(asString.value.substring(1)) .withModifiedCodepoints(cp -> cp < 128 ? Character.toLowerCase(cp) : cp).value; var head = asString.value.charAt(0); if (head < 128) { head = Character.toTitleCase(head); } return (PythonString.valueOf(head + tail)).asAsciiByteArray(); } public PythonByteArray expandTabs() { return asAsciiString().expandTabs().asAsciiByteArray(); } public PythonByteArray expandTabs(PythonInteger tabSize) { return asAsciiString().expandTabs(tabSize).asAsciiByteArray(); } public PythonBoolean isAlphaNumeric() { return asAsciiString().isAlphaNumeric(); } public PythonBoolean isAlpha() { return asAsciiString().isAlpha(); } public PythonBoolean isAscii() { for (int i = 0; i < valueBuffer.limit(); i++) { byte b = valueBuffer.get(i); if ((b & 0xFF) > 0x7F) { return PythonBoolean.FALSE; } } return PythonBoolean.TRUE; } public PythonBoolean isDigit() { return asAsciiString().isDigit(); } public PythonBoolean isLower() { return asAsciiString().isLower(); } public PythonBoolean isSpace() { return asAsciiString().isSpace(); } public PythonBoolean isTitle() { return asAsciiString().isTitle(); } public PythonBoolean isUpper() { return asAsciiString().isUpper(); } public PythonByteArray lower() { return asAsciiString().withModifiedCodepoints( cp -> cp < 128 ? Character.toLowerCase(cp) : cp).asAsciiByteArray(); } public PythonLikeList<PythonByteArray> splitLines() { return asAsciiString().splitLines() .stream() .map(PythonString::asAsciiByteArray) .collect(Collectors.toCollection(PythonLikeList::new)); } public PythonLikeList<PythonByteArray> splitLines(PythonBoolean keepEnds) { return asAsciiString().splitLines(keepEnds) .stream() .map(PythonString::asAsciiByteArray) .collect(Collectors.toCollection(PythonLikeList::new)); } public PythonByteArray swapCase() { return asAsciiString().withModifiedCodepoints( cp -> cp < 128 ? PythonString.CharacterCase.swapCase(cp) : cp).asAsciiByteArray(); } public PythonByteArray title() { return asAsciiString().title(cp -> cp < 128).asAsciiByteArray(); } public PythonByteArray upper() { return asAsciiString().withModifiedCodepoints( cp -> cp < 128 ? Character.toUpperCase(cp) : cp).asAsciiByteArray(); } public PythonByteArray zfill(PythonInteger width) { return asAsciiString().zfill(width).asAsciiByteArray(); } public PythonString asString() { return PythonString.valueOf(toString()); } public PythonString repr() { return asString(); } @Override public PythonString $method$__str__() { return PythonString.valueOf(toString()); } @Override public String toString() { StringBuilder out = new StringBuilder(valueBuffer.limit()); out.append("bytearray("); out.append(new PythonBytes(Arrays.copyOfRange(valueBuffer.array(), 0, valueBuffer.limit())).repr().value); out.append(")"); return out.toString(); } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } PythonByteArray that = (PythonByteArray) o; return valueBuffer.equals(that.valueBuffer); } @Override public int hashCode() { return valueBuffer.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/types/PythonBytes.java
package ai.timefold.jpyinterpreter.types; import java.io.ByteArrayOutputStream; import java.math.BigInteger; import java.nio.ByteBuffer; import java.nio.charset.CharacterCodingException; import java.nio.charset.Charset; import java.nio.charset.CodingErrorAction; import java.nio.charset.StandardCharsets; import java.util.Arrays; import java.util.BitSet; import java.util.stream.Collectors; import java.util.stream.IntStream; import ai.timefold.jpyinterpreter.PythonBinaryOperator; import ai.timefold.jpyinterpreter.PythonLikeObject; import ai.timefold.jpyinterpreter.PythonOverloadImplementor; import ai.timefold.jpyinterpreter.PythonUnaryOperator; import ai.timefold.jpyinterpreter.builtins.UnaryDunderBuiltin; 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.PythonLikeList; import ai.timefold.jpyinterpreter.types.collections.PythonLikeTuple; import ai.timefold.jpyinterpreter.types.errors.TypeError; import ai.timefold.jpyinterpreter.types.errors.ValueError; import ai.timefold.jpyinterpreter.types.errors.lookup.IndexError; import ai.timefold.jpyinterpreter.types.errors.unicode.UnicodeDecodeError; import ai.timefold.jpyinterpreter.types.numeric.PythonBoolean; import ai.timefold.jpyinterpreter.types.numeric.PythonInteger; import ai.timefold.jpyinterpreter.util.ByteCharSequence; import ai.timefold.jpyinterpreter.util.StringFormatter; import ai.timefold.solver.core.impl.domain.solution.cloner.PlanningImmutable; public class PythonBytes extends AbstractPythonLikeObject implements PythonBytesLikeObject, PlanningImmutable { public static final PythonBytes EMPTY = new PythonBytes(new byte[0]); private static final PythonBytes ASCII_SPACE = new PythonBytes(new byte[] { ' ' }); private static final BitSet ASCII_WHITESPACE_BITSET = asBitSet(new PythonBytes( new byte[] { ' ', '\t', '\n', '\r', 0x0b, '\f' })); public static final PythonInteger[] BYTE_TO_INT = new PythonInteger[] { PythonInteger.valueOf(0x00), PythonInteger.valueOf(0x01), PythonInteger.valueOf(0x02), PythonInteger.valueOf(0x03), PythonInteger.valueOf(0x04), PythonInteger.valueOf(0x05), PythonInteger.valueOf(0x06), PythonInteger.valueOf(0x07), PythonInteger.valueOf(0x08), PythonInteger.valueOf(0x09), PythonInteger.valueOf(0x0a), PythonInteger.valueOf(0x0b), PythonInteger.valueOf(0x0c), PythonInteger.valueOf(0x0d), PythonInteger.valueOf(0x0e), PythonInteger.valueOf(0x0f), PythonInteger.valueOf(0x10), PythonInteger.valueOf(0x11), PythonInteger.valueOf(0x12), PythonInteger.valueOf(0x13), PythonInteger.valueOf(0x14), PythonInteger.valueOf(0x15), PythonInteger.valueOf(0x16), PythonInteger.valueOf(0x17), PythonInteger.valueOf(0x18), PythonInteger.valueOf(0x19), PythonInteger.valueOf(0x1a), PythonInteger.valueOf(0x1b), PythonInteger.valueOf(0x1c), PythonInteger.valueOf(0x1d), PythonInteger.valueOf(0x1e), PythonInteger.valueOf(0x1f), PythonInteger.valueOf(0x20), PythonInteger.valueOf(0x21), PythonInteger.valueOf(0x22), PythonInteger.valueOf(0x23), PythonInteger.valueOf(0x24), PythonInteger.valueOf(0x25), PythonInteger.valueOf(0x26), PythonInteger.valueOf(0x27), PythonInteger.valueOf(0x28), PythonInteger.valueOf(0x29), PythonInteger.valueOf(0x2a), PythonInteger.valueOf(0x2b), PythonInteger.valueOf(0x2c), PythonInteger.valueOf(0x2d), PythonInteger.valueOf(0x2e), PythonInteger.valueOf(0x2f), PythonInteger.valueOf(0x30), PythonInteger.valueOf(0x31), PythonInteger.valueOf(0x32), PythonInteger.valueOf(0x33), PythonInteger.valueOf(0x34), PythonInteger.valueOf(0x35), PythonInteger.valueOf(0x36), PythonInteger.valueOf(0x37), PythonInteger.valueOf(0x38), PythonInteger.valueOf(0x39), PythonInteger.valueOf(0x3a), PythonInteger.valueOf(0x3b), PythonInteger.valueOf(0x3c), PythonInteger.valueOf(0x3d), PythonInteger.valueOf(0x3e), PythonInteger.valueOf(0x3f), PythonInteger.valueOf(0x40), PythonInteger.valueOf(0x41), PythonInteger.valueOf(0x42), PythonInteger.valueOf(0x43), PythonInteger.valueOf(0x44), PythonInteger.valueOf(0x45), PythonInteger.valueOf(0x46), PythonInteger.valueOf(0x47), PythonInteger.valueOf(0x48), PythonInteger.valueOf(0x49), PythonInteger.valueOf(0x4a), PythonInteger.valueOf(0x4b), PythonInteger.valueOf(0x4c), PythonInteger.valueOf(0x4d), PythonInteger.valueOf(0x4e), PythonInteger.valueOf(0x4f), PythonInteger.valueOf(0x50), PythonInteger.valueOf(0x51), PythonInteger.valueOf(0x52), PythonInteger.valueOf(0x53), PythonInteger.valueOf(0x54), PythonInteger.valueOf(0x55), PythonInteger.valueOf(0x56), PythonInteger.valueOf(0x57), PythonInteger.valueOf(0x58), PythonInteger.valueOf(0x59), PythonInteger.valueOf(0x5a), PythonInteger.valueOf(0x5b), PythonInteger.valueOf(0x5c), PythonInteger.valueOf(0x5d), PythonInteger.valueOf(0x5e), PythonInteger.valueOf(0x5f), PythonInteger.valueOf(0x60), PythonInteger.valueOf(0x61), PythonInteger.valueOf(0x62), PythonInteger.valueOf(0x63), PythonInteger.valueOf(0x64), PythonInteger.valueOf(0x65), PythonInteger.valueOf(0x66), PythonInteger.valueOf(0x67), PythonInteger.valueOf(0x68), PythonInteger.valueOf(0x69), PythonInteger.valueOf(0x6a), PythonInteger.valueOf(0x6b), PythonInteger.valueOf(0x6c), PythonInteger.valueOf(0x6d), PythonInteger.valueOf(0x6e), PythonInteger.valueOf(0x6f), PythonInteger.valueOf(0x70), PythonInteger.valueOf(0x71), PythonInteger.valueOf(0x72), PythonInteger.valueOf(0x73), PythonInteger.valueOf(0x74), PythonInteger.valueOf(0x75), PythonInteger.valueOf(0x76), PythonInteger.valueOf(0x77), PythonInteger.valueOf(0x78), PythonInteger.valueOf(0x79), PythonInteger.valueOf(0x7a), PythonInteger.valueOf(0x7b), PythonInteger.valueOf(0x7c), PythonInteger.valueOf(0x7d), PythonInteger.valueOf(0x7e), PythonInteger.valueOf(0x7f), PythonInteger.valueOf(0x80), PythonInteger.valueOf(0x81), PythonInteger.valueOf(0x82), PythonInteger.valueOf(0x83), PythonInteger.valueOf(0x84), PythonInteger.valueOf(0x85), PythonInteger.valueOf(0x86), PythonInteger.valueOf(0x87), PythonInteger.valueOf(0x88), PythonInteger.valueOf(0x89), PythonInteger.valueOf(0x8a), PythonInteger.valueOf(0x8b), PythonInteger.valueOf(0x8c), PythonInteger.valueOf(0x8d), PythonInteger.valueOf(0x8e), PythonInteger.valueOf(0x8f), PythonInteger.valueOf(0x90), PythonInteger.valueOf(0x91), PythonInteger.valueOf(0x92), PythonInteger.valueOf(0x93), PythonInteger.valueOf(0x94), PythonInteger.valueOf(0x95), PythonInteger.valueOf(0x96), PythonInteger.valueOf(0x97), PythonInteger.valueOf(0x98), PythonInteger.valueOf(0x99), PythonInteger.valueOf(0x9a), PythonInteger.valueOf(0x9b), PythonInteger.valueOf(0x9c), PythonInteger.valueOf(0x9d), PythonInteger.valueOf(0x9e), PythonInteger.valueOf(0x9f), PythonInteger.valueOf(0xa0), PythonInteger.valueOf(0xa1), PythonInteger.valueOf(0xa2), PythonInteger.valueOf(0xa3), PythonInteger.valueOf(0xa4), PythonInteger.valueOf(0xa5), PythonInteger.valueOf(0xa6), PythonInteger.valueOf(0xa7), PythonInteger.valueOf(0xa8), PythonInteger.valueOf(0xa9), PythonInteger.valueOf(0xaa), PythonInteger.valueOf(0xab), PythonInteger.valueOf(0xac), PythonInteger.valueOf(0xad), PythonInteger.valueOf(0xae), PythonInteger.valueOf(0xaf), PythonInteger.valueOf(0xb0), PythonInteger.valueOf(0xb1), PythonInteger.valueOf(0xb2), PythonInteger.valueOf(0xb3), PythonInteger.valueOf(0xb4), PythonInteger.valueOf(0xb5), PythonInteger.valueOf(0xb6), PythonInteger.valueOf(0xb7), PythonInteger.valueOf(0xb8), PythonInteger.valueOf(0xb9), PythonInteger.valueOf(0xba), PythonInteger.valueOf(0xbb), PythonInteger.valueOf(0xbc), PythonInteger.valueOf(0xbd), PythonInteger.valueOf(0xbe), PythonInteger.valueOf(0xbf), PythonInteger.valueOf(0xc0), PythonInteger.valueOf(0xc1), PythonInteger.valueOf(0xc2), PythonInteger.valueOf(0xc3), PythonInteger.valueOf(0xc4), PythonInteger.valueOf(0xc5), PythonInteger.valueOf(0xc6), PythonInteger.valueOf(0xc7), PythonInteger.valueOf(0xc8), PythonInteger.valueOf(0xc9), PythonInteger.valueOf(0xca), PythonInteger.valueOf(0xcb), PythonInteger.valueOf(0xcc), PythonInteger.valueOf(0xcd), PythonInteger.valueOf(0xce), PythonInteger.valueOf(0xcf), PythonInteger.valueOf(0xd0), PythonInteger.valueOf(0xd1), PythonInteger.valueOf(0xd2), PythonInteger.valueOf(0xd3), PythonInteger.valueOf(0xd4), PythonInteger.valueOf(0xd5), PythonInteger.valueOf(0xd6), PythonInteger.valueOf(0xd7), PythonInteger.valueOf(0xd8), PythonInteger.valueOf(0xd9), PythonInteger.valueOf(0xda), PythonInteger.valueOf(0xdb), PythonInteger.valueOf(0xdc), PythonInteger.valueOf(0xdd), PythonInteger.valueOf(0xde), PythonInteger.valueOf(0xdf), PythonInteger.valueOf(0xe0), PythonInteger.valueOf(0xe1), PythonInteger.valueOf(0xe2), PythonInteger.valueOf(0xe3), PythonInteger.valueOf(0xe4), PythonInteger.valueOf(0xe5), PythonInteger.valueOf(0xe6), PythonInteger.valueOf(0xe7), PythonInteger.valueOf(0xe8), PythonInteger.valueOf(0xe9), PythonInteger.valueOf(0xea), PythonInteger.valueOf(0xeb), PythonInteger.valueOf(0xec), PythonInteger.valueOf(0xed), PythonInteger.valueOf(0xee), PythonInteger.valueOf(0xef), PythonInteger.valueOf(0xf0), PythonInteger.valueOf(0xf1), PythonInteger.valueOf(0xf2), PythonInteger.valueOf(0xf3), PythonInteger.valueOf(0xf4), PythonInteger.valueOf(0xf5), PythonInteger.valueOf(0xf6), PythonInteger.valueOf(0xf7), PythonInteger.valueOf(0xf8), PythonInteger.valueOf(0xf9), PythonInteger.valueOf(0xfa), PythonInteger.valueOf(0xfb), PythonInteger.valueOf(0xfc), PythonInteger.valueOf(0xfd), PythonInteger.valueOf(0xfe), PythonInteger.valueOf(0xff), }; static { PythonOverloadImplementor.deferDispatchesFor(PythonBytes::registerMethods); } private static PythonLikeType registerMethods() throws NoSuchMethodException { BuiltinTypes.BYTES_TYPE.setConstructor(((positionalArguments, namedArguments, callerInstance) -> { if (positionalArguments.isEmpty()) { return new PythonBytes(new byte[] {}); } else if (positionalArguments.size() == 1) { PythonLikeObject arg = positionalArguments.get(0); if (arg instanceof PythonInteger) { return new PythonBytes(new byte[((PythonInteger) arg).value.intValueExact()]); } else { PythonIterator<?> iterator = (PythonIterator<?>) UnaryDunderBuiltin.ITERATOR.invoke(arg); ByteArrayOutputStream out = new ByteArrayOutputStream(); byte[] toWrite = new byte[1]; while (iterator.hasNext()) { PythonLikeObject item = iterator.nextPythonItem(); if (!(item instanceof PythonInteger)) { throw new ValueError("bytearray argument 1 must be an int or an iterable of int"); } toWrite[0] = ((PythonInteger) item).asByte(); out.writeBytes(toWrite); } return new PythonBytes(out.toByteArray()); } } else { throw new ValueError("bytearray takes 0 or 1 arguments, not " + positionalArguments.size()); } })); // Unary BuiltinTypes.BYTES_TYPE.addUnaryMethod(PythonUnaryOperator.REPRESENTATION, PythonBytes.class.getMethod("repr")); BuiltinTypes.BYTES_TYPE.addUnaryMethod(PythonUnaryOperator.AS_STRING, PythonBytes.class.getMethod("asString")); BuiltinTypes.BYTES_TYPE.addUnaryMethod(PythonUnaryOperator.ITERATOR, PythonBytes.class.getMethod("getIterator")); BuiltinTypes.BYTES_TYPE.addUnaryMethod(PythonUnaryOperator.LENGTH, PythonBytes.class.getMethod("getLength")); // Binary BuiltinTypes.BYTES_TYPE.addBinaryMethod(PythonBinaryOperator.GET_ITEM, PythonBytes.class.getMethod("getCharAt", PythonInteger.class)); BuiltinTypes.BYTES_TYPE.addBinaryMethod(PythonBinaryOperator.GET_ITEM, PythonBytes.class.getMethod("getSubsequence", PythonSlice.class)); BuiltinTypes.BYTES_TYPE.addBinaryMethod(PythonBinaryOperator.CONTAINS, PythonBytes.class.getMethod("containsSubsequence", PythonBytes.class)); BuiltinTypes.BYTES_TYPE.addBinaryMethod(PythonBinaryOperator.ADD, PythonBytes.class.getMethod("concat", PythonBytes.class)); BuiltinTypes.BYTES_TYPE.addBinaryMethod(PythonBinaryOperator.MULTIPLY, PythonBytes.class.getMethod("repeat", PythonInteger.class)); BuiltinTypes.BYTES_TYPE.addBinaryMethod(PythonBinaryOperator.MODULO, PythonBytes.class.getMethod("interpolate", PythonLikeObject.class)); BuiltinTypes.BYTES_TYPE.addBinaryMethod(PythonBinaryOperator.MODULO, PythonBytes.class.getMethod("interpolate", PythonLikeTuple.class)); BuiltinTypes.BYTES_TYPE.addBinaryMethod(PythonBinaryOperator.MODULO, PythonBytes.class.getMethod("interpolate", PythonLikeDict.class)); // Other BuiltinTypes.BYTES_TYPE.addMethod("capitalize", PythonBytes.class.getMethod("capitalize")); BuiltinTypes.BYTES_TYPE.addMethod("center", PythonBytes.class.getMethod("center", PythonInteger.class)); BuiltinTypes.BYTES_TYPE.addMethod("center", PythonBytes.class.getMethod("center", PythonInteger.class, PythonBytes.class)); BuiltinTypes.BYTES_TYPE.addMethod("count", PythonBytes.class.getMethod("count", PythonInteger.class)); BuiltinTypes.BYTES_TYPE.addMethod("count", PythonBytes.class.getMethod("count", PythonInteger.class, PythonInteger.class)); BuiltinTypes.BYTES_TYPE.addMethod("count", PythonBytes.class.getMethod("count", PythonInteger.class, PythonInteger.class, PythonInteger.class)); BuiltinTypes.BYTES_TYPE.addMethod("count", PythonBytes.class.getMethod("count", PythonBytes.class)); BuiltinTypes.BYTES_TYPE.addMethod("count", PythonBytes.class.getMethod("count", PythonBytes.class, PythonInteger.class)); BuiltinTypes.BYTES_TYPE.addMethod("count", PythonBytes.class.getMethod("count", PythonBytes.class, PythonInteger.class, PythonInteger.class)); // TODO: decode BuiltinTypes.BYTES_TYPE.addMethod("endswith", PythonBytes.class.getMethod("endsWith", PythonBytes.class)); BuiltinTypes.BYTES_TYPE.addMethod("endswith", PythonBytes.class.getMethod("endsWith", PythonLikeTuple.class)); BuiltinTypes.BYTES_TYPE.addMethod("endswith", PythonBytes.class.getMethod("endsWith", PythonBytes.class, PythonInteger.class)); BuiltinTypes.BYTES_TYPE.addMethod("endswith", PythonBytes.class.getMethod("endsWith", PythonLikeTuple.class, PythonInteger.class)); BuiltinTypes.BYTES_TYPE.addMethod("endswith", PythonBytes.class.getMethod("endsWith", PythonBytes.class, PythonInteger.class, PythonInteger.class)); BuiltinTypes.BYTES_TYPE.addMethod("endswith", PythonBytes.class.getMethod("endsWith", PythonLikeTuple.class, PythonInteger.class, PythonInteger.class)); BuiltinTypes.BYTES_TYPE.addMethod("expandtabs", PythonBytes.class.getMethod("expandTabs")); BuiltinTypes.BYTES_TYPE.addMethod("expandtabs", PythonBytes.class.getMethod("expandTabs", PythonInteger.class)); BuiltinTypes.BYTES_TYPE.addMethod("find", PythonBytes.class.getMethod("find", PythonBytes.class)); BuiltinTypes.BYTES_TYPE.addMethod("find", PythonBytes.class.getMethod("find", PythonInteger.class)); BuiltinTypes.BYTES_TYPE.addMethod("find", PythonBytes.class.getMethod("find", PythonBytes.class, PythonInteger.class)); BuiltinTypes.BYTES_TYPE.addMethod("find", PythonBytes.class.getMethod("find", PythonInteger.class, PythonInteger.class)); BuiltinTypes.BYTES_TYPE.addMethod("find", PythonBytes.class.getMethod("find", PythonBytes.class, PythonInteger.class, PythonInteger.class)); BuiltinTypes.BYTES_TYPE.addMethod("find", PythonBytes.class.getMethod("find", PythonInteger.class, PythonInteger.class, PythonInteger.class)); BuiltinTypes.BYTES_TYPE.addMethod("index", PythonBytes.class.getMethod("index", PythonBytes.class)); BuiltinTypes.BYTES_TYPE.addMethod("index", PythonBytes.class.getMethod("index", PythonInteger.class)); BuiltinTypes.BYTES_TYPE.addMethod("index", PythonBytes.class.getMethod("index", PythonBytes.class, PythonInteger.class)); BuiltinTypes.BYTES_TYPE.addMethod("index", PythonBytes.class.getMethod("index", PythonInteger.class, PythonInteger.class)); BuiltinTypes.BYTES_TYPE.addMethod("index", PythonBytes.class.getMethod("index", PythonBytes.class, PythonInteger.class, PythonInteger.class)); BuiltinTypes.BYTES_TYPE.addMethod("index", PythonBytes.class.getMethod("index", PythonInteger.class, PythonInteger.class, PythonInteger.class)); BuiltinTypes.BYTES_TYPE.addMethod("isalnum", PythonBytes.class.getMethod("isAlphaNumeric")); BuiltinTypes.BYTES_TYPE.addMethod("isalpha", PythonBytes.class.getMethod("isAlpha")); BuiltinTypes.BYTES_TYPE.addMethod("isascii", PythonBytes.class.getMethod("isAscii")); BuiltinTypes.BYTES_TYPE.addMethod("isdigit", PythonBytes.class.getMethod("isDigit")); BuiltinTypes.BYTES_TYPE.addMethod("islower", PythonBytes.class.getMethod("isLower")); BuiltinTypes.BYTES_TYPE.addMethod("isspace", PythonBytes.class.getMethod("isSpace")); BuiltinTypes.BYTES_TYPE.addMethod("istitle", PythonBytes.class.getMethod("isTitle")); BuiltinTypes.BYTES_TYPE.addMethod("isupper", PythonBytes.class.getMethod("isUpper")); BuiltinTypes.BYTES_TYPE.addMethod("join", PythonBytes.class.getMethod("join", PythonLikeObject.class)); BuiltinTypes.BYTES_TYPE.addMethod("ljust", PythonBytes.class.getMethod("leftJustify", PythonInteger.class)); BuiltinTypes.BYTES_TYPE.addMethod("ljust", PythonBytes.class.getMethod("leftJustify", PythonInteger.class, PythonBytes.class)); BuiltinTypes.BYTES_TYPE.addMethod("lower", PythonBytes.class.getMethod("lower")); BuiltinTypes.BYTES_TYPE.addMethod("lstrip", PythonBytes.class.getMethod("leftStrip")); BuiltinTypes.BYTES_TYPE.addMethod("lstrip", PythonBytes.class.getMethod("leftStrip", PythonNone.class)); BuiltinTypes.BYTES_TYPE.addMethod("lstrip", PythonBytes.class.getMethod("leftStrip", PythonBytes.class)); // TODO: maketrans BuiltinTypes.BYTES_TYPE.addMethod("partition", PythonBytes.class.getMethod("partition", PythonBytes.class)); BuiltinTypes.BYTES_TYPE.addMethod("removeprefix", PythonBytes.class.getMethod("removePrefix", PythonBytes.class)); BuiltinTypes.BYTES_TYPE.addMethod("removesuffix", PythonBytes.class.getMethod("removeSuffix", PythonBytes.class)); BuiltinTypes.BYTES_TYPE.addMethod("replace", PythonBytes.class.getMethod("replace", PythonBytes.class, PythonBytes.class)); BuiltinTypes.BYTES_TYPE.addMethod("replace", PythonBytes.class.getMethod("replace", PythonBytes.class, PythonBytes.class, PythonInteger.class)); BuiltinTypes.BYTES_TYPE.addMethod("rfind", PythonBytes.class.getMethod("rightFind", PythonBytes.class)); BuiltinTypes.BYTES_TYPE.addMethod("rfind", PythonBytes.class.getMethod("rightFind", PythonInteger.class)); BuiltinTypes.BYTES_TYPE.addMethod("rfind", PythonBytes.class.getMethod("rightFind", PythonBytes.class, PythonInteger.class)); BuiltinTypes.BYTES_TYPE.addMethod("rfind", PythonBytes.class.getMethod("rightFind", PythonInteger.class, PythonInteger.class)); BuiltinTypes.BYTES_TYPE.addMethod("rfind", PythonBytes.class.getMethod("rightFind", PythonBytes.class, PythonInteger.class, PythonInteger.class)); BuiltinTypes.BYTES_TYPE.addMethod("rfind", PythonBytes.class.getMethod("rightFind", PythonInteger.class, PythonInteger.class, PythonInteger.class)); BuiltinTypes.BYTES_TYPE.addMethod("rindex", PythonBytes.class.getMethod("rightIndex", PythonBytes.class)); BuiltinTypes.BYTES_TYPE.addMethod("rindex", PythonBytes.class.getMethod("rightIndex", PythonInteger.class)); BuiltinTypes.BYTES_TYPE.addMethod("rindex", PythonBytes.class.getMethod("rightIndex", PythonBytes.class, PythonInteger.class)); BuiltinTypes.BYTES_TYPE.addMethod("rindex", PythonBytes.class.getMethod("rightIndex", PythonInteger.class, PythonInteger.class)); BuiltinTypes.BYTES_TYPE.addMethod("rindex", PythonBytes.class.getMethod("rightIndex", PythonBytes.class, PythonInteger.class, PythonInteger.class)); BuiltinTypes.BYTES_TYPE.addMethod("rindex", PythonBytes.class.getMethod("rightIndex", PythonInteger.class, PythonInteger.class, PythonInteger.class)); BuiltinTypes.BYTES_TYPE.addMethod("rjust", PythonBytes.class.getMethod("rightJustify", PythonInteger.class)); BuiltinTypes.BYTES_TYPE.addMethod("rjust", PythonBytes.class.getMethod("rightJustify", PythonInteger.class, PythonBytes.class)); BuiltinTypes.BYTES_TYPE.addMethod("rpartition", PythonBytes.class.getMethod("rightPartition", PythonBytes.class)); BuiltinTypes.BYTES_TYPE.addMethod("rsplit", PythonBytes.class.getMethod("rightSplit")); BuiltinTypes.BYTES_TYPE.addMethod("rsplit", PythonBytes.class.getMethod("rightSplit", PythonNone.class)); BuiltinTypes.BYTES_TYPE.addMethod("rsplit", PythonBytes.class.getMethod("rightSplit", PythonBytes.class)); BuiltinTypes.BYTES_TYPE.addMethod("rsplit", PythonBytes.class.getMethod("rightSplit", PythonNone.class, PythonInteger.class)); BuiltinTypes.BYTES_TYPE.addMethod("rsplit", PythonBytes.class.getMethod("rightSplit", PythonBytes.class, PythonInteger.class)); BuiltinTypes.BYTES_TYPE.addMethod("rstrip", PythonBytes.class.getMethod("rightStrip")); BuiltinTypes.BYTES_TYPE.addMethod("rstrip", PythonBytes.class.getMethod("rightStrip", PythonNone.class)); BuiltinTypes.BYTES_TYPE.addMethod("rstrip", PythonBytes.class.getMethod("rightStrip", PythonBytes.class)); BuiltinTypes.BYTES_TYPE.addMethod("split", PythonBytes.class.getMethod("split")); BuiltinTypes.BYTES_TYPE.addMethod("split", PythonBytes.class.getMethod("split", PythonNone.class)); BuiltinTypes.BYTES_TYPE.addMethod("split", PythonBytes.class.getMethod("split", PythonBytes.class)); BuiltinTypes.BYTES_TYPE.addMethod("split", PythonBytes.class.getMethod("split", PythonNone.class, PythonInteger.class)); BuiltinTypes.BYTES_TYPE.addMethod("split", PythonBytes.class.getMethod("split", PythonBytes.class, PythonInteger.class)); BuiltinTypes.BYTES_TYPE.addMethod("splitlines", PythonBytes.class.getMethod("splitLines")); BuiltinTypes.BYTES_TYPE.addMethod("splitlines", PythonBytes.class.getMethod("splitLines", PythonBoolean.class)); BuiltinTypes.BYTES_TYPE.addMethod("startswith", PythonBytes.class.getMethod("startsWith", PythonBytes.class)); BuiltinTypes.BYTES_TYPE.addMethod("startswith", PythonBytes.class.getMethod("startsWith", PythonLikeTuple.class)); BuiltinTypes.BYTES_TYPE.addMethod("startswith", PythonBytes.class.getMethod("startsWith", PythonBytes.class, PythonInteger.class)); BuiltinTypes.BYTES_TYPE.addMethod("startswith", PythonBytes.class.getMethod("startsWith", PythonLikeTuple.class, PythonInteger.class)); BuiltinTypes.BYTES_TYPE.addMethod("startswith", PythonBytes.class.getMethod("startsWith", PythonBytes.class, PythonInteger.class, PythonInteger.class)); BuiltinTypes.BYTES_TYPE.addMethod("startswith", PythonBytes.class.getMethod("startsWith", PythonLikeTuple.class, PythonInteger.class, PythonInteger.class)); BuiltinTypes.BYTES_TYPE.addMethod("strip", PythonBytes.class.getMethod("strip")); BuiltinTypes.BYTES_TYPE.addMethod("strip", PythonBytes.class.getMethod("strip", PythonNone.class)); BuiltinTypes.BYTES_TYPE.addMethod("strip", PythonBytes.class.getMethod("strip", PythonBytes.class)); BuiltinTypes.BYTES_TYPE.addMethod("swapcase", PythonBytes.class.getMethod("swapCase")); BuiltinTypes.BYTES_TYPE.addMethod("title", PythonBytes.class.getMethod("title")); BuiltinTypes.BYTES_TYPE.addMethod("translate", PythonBytes.class.getMethod("translate", PythonBytes.class)); BuiltinTypes.BYTES_TYPE.addMethod("upper", PythonBytes.class.getMethod("upper")); BuiltinTypes.BYTES_TYPE.addMethod("zfill", PythonBytes.class.getMethod("zfill", PythonInteger.class)); return BuiltinTypes.BYTES_TYPE; } public final byte[] value; public PythonBytes(byte[] value) { super(BuiltinTypes.BYTES_TYPE); this.value = value; } @Override public ByteBuffer asByteBuffer() { return ByteBuffer.wrap(value).asReadOnlyBuffer(); } public final ByteCharSequence asCharSequence() { return new ByteCharSequence(value); } public final PythonString asAsciiString() { return PythonString.valueOf(asCharSequence().toString()); } public static PythonBytes fromIntTuple(PythonLikeTuple tuple) { byte[] out = new byte[tuple.size()]; IntStream.range(0, tuple.size()).forEach(index -> out[index] = ((PythonInteger) tuple.get(index)).asByte()); return new PythonBytes(out); } public final PythonLikeTuple asIntTuple() { return IntStream.range(0, value.length).mapToObj(index -> BYTE_TO_INT[Byte.toUnsignedInt(value[index])]) .collect(Collectors.toCollection(PythonLikeTuple::new)); } private static BitSet asBitSet(PythonBytes bytesInBitSet) { BitSet out = new BitSet(); for (byte item : bytesInBitSet.value) { out.set(item & 0xFF); } return out; } public PythonInteger getLength() { return PythonInteger.valueOf(value.length); } public PythonInteger getCharAt(PythonInteger position) { int index = PythonSlice.asIntIndexForLength(position, value.length); if (index >= value.length) { throw new IndexError("position " + position + " larger than bytes length " + value.length); } else if (index < 0) { throw new IndexError("position " + position + " is less than 0"); } return BYTE_TO_INT[Byte.toUnsignedInt(value[index])]; } public PythonBytes getSubsequence(PythonSlice slice) { int length = value.length; int start = slice.getStartIndex(length); int stop = slice.getStopIndex(length); int step = slice.getStrideLength(); if (step == 1) { if (stop <= start) { return EMPTY; } else { return new PythonBytes(Arrays.copyOfRange(value, start, stop)); } } else { byte[] out = new byte[slice.getSliceSize(length)]; slice.iterate(length, (index, iteration) -> { out[iteration] = value[index]; }); return new PythonBytes(out); } } public PythonBoolean containsSubsequence(PythonBytes subsequence) { if (subsequence.value.length == 0) { return PythonBoolean.TRUE; } if (subsequence.value.length > value.length) { return PythonBoolean.FALSE; } for (int i = 0; i <= value.length - subsequence.value.length; i++) { if (Arrays.equals(value, i, i + subsequence.value.length, subsequence.value, 0, subsequence.value.length)) { return PythonBoolean.TRUE; } } return PythonBoolean.FALSE; } public PythonBytes concat(PythonBytes other) { if (value.length == 0) { return other; } else if (other.value.length == 0) { return this; } else { byte[] out = new byte[value.length + other.value.length]; System.arraycopy(value, 0, out, 0, value.length); System.arraycopy(other.value, 0, out, value.length, other.value.length); return new PythonBytes(out); } } public PythonBytes repeat(PythonInteger times) { int timesAsInt = times.value.intValueExact(); if (timesAsInt <= 0) { return EMPTY; } if (timesAsInt == 1 || value.length == 0) { return this; } byte[] out = new byte[value.length * timesAsInt]; for (int i = 0; i < timesAsInt; i++) { System.arraycopy(value, 0, out, i * value.length, value.length); } return new PythonBytes(out); } public DelegatePythonIterator<PythonInteger> getIterator() { return new DelegatePythonIterator<>(IntStream.range(0, value.length) .mapToObj(index -> BYTE_TO_INT[Byte.toUnsignedInt(value[index])]) .iterator()); } public PythonInteger countByte(byte query, int start, int end) { int count = 0; for (int i = start; i < end; i++) { if (value[i] == query) { count++; } } return PythonInteger.valueOf(count); } public PythonInteger count(PythonInteger byteAsInt) { byte query = byteAsInt.asByte(); return countByte(query, 0, value.length); } public PythonInteger count(PythonInteger byteAsInt, PythonInteger start) { byte query = byteAsInt.asByte(); int startAsInt = PythonSlice.asValidStartIntIndexForLength(start, value.length); return countByte(query, startAsInt, value.length); } public PythonInteger count(PythonInteger byteAsInt, PythonInteger start, PythonInteger end) { byte query = byteAsInt.asByte(); int startAsInt = PythonSlice.asValidStartIntIndexForLength(start, value.length); int endAsInt = PythonSlice.asValidEndIntIndexForLength(end, value.length); return countByte(query, startAsInt, endAsInt); } private PythonInteger countSubsequence(byte[] query, int from, int to) { int count = 0; if ((to - from) == 0 || query.length > (to - from)) { return PythonInteger.ZERO; } if (query.length == 0) { return PythonInteger.valueOf((to - from) + 1); } for (int i = from; i <= to - query.length; i++) { if (Arrays.equals(value, i, i + query.length, query, 0, query.length)) { count++; i += query.length - 1; } } return PythonInteger.valueOf(count); } public PythonInteger count(PythonBytes bytes) { return countSubsequence(bytes.value, 0, value.length); } public PythonInteger count(PythonBytes bytes, PythonInteger start) { int startAsInt = PythonSlice.asValidStartIntIndexForLength(start, value.length); return countSubsequence(bytes.value, startAsInt, value.length); } public PythonInteger count(PythonBytes bytes, PythonInteger start, PythonInteger end) { int startAsInt = PythonSlice.asValidStartIntIndexForLength(start, value.length); int endAsInt = PythonSlice.asValidEndIntIndexForLength(end, value.length); return countSubsequence(bytes.value, startAsInt, endAsInt); } public boolean hasPrefix(byte[] prefixBytes, int start, int end) { if (prefixBytes.length > end - start) { return false; } for (int i = 0; i < prefixBytes.length; i++) { if (prefixBytes[i] != value[i + start]) { return false; } } return true; } public boolean hasSuffix(byte[] suffixBytes, int start, int end) { if (suffixBytes.length > end - start) { return false; } for (int i = 1; i <= suffixBytes.length; i++) { if (suffixBytes[suffixBytes.length - i] != value[end - i]) { return false; } } return true; } public PythonBytes removePrefix(PythonBytes prefix) { byte[] prefixBytes = prefix.value; return hasPrefix(prefixBytes, 0, value.length) ? new PythonBytes(Arrays.copyOfRange(value, prefixBytes.length, value.length)) : this; } public PythonBytes removeSuffix(PythonBytes suffix) { byte[] suffixBytes = suffix.value; return hasSuffix(suffixBytes, 0, value.length) ? new PythonBytes(Arrays.copyOfRange(value, 0, value.length - suffixBytes.length)) : this; } public PythonString decode() { try { return PythonString.valueOf(StandardCharsets.UTF_8.newDecoder() .onMalformedInput(CodingErrorAction.REPORT) .decode(ByteBuffer.wrap(value)).toString()); } catch (CharacterCodingException e) { throw new UnicodeDecodeError(e.getMessage()); } } public PythonString decode(PythonString charset) { try { return PythonString.valueOf(Charset.forName(charset.value).newDecoder() .onMalformedInput(CodingErrorAction.REPORT) .decode(ByteBuffer.wrap(value)).toString()); } catch (CharacterCodingException e) { throw new UnicodeDecodeError(e.getMessage()); } } public PythonString decode(PythonString charset, PythonString errorActionString) { CodingErrorAction errorAction; switch (errorActionString.value) { case "strict": errorAction = CodingErrorAction.REPORT; break; case "ignore": errorAction = CodingErrorAction.IGNORE; break; case "replace": errorAction = CodingErrorAction.REPLACE; break; default: throw new ValueError(errorActionString.repr() + " is not a valid value for errors. Possible values are: " + "\"strict\", \"ignore\", \"replace\"."); } try { return PythonString.valueOf(Charset.forName(charset.value).newDecoder() .onMalformedInput(errorAction) .decode(ByteBuffer.wrap(value)).toString()); } catch (CharacterCodingException e) { throw new UnicodeDecodeError(e.getMessage()); } } public PythonBoolean endsWith(PythonBytes suffix) { return PythonBoolean.valueOf(hasSuffix(suffix.value, 0, value.length)); } public PythonBoolean endsWith(PythonBytes suffix, PythonInteger start) { int startAsInt = PythonSlice.asValidStartIntIndexForLength(start, value.length); return PythonBoolean.valueOf(hasSuffix(suffix.value, startAsInt, value.length)); } public PythonBoolean endsWith(PythonBytes suffix, PythonInteger start, PythonInteger end) { int startAsInt = PythonSlice.asValidStartIntIndexForLength(start, value.length); int endAsInt = PythonSlice.asValidEndIntIndexForLength(end, value.length); return PythonBoolean.valueOf(hasSuffix(suffix.value, startAsInt, endAsInt)); } public PythonBoolean endsWith(PythonLikeTuple<PythonBytes> suffixes) { for (PythonBytes suffix : suffixes) { if (hasSuffix(suffix.value, 0, value.length)) { return PythonBoolean.TRUE; } } return PythonBoolean.FALSE; } public PythonBoolean endsWith(PythonLikeTuple<PythonBytes> suffixes, PythonInteger start) { int startAsInt = PythonSlice.asValidStartIntIndexForLength(start, value.length); for (PythonBytes suffix : suffixes) { if (hasSuffix(suffix.value, startAsInt, value.length)) { return PythonBoolean.TRUE; } } return PythonBoolean.FALSE; } public PythonBoolean endsWith(PythonLikeTuple<PythonBytes> suffixes, PythonInteger start, PythonInteger end) { int startAsInt = PythonSlice.asValidStartIntIndexForLength(start, value.length); int endAsInt = PythonSlice.asValidEndIntIndexForLength(end, value.length); for (PythonBytes suffix : suffixes) { if (hasSuffix(suffix.value, startAsInt, endAsInt)) { return PythonBoolean.TRUE; } } return PythonBoolean.FALSE; } private PythonInteger find(PythonInteger query, int start, int end) { byte queryByte = query.asByte(); for (int i = start; i < end; i++) { if (value[i] == queryByte) { return PythonInteger.valueOf(i); } } return PythonInteger.valueOf(-1); } private PythonInteger index(PythonInteger query, int start, int end) { byte queryByte = query.asByte(); for (int i = start; i < end; i++) { if (value[i] == queryByte) { return PythonInteger.valueOf(i); } } throw new ValueError("Subsequence not found"); } public PythonInteger find(PythonInteger query) { return find(query, 0, value.length); } public PythonInteger find(PythonInteger query, PythonInteger start) { int startAsInt = PythonSlice.asValidStartIntIndexForLength(start, value.length); return find(query, startAsInt, value.length); } public PythonInteger find(PythonInteger query, PythonInteger start, PythonInteger end) { int startAsInt = PythonSlice.asValidStartIntIndexForLength(start, value.length); int endAsInt = PythonSlice.asValidEndIntIndexForLength(end, value.length); return find(query, startAsInt, endAsInt); } public PythonInteger index(PythonInteger query) { return index(query, 0, value.length); } public PythonInteger index(PythonInteger query, PythonInteger start) { int startAsInt = PythonSlice.asValidStartIntIndexForLength(start, value.length); return index(query, startAsInt, value.length); } public PythonInteger index(PythonInteger query, PythonInteger start, PythonInteger end) { int startAsInt = PythonSlice.asValidStartIntIndexForLength(start, value.length); int endAsInt = PythonSlice.asValidEndIntIndexForLength(end, value.length); return index(query, startAsInt, endAsInt); } private PythonInteger find(PythonBytesLikeObject query, int start, int end) { byte[] queryBytes = query.asByteArray(); if (queryBytes.length == 0) { return (value.length > 0) ? PythonInteger.ZERO : PythonInteger.valueOf(-1); } for (int i = start; i <= end - queryBytes.length; i++) { if (Arrays.equals(value, i, i + queryBytes.length, queryBytes, 0, queryBytes.length)) { return PythonInteger.valueOf(i); } } return PythonInteger.valueOf(-1); } private PythonInteger index(PythonBytesLikeObject query, int start, int end) { byte[] queryBytes = query.asByteArray(); if (queryBytes.length == 0) { if (value.length > 0) { return PythonInteger.ZERO; } else { throw new ValueError("Subsequence not found"); } } for (int i = start; i <= end - queryBytes.length; i++) { if (Arrays.equals(value, i, i + queryBytes.length, queryBytes, 0, queryBytes.length)) { return PythonInteger.valueOf(i); } } throw new ValueError("Subsequence not found"); } public PythonInteger find(PythonBytes query) { return find(query, 0, value.length); } public PythonInteger find(PythonBytes query, PythonInteger start) { int startAsInt = PythonSlice.asValidStartIntIndexForLength(start, value.length); return find(query, startAsInt, value.length); } public PythonInteger find(PythonBytes query, PythonInteger start, PythonInteger end) { int startAsInt = PythonSlice.asValidStartIntIndexForLength(start, value.length); int endAsInt = PythonSlice.asValidEndIntIndexForLength(end, value.length); return find(query, startAsInt, endAsInt); } public PythonInteger index(PythonBytes query) { return index(query, 0, value.length); } public PythonInteger index(PythonBytes query, PythonInteger start) { int startAsInt = PythonSlice.asValidStartIntIndexForLength(start, value.length); return index(query, startAsInt, value.length); } public PythonInteger index(PythonBytes query, PythonInteger start, PythonInteger end) { int startAsInt = PythonSlice.asValidStartIntIndexForLength(start, value.length); int endAsInt = PythonSlice.asValidEndIntIndexForLength(end, value.length); return index(query, startAsInt, endAsInt); } public PythonBytes interpolate(PythonLikeObject object) { if (object instanceof PythonLikeTuple) { return interpolate((PythonLikeTuple) object); } else if (object instanceof PythonLikeDict) { return interpolate((PythonLikeDict) object); } else { return interpolate(PythonLikeTuple.fromItems(object)); } } public PythonBytes interpolate(PythonLikeTuple tuple) { return PythonString.valueOf(StringFormatter.printfInterpolate(asCharSequence(), tuple, StringFormatter.PrintfStringType.BYTES)).asAsciiBytes(); } public PythonBytes interpolate(PythonLikeDict dict) { return PythonString.valueOf(StringFormatter.printfInterpolate(asCharSequence(), dict, StringFormatter.PrintfStringType.BYTES)).asAsciiBytes(); } public PythonBytes join(PythonLikeObject iterable) { PythonIterator<?> iterator = (PythonIterator<?>) UnaryDunderBuiltin.ITERATOR.invoke(iterable); ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); while (iterator.hasNext()) { PythonLikeObject item = iterator.nextPythonItem(); if (!(item instanceof PythonBytesLikeObject)) { throw new TypeError("type " + item.$getType() + " is not a bytes-like type"); } outputStream.writeBytes(((PythonBytesLikeObject) item).asByteArray()); if (iterator.hasNext()) { outputStream.writeBytes(value); } } return new PythonBytes(outputStream.toByteArray()); } private PythonLikeTuple partition(PythonBytesLikeObject sep, int start, int end) { byte[] sepBytes = sep.asByteArray(); for (int i = start; i < end - sepBytes.length; i++) { int j = 0; for (; j < sepBytes.length; j++) { if (value[i + j] != sepBytes[j]) { break; } } if (j == sepBytes.length) { return PythonLikeTuple.fromItems( new PythonBytes(Arrays.copyOfRange(value, 0, i)), sep, new PythonBytes(Arrays.copyOfRange(value, i + sepBytes.length, value.length))); } } return PythonLikeTuple.fromItems( this, EMPTY, EMPTY); } public PythonLikeTuple partition(PythonBytes sep) { return partition(sep, 0, value.length); } public PythonLikeTuple partition(PythonBytes sep, PythonInteger start) { int startAsInt = PythonSlice.asValidStartIntIndexForLength(start, value.length); return partition(sep, startAsInt, value.length); } public PythonLikeTuple partition(PythonBytes sep, PythonInteger start, PythonInteger end) { int startAsInt = PythonSlice.asValidStartIntIndexForLength(start, value.length); int endAsInt = PythonSlice.asValidStartIntIndexForLength(end, value.length); return partition(sep, startAsInt, endAsInt); } public PythonBytes replace(PythonBytesLikeObject old, PythonBytesLikeObject replacement) { byte[] oldBytes = old.asByteArray(); byte[] replacementBytes = replacement.asByteArray(); ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); int lastReplacementEnd = 0; for (int i = 0; i < value.length - oldBytes.length; i++) { if (!Arrays.equals(value, i, i + oldBytes.length, oldBytes, 0, oldBytes.length)) { continue; } outputStream.write(value, lastReplacementEnd, i - lastReplacementEnd); outputStream.writeBytes(replacementBytes); i += oldBytes.length; lastReplacementEnd = i; } outputStream.write(value, lastReplacementEnd, value.length - lastReplacementEnd); return new PythonBytes(outputStream.toByteArray()); } public PythonBytes replace(PythonBytesLikeObject old, PythonBytesLikeObject replacement, BigInteger count) { byte[] oldBytes = old.asByteArray(); byte[] replacementBytes = replacement.asByteArray(); ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); int lastReplacementEnd = 0; for (int i = 0; i < value.length - oldBytes.length; i++) { if (count.compareTo(BigInteger.ZERO) == 0) { break; } if (!Arrays.equals(value, i, i + oldBytes.length, oldBytes, 0, oldBytes.length)) { continue; } outputStream.write(value, lastReplacementEnd, i - lastReplacementEnd); outputStream.writeBytes(replacementBytes); i += oldBytes.length; lastReplacementEnd = i; count = count.subtract(BigInteger.ONE); } outputStream.write(value, lastReplacementEnd, value.length - lastReplacementEnd); return new PythonBytes(outputStream.toByteArray()); } public PythonBytes replace(PythonBytes old, PythonBytes replacement) { return replace((PythonBytesLikeObject) old, replacement); } public PythonBytes replace(PythonBytes old, PythonBytes replacement, PythonInteger count) { return replace(old, replacement, count.value); } private PythonInteger rightFind(PythonInteger query, int start, int end) { byte queryByte = query.asByte(); for (int i = end - 1; i >= start; i--) { if (value[i] == queryByte) { return PythonInteger.valueOf(i); } } return PythonInteger.valueOf(-1); } private PythonInteger rightIndex(PythonInteger query, int start, int end) { byte queryByte = query.asByte(); for (int i = end - 1; i >= start; i--) { if (value[i] == queryByte) { return PythonInteger.valueOf(i); } } throw new ValueError("Subsequence not found"); } public PythonInteger rightFind(PythonInteger query) { return rightFind(query, 0, value.length); } public PythonInteger rightFind(PythonInteger query, PythonInteger start) { int startAsInt = PythonSlice.asValidStartIntIndexForLength(start, value.length); return rightFind(query, startAsInt, value.length); } public PythonInteger rightFind(PythonInteger query, PythonInteger start, PythonInteger end) { int startAsInt = PythonSlice.asValidStartIntIndexForLength(start, value.length); int endAsInt = PythonSlice.asValidEndIntIndexForLength(end, value.length); return rightFind(query, startAsInt, endAsInt); } public PythonInteger rightIndex(PythonInteger query) { return rightIndex(query, 0, value.length); } public PythonInteger rightIndex(PythonInteger query, PythonInteger start) { int startAsInt = PythonSlice.asValidStartIntIndexForLength(start, value.length); return rightIndex(query, startAsInt, value.length); } public PythonInteger rightIndex(PythonInteger query, PythonInteger start, PythonInteger end) { int startAsInt = PythonSlice.asValidStartIntIndexForLength(start, value.length); int endAsInt = PythonSlice.asValidEndIntIndexForLength(end, value.length); return rightIndex(query, startAsInt, endAsInt); } private PythonInteger rightFind(PythonBytesLikeObject query, int start, int end) { byte[] queryBytes = query.asByteArray(); for (int i = end - queryBytes.length; i >= start; i--) { int j = 0; for (; j < queryBytes.length; j++) { if (value[i + j] != queryBytes[j]) { break; } } if (j == queryBytes.length) { return PythonInteger.valueOf(i); } } return PythonInteger.valueOf(-1); } private PythonInteger rightIndex(PythonBytesLikeObject query, int start, int end) { byte[] queryBytes = query.asByteArray(); for (int i = end - queryBytes.length; i >= start; i--) { int j = 0; for (; j < queryBytes.length; j++) { if (value[i + j] != queryBytes[j]) { break; } } if (j == queryBytes.length) { return PythonInteger.valueOf(i); } } throw new ValueError("Subsequence not found"); } public PythonInteger rightFind(PythonBytes query) { return rightFind(query, 0, value.length); } public PythonInteger rightFind(PythonBytes query, PythonInteger start) { int startAsInt = PythonSlice.asValidStartIntIndexForLength(start, value.length); return rightFind(query, startAsInt, value.length); } public PythonInteger rightFind(PythonBytes query, PythonInteger start, PythonInteger end) { int startAsInt = PythonSlice.asValidStartIntIndexForLength(start, value.length); int endAsInt = PythonSlice.asValidEndIntIndexForLength(end, value.length); return rightFind(query, startAsInt, endAsInt); } public PythonInteger rightIndex(PythonBytes query) { return rightIndex(query, 0, value.length); } public PythonInteger rightIndex(PythonBytes query, PythonInteger start) { int startAsInt = PythonSlice.asValidStartIntIndexForLength(start, value.length); return rightIndex(query, startAsInt, value.length); } public PythonInteger rightIndex(PythonBytes query, PythonInteger start, PythonInteger end) { int startAsInt = PythonSlice.asValidStartIntIndexForLength(start, value.length); int endAsInt = PythonSlice.asValidEndIntIndexForLength(end, value.length); return rightIndex(query, startAsInt, endAsInt); } private PythonLikeTuple rightPartition(PythonBytesLikeObject sep, int start, int end) { byte[] sepBytes = sep.asByteArray(); for (int i = end - sepBytes.length; i >= start; i--) { if (!Arrays.equals(value, i, i + sepBytes.length, sepBytes, 0, sepBytes.length)) { continue; } return PythonLikeTuple.fromItems( new PythonBytes(Arrays.copyOfRange(value, 0, i)), sep, new PythonBytes(Arrays.copyOfRange(value, i + sepBytes.length, value.length))); } return PythonLikeTuple.fromItems( EMPTY, EMPTY, this); } public PythonLikeTuple rightPartition(PythonBytes sep) { return rightPartition(sep, 0, value.length); } public PythonBoolean startsWith(PythonBytes prefix) { return PythonBoolean.valueOf(hasPrefix(prefix.value, 0, value.length)); } public PythonBoolean startsWith(PythonBytes prefix, PythonInteger start) { int startAsInt = PythonSlice.asValidStartIntIndexForLength(start, value.length); return PythonBoolean.valueOf(hasPrefix(prefix.value, startAsInt, value.length)); } public PythonBoolean startsWith(PythonBytes prefix, PythonInteger start, PythonInteger end) { int startAsInt = PythonSlice.asValidStartIntIndexForLength(start, value.length); int endAsInt = PythonSlice.asValidEndIntIndexForLength(end, value.length); return PythonBoolean.valueOf(hasPrefix(prefix.value, startAsInt, endAsInt)); } public PythonBoolean startsWith(PythonLikeTuple<PythonBytes> prefixes) { for (PythonBytes prefix : prefixes) { if (hasPrefix(prefix.value, 0, value.length)) { return PythonBoolean.TRUE; } } return PythonBoolean.FALSE; } public PythonBoolean startsWith(PythonLikeTuple<PythonBytes> prefixes, PythonInteger start) { int startAsInt = PythonSlice.asValidStartIntIndexForLength(start, value.length); for (PythonBytes prefix : prefixes) { if (hasPrefix(prefix.value, startAsInt, value.length)) { return PythonBoolean.TRUE; } } return PythonBoolean.FALSE; } public PythonBoolean startsWith(PythonLikeTuple<PythonBytes> prefixes, PythonInteger start, PythonInteger end) { int startAsInt = PythonSlice.asValidStartIntIndexForLength(start, value.length); int endAsInt = PythonSlice.asValidEndIntIndexForLength(end, value.length); for (PythonBytes prefix : prefixes) { if (hasPrefix(prefix.value, startAsInt, endAsInt)) { return PythonBoolean.TRUE; } } return PythonBoolean.FALSE; } public PythonBytes translate(PythonBytes table) { byte[] tableBytes = table.value; if (tableBytes.length != 256) { throw new ValueError("translate table must be a bytes object of length 256"); } byte[] out = new byte[value.length]; for (int i = 0; i < value.length; i++) { out[i] = tableBytes[value[i] & 0xFF]; } return new PythonBytes(out); } public PythonBytes translate(PythonNone table) { return this; } public PythonBytes translate(PythonBytes table, PythonBytes delete) { byte[] tableBytes = table.value; if (tableBytes.length != 256) { throw new ValueError("translate table must be a bytes object of length 256"); } ByteArrayOutputStream out = new ByteArrayOutputStream(value.length); BitSet removedSet = asBitSet(delete); for (byte b : value) { if (!removedSet.get(b & 0xFF)) { out.write(tableBytes, b & 0xFF, 1); } } return new PythonBytes(out.toByteArray()); } public PythonBytes translate(PythonNone table, PythonBytes delete) { ByteArrayOutputStream out = new ByteArrayOutputStream(value.length); BitSet removedSet = asBitSet(delete); for (int i = 0; i < value.length; i++) { if (!removedSet.get(value[i] & 0xFF)) { out.write(value, i, 1); } } return new PythonBytes(out.toByteArray()); } public PythonBytes center(PythonInteger fillWidth) { return center(fillWidth, ASCII_SPACE); } public PythonBytes center(PythonInteger fillWidth, PythonBytes fillCharacter) { if (fillCharacter.value.length != 1) { throw new TypeError("center() argument 2 must be a byte string of length 1"); } int widthAsInt = fillWidth.value.intValueExact(); if (widthAsInt <= value.length) { return this; } int extraWidth = widthAsInt - value.length; int rightPadding = extraWidth / 2; // left padding get extra character if extraWidth is odd int leftPadding = rightPadding + (extraWidth & 1); // x & 1 == x % 2 byte[] out = new byte[widthAsInt]; Arrays.fill(out, 0, leftPadding, fillCharacter.value[0]); System.arraycopy(value, 0, out, leftPadding, value.length); Arrays.fill(out, leftPadding + value.length, widthAsInt, fillCharacter.value[0]); return new PythonBytes(out); } public PythonBytes leftJustify(PythonInteger fillWidth) { return leftJustify(fillWidth, ASCII_SPACE); } public PythonBytes leftJustify(PythonInteger fillWidth, PythonBytes fillCharacter) { if (fillCharacter.value.length != 1) { throw new TypeError("ljust() argument 2 must be a byte string of length 1"); } int widthAsInt = fillWidth.value.intValueExact(); if (widthAsInt <= value.length) { return this; } byte[] out = new byte[widthAsInt]; System.arraycopy(value, 0, out, 0, value.length); Arrays.fill(out, value.length, widthAsInt, fillCharacter.value[0]); return new PythonBytes(out); } public PythonBytes rightJustify(PythonInteger fillWidth) { return rightJustify(fillWidth, ASCII_SPACE); } public PythonBytes rightJustify(PythonInteger fillWidth, PythonBytes fillCharacter) { if (fillCharacter.value.length != 1) { throw new TypeError("rjust() argument 2 must be a byte string of length 1"); } int widthAsInt = fillWidth.value.intValueExact(); if (widthAsInt <= value.length) { return this; } int extraWidth = widthAsInt - value.length; byte[] out = new byte[widthAsInt]; Arrays.fill(out, 0, extraWidth, fillCharacter.value[0]); System.arraycopy(value, 0, out, extraWidth, value.length); return new PythonBytes(out); } public PythonBytes strip() { return strip(ASCII_SPACE); } public PythonBytes strip(PythonNone ignored) { return strip(); } public PythonBytes strip(PythonBytes bytesToStrip) { BitSet toStrip = asBitSet(bytesToStrip); int start = 0; int end = value.length - 1; while (start < value.length && toStrip.get(value[start] & 0xFF)) { start++; } while (end >= start && toStrip.get(value[end] & 0xFF)) { end--; } if (end < start) { return new PythonBytes(new byte[] {}); } return new PythonBytes(Arrays.copyOfRange(value, start, end + 1)); } public PythonBytes leftStrip() { return leftStrip(ASCII_SPACE); } public PythonBytes leftStrip(PythonNone ignored) { return leftStrip(); } public PythonBytes leftStrip(PythonBytes bytesToStrip) { BitSet toStrip = asBitSet(bytesToStrip); int start = 0; while (start < value.length && toStrip.get(value[start] & 0xFF)) { start++; } if (start == value.length) { return new PythonBytes(new byte[] {}); } return new PythonBytes(Arrays.copyOfRange(value, start, value.length)); } public PythonBytes rightStrip() { return rightStrip(ASCII_SPACE); } public PythonBytes rightStrip(PythonNone ignored) { return rightStrip(); } public PythonBytes rightStrip(PythonBytes bytesToStrip) { BitSet toStrip = asBitSet(bytesToStrip); int end = value.length - 1; while (end >= 0 && toStrip.get(value[end] & 0xFF)) { end--; } if (end < 0) { return new PythonBytes(new byte[] {}); } return new PythonBytes(Arrays.copyOfRange(value, 0, end + 1)); } public PythonLikeList<PythonBytes> split() { PythonLikeList<PythonBytes> out = new PythonLikeList<>(); int start = 0; int end = value.length; while (end > 0 && ASCII_WHITESPACE_BITSET.get(value[end - 1] & 0xFF)) { end--; } while (start < end && ASCII_WHITESPACE_BITSET.get(value[start] & 0xFF)) { start++; } if (start == end) { return out; } int lastEnd = start; while (start < end - 1) { while (start < end - 1 && !ASCII_WHITESPACE_BITSET.get(value[start] & 0xFF)) { start++; } if (start != end - 1) { out.add(new PythonBytes(Arrays.copyOfRange(value, lastEnd, start))); lastEnd = start + 1; start = lastEnd; } } if (lastEnd != end) { out.add(new PythonBytes(Arrays.copyOfRange(value, lastEnd, end))); } return out; } public PythonLikeList<PythonBytes> split(PythonNone ignored) { return split(); } public PythonLikeList<PythonBytes> split(PythonBytes seperator) { PythonLikeList<PythonBytes> out = new PythonLikeList<>(); int start = 0; int end = value.length; int lastEnd = start; while (start < end - seperator.value.length) { while (start < end - seperator.value.length && !Arrays.equals(value, start, start + seperator.value.length, seperator.value, 0, seperator.value.length)) { start++; } if (start != end - seperator.value.length) { out.add(new PythonBytes(Arrays.copyOfRange(value, lastEnd, start))); lastEnd = start + seperator.value.length; start = lastEnd; } } if (Arrays.equals(value, start, start + seperator.value.length, seperator.value, 0, seperator.value.length)) { out.add(new PythonBytes(Arrays.copyOfRange(value, lastEnd, start))); lastEnd = start + seperator.value.length; } out.add(new PythonBytes(Arrays.copyOfRange(value, lastEnd, end))); return out; } public PythonLikeList<PythonBytes> split(PythonBytes seperator, PythonInteger maxSplits) { if (maxSplits.equals(new PythonInteger(-1))) { return split(seperator); } PythonLikeList<PythonBytes> out = new PythonLikeList<>(); int start = 0; int end = value.length; int lastEnd = start; while (start < end - seperator.value.length && maxSplits.compareTo(PythonInteger.ONE) >= 0) { while (start < end - seperator.value.length && !Arrays.equals(value, start, start + seperator.value.length, seperator.value, 0, seperator.value.length)) { start++; } if (start != end - seperator.value.length) { out.add(new PythonBytes(Arrays.copyOfRange(value, lastEnd, start))); lastEnd = start + seperator.value.length; start = lastEnd; maxSplits = maxSplits.subtract(PythonInteger.ONE); } } if (maxSplits.compareTo(PythonInteger.ONE) >= 0 && Arrays.equals(value, start, start + seperator.value.length, seperator.value, 0, seperator.value.length)) { out.add(new PythonBytes(Arrays.copyOfRange(value, lastEnd, start))); lastEnd = start + seperator.value.length; } out.add(new PythonBytes(Arrays.copyOfRange(value, lastEnd, end))); return out; } public PythonLikeList<PythonBytes> split(PythonNone seperator, PythonInteger maxSplits) { if (maxSplits.equals(new PythonInteger(-1))) { return split(seperator); } PythonLikeList<PythonBytes> out = new PythonLikeList<>(); int start = 0; int end = value.length; while (end > 0 && ASCII_WHITESPACE_BITSET.get(value[end - 1] & 0xFF)) { end--; } while (start < end && ASCII_WHITESPACE_BITSET.get(value[start] & 0xFF)) { start++; } if (start == end) { return out; } int lastEnd = start; while (start < end - 1 && maxSplits.compareTo(PythonInteger.ONE) >= 0) { while (start < end - 1 && !ASCII_WHITESPACE_BITSET.get(value[start] & 0xFF)) { start++; } if (start != end - 1) { out.add(new PythonBytes(Arrays.copyOfRange(value, lastEnd, start))); lastEnd = start + 1; start = lastEnd; maxSplits = maxSplits.subtract(PythonInteger.ONE); } } if (lastEnd != end) { out.add(new PythonBytes(Arrays.copyOfRange(value, lastEnd, end))); } return out; } public PythonLikeList<PythonBytes> rightSplit() { return split(); } public PythonLikeList<PythonBytes> rightSplit(PythonNone ignored) { return rightSplit(); } public PythonLikeList<PythonBytes> rightSplit(PythonBytes seperator) { return split(seperator); } private static byte[] reverseInplace(byte[] array) { for (int i = 0; i < array.length >> 1; i++) { byte temp = array[i]; array[i] = array[array.length - i - 1]; array[array.length - i - 1] = temp; } return array; } public PythonLikeList<PythonBytes> rightSplit(PythonBytes seperator, PythonInteger maxSplits) { if (maxSplits.equals(new PythonInteger(-1))) { return split(seperator); } PythonLikeList<PythonBytes> out = new PythonLikeList<>(); byte[] reversedValue = reverseInplace(value.clone()); byte[] reversedSep = reverseInplace(seperator.value.clone()); int start = 0; int end = reversedValue.length; int lastEnd = start; while (start < end - reversedSep.length && maxSplits.compareTo(PythonInteger.ONE) >= 0) { while (start < end - reversedSep.length && !Arrays.equals(reversedValue, start, start + reversedSep.length, reversedSep, 0, reversedSep.length)) { start++; } if (start != end - reversedSep.length) { out.add(new PythonBytes(reverseInplace(Arrays.copyOfRange(reversedValue, lastEnd, start)))); lastEnd = start + reversedSep.length; start = lastEnd; maxSplits = maxSplits.subtract(PythonInteger.ONE); } } if (maxSplits.compareTo(PythonInteger.ONE) >= 0 && Arrays.equals(reversedValue, start, start + reversedSep.length, reversedSep, 0, reversedSep.length)) { out.add(new PythonBytes(reverseInplace(Arrays.copyOfRange(reversedValue, lastEnd, start)))); lastEnd = start + seperator.value.length; } out.add(new PythonBytes(reverseInplace(Arrays.copyOfRange(reversedValue, lastEnd, end)))); out.reverse(); return out; } public PythonLikeList<PythonBytes> rightSplit(PythonNone seperator, PythonInteger maxSplits) { if (maxSplits.equals(new PythonInteger(-1))) { return split(seperator); } PythonLikeList<PythonBytes> out = new PythonLikeList<>(); byte[] reversedValue = reverseInplace(value.clone()); int start = 0; int end = value.length; while (end > 0 && ASCII_WHITESPACE_BITSET.get(value[end - 1] & 0xFF)) { end--; } while (start < end && ASCII_WHITESPACE_BITSET.get(value[start] & 0xFF)) { start++; } if (start == end) { return out; } int lastEnd = start; while (start < end - 1 && maxSplits.compareTo(PythonInteger.ONE) >= 0) { while (start < end - 1 && !ASCII_WHITESPACE_BITSET.get(reversedValue[start] & 0xFF)) { start++; } if (start != end - 1) { out.add(new PythonBytes(reverseInplace(Arrays.copyOfRange(reversedValue, lastEnd, start)))); lastEnd = start + 1; start = lastEnd; maxSplits = maxSplits.subtract(PythonInteger.ONE); } } if (lastEnd != end) { out.add(new PythonBytes(reverseInplace(Arrays.copyOfRange(reversedValue, lastEnd, end)))); } out.reverse(); return out; } public PythonBytes capitalize() { var asString = asAsciiString(); if (asString.value.isEmpty()) { return this; } var tail = PythonString.valueOf(asString.value.substring(1)) .withModifiedCodepoints(cp -> cp < 128 ? Character.toLowerCase(cp) : cp).value; var head = asString.value.charAt(0); if (head < 128) { head = Character.toTitleCase(head); } return (PythonString.valueOf(head + tail)).asAsciiBytes(); } public PythonBytes expandTabs() { return asAsciiString().expandTabs().asAsciiBytes(); } public PythonBytes expandTabs(PythonInteger tabSize) { return asAsciiString().expandTabs(tabSize).asAsciiBytes(); } public PythonBoolean isAlphaNumeric() { return asAsciiString().isAlphaNumeric(); } public PythonBoolean isAlpha() { return asAsciiString().isAlpha(); } public PythonBoolean isAscii() { for (byte b : value) { if ((b & 0xFF) > 0x7F) { return PythonBoolean.FALSE; } } return PythonBoolean.TRUE; } public PythonBoolean isDigit() { return asAsciiString().isDigit(); } public PythonBoolean isLower() { return asAsciiString().isLower(); } public PythonBoolean isSpace() { return asAsciiString().isSpace(); } public PythonBoolean isTitle() { return asAsciiString().isTitle(); } public PythonBoolean isUpper() { return asAsciiString().isUpper(); } public PythonBytes lower() { return asAsciiString().withModifiedCodepoints( cp -> cp < 128 ? Character.toLowerCase(cp) : cp).asAsciiBytes(); } public PythonLikeList<PythonBytes> splitLines() { return asAsciiString().splitLines() .stream() .map(PythonString::asAsciiBytes) .collect(Collectors.toCollection(PythonLikeList::new)); } public PythonLikeList<PythonBytes> splitLines(PythonBoolean keepEnds) { return asAsciiString().splitLines(keepEnds) .stream() .map(PythonString::asAsciiBytes) .collect(Collectors.toCollection(PythonLikeList::new)); } public PythonBytes swapCase() { return asAsciiString().withModifiedCodepoints( cp -> cp < 128 ? PythonString.CharacterCase.swapCase(cp) : cp).asAsciiBytes(); } public PythonBytes title() { return asAsciiString().title(cp -> cp < 128).asAsciiBytes(); } public PythonBytes upper() { return asAsciiString().withModifiedCodepoints( cp -> cp < 128 ? Character.toUpperCase(cp) : cp).asAsciiBytes(); } public PythonBytes zfill(PythonInteger width) { return asAsciiString().zfill(width).asAsciiBytes(); } public PythonString asString() { return PythonString.valueOf(toString()); } public PythonString repr() { return asString(); } @Override public PythonString $method$__str__() { return PythonString.valueOf(toString()); } @Override public String toString() { boolean hasSingleQuotes = false; boolean hasDoubleQuotes = false; for (byte b : value) { switch (b) { case '\'': hasSingleQuotes = true; break; case '\"': hasDoubleQuotes = true; break; // Default: do nothing } } StringBuilder out = new StringBuilder(value.length); out.append("b"); if (!hasSingleQuotes || hasDoubleQuotes) { out.append('\''); } else { out.append('\"'); } boolean escapeSingleQuotes = hasSingleQuotes && hasDoubleQuotes; for (byte b : value) { switch (b) { case '\'': if (escapeSingleQuotes) { out.append("\\'"); } else { out.append('\''); } break; case '\\': out.append("\\\\"); break; case '\t': out.append("\\t"); break; case '\n': out.append("\\n"); break; case '\r': out.append("\\r"); break; default: out.append((char) (b & 0xFF)); break; } } if (!hasSingleQuotes || hasDoubleQuotes) { out.append('\''); } else { out.append('\"'); } return out.toString(); } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } PythonBytes that = (PythonBytes) o; return Arrays.equals(value, that.value); } @Override public int hashCode() { return Arrays.hashCode(value); } @Override public PythonInteger $method$__hash__() { return PythonInteger.valueOf(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/types/PythonBytesLikeObject.java
package ai.timefold.jpyinterpreter.types; import java.nio.ByteBuffer; import ai.timefold.jpyinterpreter.PythonLikeObject; public interface PythonBytesLikeObject extends PythonLikeObject { ByteBuffer asByteBuffer(); default byte[] asByteArray() { ByteBuffer byteBuffer = asByteBuffer(); byte[] out = new byte[byteBuffer.limit()]; byteBuffer.get(out); return out; } }
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/types/PythonCell.java
package ai.timefold.jpyinterpreter.types; import java.util.concurrent.atomic.AtomicReference; import ai.timefold.jpyinterpreter.PythonLikeObject; /** * Holds a reference to a PythonLikeObject. Cannot use {@link AtomicReference}, * since cells are stored in a tuple via BUILD_TUPLE and thus need to be a {@link PythonLikeObject}. */ public class PythonCell extends AbstractPythonLikeObject { public static final PythonLikeType CELL_TYPE = new PythonLikeType("cell", PythonCell.class), $TYPE = CELL_TYPE; /** * The value the cell stores. */ public PythonLikeObject cellValue; public PythonCell() { super(CELL_TYPE); } }
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/types/PythonCode.java
package ai.timefold.jpyinterpreter.types; /** * Holds a reference to a PythonLikeFunction's Class. Cannot use {@link Class}, * since code can be accessed like a {@code PythonLikeObject} */ public class PythonCode extends AbstractPythonLikeObject { public static final PythonLikeType CODE_TYPE = new PythonLikeType("code", PythonCode.class), $TYPE = CODE_TYPE; /** * The class of the function that implement the code */ public final Class<? extends PythonLikeFunction> functionClass; public PythonCode(final Class<? extends PythonLikeFunction> functionClass) { super(CODE_TYPE); this.functionClass = functionClass; } }
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/types/PythonGenerator.java
package ai.timefold.jpyinterpreter.types; import java.util.Iterator; import ai.timefold.jpyinterpreter.MethodDescriptor; import ai.timefold.jpyinterpreter.PythonFunctionSignature; import ai.timefold.jpyinterpreter.PythonLikeObject; import ai.timefold.jpyinterpreter.PythonOverloadImplementor; import ai.timefold.jpyinterpreter.PythonUnaryOperator; import ai.timefold.jpyinterpreter.types.errors.GeneratorExit; import ai.timefold.jpyinterpreter.types.errors.PythonBaseException; public abstract class PythonGenerator extends AbstractPythonLikeObject implements Iterator<PythonLikeObject> { public static PythonLikeType $TYPE = BuiltinTypes.GENERATOR_TYPE; static { PythonOverloadImplementor.deferDispatchesFor(PythonGenerator::registerMethods); } private static PythonLikeType registerMethods() throws NoSuchMethodException { BuiltinTypes.GENERATOR_TYPE.addUnaryMethod(PythonUnaryOperator.ITERATOR, new PythonFunctionSignature( new MethodDescriptor(PythonGenerator.class.getMethod("asPythonIterator")), BuiltinTypes.GENERATOR_TYPE)); BuiltinTypes.GENERATOR_TYPE.addUnaryMethod(PythonUnaryOperator.NEXT, new PythonFunctionSignature( new MethodDescriptor(PythonGenerator.class.getMethod("next")), BuiltinTypes.BASE_TYPE)); BuiltinTypes.GENERATOR_TYPE.addMethod("send", new PythonFunctionSignature( new MethodDescriptor(PythonGenerator.class.getMethod("send", PythonLikeObject.class)), BuiltinTypes.BASE_TYPE, BuiltinTypes.BASE_TYPE)); BuiltinTypes.GENERATOR_TYPE.addMethod("throw", new PythonFunctionSignature( new MethodDescriptor(PythonGenerator.class.getMethod("throwValue", Throwable.class)), BuiltinTypes.BASE_TYPE, PythonBaseException.BASE_EXCEPTION_TYPE)); BuiltinTypes.GENERATOR_TYPE.addMethod("close", new PythonFunctionSignature( new MethodDescriptor(PythonGenerator.class.getMethod("close")), BuiltinTypes.BASE_TYPE)); return BuiltinTypes.GENERATOR_TYPE; } public PythonLikeObject sentValue; public Throwable thrownValue; public PythonGenerator() { super(BuiltinTypes.GENERATOR_TYPE); sentValue = PythonNone.INSTANCE; thrownValue = null; } public PythonNone close() { this.thrownValue = new GeneratorExit(); next(); return PythonNone.INSTANCE; } public PythonLikeObject send(PythonLikeObject sentValue) { this.sentValue = sentValue; return next(); } public PythonLikeObject throwValue(Throwable thrownValue) { this.thrownValue = thrownValue; return next(); } public PythonGenerator asPythonIterator() { return this; } }
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/types/PythonJavaTypeMapping.java
package ai.timefold.jpyinterpreter.types; public interface PythonJavaTypeMapping<PythonType_, JavaType_> { PythonLikeType getPythonType(); Class<? extends JavaType_> getJavaType(); PythonType_ toPythonObject(JavaType_ javaObject); JavaType_ toJavaObject(PythonType_ pythonObject); }
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/types/PythonKnownFunctionType.java
package ai.timefold.jpyinterpreter.types; import java.util.List; import java.util.Optional; import java.util.stream.Collectors; import ai.timefold.jpyinterpreter.MethodDescriptor; import ai.timefold.jpyinterpreter.PythonFunctionSignature; public class PythonKnownFunctionType extends PythonLikeType { final List<PythonFunctionSignature> overloadFunctionSignatureList; public PythonKnownFunctionType(String methodName, List<PythonFunctionSignature> overloadFunctionSignatureList) { super("function-" + methodName, PythonKnownFunctionType.class, List.of(BuiltinTypes.FUNCTION_TYPE)); this.overloadFunctionSignatureList = overloadFunctionSignatureList; } public List<PythonFunctionSignature> getOverloadFunctionSignatureList() { return overloadFunctionSignatureList; } public boolean isStaticMethod() { return overloadFunctionSignatureList.get(0).getMethodDescriptor().getMethodType() == MethodDescriptor.MethodType.STATIC; } public boolean isClassMethod() { return overloadFunctionSignatureList.get(0).getMethodDescriptor().getMethodType() == MethodDescriptor.MethodType.CLASS; } @Override public PythonLikeType $getType() { return BuiltinTypes.BASE_TYPE; } @Override public PythonLikeType $getGenericType() { return BuiltinTypes.BASE_TYPE; } public Optional<PythonFunctionSignature> getDefaultFunctionSignature() { return overloadFunctionSignatureList.stream().findAny(); } public Optional<PythonFunctionSignature> getFunctionForParameters(PythonLikeType... parameters) { List<PythonFunctionSignature> matchingOverloads = overloadFunctionSignatureList.stream() .filter(signature -> signature.matchesParameters(parameters)) .collect(Collectors.toList()); if (matchingOverloads.isEmpty()) { return Optional.empty(); } PythonFunctionSignature best = matchingOverloads.get(0); for (PythonFunctionSignature signature : matchingOverloads) { if (signature.moreSpecificThan(best)) { best = signature; } } return Optional.of(best); } public Optional<PythonFunctionSignature> getFunctionForParameters(int positionalItemCount, List<String> keywordNames, List<PythonLikeType> callStackTypeList) { List<PythonFunctionSignature> matchingOverloads = overloadFunctionSignatureList.stream() .filter(signature -> signature.matchesParameters(positionalItemCount, keywordNames, callStackTypeList)) .collect(Collectors.toList()); if (matchingOverloads.isEmpty()) { return Optional.empty(); } PythonFunctionSignature best = matchingOverloads.get(0); for (PythonFunctionSignature signature : matchingOverloads) { if (signature.moreSpecificThan(best)) { best = signature; } } return Optional.of(best); } }
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/types/PythonLikeComparable.java
package ai.timefold.jpyinterpreter.types; import ai.timefold.jpyinterpreter.MethodDescriptor; import ai.timefold.jpyinterpreter.PythonBinaryOperator; import ai.timefold.jpyinterpreter.PythonFunctionSignature; import ai.timefold.jpyinterpreter.types.numeric.PythonBoolean; public interface PythonLikeComparable<T> extends Comparable<T> { static void setup(PythonLikeType type) { try { type.addBinaryMethod(PythonBinaryOperator.LESS_THAN, new PythonFunctionSignature( new MethodDescriptor(PythonLikeComparable.class.getMethod("lessThan", Object.class)), BuiltinTypes.BOOLEAN_TYPE, type)); type.addBinaryMethod(PythonBinaryOperator.GREATER_THAN, new PythonFunctionSignature( new MethodDescriptor(PythonLikeComparable.class.getMethod("greaterThan", Object.class)), BuiltinTypes.BOOLEAN_TYPE, type)); type.addBinaryMethod(PythonBinaryOperator.LESS_THAN_OR_EQUAL, new PythonFunctionSignature( new MethodDescriptor(PythonLikeComparable.class.getMethod("lessThanOrEqual", Object.class)), BuiltinTypes.BOOLEAN_TYPE, type)); type.addBinaryMethod(PythonBinaryOperator.GREATER_THAN_OR_EQUAL, new PythonFunctionSignature( new MethodDescriptor(PythonLikeComparable.class.getMethod("greaterThanOrEqual", Object.class)), BuiltinTypes.BOOLEAN_TYPE, type)); } catch (NoSuchMethodException e) { throw new IllegalStateException(e); } } default PythonBoolean lessThan(T other) { return PythonBoolean.valueOf(compareTo(other) < 0); } default PythonBoolean greaterThan(T other) { return PythonBoolean.valueOf(compareTo(other) > 0); } default PythonBoolean lessThanOrEqual(T other) { return PythonBoolean.valueOf(compareTo(other) <= 0); } default PythonBoolean greaterThanOrEqual(T other) { return PythonBoolean.valueOf(compareTo(other) >= 0); } }
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/types/PythonLikeFunction.java
package ai.timefold.jpyinterpreter.types; import java.util.List; import java.util.Map; import ai.timefold.jpyinterpreter.PythonLikeObject; public interface PythonLikeFunction extends PythonLikeObject { static PythonLikeType getStaticFunctionType() { return BuiltinTypes.STATIC_FUNCTION_TYPE; } static PythonLikeType getFunctionType() { return BuiltinTypes.FUNCTION_TYPE; } static PythonLikeType getClassFunctionType() { return BuiltinTypes.CLASS_FUNCTION_TYPE; } /** * Calls the function with positional arguments and named arguments. * * @param positionalArguments Positional arguments * @param namedArguments Named arguments * @param callerInstance The first argument passed to the caller, if any; null otherwise (used for super) * @return The function result */ PythonLikeObject $call(List<PythonLikeObject> positionalArguments, Map<PythonString, PythonLikeObject> namedArguments, PythonLikeObject callerInstance); @Override default PythonLikeObject $getAttributeOrNull(String attributeName) { return null; } @Override default void $setAttribute(String attributeName, PythonLikeObject value) { throw new UnsupportedOperationException(); } @Override default void $deleteAttribute(String attributeName) { throw new UnsupportedOperationException(); } @Override default PythonLikeType $getType() { return BuiltinTypes.FUNCTION_TYPE; } }
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/types/PythonLikeGenericType.java
package ai.timefold.jpyinterpreter.types; import java.util.Optional; import ai.timefold.jpyinterpreter.FieldDescriptor; import ai.timefold.jpyinterpreter.PythonClassTranslator; public class PythonLikeGenericType extends PythonLikeType { final PythonLikeType origin; public PythonLikeGenericType(PythonLikeType origin) { super(BuiltinTypes.TYPE_TYPE.getTypeName(), PythonLikeType.class); this.origin = origin; } public PythonLikeType getOrigin() { return origin; } @Override public Optional<FieldDescriptor> getInstanceFieldDescriptor(String fieldName) { Optional<PythonKnownFunctionType> maybeMethodType = getMethodType(fieldName); if (maybeMethodType.isEmpty()) { return BuiltinTypes.TYPE_TYPE.getInstanceFieldDescriptor(fieldName); } else { PythonKnownFunctionType knownFunctionType = maybeMethodType.get(); FieldDescriptor out = new FieldDescriptor(fieldName, PythonClassTranslator.getJavaMethodName(fieldName), origin.getJavaTypeInternalName(), knownFunctionType.getJavaTypeDescriptor(), knownFunctionType, false, false); return Optional.of(out); } } @Override public Optional<PythonKnownFunctionType> getMethodType(String methodName) { Optional<PythonKnownFunctionType> originKnownFunctionType = origin.getMethodType(methodName); if (originKnownFunctionType.isEmpty()) { return originKnownFunctionType; } PythonKnownFunctionType knownFunctionType = originKnownFunctionType.get(); if (knownFunctionType.isStaticMethod() || knownFunctionType.isClassMethod()) { return originKnownFunctionType; } else { return Optional.empty(); } } @Override public Optional<PythonClassTranslator.PythonMethodKind> getMethodKind(String methodName) { Optional<PythonClassTranslator.PythonMethodKind> originMethodKind = origin.getMethodKind(methodName); if (originMethodKind.isEmpty()) { return originMethodKind; } switch (originMethodKind.get()) { case STATIC_METHOD: case CLASS_METHOD: return originMethodKind; default: return Optional.empty(); } } @Override public String toString() { return "<class type[" + origin.getTypeName() + "]>"; } }
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/types/PythonLikeType.java
package ai.timefold.jpyinterpreter.types; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.Comparator; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Objects; import java.util.Optional; import java.util.Set; import java.util.function.Consumer; import java.util.stream.Stream; import ai.timefold.jpyinterpreter.FieldDescriptor; import ai.timefold.jpyinterpreter.PythonBinaryOperator; import ai.timefold.jpyinterpreter.PythonClassTranslator; import ai.timefold.jpyinterpreter.PythonFunctionSignature; import ai.timefold.jpyinterpreter.PythonLikeObject; import ai.timefold.jpyinterpreter.PythonOverloadImplementor; import ai.timefold.jpyinterpreter.PythonTernaryOperator; import ai.timefold.jpyinterpreter.PythonUnaryOperator; import ai.timefold.jpyinterpreter.builtins.TernaryDunderBuiltin; import ai.timefold.jpyinterpreter.types.collections.PythonLikeDict; import ai.timefold.jpyinterpreter.types.collections.PythonLikeTuple; import ai.timefold.jpyinterpreter.types.errors.AttributeError; import ai.timefold.jpyinterpreter.types.errors.TypeError; import ai.timefold.jpyinterpreter.types.errors.ValueError; import ai.timefold.jpyinterpreter.types.wrappers.JavaObjectWrapper; import org.objectweb.asm.Type; public class PythonLikeType implements PythonLikeObject, PythonLikeFunction { public final Map<String, PythonLikeObject> __dir__; private final String TYPE_NAME; private final String JAVA_TYPE_INTERNAL_NAME; private final List<PythonLikeType> PARENT_TYPES; public final List<PythonLikeType> MRO; private Class<?> javaObjectWrapperType = null; private final Map<String, PythonKnownFunctionType> functionNameToKnownFunctionType; private Optional<PythonKnownFunctionType> constructorKnownFunctionType; private final Map<String, FieldDescriptor> instanceFieldToFieldDescriptorMap; private PythonLikeFunction constructor; public PythonLikeType(String typeName, Class<? extends PythonLikeObject> javaClass) { this(typeName, javaClass, List.of(BuiltinTypes.BASE_TYPE)); } public PythonLikeType(String typeName, Class<? extends PythonLikeObject> javaClass, Class<?> javaObjectWrapperType) { this(typeName, javaClass, List.of(BuiltinTypes.BASE_TYPE)); this.javaObjectWrapperType = javaObjectWrapperType; } public PythonLikeType(String typeName, Class<? extends PythonLikeObject> javaClass, List<PythonLikeType> parents) { TYPE_NAME = typeName; JAVA_TYPE_INTERNAL_NAME = Type.getInternalName(javaClass); PARENT_TYPES = parents; constructor = (positional, keywords, callerInstance) -> { throw new UnsupportedOperationException("Cannot create instance of type (" + TYPE_NAME + ")."); }; __dir__ = new HashMap<>(); functionNameToKnownFunctionType = new HashMap<>(); constructorKnownFunctionType = Optional.empty(); instanceFieldToFieldDescriptorMap = new HashMap<>(); MRO = determineMRO(); } public PythonLikeType(String typeName, String javaTypeInternalName, List<PythonLikeType> parents) { TYPE_NAME = typeName; JAVA_TYPE_INTERNAL_NAME = javaTypeInternalName; PARENT_TYPES = parents; constructor = (positional, keywords, callerInstance) -> { throw new UnsupportedOperationException("Cannot create instance of type (" + TYPE_NAME + ")."); }; __dir__ = new HashMap<>(); functionNameToKnownFunctionType = new HashMap<>(); constructorKnownFunctionType = Optional.empty(); instanceFieldToFieldDescriptorMap = new HashMap<>(); MRO = determineMRO(); } public PythonLikeType(String typeName, Class<? extends PythonLikeObject> javaClass, Consumer<PythonLikeType> initializer) { this(typeName, javaClass, List.of(BuiltinTypes.BASE_TYPE)); initializer.accept(this); } private PythonLikeType(String typeName, String internalName) { TYPE_NAME = typeName; JAVA_TYPE_INTERNAL_NAME = internalName; PARENT_TYPES = new ArrayList<>(); constructor = (positional, keywords, callerInstance) -> { throw new UnsupportedOperationException("Cannot create instance of type (" + TYPE_NAME + ")."); }; __dir__ = new HashMap<>(); functionNameToKnownFunctionType = new HashMap<>(); constructorKnownFunctionType = Optional.empty(); instanceFieldToFieldDescriptorMap = new HashMap<>(); MRO = new ArrayList<>(); } public static PythonLikeType getTypeForNewClass(String typeName, String internalName) { var out = new PythonLikeType(typeName, internalName); out.__dir__.put("__class__", out); return out; } public void initializeNewType(List<PythonLikeType> superClassTypes) { PARENT_TYPES.addAll(superClassTypes); MRO.addAll(determineMRO()); } private List<PythonLikeType> determineMRO() { List<PythonLikeType> out = new ArrayList<>(); out.add(this); out.addAll(mergeMRO()); return out; } private List<PythonLikeType> mergeMRO() { List<PythonLikeType> out = new ArrayList<>(); List<List<PythonLikeType>> parentMROLists = new ArrayList<>(); for (PythonLikeType parent : PARENT_TYPES) { parentMROLists.add(new ArrayList<>(parent.MRO)); } parentMROLists.add(new ArrayList<>(PARENT_TYPES)); // to preserve local precedent order, add list of parents last while (!parentMROLists.stream().allMatch(List::isEmpty)) { boolean candidateFound = false; for (List<PythonLikeType> parentMRO : parentMROLists) { if (!parentMRO.isEmpty()) { PythonLikeType candidate = parentMRO.get(0); if (parentMROLists.stream().allMatch(mro -> mro.indexOf(candidate) < 1)) { out.add(candidate); parentMROLists.forEach(mro -> { if (!mro.isEmpty() && mro.get(0) == candidate) { mro.remove(0); } }); candidateFound = true; break; } } } if (!candidateFound) { throw new TypeError("Cannot calculate MRO; Cycle found"); } } return out; } public boolean isInstance(PythonLikeObject object) { PythonLikeType objectType = object.$getType(); return objectType.isSubclassOf(this); } public static PythonLikeType registerBaseType() { try { BuiltinTypes.BASE_TYPE.addBinaryMethod(PythonBinaryOperator.GET_ATTRIBUTE, PythonLikeObject.class.getMethod("$method$__getattribute__", PythonString.class)); BuiltinTypes.BASE_TYPE.addTernaryMethod(PythonTernaryOperator.SET_ATTRIBUTE, PythonLikeObject.class.getMethod("$method$__setattr__", PythonString.class, PythonLikeObject.class)); BuiltinTypes.BASE_TYPE.addBinaryMethod(PythonBinaryOperator.DELETE_ATTRIBUTE, PythonLikeObject.class.getMethod("$method$__delattr__", PythonString.class)); BuiltinTypes.BASE_TYPE.addBinaryMethod(PythonBinaryOperator.EQUAL, PythonLikeObject.class.getMethod("$method$__eq__", PythonLikeObject.class)); BuiltinTypes.BASE_TYPE.addBinaryMethod(PythonBinaryOperator.NOT_EQUAL, PythonLikeObject.class.getMethod("$method$__ne__", PythonLikeObject.class)); BuiltinTypes.BASE_TYPE.addUnaryMethod(PythonUnaryOperator.AS_STRING, PythonLikeObject.class.getMethod("$method$__str__")); BuiltinTypes.BASE_TYPE.addUnaryMethod(PythonUnaryOperator.REPRESENTATION, PythonLikeObject.class.getMethod("$method$__repr__")); BuiltinTypes.BASE_TYPE.addUnaryMethod(PythonUnaryOperator.HASH, PythonLikeObject.class.getMethod("$method$__hash__")); BuiltinTypes.BASE_TYPE.addBinaryMethod(PythonBinaryOperator.FORMAT, PythonLikeObject.class.getMethod("$method$__format__", PythonLikeObject.class)); BuiltinTypes.BASE_TYPE .setConstructor((vargs, kwargs, callerInstance) -> new AbstractPythonLikeObject(BuiltinTypes.BASE_TYPE) { }); PythonOverloadImplementor.createDispatchesFor(BuiltinTypes.BASE_TYPE); } catch (NoSuchMethodException e) { throw new IllegalStateException(e); } return BuiltinTypes.BASE_TYPE; } public Class<?> getJavaObjectWrapperType() { if (javaObjectWrapperType == null) { throw new IllegalStateException("Can only call this method on %s types." .formatted(JavaObjectWrapper.class.getSimpleName())); } return javaObjectWrapperType; } public static PythonLikeType registerTypeType() { BuiltinTypes.TYPE_TYPE.setConstructor((positional, keywords, callerInstance) -> { if (positional.size() == 1) { return positional.get(0).$getType(); } else if (positional.size() == 3) { var name = (PythonString) positional.get(0); var baseClasses = (PythonLikeTuple) positional.get(1); var dict = (PythonLikeDict<PythonLikeObject, PythonLikeObject>) positional.get(2); PythonLikeType out; if (baseClasses.isEmpty()) { out = new PythonLikeType(name.value, PythonLikeObject.class); } else { out = new PythonLikeType(name.value, PythonLikeObject.class, (List) baseClasses); } for (Map.Entry<PythonLikeObject, PythonLikeObject> entry : dict.entrySet()) { PythonString attributeName = (PythonString) entry.getKey(); out.$setAttribute(attributeName.value, entry.getValue()); } return out; } else { throw new ValueError("type takes 1 or 3 positional arguments, got " + positional.size()); } }); return BuiltinTypes.TYPE_TYPE; } @Override public PythonLikeObject $method$__getattribute__(PythonString pythonName) { String name = pythonName.value; PythonLikeObject typeResult = this.$getAttributeOrNull(name); if (typeResult != null) { PythonLikeObject maybeDescriptor = typeResult.$getAttributeOrNull(PythonTernaryOperator.GET.dunderMethod); if (maybeDescriptor == null) { maybeDescriptor = typeResult.$getType().$getAttributeOrNull(PythonTernaryOperator.GET.dunderMethod); } if (maybeDescriptor != null) { if (!(maybeDescriptor instanceof PythonLikeFunction)) { throw new UnsupportedOperationException("'" + maybeDescriptor.$getType() + "' is not callable"); } return TernaryDunderBuiltin.GET_DESCRIPTOR.invoke(typeResult, PythonNone.INSTANCE, this); } return typeResult; } throw new AttributeError("object '" + this + "' does not have attribute '" + name + "'"); } public void addMethod(String methodName, Method method) { addMethod(methodName, PythonFunctionSignature.forMethod(method)); } public void addUnaryMethod(PythonUnaryOperator operator, Method method) { addMethod(operator.getDunderMethod(), PythonFunctionSignature.forMethod(method)); } public void addBinaryMethod(PythonBinaryOperator operator, Method method) { addMethod(operator.getDunderMethod(), PythonFunctionSignature.forMethod(method)); if (operator.hasRightDunderMethod() && !operator.isComparisonMethod()) { addMethod(operator.getRightDunderMethod(), PythonFunctionSignature.forMethod(method)); } } public void addLeftBinaryMethod(PythonBinaryOperator operator, Method method) { addMethod(operator.getDunderMethod(), PythonFunctionSignature.forMethod(method)); } public void addRightBinaryMethod(PythonBinaryOperator operator, Method method) { addMethod(operator.getRightDunderMethod(), PythonFunctionSignature.forMethod(method)); } public void addTernaryMethod(PythonTernaryOperator operator, Method method) { addMethod(operator.getDunderMethod(), PythonFunctionSignature.forMethod(method)); } public void addUnaryMethod(PythonUnaryOperator operator, PythonFunctionSignature method) { addMethod(operator.getDunderMethod(), method); } public void addBinaryMethod(PythonBinaryOperator operator, PythonFunctionSignature method) { addMethod(operator.getDunderMethod(), method); if (operator.hasRightDunderMethod() && !operator.isComparisonMethod()) { addMethod(operator.getRightDunderMethod(), method); } } public void addLeftBinaryMethod(PythonBinaryOperator operator, PythonFunctionSignature method) { addMethod(operator.getDunderMethod(), method); } public void addRightBinaryMethod(PythonBinaryOperator operator, PythonFunctionSignature method) { addMethod(operator.getRightDunderMethod(), method); } public void addTernaryMethod(PythonTernaryOperator operator, PythonFunctionSignature method) { addMethod(operator.getDunderMethod(), method); } public void clearMethod(String methodName) { PythonKnownFunctionType knownFunctionType = functionNameToKnownFunctionType.computeIfAbsent(methodName, key -> new PythonKnownFunctionType(methodName, new ArrayList<>())); knownFunctionType.getOverloadFunctionSignatureList().clear(); } public void addMethod(String methodName, PythonFunctionSignature method) { PythonKnownFunctionType knownFunctionType = functionNameToKnownFunctionType.computeIfAbsent(methodName, key -> new PythonKnownFunctionType(methodName, new ArrayList<>())); knownFunctionType.getOverloadFunctionSignatureList().add(method); } public Set<String> getKnownMethodsDefinedByClass() { return functionNameToKnownFunctionType.keySet(); } public Set<String> getKnownMethods() { Set<String> out = new HashSet<>(); getAssignableTypesStream().forEach(type -> out.addAll(type.getKnownMethodsDefinedByClass())); return out; } public void setConstructor(PythonLikeFunction constructor) { this.constructor = constructor; } public void addConstructor(PythonFunctionSignature constructor) { if (constructorKnownFunctionType.isEmpty()) { constructorKnownFunctionType = Optional.of(new PythonKnownFunctionType("<init>", new ArrayList<>())); } constructorKnownFunctionType.get().getOverloadFunctionSignatureList().add(constructor); } public Optional<PythonKnownFunctionType> getMethodType(String methodName) { PythonKnownFunctionType out = new PythonKnownFunctionType(methodName, new ArrayList<>()); getAssignableTypesStream().forEach(type -> { PythonKnownFunctionType knownFunctionType = type.functionNameToKnownFunctionType.get(methodName); if (knownFunctionType != null) { out.getOverloadFunctionSignatureList().addAll(knownFunctionType.getOverloadFunctionSignatureList()); } }); if (out.getOverloadFunctionSignatureList().isEmpty()) { return Optional.empty(); } return Optional.of(out); } public Optional<PythonClassTranslator.PythonMethodKind> getMethodKind(String methodName) { PythonLikeObject maybeMethod = this.$getAttributeOrNull(methodName); if (maybeMethod != null) { PythonLikeType methodKind = maybeMethod.$getType(); if (methodKind == BuiltinTypes.FUNCTION_TYPE) { return Optional.of(PythonClassTranslator.PythonMethodKind.VIRTUAL_METHOD); } if (methodKind == BuiltinTypes.STATIC_FUNCTION_TYPE) { return Optional.of(PythonClassTranslator.PythonMethodKind.STATIC_METHOD); } if (methodKind == BuiltinTypes.CLASS_FUNCTION_TYPE) { return Optional.of(PythonClassTranslator.PythonMethodKind.CLASS_METHOD); } return Optional.empty(); } Optional<PythonKnownFunctionType> maybeKnownFunctionType = getMethodType(methodName); if (maybeKnownFunctionType.isPresent()) { PythonKnownFunctionType knownFunctionType = maybeKnownFunctionType.get(); switch (knownFunctionType.getOverloadFunctionSignatureList().get(0).getMethodDescriptor().getMethodType()) { case VIRTUAL: case INTERFACE: case CONSTRUCTOR: case STATIC_AS_VIRTUAL: return Optional.of(PythonClassTranslator.PythonMethodKind.VIRTUAL_METHOD); case STATIC: return Optional.of(PythonClassTranslator.PythonMethodKind.STATIC_METHOD); case CLASS: return Optional.of(PythonClassTranslator.PythonMethodKind.CLASS_METHOD); default: throw new IllegalStateException("Unhandled case " + knownFunctionType.getOverloadFunctionSignatureList() .get(0).getMethodDescriptor().getMethodType()); } } return Optional.empty(); } public Optional<PythonKnownFunctionType> getConstructorType() { return constructorKnownFunctionType; } public Optional<FieldDescriptor> getInstanceFieldDescriptor(String fieldName) { return getAssignableTypesStream().map(PythonLikeType::getInstanceFieldToFieldDescriptorMap) .filter(map -> map.containsKey(fieldName)) .map(map -> map.get(fieldName)) .findAny(); } public void addInstanceField(FieldDescriptor fieldDescriptor) { Optional<FieldDescriptor> maybeExistingField = getInstanceFieldDescriptor(fieldDescriptor.pythonFieldName()); if (maybeExistingField.isPresent()) { PythonLikeType existingFieldType = maybeExistingField.get().fieldPythonLikeType(); if (!fieldDescriptor.fieldPythonLikeType().isSubclassOf(existingFieldType)) { throw new IllegalStateException("Field (" + fieldDescriptor.pythonFieldName() + ") already exist with type (" + existingFieldType + ") which is not assignable from (" + fieldDescriptor.fieldPythonLikeType() + ")."); } } else { instanceFieldToFieldDescriptorMap.put(fieldDescriptor.pythonFieldName(), fieldDescriptor); } } private Map<String, FieldDescriptor> getInstanceFieldToFieldDescriptorMap() { return instanceFieldToFieldDescriptorMap; } public PythonLikeType unifyWith(PythonLikeType other) { Optional<PythonLikeType> maybeCommonType = other.getAssignableTypesStream().filter(otherType -> { if (otherType.isSubclassOf(this)) { return true; } return this.isSubclassOf(otherType); }).findAny(); if (maybeCommonType.isPresent() && maybeCommonType.get() != BuiltinTypes.BASE_TYPE) { PythonLikeType commonType = maybeCommonType.get(); if (commonType.isSubclassOf(this)) { return this; } else { return commonType; } } for (PythonLikeType parent : getParentList()) { PythonLikeType parentUnification = parent.unifyWith(other); if (parentUnification != BuiltinTypes.BASE_TYPE) { return parentUnification; } } return BuiltinTypes.BASE_TYPE; } public boolean isSubclassOf(PythonLikeType type) { return isSubclassOf(type, new HashSet<>()); } private Stream<PythonLikeType> getAssignableTypesStream() { return Stream.concat( Stream.of(this), getParentList().stream() .flatMap(PythonLikeType::getAssignableTypesStream)) .distinct(); } private boolean isSubclassOf(PythonLikeType type, Set<PythonLikeType> visited) { if (visited.contains(this)) { return false; } if (this == type) { return true; } visited.add(this); for (PythonLikeType parent : PARENT_TYPES) { if (parent.isSubclassOf(type, visited)) { return true; } } return false; } public int getDepth() { if (PARENT_TYPES.size() == 0) { return 0; } else { return 1 + PARENT_TYPES.stream().map(PythonLikeType::getDepth).max(Comparator.naturalOrder()).get(); } } @Override public PythonLikeObject $call(List<PythonLikeObject> positionalArguments, Map<PythonString, PythonLikeObject> namedArguments, PythonLikeObject callerInstance) { return constructor.$call(positionalArguments, namedArguments, null); } public PythonLikeObject loadMethod(String methodName) { PythonLikeObject out = this.$getAttributeOrNull(methodName); if (out == null) { return null; } if (out.$getType() == BuiltinTypes.FUNCTION_TYPE) { return out; } return null; //if (out.$getType() == PythonLikeFunction.getClassFunctionType()) { // return FunctionBuiltinOperations.bindFunctionToType((PythonLikeFunction) out, null, this); //} else { // return null; //} } public PythonLikeType getDefiningTypeOrNull(String attributeName) { if (__dir__.containsKey(attributeName) && (this == BuiltinTypes.BASE_TYPE || (__dir__.get(attributeName).getClass() != BuiltinTypes.BASE_TYPE.__dir__.get(attributeName) .getClass()))) { return this; } for (PythonLikeType parent : PARENT_TYPES) { PythonLikeType out = parent.getDefiningTypeOrNull(attributeName); if (out != null) { return out; } } return null; } public PythonLikeObject $getAttributeOrNull(String attributeName) { PythonLikeObject out = __dir__.get(attributeName); if (out == null) { for (PythonLikeType type : PARENT_TYPES) { out = type.$getAttributeOrNull(attributeName); if (out != null) { return out; } } return null; } else { return out; } } @Override public void $setAttribute(String attributeName, PythonLikeObject value) { __dir__.put(attributeName, value); } @Override public void $deleteAttribute(String attributeName) { // TODO: Descriptors: https://docs.python.org/3/howto/descriptor.html __dir__.remove(attributeName); } @Override public PythonLikeType $getType() { return BuiltinTypes.TYPE_TYPE; } @Override public PythonLikeType $getGenericType() { return new PythonLikeGenericType(this); } public String getTypeName() { return TYPE_NAME; } public String getJavaTypeInternalName() { return JAVA_TYPE_INTERNAL_NAME; } public String getJavaTypeDescriptor() { return "L" + JAVA_TYPE_INTERNAL_NAME + ";"; } /** * Return the Java class corresponding to this type, if it exists. Throws {@link ClassNotFoundException} otherwise. */ public Class<?> getJavaClass() throws ClassNotFoundException { return Class.forName(JAVA_TYPE_INTERNAL_NAME.replace('/', '.'), true, BuiltinTypes.asmClassLoader); } /** * Return the Java class corresponding to this type, if it exists. Returns {@code defaultValue} otherwise. * * @param defaultValue the value to return */ public Class<?> getJavaClassOrDefault(Class<?> defaultValue) { try { return getJavaClass(); } catch (ClassNotFoundException e) { return defaultValue; } } public List<PythonLikeType> getParentList() { return PARENT_TYPES; } @Override public PythonString $method$__str__() { return PythonString.valueOf(toString()); } @Override public String toString() { return "<class " + TYPE_NAME + ">"; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (!(o instanceof PythonLikeType that)) { return false; } return Objects.equals(JAVA_TYPE_INTERNAL_NAME, that.JAVA_TYPE_INTERNAL_NAME); } @Override public int hashCode() { return JAVA_TYPE_INTERNAL_NAME.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/types/PythonModule.java
package ai.timefold.jpyinterpreter.types; import java.util.Map; import ai.timefold.jpyinterpreter.CPythonBackedPythonInterpreter; import ai.timefold.jpyinterpreter.PythonLikeObject; import ai.timefold.jpyinterpreter.types.wrappers.OpaquePythonReference; public class PythonModule extends AbstractPythonLikeObject { public static PythonLikeType MODULE_TYPE = BuiltinTypes.MODULE_TYPE; public static PythonLikeType $TYPE = MODULE_TYPE; private OpaquePythonReference pythonReference; private Map<Number, PythonLikeObject> referenceMap; public PythonModule(Map<Number, PythonLikeObject> referenceMap) { super(MODULE_TYPE); this.referenceMap = referenceMap; } public void addItem(String itemName, PythonLikeObject itemValue) { $setAttribute(itemName, itemValue); } public OpaquePythonReference getPythonReference() { return pythonReference; } public void setPythonReference(OpaquePythonReference pythonReference) { this.pythonReference = pythonReference; } @Override public PythonLikeObject $getAttributeOrNull(String attributeName) { PythonLikeObject result = super.$getAttributeOrNull(attributeName); if (result == null) { PythonLikeObject actual = CPythonBackedPythonInterpreter.lookupAttributeOnPythonReference(pythonReference, attributeName, referenceMap); $setAttribute(attributeName, actual); return actual; } return 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/types/PythonNone.java
package ai.timefold.jpyinterpreter.types; import ai.timefold.jpyinterpreter.PythonBinaryOperator; import ai.timefold.jpyinterpreter.PythonLikeObject; import ai.timefold.jpyinterpreter.PythonOverloadImplementor; import ai.timefold.jpyinterpreter.PythonUnaryOperator; import ai.timefold.jpyinterpreter.builtins.GlobalBuiltins; import ai.timefold.jpyinterpreter.types.numeric.PythonBoolean; import ai.timefold.solver.core.impl.domain.solution.cloner.PlanningImmutable; public class PythonNone extends AbstractPythonLikeObject implements PlanningImmutable { public static final PythonNone INSTANCE; static { PythonOverloadImplementor.deferDispatchesFor(PythonNone::registerMethods); INSTANCE = new PythonNone(); } private static PythonLikeType registerMethods() throws NoSuchMethodException { BuiltinTypes.NONE_TYPE.addUnaryMethod(PythonUnaryOperator.AS_BOOLEAN, PythonNone.class.getMethod("asBool")); BuiltinTypes.NONE_TYPE.addBinaryMethod(PythonBinaryOperator.EQUAL, PythonNone.class.getMethod("equalsObject", PythonLikeObject.class)); BuiltinTypes.NONE_TYPE.addBinaryMethod(PythonBinaryOperator.NOT_EQUAL, PythonNone.class.getMethod("notEqualsObject", PythonLikeObject.class)); GlobalBuiltins.addBuiltinConstant("None", INSTANCE); return BuiltinTypes.NONE_TYPE; } private PythonNone() { super(BuiltinTypes.NONE_TYPE); } @Override public PythonString $method$__str__() { return PythonString.valueOf(toString()); } @Override public String toString() { return "None"; } public PythonBoolean asBool() { return PythonBoolean.FALSE; } public PythonBoolean equalsObject(PythonLikeObject other) { return PythonBoolean.valueOf(this == other); } public PythonBoolean notEqualsObject(PythonLikeObject other) { return PythonBoolean.valueOf(this != other); } }
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/types/PythonRange.java
package ai.timefold.jpyinterpreter.types; import java.lang.reflect.Array; import java.math.BigInteger; import java.util.Collection; import java.util.Iterator; import java.util.List; import java.util.ListIterator; import java.util.Map; import ai.timefold.jpyinterpreter.PythonBinaryOperator; import ai.timefold.jpyinterpreter.PythonLikeObject; import ai.timefold.jpyinterpreter.PythonOverloadImplementor; import ai.timefold.jpyinterpreter.PythonUnaryOperator; import ai.timefold.jpyinterpreter.builtins.UnaryDunderBuiltin; import ai.timefold.jpyinterpreter.types.collections.DelegatePythonIterator; import ai.timefold.jpyinterpreter.types.errors.ValueError; import ai.timefold.jpyinterpreter.types.numeric.PythonBoolean; import ai.timefold.jpyinterpreter.types.numeric.PythonInteger; public class PythonRange extends AbstractPythonLikeObject implements List<PythonInteger> { public static PythonLikeType $TYPE = BuiltinTypes.RANGE_TYPE; public final PythonInteger start; public final PythonInteger stop; public final PythonInteger step; static { PythonOverloadImplementor.deferDispatchesFor(PythonRange::registerMethods); } private static PythonLikeType registerMethods() throws NoSuchMethodException { // Constructor BuiltinTypes.RANGE_TYPE.setConstructor(((positionalArguments, namedArguments, callerInstance) -> { PythonLikeObject start; PythonLikeObject stop; PythonLikeObject step; namedArguments = (namedArguments != null) ? namedArguments : Map.of(); if (positionalArguments.size() == 3) { start = positionalArguments.get(0); stop = positionalArguments.get(1); step = positionalArguments.get(2); } else if (positionalArguments.size() == 2) { start = positionalArguments.get(0); stop = positionalArguments.get(1); step = namedArguments.getOrDefault(PythonString.valueOf("step"), PythonInteger.valueOf(1)); } else if (positionalArguments.size() == 1 && namedArguments.containsKey(PythonString.valueOf("stop"))) { start = positionalArguments.get(0); stop = namedArguments.get(PythonString.valueOf("stop")); step = namedArguments.getOrDefault(PythonString.valueOf("step"), PythonInteger.valueOf(1)); } else if (positionalArguments.size() == 1) { stop = positionalArguments.get(0); start = PythonInteger.valueOf(0); step = namedArguments.getOrDefault(PythonString.valueOf("step"), PythonInteger.valueOf(1)); } else if (positionalArguments.isEmpty()) { start = namedArguments.getOrDefault(PythonString.valueOf("start"), PythonInteger.valueOf(0)); stop = namedArguments.get(PythonString.valueOf("stop")); step = namedArguments.getOrDefault(PythonString.valueOf("step"), PythonInteger.valueOf(1)); } else { throw new ValueError("range expects 1 to 3 arguments, got " + positionalArguments.size()); } PythonInteger intStart, intStop, intStep; if (start instanceof PythonInteger) { intStart = (PythonInteger) start; } else { intStart = (PythonInteger) UnaryDunderBuiltin.INDEX.invoke(start); } if (stop instanceof PythonInteger) { intStop = (PythonInteger) stop; } else { intStop = (PythonInteger) UnaryDunderBuiltin.INDEX.invoke(stop); } if (step instanceof PythonInteger) { intStep = (PythonInteger) step; } else { intStep = (PythonInteger) UnaryDunderBuiltin.INDEX.invoke(step); } return new PythonRange(intStart, intStop, intStep); })); // Unary methods BuiltinTypes.RANGE_TYPE.addUnaryMethod(PythonUnaryOperator.LENGTH, PythonRange.class.getMethod("getLength")); BuiltinTypes.RANGE_TYPE.addUnaryMethod(PythonUnaryOperator.ITERATOR, PythonRange.class.getMethod("getPythonIterator")); // Binary methods BuiltinTypes.RANGE_TYPE.addBinaryMethod(PythonBinaryOperator.GET_ITEM, PythonRange.class.getMethod("getItem", PythonInteger.class)); BuiltinTypes.RANGE_TYPE.addBinaryMethod(PythonBinaryOperator.CONTAINS, PythonRange.class.getMethod("isObjectInRange", PythonLikeObject.class)); return BuiltinTypes.RANGE_TYPE; } public PythonRange(PythonInteger start, PythonInteger stop, PythonInteger step) { super(BuiltinTypes.RANGE_TYPE); this.start = start; this.stop = stop; this.step = step; $setAttribute("start", start); $setAttribute("stop", stop); $setAttribute("step", step); } @Override public int size() { // Need to use ceil division BigInteger[] divideAndRemainder = stop.value.subtract(start.value).divideAndRemainder(step.value); if (divideAndRemainder[1].equals(BigInteger.ZERO)) { return divideAndRemainder[0].intValueExact(); } else { return divideAndRemainder[0].intValueExact() + 1; } } public PythonInteger getLength() { return PythonInteger.valueOf(size()); } @Override public boolean isEmpty() { return size() == 0; } @Override public boolean contains(Object o) { if (!(o instanceof PythonInteger)) { return false; } PythonInteger query = (PythonInteger) o; if (step.value.compareTo(BigInteger.ZERO) < 0) { if (query.value.compareTo(stop.value) < 0) { return false; } } else { if (query.value.compareTo(stop.value) > 0) { return false; } } BigInteger relativeToStart = query.value.subtract(start.value); BigInteger[] divisionAndRemainder = relativeToStart.divideAndRemainder(step.value); if (!divisionAndRemainder[1].equals(BigInteger.ZERO)) { return false; // cannot be represented as start + step * i } return divisionAndRemainder[0].compareTo(BigInteger.ZERO) >= 0; // return true iff i is not negative } public PythonBoolean isObjectInRange(PythonLikeObject query) { return PythonBoolean.valueOf(contains(query)); } @Override public Iterator<PythonInteger> iterator() { return new RangeIterator(start, stop, step, start, 0); } public DelegatePythonIterator getPythonIterator() { return new DelegatePythonIterator(iterator()); } @Override public Object[] toArray() { PythonInteger[] out = new PythonInteger[size()]; for (int i = 0; i < out.length; i++) { out[i] = get(i); } return out; } @Override public <T> T[] toArray(T[] ts) { T[] out = ts; if (ts.length < size()) { out = (T[]) Array.newInstance(ts.getClass().getComponentType(), size()); } for (int i = 0; i < out.length; i++) { out[i] = (T) get(i); } if (out.length > size()) { out[size()] = null; } return out; } @Override public boolean containsAll(Collection<?> collection) { for (Object o : collection) { if (!contains(o)) { return false; } } return true; } @Override public PythonInteger get(int i) { if (i < 0) { throw new IndexOutOfBoundsException(); } PythonInteger out = start.add(step.multiply(PythonInteger.valueOf(i))); if (!contains(out)) { throw new IndexOutOfBoundsException(); } return out; } public PythonInteger getItem(PythonInteger index) { if (index.value.compareTo(BigInteger.ZERO) < 0) { throw new IndexOutOfBoundsException(); } PythonInteger out = start.add(step.multiply(index)); if (!contains(out)) { throw new IndexOutOfBoundsException(); } return out; } @Override public int indexOf(Object o) { if (!contains(o)) { return -1; } PythonInteger query = (PythonInteger) o; BigInteger relativeToStart = query.value.subtract(start.value); return relativeToStart.divide(step.value).intValueExact(); } @Override public int lastIndexOf(Object o) { return indexOf(o); } @Override public ListIterator<PythonInteger> listIterator() { return new RangeIterator(start, stop, step, start, 0); } @Override public ListIterator<PythonInteger> listIterator(int i) { return new RangeIterator(get(i), stop, step, get(i), i); } @Override public List<PythonInteger> subList(int startIndexInclusive, int endIndexExclusive) { return new PythonRange(get(startIndexInclusive), get(endIndexExclusive), step); } @Override public boolean addAll(Collection<? extends PythonInteger> collection) { throw new UnsupportedOperationException("Cannot modify range"); } @Override public boolean addAll(int i, Collection<? extends PythonInteger> collection) { throw new UnsupportedOperationException("Cannot modify range"); } @Override public boolean removeAll(Collection<?> collection) { throw new UnsupportedOperationException("Cannot modify range"); } @Override public boolean retainAll(Collection<?> collection) { throw new UnsupportedOperationException("Cannot modify range"); } @Override public void clear() { throw new UnsupportedOperationException("Cannot modify range"); } @Override public PythonInteger set(int i, PythonInteger pythonInteger) { throw new UnsupportedOperationException("Cannot modify range"); } @Override public void add(int i, PythonInteger pythonInteger) { throw new UnsupportedOperationException("Cannot modify range"); } @Override public PythonInteger remove(int i) { throw new UnsupportedOperationException("Cannot modify range"); } @Override public boolean add(PythonInteger pythonInteger) { throw new UnsupportedOperationException("Cannot modify range"); } @Override public boolean remove(Object o) { throw new UnsupportedOperationException("Cannot modify range"); } public static class RangeIterator implements ListIterator<PythonInteger> { final PythonInteger startValue; final PythonInteger stopValue; final PythonInteger step; final int startOffset; PythonInteger currentValue; public RangeIterator(PythonInteger startValue, PythonInteger stopValue, PythonInteger step, PythonInteger currentValue, int startOffset) { this.startValue = startValue; this.stopValue = stopValue; this.step = step; this.currentValue = currentValue; this.startOffset = startOffset; } @Override public boolean hasNext() { if (step.value.compareTo(BigInteger.ZERO) < 0) { return currentValue.compareTo(stopValue) > 0; } else { return currentValue.compareTo(stopValue) < 0; } } @Override public PythonInteger next() { PythonInteger out = currentValue; currentValue = currentValue.add(step); return out; } @Override public boolean hasPrevious() { if (step.value.compareTo(BigInteger.ZERO) < 0) { return currentValue.compareTo(startValue) < 0; } else { return currentValue.compareTo(startValue) > 0; } } @Override public PythonInteger previous() { PythonInteger out = currentValue; currentValue = currentValue.subtract(step); return out; } @Override public int nextIndex() { return currentValue.value.divide(step.value).intValueExact() + startOffset + 1; } @Override public int previousIndex() { return currentValue.value.divide(step.value).intValueExact() + startOffset - 1; } @Override public void remove() { throw new UnsupportedOperationException("Cannot modify range"); } @Override public void set(PythonInteger pythonInteger) { throw new UnsupportedOperationException("Cannot modify range"); } @Override public void add(PythonInteger pythonInteger) { throw new UnsupportedOperationException("Cannot modify range"); } } }
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/types/PythonSlice.java
package ai.timefold.jpyinterpreter.types; import java.util.Map; import java.util.Objects; import ai.timefold.jpyinterpreter.PythonBinaryOperator; import ai.timefold.jpyinterpreter.PythonLikeObject; import ai.timefold.jpyinterpreter.PythonOverloadImplementor; import ai.timefold.jpyinterpreter.PythonUnaryOperator; import ai.timefold.jpyinterpreter.builtins.UnaryDunderBuiltin; import ai.timefold.jpyinterpreter.types.collections.PythonLikeTuple; import ai.timefold.jpyinterpreter.types.errors.ValueError; import ai.timefold.jpyinterpreter.types.numeric.PythonBoolean; import ai.timefold.jpyinterpreter.types.numeric.PythonInteger; public class PythonSlice extends AbstractPythonLikeObject { public static PythonLikeType SLICE_TYPE = new PythonLikeType("slice", PythonSlice.class); public static PythonLikeType $TYPE = SLICE_TYPE; public final PythonLikeObject start; public final PythonLikeObject stop; public final PythonLikeObject step; static { PythonOverloadImplementor.deferDispatchesFor(PythonSlice::registerMethods); } private static PythonLikeType registerMethods() throws NoSuchMethodException { // Constructor SLICE_TYPE.setConstructor(((positionalArguments, namedArguments, callerInstance) -> { PythonLikeObject start; PythonLikeObject stop; PythonLikeObject step; namedArguments = (namedArguments != null) ? namedArguments : Map.of(); if (positionalArguments.size() == 3) { start = positionalArguments.get(0); stop = positionalArguments.get(1); step = positionalArguments.get(2); } else if (positionalArguments.size() == 2) { start = positionalArguments.get(0); stop = positionalArguments.get(1); step = namedArguments.getOrDefault(PythonString.valueOf("step"), PythonNone.INSTANCE); } else if (positionalArguments.size() == 1 && namedArguments.containsKey(PythonString.valueOf("stop"))) { start = positionalArguments.get(0); stop = namedArguments.getOrDefault(PythonString.valueOf("stop"), PythonNone.INSTANCE); step = namedArguments.getOrDefault(PythonString.valueOf("step"), PythonNone.INSTANCE); } else if (positionalArguments.size() == 1) { stop = positionalArguments.get(0); start = PythonInteger.valueOf(0); step = namedArguments.getOrDefault(PythonString.valueOf("step"), PythonNone.INSTANCE); } else if (positionalArguments.isEmpty()) { start = namedArguments.getOrDefault(PythonString.valueOf("start"), PythonInteger.valueOf(0)); stop = namedArguments.getOrDefault(PythonString.valueOf("stop"), PythonNone.INSTANCE); step = namedArguments.getOrDefault(PythonString.valueOf("step"), PythonNone.INSTANCE); } else { throw new ValueError("slice expects 1 to 3 arguments, got " + positionalArguments.size()); } return new PythonSlice(start, stop, step); })); // Unary SLICE_TYPE.addUnaryMethod(PythonUnaryOperator.HASH, PythonSlice.class.getMethod("pythonHash")); // Binary SLICE_TYPE.addBinaryMethod(PythonBinaryOperator.EQUAL, PythonSlice.class.getMethod("pythonEquals", PythonSlice.class)); // Other methods SLICE_TYPE.addMethod("indices", PythonSlice.class.getMethod("indices", PythonInteger.class)); return SLICE_TYPE; } public PythonSlice(PythonLikeObject start, PythonLikeObject stop, PythonLikeObject step) { super(SLICE_TYPE); this.start = start; this.stop = stop; this.step = step; $setAttribute("start", (start != null) ? start : PythonNone.INSTANCE); $setAttribute("stop", (stop != null) ? stop : PythonNone.INSTANCE); $setAttribute("step", (step != null) ? step : PythonNone.INSTANCE); } /** * Convert index into a index for a sequence of length {@code length}. May be outside the range * [0, length - 1]. Use for indexing into a sequence. * * @param index The given index * @param length The length * @return index, if index in [0, length -1]; length - index, if index &lt; 0. */ public static int asIntIndexForLength(PythonInteger index, int length) { int indexAsInt = index.value.intValueExact(); if (indexAsInt < 0) { return length + indexAsInt; } else { return indexAsInt; } } /** * Convert index into a VALID start index for a sequence of length {@code length}. bounding it to the * range [0, length - 1]. Use for sequence operations that need to search an portion of a sequence. * * @param index The given index * @param length The length * @return index, if index in [0, length -1]; length - index, if index &lt; 0 and -index &le; length; * otherwise 0 (if the index represent a position before 0) or length - 1 (if the index represent a * position after the sequence). */ public static int asValidStartIntIndexForLength(PythonInteger index, int length) { int indexAsInt = index.value.intValueExact(); if (indexAsInt < 0) { return Math.max(0, Math.min(length - 1, length + indexAsInt)); } else { return Math.max(0, Math.min(length - 1, indexAsInt)); } } /** * Convert index into a VALID end index for a sequence of length {@code length}. bounding it to the * range [0, length]. Use for sequence operations that need to search an portion of a sequence. * * @param index The given index * @param length The length * @return index, if index in [0, length]; length - index, if index &lt; 0 and -index &le; length + 1; * otherwise 0 (if the index represent a position before 0) or length (if the index represent a * position after the sequence). */ public static int asValidEndIntIndexForLength(PythonInteger index, int length) { int indexAsInt = index.value.intValueExact(); if (indexAsInt < 0) { return Math.max(0, Math.min(length, length + indexAsInt)); } else { return Math.max(0, Math.min(length, indexAsInt)); } } private record SliceIndices(int start, int stop, int strideLength) { } private SliceIndices getSliceIndices(int length) { return new SliceIndices(getStartIndex(length), getStopIndex(length), getStrideLength()); } private SliceIndices getSliceIndices(PythonInteger length) { return getSliceIndices(length.getValue().intValue()); } public PythonLikeTuple indices(PythonInteger sequenceLength) { var sliceIndices = getSliceIndices(sequenceLength); return PythonLikeTuple.fromItems(PythonInteger.valueOf(sliceIndices.start), PythonInteger.valueOf(sliceIndices.start), PythonInteger.valueOf(sliceIndices.strideLength)); } public int getStartIndex(int length) { int startIndex; boolean isReversed = getStrideLength() < 0; if (start instanceof PythonInteger) { startIndex = ((PythonInteger) start).value.intValueExact(); } else if (start == PythonNone.INSTANCE) { startIndex = isReversed ? length - 1 : 0; } else { startIndex = ((PythonInteger) UnaryDunderBuiltin.INDEX.invoke(start)).value.intValueExact(); } if (startIndex < 0) { startIndex = length + startIndex; } if (!isReversed && startIndex > length) { startIndex = length; } else if (isReversed && startIndex > length - 1) { startIndex = length - 1; } return startIndex; } public int getStopIndex(int length) { int stopIndex; boolean isReversed = getStrideLength() < 0; if (stop instanceof PythonInteger) { stopIndex = ((PythonInteger) stop).value.intValueExact(); } else if (stop == PythonNone.INSTANCE) { stopIndex = isReversed ? -length - 1 : length; // use -length - 1 so length - stopIndex = -1 } else { stopIndex = ((PythonInteger) UnaryDunderBuiltin.INDEX.invoke(stop)).value.intValueExact(); } if (stopIndex < 0) { stopIndex = length + stopIndex; } if (!isReversed && stopIndex > length) { stopIndex = length; } else if (isReversed && stopIndex > length - 1) { stopIndex = length - 1; } return stopIndex; } public int getStrideLength() { PythonInteger strideLength; if (step instanceof PythonInteger) { strideLength = (PythonInteger) step; } else if (step != null && step != PythonNone.INSTANCE) { strideLength = (PythonInteger) UnaryDunderBuiltin.INDEX.invoke(step); } else { strideLength = PythonInteger.ONE; } int out = strideLength.value.intValueExact(); if (out == 0) { throw new ValueError("stride length cannot be zero"); } return out; } public void iterate(int length, SliceConsumer consumer) { var sliceIndices = getSliceIndices(length); int step = 0; if (sliceIndices.strideLength < 0) { for (int i = sliceIndices.start; i > sliceIndices.stop; i += sliceIndices.strideLength) { consumer.accept(i, step); step++; } } else { for (int i = sliceIndices.start; i < sliceIndices.stop; i += sliceIndices.strideLength) { consumer.accept(i, step); step++; } } } private boolean isReversed() { return getStrideLength() < 0; } public int getSliceSize(int length) { var sliceIndices = getSliceIndices(length); int span = sliceIndices.stop - sliceIndices.start; int strideLength = sliceIndices.strideLength; // ceil division return span / strideLength + (span % strideLength == 0 ? 0 : 1); } public PythonBoolean pythonEquals(PythonSlice other) { return PythonBoolean.valueOf(this.equals(other)); } public PythonInteger pythonHash() { return PythonInteger.valueOf(hashCode()); } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } PythonSlice that = (PythonSlice) o; return Objects.equals(start, that.start) && Objects.equals(stop, that.stop) && Objects.equals(step, that.step); } @Override public int hashCode() { return Objects.hash(start, stop, step); } @Override public PythonInteger $method$__hash__() { return PythonInteger.valueOf(hashCode()); } public interface SliceConsumer { void accept(int index, int step); } }
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/types/PythonString.java
package ai.timefold.jpyinterpreter.types; import java.nio.ByteBuffer; import java.nio.CharBuffer; import java.nio.charset.CharacterCodingException; import java.nio.charset.Charset; import java.nio.charset.CodingErrorAction; import java.nio.charset.StandardCharsets; import java.util.Arrays; import java.util.Collections; import java.util.List; import java.util.Map; import java.util.function.IntPredicate; import java.util.function.IntUnaryOperator; import java.util.regex.Matcher; import java.util.regex.Pattern; import java.util.stream.Collectors; import java.util.stream.IntStream; import ai.timefold.jpyinterpreter.PythonBinaryOperator; import ai.timefold.jpyinterpreter.PythonLikeObject; import ai.timefold.jpyinterpreter.PythonOverloadImplementor; import ai.timefold.jpyinterpreter.PythonUnaryOperator; import ai.timefold.jpyinterpreter.builtins.BinaryDunderBuiltin; import ai.timefold.jpyinterpreter.builtins.UnaryDunderBuiltin; 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.PythonLikeList; import ai.timefold.jpyinterpreter.types.collections.PythonLikeTuple; import ai.timefold.jpyinterpreter.types.errors.TypeError; import ai.timefold.jpyinterpreter.types.errors.ValueError; import ai.timefold.jpyinterpreter.types.errors.lookup.IndexError; import ai.timefold.jpyinterpreter.types.errors.lookup.LookupError; import ai.timefold.jpyinterpreter.types.errors.unicode.UnicodeDecodeError; import ai.timefold.jpyinterpreter.types.errors.unicode.UnicodeEncodeError; import ai.timefold.jpyinterpreter.types.numeric.PythonBoolean; import ai.timefold.jpyinterpreter.types.numeric.PythonInteger; import ai.timefold.jpyinterpreter.util.DefaultFormatSpec; import ai.timefold.jpyinterpreter.util.StringFormatter; import ai.timefold.jpyinterpreter.util.arguments.ArgumentSpec; import ai.timefold.solver.core.impl.domain.solution.cloner.PlanningImmutable; public class PythonString extends AbstractPythonLikeObject implements PythonLikeComparable<PythonString>, PlanningImmutable { public final String value; public final static PythonString EMPTY = new PythonString(""); static { PythonOverloadImplementor.deferDispatchesFor(PythonString::registerMethods); } private static PythonLikeType registerMethods() throws NoSuchMethodException { PythonLikeComparable.setup(BuiltinTypes.STRING_TYPE); BuiltinTypes.STRING_TYPE.setConstructor((positionalArguments, namedArguments, callerInstance) -> { if (positionalArguments.size() == 1) { // TODO: Named arguments return UnaryDunderBuiltin.STR.invoke(positionalArguments.get(0)); } else if (positionalArguments.size() == 2) { if (!(positionalArguments.get(0) instanceof PythonBytes) || !(positionalArguments.get(1) instanceof PythonString)) { throw new TypeError(); // TODO: Better error message } return ((PythonBytes) positionalArguments.get(0)).decode((PythonString) positionalArguments.get(1)); } else if (positionalArguments.size() == 3) { if (!(positionalArguments.get(0) instanceof PythonBytes) || !(positionalArguments.get(1) instanceof PythonString) || !(positionalArguments.get(2) instanceof PythonString)) { throw new TypeError(); // TODO: Better error message } return ((PythonBytes) positionalArguments.get(0)).decode((PythonString) positionalArguments.get(1), (PythonString) positionalArguments.get(2)); } else { throw new ValueError("str expects 1 or 3 arguments, got " + positionalArguments.size()); } }); // Unary BuiltinTypes.STRING_TYPE.addUnaryMethod(PythonUnaryOperator.REPRESENTATION, PythonString.class.getMethod("repr")); BuiltinTypes.STRING_TYPE.addUnaryMethod(PythonUnaryOperator.AS_STRING, PythonString.class.getMethod("asString")); BuiltinTypes.STRING_TYPE.addUnaryMethod(PythonUnaryOperator.ITERATOR, PythonString.class.getMethod("getIterator")); BuiltinTypes.STRING_TYPE.addUnaryMethod(PythonUnaryOperator.LENGTH, PythonString.class.getMethod("getLength")); // Binary BuiltinTypes.STRING_TYPE.addBinaryMethod(PythonBinaryOperator.GET_ITEM, PythonString.class.getMethod("getCharAt", PythonInteger.class)); BuiltinTypes.STRING_TYPE.addBinaryMethod(PythonBinaryOperator.GET_ITEM, PythonString.class.getMethod("getSubstring", PythonSlice.class)); BuiltinTypes.STRING_TYPE.addBinaryMethod(PythonBinaryOperator.CONTAINS, PythonString.class.getMethod("containsSubstring", PythonString.class)); BuiltinTypes.STRING_TYPE.addBinaryMethod(PythonBinaryOperator.ADD, PythonString.class.getMethod("concat", PythonString.class)); BuiltinTypes.STRING_TYPE.addBinaryMethod(PythonBinaryOperator.MULTIPLY, PythonString.class.getMethod("repeat", PythonInteger.class)); BuiltinTypes.STRING_TYPE.addBinaryMethod(PythonBinaryOperator.MODULO, PythonString.class.getMethod("interpolate", PythonLikeObject.class)); BuiltinTypes.STRING_TYPE.addBinaryMethod(PythonBinaryOperator.MODULO, PythonString.class.getMethod("interpolate", PythonLikeTuple.class)); BuiltinTypes.STRING_TYPE.addBinaryMethod(PythonBinaryOperator.MODULO, PythonString.class.getMethod("interpolate", PythonLikeDict.class)); BuiltinTypes.STRING_TYPE.addBinaryMethod(PythonBinaryOperator.FORMAT, PythonString.class.getMethod("formatSelf")); BuiltinTypes.STRING_TYPE.addBinaryMethod(PythonBinaryOperator.FORMAT, PythonString.class.getMethod("formatSelf", PythonString.class)); // Other BuiltinTypes.STRING_TYPE.addMethod("capitalize", PythonString.class.getMethod("capitalize")); BuiltinTypes.STRING_TYPE.addMethod("casefold", PythonString.class.getMethod("casefold")); BuiltinTypes.STRING_TYPE.addMethod("center", PythonString.class.getMethod("center", PythonInteger.class)); BuiltinTypes.STRING_TYPE.addMethod("center", PythonString.class.getMethod("center", PythonInteger.class, PythonString.class)); BuiltinTypes.STRING_TYPE.addMethod("count", PythonString.class.getMethod("count", PythonString.class)); BuiltinTypes.STRING_TYPE.addMethod("count", PythonString.class.getMethod("count", PythonString.class, PythonInteger.class)); BuiltinTypes.STRING_TYPE.addMethod("count", PythonString.class.getMethod("count", PythonString.class, PythonInteger.class, PythonInteger.class)); // TODO: encode BuiltinTypes.STRING_TYPE.addMethod("endswith", PythonString.class.getMethod("endsWith", PythonString.class)); BuiltinTypes.STRING_TYPE.addMethod("endswith", PythonString.class.getMethod("endsWith", PythonLikeTuple.class)); BuiltinTypes.STRING_TYPE.addMethod("endswith", PythonString.class.getMethod("endsWith", PythonString.class, PythonInteger.class)); BuiltinTypes.STRING_TYPE.addMethod("endswith", PythonString.class.getMethod("endsWith", PythonLikeTuple.class, PythonInteger.class)); BuiltinTypes.STRING_TYPE.addMethod("endswith", PythonString.class.getMethod("endsWith", PythonString.class, PythonInteger.class, PythonInteger.class)); BuiltinTypes.STRING_TYPE.addMethod("endswith", PythonString.class.getMethod("endsWith", PythonLikeTuple.class, PythonInteger.class, PythonInteger.class)); BuiltinTypes.STRING_TYPE.addMethod("expandtabs", PythonString.class.getMethod("expandTabs")); BuiltinTypes.STRING_TYPE.addMethod("expandtabs", PythonString.class.getMethod("expandTabs", PythonInteger.class)); BuiltinTypes.STRING_TYPE.addMethod("find", PythonString.class.getMethod("findSubstringIndex", PythonString.class)); BuiltinTypes.STRING_TYPE.addMethod("find", PythonString.class.getMethod("findSubstringIndex", PythonString.class, PythonInteger.class)); BuiltinTypes.STRING_TYPE.addMethod("find", PythonString.class.getMethod("findSubstringIndex", PythonString.class, PythonInteger.class, PythonInteger.class)); BuiltinTypes.STRING_TYPE.addMethod("format", ArgumentSpec.forFunctionReturning("format", PythonString.class.getName()) .addExtraPositionalVarArgument("vargs") .addExtraKeywordVarArgument("kwargs") .asPythonFunctionSignature(PythonString.class.getMethod("format", List.class, Map.class))); BuiltinTypes.STRING_TYPE.addMethod("format_map", PythonString.class.getMethod("formatMap", PythonLikeDict.class)); BuiltinTypes.STRING_TYPE.addMethod("index", PythonString.class.getMethod("findSubstringIndexOrError", PythonString.class)); BuiltinTypes.STRING_TYPE.addMethod("index", PythonString.class.getMethod("findSubstringIndexOrError", PythonString.class, PythonInteger.class)); BuiltinTypes.STRING_TYPE.addMethod("index", PythonString.class.getMethod("findSubstringIndexOrError", PythonString.class, PythonInteger.class, PythonInteger.class)); BuiltinTypes.STRING_TYPE.addMethod("isalnum", PythonString.class.getMethod("isAlphaNumeric")); BuiltinTypes.STRING_TYPE.addMethod("isalpha", PythonString.class.getMethod("isAlpha")); BuiltinTypes.STRING_TYPE.addMethod("isascii", PythonString.class.getMethod("isAscii")); BuiltinTypes.STRING_TYPE.addMethod("isdecimal", PythonString.class.getMethod("isDecimal")); BuiltinTypes.STRING_TYPE.addMethod("isdigit", PythonString.class.getMethod("isDigit")); BuiltinTypes.STRING_TYPE.addMethod("isidentifier", PythonString.class.getMethod("isIdentifier")); BuiltinTypes.STRING_TYPE.addMethod("islower", PythonString.class.getMethod("isLower")); BuiltinTypes.STRING_TYPE.addMethod("isnumeric", PythonString.class.getMethod("isNumeric")); BuiltinTypes.STRING_TYPE.addMethod("isprintable", PythonString.class.getMethod("isPrintable")); BuiltinTypes.STRING_TYPE.addMethod("isspace", PythonString.class.getMethod("isSpace")); BuiltinTypes.STRING_TYPE.addMethod("istitle", PythonString.class.getMethod("isTitle")); BuiltinTypes.STRING_TYPE.addMethod("isupper", PythonString.class.getMethod("isUpper")); BuiltinTypes.STRING_TYPE.addMethod("join", PythonString.class.getMethod("join", PythonLikeObject.class)); BuiltinTypes.STRING_TYPE.addMethod("ljust", PythonString.class.getMethod("leftJustify", PythonInteger.class)); BuiltinTypes.STRING_TYPE.addMethod("ljust", PythonString.class.getMethod("leftJustify", PythonInteger.class, PythonString.class)); BuiltinTypes.STRING_TYPE.addMethod("lower", PythonString.class.getMethod("lower")); BuiltinTypes.STRING_TYPE.addMethod("lstrip", PythonString.class.getMethod("leftStrip")); BuiltinTypes.STRING_TYPE.addMethod("lstrip", PythonString.class.getMethod("leftStrip", PythonNone.class)); BuiltinTypes.STRING_TYPE.addMethod("lstrip", PythonString.class.getMethod("leftStrip", PythonString.class)); // TODO: maketrans BuiltinTypes.STRING_TYPE.addMethod("partition", PythonString.class.getMethod("partition", PythonString.class)); BuiltinTypes.STRING_TYPE.addMethod("removeprefix", PythonString.class.getMethod("removePrefix", PythonString.class)); BuiltinTypes.STRING_TYPE.addMethod("removesuffix", PythonString.class.getMethod("removeSuffix", PythonString.class)); BuiltinTypes.STRING_TYPE.addMethod("replace", PythonString.class.getMethod("replaceAll", PythonString.class, PythonString.class)); BuiltinTypes.STRING_TYPE.addMethod("replace", PythonString.class.getMethod("replaceUpToCount", PythonString.class, PythonString.class, PythonInteger.class)); BuiltinTypes.STRING_TYPE.addMethod("rfind", PythonString.class.getMethod("rightFindSubstringIndex", PythonString.class)); BuiltinTypes.STRING_TYPE.addMethod("rfind", PythonString.class.getMethod("rightFindSubstringIndex", PythonString.class, PythonInteger.class)); BuiltinTypes.STRING_TYPE.addMethod("rfind", PythonString.class.getMethod("rightFindSubstringIndex", PythonString.class, PythonInteger.class, PythonInteger.class)); BuiltinTypes.STRING_TYPE.addMethod("rindex", PythonString.class.getMethod("rightFindSubstringIndexOrError", PythonString.class)); BuiltinTypes.STRING_TYPE.addMethod("rindex", PythonString.class.getMethod("rightFindSubstringIndexOrError", PythonString.class, PythonInteger.class)); BuiltinTypes.STRING_TYPE.addMethod("rindex", PythonString.class.getMethod("rightFindSubstringIndexOrError", PythonString.class, PythonInteger.class, PythonInteger.class)); BuiltinTypes.STRING_TYPE.addMethod("rjust", PythonString.class.getMethod("rightJustify", PythonInteger.class)); BuiltinTypes.STRING_TYPE.addMethod("rjust", PythonString.class.getMethod("rightJustify", PythonInteger.class, PythonString.class)); BuiltinTypes.STRING_TYPE.addMethod("rpartition", PythonString.class.getMethod("rightPartition", PythonString.class)); BuiltinTypes.STRING_TYPE.addMethod("rsplit", PythonString.class.getMethod("rightSplit")); BuiltinTypes.STRING_TYPE.addMethod("rsplit", PythonString.class.getMethod("rightSplit", PythonNone.class)); BuiltinTypes.STRING_TYPE.addMethod("rsplit", PythonString.class.getMethod("rightSplit", PythonString.class)); BuiltinTypes.STRING_TYPE.addMethod("rsplit", PythonString.class.getMethod("rightSplit", PythonNone.class, PythonInteger.class)); BuiltinTypes.STRING_TYPE.addMethod("rsplit", PythonString.class.getMethod("rightSplit", PythonString.class, PythonInteger.class)); BuiltinTypes.STRING_TYPE.addMethod("rstrip", PythonString.class.getMethod("rightStrip")); BuiltinTypes.STRING_TYPE.addMethod("rstrip", PythonString.class.getMethod("rightStrip", PythonNone.class)); BuiltinTypes.STRING_TYPE.addMethod("rstrip", PythonString.class.getMethod("rightStrip", PythonString.class)); BuiltinTypes.STRING_TYPE.addMethod("split", PythonString.class.getMethod("split")); BuiltinTypes.STRING_TYPE.addMethod("split", PythonString.class.getMethod("split", PythonNone.class)); BuiltinTypes.STRING_TYPE.addMethod("split", PythonString.class.getMethod("split", PythonString.class)); BuiltinTypes.STRING_TYPE.addMethod("split", PythonString.class.getMethod("split", PythonNone.class, PythonInteger.class)); BuiltinTypes.STRING_TYPE.addMethod("split", PythonString.class.getMethod("split", PythonString.class, PythonInteger.class)); BuiltinTypes.STRING_TYPE.addMethod("splitlines", PythonString.class.getMethod("splitLines")); BuiltinTypes.STRING_TYPE.addMethod("splitlines", PythonString.class.getMethod("splitLines", PythonBoolean.class)); BuiltinTypes.STRING_TYPE.addMethod("startswith", PythonString.class.getMethod("startsWith", PythonString.class)); BuiltinTypes.STRING_TYPE.addMethod("startswith", PythonString.class.getMethod("startsWith", PythonLikeTuple.class)); BuiltinTypes.STRING_TYPE.addMethod("startswith", PythonString.class.getMethod("startsWith", PythonString.class, PythonInteger.class)); BuiltinTypes.STRING_TYPE.addMethod("startswith", PythonString.class.getMethod("startsWith", PythonLikeTuple.class, PythonInteger.class)); BuiltinTypes.STRING_TYPE.addMethod("startswith", PythonString.class.getMethod("startsWith", PythonString.class, PythonInteger.class, PythonInteger.class)); BuiltinTypes.STRING_TYPE.addMethod("startswith", PythonString.class.getMethod("startsWith", PythonLikeTuple.class, PythonInteger.class, PythonInteger.class)); BuiltinTypes.STRING_TYPE.addMethod("strip", PythonString.class.getMethod("strip")); BuiltinTypes.STRING_TYPE.addMethod("strip", PythonString.class.getMethod("strip", PythonNone.class)); BuiltinTypes.STRING_TYPE.addMethod("strip", PythonString.class.getMethod("strip", PythonString.class)); BuiltinTypes.STRING_TYPE.addMethod("swapcase", PythonString.class.getMethod("swapCase")); BuiltinTypes.STRING_TYPE.addMethod("title", PythonString.class.getMethod("title")); BuiltinTypes.STRING_TYPE.addMethod("translate", PythonString.class.getMethod("translate", PythonLikeObject.class)); BuiltinTypes.STRING_TYPE.addMethod("upper", PythonString.class.getMethod("upper")); BuiltinTypes.STRING_TYPE.addMethod("zfill", PythonString.class.getMethod("zfill", PythonInteger.class)); return BuiltinTypes.STRING_TYPE; } public PythonString(String value) { super(BuiltinTypes.STRING_TYPE); this.value = value; } public static PythonString valueOf(String value) { return new PythonString(value); } public String getValue() { return value; } public final PythonBytes asAsciiBytes() { char[] charData = value.toCharArray(); int length = 0; for (char charDatum : charData) { if (charDatum < 0xFF) { length++; } else { length += 2; } } byte[] out = new byte[length]; int outIndex = 0; for (char charDatum : charData) { if (charDatum < 0xFF) { out[outIndex] = (byte) charDatum; outIndex++; } else { out[outIndex] = (byte) ((charDatum & 0xFF00) >> 8); outIndex++; out[outIndex] = (byte) (charDatum & 0x00FF); outIndex++; } } return new PythonBytes(out); } public final PythonByteArray asAsciiByteArray() { return new PythonByteArray(asAsciiBytes().value); } public PythonBytes encode() { try { ByteBuffer byteBuffer = StandardCharsets.UTF_8.newEncoder() .onMalformedInput(CodingErrorAction.REPORT) .encode(CharBuffer.wrap(value)); byte[] out = new byte[byteBuffer.limit()]; byteBuffer.get(out); return new PythonBytes(out); } catch (CharacterCodingException e) { throw new UnicodeEncodeError(e.getMessage()); } } public PythonBytes encode(PythonString charset) { try { ByteBuffer byteBuffer = Charset.forName(charset.value).newEncoder() .onMalformedInput(CodingErrorAction.REPORT) .encode(CharBuffer.wrap(value)); byte[] out = new byte[byteBuffer.limit()]; byteBuffer.get(out); return new PythonBytes(out); } catch (CharacterCodingException e) { throw new UnicodeDecodeError(e.getMessage()); } } public PythonBytes encode(PythonString charset, PythonString errorActionString) { CodingErrorAction errorAction; switch (errorActionString.value) { case "strict": errorAction = CodingErrorAction.REPORT; break; case "ignore": errorAction = CodingErrorAction.IGNORE; break; case "replace": errorAction = CodingErrorAction.REPLACE; break; default: throw new ValueError(errorActionString.repr() + " is not a valid value for errors. Possible values are: " + "\"strict\", \"ignore\", \"replace\"."); } try { ByteBuffer byteBuffer = Charset.forName(charset.value).newEncoder() .onMalformedInput(errorAction) .encode(CharBuffer.wrap(value)); byte[] out = new byte[byteBuffer.limit()]; byteBuffer.get(out); return new PythonBytes(out); } catch (CharacterCodingException e) { throw new UnicodeDecodeError(e.getMessage()); } } public int length() { return value.length(); } public PythonInteger getLength() { return PythonInteger.valueOf(value.length()); } public PythonString getCharAt(PythonInteger position) { int index = PythonSlice.asIntIndexForLength(position, value.length()); if (index >= value.length()) { throw new IndexError("position " + position + " larger than string length " + value.length()); } else if (index < 0) { throw new IndexError("position " + position + " is less than 0"); } return new PythonString(Character.toString(value.charAt(index))); } public PythonString getSubstring(PythonSlice slice) { int length = value.length(); int start = slice.getStartIndex(length); int stop = slice.getStopIndex(length); int step = slice.getStrideLength(); if (step == 1) { if (stop <= start) { return PythonString.valueOf(""); } else { return PythonString.valueOf(value.substring(start, stop)); } } else { StringBuilder out = new StringBuilder(); if (step > 0) { for (int i = start; i < stop; i += step) { out.append(value.charAt(i)); } } else { for (int i = start; i > stop; i += step) { out.append(value.charAt(i)); } } return PythonString.valueOf(out.toString()); } } public PythonBoolean containsSubstring(PythonString substring) { return PythonBoolean.valueOf(value.contains(substring.value)); } public PythonString concat(PythonString other) { if (value.isEmpty()) { return other; } else if (other.value.isEmpty()) { return this; } else { return PythonString.valueOf(value + other.value); } } public PythonString repeat(PythonInteger times) { int timesAsInt = times.value.intValueExact(); if (timesAsInt <= 0) { return EMPTY; } if (timesAsInt == 1) { return this; } return PythonString.valueOf(value.repeat(timesAsInt)); } public DelegatePythonIterator getIterator() { return new DelegatePythonIterator(value.chars().mapToObj(charVal -> new PythonString(Character.toString(charVal))) .iterator()); } public PythonString capitalize() { if (value.isEmpty()) { return this; } return PythonString.valueOf(Character.toTitleCase(value.charAt(0)) + value.substring(1).toLowerCase()); } public PythonString title() { return title(ignored -> true); } public PythonString title(IntPredicate predicate) { if (value.isEmpty()) { return this; } int length = value.length(); boolean previousIsWordBoundary = true; StringBuilder out = new StringBuilder(length); for (int i = 0; i < length; i++) { char character = value.charAt(i); if (predicate.test(character)) { if (previousIsWordBoundary) { out.append(Character.toTitleCase(character)); } else { out.append(Character.toLowerCase(character)); } } else { out.append(character); } previousIsWordBoundary = !Character.isAlphabetic(character); } return PythonString.valueOf(out.toString()); } public PythonString casefold() { // This will work for the majority of cases, but fail for some cases return PythonString.valueOf(value.toUpperCase().toLowerCase()); } public PythonString swapCase() { return withModifiedCodepoints(CharacterCase::swapCase); } public PythonString lower() { return PythonString.valueOf(value.toLowerCase()); } public PythonString upper() { return PythonString.valueOf(value.toUpperCase()); } public PythonString withModifiedCodepoints(IntUnaryOperator modifier) { return PythonString.valueOf(value.codePoints() .map(modifier) .collect(StringBuilder::new, StringBuilder::appendCodePoint, StringBuilder::append) .toString()); } public PythonString center(PythonInteger width) { return center(width, PythonString.valueOf(" ")); } public PythonString center(PythonInteger width, PythonString fillChar) { int widthAsInt = width.value.intValueExact(); if (widthAsInt <= value.length()) { return this; } int extraWidth = widthAsInt - value.length(); int rightPadding = extraWidth / 2; // left padding get extra character if extraWidth is odd int leftPadding = rightPadding + (extraWidth & 1); // x & 1 == x % 2 if (fillChar.value.length() != 1) { throw new TypeError("The fill character must be exactly one character long"); } String fillCharAsString = fillChar.value; return PythonString.valueOf(fillCharAsString.repeat(leftPadding) + value + fillCharAsString.repeat(rightPadding)); } public PythonString rightJustify(PythonInteger width) { return rightJustify(width, PythonString.valueOf(" ")); } public PythonString rightJustify(PythonInteger width, PythonString fillChar) { int widthAsInt = width.value.intValueExact(); if (widthAsInt <= value.length()) { return this; } int leftPadding = widthAsInt - value.length(); if (fillChar.value.length() != 1) { throw new TypeError("The fill character must be exactly one character long"); } return PythonString.valueOf(fillChar.value.repeat(leftPadding) + value); } public PythonString leftJustify(PythonInteger width) { return leftJustify(width, PythonString.valueOf(" ")); } public PythonString leftJustify(PythonInteger width, PythonString fillChar) { int widthAsInt = width.value.intValueExact(); if (widthAsInt <= value.length()) { return this; } int rightPadding = widthAsInt - value.length(); if (fillChar.value.length() != 1) { throw new TypeError("The fill character must be exactly one character long"); } return PythonString.valueOf(value + fillChar.value.repeat(rightPadding)); } public PythonInteger count(PythonString sub) { Matcher matcher = Pattern.compile(Pattern.quote(sub.value)).matcher(value); return PythonInteger.valueOf(matcher.results().count()); } public PythonInteger count(PythonString sub, PythonInteger start) { int startIndex = PythonSlice.asValidStartIntIndexForLength(start, value.length()); Matcher matcher = Pattern.compile(Pattern.quote(sub.value)).matcher(value.substring(startIndex)); return PythonInteger.valueOf(matcher.results().count()); } public PythonInteger count(PythonString sub, PythonInteger start, PythonInteger end) { int startIndex = PythonSlice.asValidStartIntIndexForLength(start, value.length()); int endIndex = PythonSlice.asValidEndIntIndexForLength(end, value.length()); Matcher matcher = Pattern.compile(Pattern.quote(sub.value)).matcher(value.substring(startIndex, endIndex)); return PythonInteger.valueOf(matcher.results().count()); } // TODO: encode https://docs.python.org/3/library/stdtypes.html#str.encode public PythonBoolean startsWith(PythonString prefix) { return PythonBoolean.valueOf(value.startsWith(prefix.value)); } public PythonBoolean startsWith(PythonLikeTuple<PythonString> prefixTuple) { for (PythonString prefix : prefixTuple) { if (value.startsWith(prefix.value)) { return PythonBoolean.TRUE; } } return PythonBoolean.FALSE; } public PythonBoolean startsWith(PythonString prefix, PythonInteger start) { int startIndex = PythonSlice.asValidStartIntIndexForLength(start, value.length()); return PythonBoolean.valueOf(value.substring(startIndex).startsWith(prefix.value)); } public PythonBoolean startsWith(PythonLikeTuple<PythonString> prefixTuple, PythonInteger start) { int startIndex = PythonSlice.asValidStartIntIndexForLength(start, value.length()); String toCheck = value.substring(startIndex); for (PythonString prefix : prefixTuple) { if (toCheck.startsWith(prefix.value)) { return PythonBoolean.TRUE; } } return PythonBoolean.FALSE; } public PythonBoolean startsWith(PythonString prefix, PythonInteger start, PythonInteger end) { int startIndex = PythonSlice.asValidStartIntIndexForLength(start, value.length()); int endIndex = PythonSlice.asValidEndIntIndexForLength(end, value.length()); return PythonBoolean.valueOf(value.substring(startIndex, endIndex).startsWith(prefix.value)); } public PythonBoolean startsWith(PythonLikeTuple<PythonString> prefixTuple, PythonInteger start, PythonInteger end) { int startIndex = PythonSlice.asValidStartIntIndexForLength(start, value.length()); int endIndex = PythonSlice.asValidEndIntIndexForLength(end, value.length()); String toCheck = value.substring(startIndex, endIndex); for (PythonString prefix : prefixTuple) { if (toCheck.startsWith(prefix.value)) { return PythonBoolean.TRUE; } } return PythonBoolean.FALSE; } public PythonBoolean endsWith(PythonString suffix) { return PythonBoolean.valueOf(value.endsWith(suffix.value)); } public PythonBoolean endsWith(PythonLikeTuple<PythonString> suffixTuple) { for (PythonString suffix : suffixTuple) { if (value.endsWith(suffix.value)) { return PythonBoolean.TRUE; } } return PythonBoolean.FALSE; } public PythonBoolean endsWith(PythonString suffix, PythonInteger start) { int startIndex = PythonSlice.asValidStartIntIndexForLength(start, value.length()); return PythonBoolean.valueOf(value.substring(startIndex).endsWith(suffix.value)); } public PythonBoolean endsWith(PythonLikeTuple<PythonString> suffixTuple, PythonInteger start) { int startIndex = PythonSlice.asValidStartIntIndexForLength(start, value.length()); String toCheck = value.substring(startIndex); for (PythonString suffix : suffixTuple) { if (toCheck.endsWith(suffix.value)) { return PythonBoolean.TRUE; } } return PythonBoolean.FALSE; } public PythonBoolean endsWith(PythonString suffix, PythonInteger start, PythonInteger end) { int startIndex = PythonSlice.asValidStartIntIndexForLength(start, value.length()); int endIndex = PythonSlice.asValidEndIntIndexForLength(end, value.length()); return PythonBoolean.valueOf(value.substring(startIndex, endIndex).endsWith(suffix.value)); } public PythonBoolean endsWith(PythonLikeTuple<PythonString> suffixTuple, PythonInteger start, PythonInteger end) { int startIndex = PythonSlice.asValidStartIntIndexForLength(start, value.length()); int endIndex = PythonSlice.asValidEndIntIndexForLength(end, value.length()); String toCheck = value.substring(startIndex, endIndex); for (PythonString suffix : suffixTuple) { if (toCheck.endsWith(suffix.value)) { return PythonBoolean.TRUE; } } return PythonBoolean.FALSE; } public PythonString expandTabs() { return expandTabs(PythonInteger.valueOf(8)); } public PythonString expandTabs(PythonInteger tabsize) { int tabsizeAsInt = tabsize.value.intValueExact(); int column = 0; int length = value.length(); StringBuilder builder = new StringBuilder(); for (int i = 0; i < length; i++) { char character = value.charAt(i); if (character == '\n' || character == '\r') { builder.append(character); column = 0; continue; } if (character == '\t') { int remainder = tabsizeAsInt - (column % tabsizeAsInt); builder.append(" ".repeat(remainder)); column += remainder; continue; } builder.append(character); column++; } return PythonString.valueOf(builder.toString()); } public PythonInteger findSubstringIndex(PythonString substring) { return PythonInteger.valueOf(value.indexOf(substring.value)); } public PythonInteger findSubstringIndex(PythonString substring, PythonInteger start) { int startIndex = PythonSlice.asValidStartIntIndexForLength(start, value.length()); int result = value.indexOf(substring.value, startIndex); return PythonInteger.valueOf(result); } public PythonInteger findSubstringIndex(PythonString substring, PythonInteger start, PythonInteger end) { int startIndex = PythonSlice.asValidStartIntIndexForLength(start, value.length()); int endIndex = PythonSlice.asValidEndIntIndexForLength(end, value.length()); int result = value.substring(startIndex, endIndex).indexOf(substring.value); return PythonInteger.valueOf(result < 0 ? result : result + startIndex); } public PythonInteger rightFindSubstringIndex(PythonString substring) { return PythonInteger.valueOf(value.lastIndexOf(substring.value)); } public PythonInteger rightFindSubstringIndex(PythonString substring, PythonInteger start) { int startIndex = PythonSlice.asValidStartIntIndexForLength(start, value.length()); int result = value.substring(startIndex).lastIndexOf(substring.value); return PythonInteger.valueOf(result < 0 ? result : result + startIndex); } public PythonInteger rightFindSubstringIndex(PythonString substring, PythonInteger start, PythonInteger end) { int startIndex = PythonSlice.asValidStartIntIndexForLength(start, value.length()); int endIndex = PythonSlice.asValidEndIntIndexForLength(end, value.length()); int result = value.substring(startIndex, endIndex).lastIndexOf(substring.value); return PythonInteger.valueOf(result < 0 ? result : result + startIndex); } public PythonString format(List<PythonLikeObject> positionalArguments, Map<PythonString, PythonLikeObject> namedArguments) { return PythonString.valueOf(StringFormatter.format(value, positionalArguments, namedArguments)); } public PythonString formatMap(PythonLikeDict dict) { return format(Collections.emptyList(), (Map) dict); } public PythonString formatSelf() { return this; } public PythonString formatSelf(PythonString spec) { if (spec.value.isEmpty()) { return this; } DefaultFormatSpec formatSpec = DefaultFormatSpec.fromStringSpec(spec); StringBuilder out = new StringBuilder(); switch (formatSpec.conversionType.orElse(DefaultFormatSpec.ConversionType.STRING)) { case STRING: out.append(value); break; default: throw new ValueError("Invalid conversion type for str: " + formatSpec.conversionType); } StringFormatter.align(out, formatSpec, DefaultFormatSpec.AlignmentOption.LEFT_ALIGN); return PythonString.valueOf(out.toString()); } public PythonString interpolate(PythonLikeObject object) { if (object instanceof PythonLikeTuple) { return interpolate((PythonLikeTuple) object); } else if (object instanceof PythonLikeDict) { return interpolate((PythonLikeDict) object); } else { return interpolate(PythonLikeTuple.fromItems(object)); } } public PythonString interpolate(PythonLikeTuple tuple) { return PythonString.valueOf(StringFormatter.printfInterpolate(value, tuple, StringFormatter.PrintfStringType.STRING)); } public PythonString interpolate(PythonLikeDict dict) { return PythonString.valueOf(StringFormatter.printfInterpolate(value, dict, StringFormatter.PrintfStringType.STRING)); } public PythonInteger findSubstringIndexOrError(PythonString substring) { int result = value.indexOf(substring.value); if (result == -1) { throw new ValueError("substring not found"); } return PythonInteger.valueOf(result); } public PythonInteger findSubstringIndexOrError(PythonString substring, PythonInteger start) { int startIndex = PythonSlice.asValidStartIntIndexForLength(start, value.length()); int result = value.indexOf(substring.value, startIndex); if (result == -1) { throw new ValueError("substring not found"); } return PythonInteger.valueOf(result); } public PythonInteger findSubstringIndexOrError(PythonString substring, PythonInteger start, PythonInteger end) { int startIndex = PythonSlice.asValidStartIntIndexForLength(start, value.length()); int endIndex = PythonSlice.asValidEndIntIndexForLength(end, value.length()); int result = value.substring(startIndex, endIndex).indexOf(substring.value); if (result == -1) { throw new ValueError("substring not found"); } return PythonInteger.valueOf(result + startIndex); } public PythonInteger rightFindSubstringIndexOrError(PythonString substring) { int result = value.lastIndexOf(substring.value); if (result == -1) { throw new ValueError("substring not found"); } return PythonInteger.valueOf(result); } public PythonInteger rightFindSubstringIndexOrError(PythonString substring, PythonInteger start) { int startIndex = PythonSlice.asValidStartIntIndexForLength(start, value.length()); int result = value.substring(startIndex).lastIndexOf(substring.value); if (result == -1) { throw new ValueError("substring not found"); } return PythonInteger.valueOf(result + startIndex); } public PythonInteger rightFindSubstringIndexOrError(PythonString substring, PythonInteger start, PythonInteger end) { int startIndex = PythonSlice.asValidStartIntIndexForLength(start, value.length()); int endIndex = PythonSlice.asValidEndIntIndexForLength(end, value.length()); int result = value.substring(startIndex, endIndex).lastIndexOf(substring.value); if (result == -1) { throw new ValueError("substring not found"); } return PythonInteger.valueOf(result + startIndex); } private PythonBoolean allCharactersHaveProperty(IntPredicate predicate) { int length = value.length(); if (length == 0) { return PythonBoolean.FALSE; } for (int i = 0; i < length; i++) { char character = value.charAt(i); if (!predicate.test(character)) { return PythonBoolean.FALSE; } } return PythonBoolean.TRUE; } public PythonBoolean isAlphaNumeric() { return allCharactersHaveProperty( character -> Character.isLetter(character) || Character.getNumericValue(character) != -1); } public PythonBoolean isAlpha() { return allCharactersHaveProperty(Character::isLetter); } public PythonBoolean isAscii() { if (value.isEmpty()) { return PythonBoolean.TRUE; } return allCharactersHaveProperty(character -> character <= 127); } public PythonBoolean isDecimal() { return allCharactersHaveProperty(Character::isDigit); } private boolean isSuperscriptOrSubscript(int character) { String characterName = Character.getName(character); return characterName.contains("SUPERSCRIPT") || characterName.contains("SUBSCRIPT"); } public PythonBoolean isDigit() { return allCharactersHaveProperty(character -> { if (Character.getType(character) == Character.DECIMAL_DIGIT_NUMBER) { return true; } return Character.isDigit(character) || (Character.getNumericValue(character) >= 0 && isSuperscriptOrSubscript(character)); }); } public PythonBoolean isIdentifier() { int length = value.length(); if (length == 0) { return PythonBoolean.FALSE; } char firstChar = value.charAt(0); if (!isPythonIdentifierStart(firstChar)) { return PythonBoolean.FALSE; } for (int i = 1; i < length; i++) { char character = value.charAt(i); if (!isPythonIdentifierPart(character)) { return PythonBoolean.FALSE; } } return PythonBoolean.TRUE; } private static boolean isPythonIdentifierStart(char character) { if (Character.isLetter(character)) { return true; } if (Character.getType(character) == Character.LETTER_NUMBER) { return true; } switch (character) { case '_': case 0x1885: case 0x1886: case 0x2118: case 0x212E: case 0x309B: case 0x309C: return true; default: return false; } } private static boolean isPythonIdentifierPart(char character) { if (isPythonIdentifierStart(character)) { return true; } switch (Character.getType(character)) { case Character.NON_SPACING_MARK: case Character.COMBINING_SPACING_MARK: case Character.DECIMAL_DIGIT_NUMBER: case Character.CONNECTOR_PUNCTUATION: return true; } switch (character) { case 0x00B7: case 0x0387: case 0x19DA: return true; default: return character >= 0x1369 && character <= 0x1371; } } private static boolean hasCase(int character) { return Character.isUpperCase(character) || Character.isLowerCase(character) || Character.isTitleCase(character); } private boolean hasCaseCharacters() { return !allCharactersHaveProperty(character -> !hasCase(character)).getBooleanValue(); } public PythonBoolean isLower() { if (hasCaseCharacters()) { return allCharactersHaveProperty(character -> !hasCase(character) || Character.isLowerCase(character)); } else { return PythonBoolean.FALSE; } } public PythonBoolean isNumeric() { return allCharactersHaveProperty(character -> { switch (Character.getType(character)) { case Character.OTHER_NUMBER: case Character.DECIMAL_DIGIT_NUMBER: return true; default: return !Character.isLetter(character) && Character.getNumericValue(character) != -1; } }); } private static boolean isCharacterPrintable(int character) { if (character == ' ') { return true; } switch (Character.getType(character)) { // Others case Character.PRIVATE_USE: case Character.FORMAT: case Character.CONTROL: case Character.UNASSIGNED: // Separators case Character.SPACE_SEPARATOR: case Character.LINE_SEPARATOR: case Character.PARAGRAPH_SEPARATOR: return false; default: return true; } } public PythonBoolean isPrintable() { if (value.isEmpty()) { return PythonBoolean.TRUE; } return allCharactersHaveProperty(PythonString::isCharacterPrintable); } public PythonBoolean isSpace() { return PythonBoolean.valueOf(!value.isEmpty() && value.isBlank()); } public PythonBoolean isUpper() { if (hasCaseCharacters()) { return allCharactersHaveProperty(character -> !hasCase(character) || Character.isUpperCase(character)); } else { return PythonBoolean.FALSE; } } enum CharacterCase { UNCASED, LOWER, UPPER; public static CharacterCase getCase(int character) { if (Character.isLowerCase(character)) { return LOWER; } else if (Character.isUpperCase(character)) { return UPPER; } else { return UNCASED; } } public static int swapCase(int character) { if (Character.isLowerCase(character)) { return Character.toUpperCase(character); } else if (Character.isUpperCase(character)) { return Character.toLowerCase(character); } return character; } } public PythonBoolean isTitle() { int length = value.length(); if (length == 0) { return PythonBoolean.FALSE; } CharacterCase previousType = CharacterCase.UNCASED; for (int i = 0; i < length; i++) { char character = value.charAt(i); CharacterCase characterCase = CharacterCase.getCase(character); if (characterCase == CharacterCase.UNCASED && Character.isLetter(character)) { return PythonBoolean.FALSE; } switch (previousType) { case UNCASED: if (characterCase != CharacterCase.UPPER) { return PythonBoolean.FALSE; } break; case UPPER: case LOWER: if (characterCase == CharacterCase.UPPER) { return PythonBoolean.FALSE; } break; } previousType = characterCase; } return PythonBoolean.TRUE; } public PythonString join(PythonLikeObject iterable) { PythonIterator iterator = (PythonIterator) UnaryDunderBuiltin.ITERATOR.invoke(iterable); int index = 0; StringBuilder out = new StringBuilder(); while (iterator.hasNext()) { PythonLikeObject maybeString = iterator.nextPythonItem(); if (!(maybeString instanceof PythonString)) { throw new TypeError("sequence item " + index + ": expected str instance, " + maybeString.$getType().getTypeName() + " found"); } PythonString string = (PythonString) maybeString; out.append(string.value); if (iterator.hasNext()) { out.append(value); } index++; } return PythonString.valueOf(out.toString()); } public PythonString strip() { return PythonString.valueOf(value.strip()); } public PythonString strip(PythonNone ignored) { return strip(); } public PythonString strip(PythonString toStrip) { int length = value.length(); int start = 0; int end = length - 1; for (; start < length; start++) { if (toStrip.value.indexOf(value.charAt(start)) == -1) { break; } } if (start == length) { return EMPTY; } for (; end >= start; end--) { if (toStrip.value.indexOf(value.charAt(end)) == -1) { break; } } return PythonString.valueOf(value.substring(start, end + 1)); } public PythonString leftStrip() { return PythonString.valueOf(value.stripLeading()); } public PythonString leftStrip(PythonNone ignored) { return leftStrip(); } public PythonString leftStrip(PythonString toStrip) { int length = value.length(); for (int i = 0; i < length; i++) { if (toStrip.value.indexOf(value.charAt(i)) == -1) { return PythonString.valueOf(value.substring(i)); } } return EMPTY; } public PythonString rightStrip() { return PythonString.valueOf(value.stripTrailing()); } public PythonString rightStrip(PythonNone ignored) { return rightStrip(); } public PythonString rightStrip(PythonString toStrip) { int length = value.length(); for (int i = length - 1; i >= 0; i--) { if (toStrip.value.indexOf(value.charAt(i)) == -1) { return PythonString.valueOf(value.substring(0, i + 1)); } } return EMPTY; } public PythonLikeTuple partition(PythonString seperator) { int firstIndex = value.indexOf(seperator.value); if (firstIndex != -1) { return PythonLikeTuple.fromItems( PythonString.valueOf(value.substring(0, firstIndex)), seperator, PythonString.valueOf(value.substring(firstIndex + seperator.value.length()))); } else { return PythonLikeTuple.fromItems( this, EMPTY, EMPTY); } } public PythonLikeTuple rightPartition(PythonString seperator) { int lastIndex = value.lastIndexOf(seperator.value); if (lastIndex != -1) { return PythonLikeTuple.fromItems( PythonString.valueOf(value.substring(0, lastIndex)), seperator, PythonString.valueOf(value.substring(lastIndex + seperator.value.length()))); } else { return PythonLikeTuple.fromItems( EMPTY, EMPTY, this); } } public PythonString removePrefix(PythonString prefix) { if (value.startsWith(prefix.value)) { return new PythonString(value.substring(prefix.value.length())); } return this; } public PythonString removeSuffix(PythonString suffix) { if (value.endsWith(suffix.value)) { return new PythonString(value.substring(0, value.length() - suffix.value.length())); } return this; } public PythonString replaceAll(PythonString old, PythonString replacement) { return PythonString.valueOf(value.replaceAll(Pattern.quote(old.value), replacement.value)); } public PythonString replaceUpToCount(PythonString old, PythonString replacement, PythonInteger count) { int countAsInt = count.value.intValueExact(); if (countAsInt < 0) { // negative count act the same as replace all return replaceAll(old, replacement); } Matcher matcher = Pattern.compile(Pattern.quote(old.value)).matcher(value); StringBuilder out = new StringBuilder(); int start = 0; while (countAsInt > 0) { if (matcher.find()) { out.append(value, start, matcher.start()); out.append(replacement.value); start = matcher.end(); } else { break; } countAsInt--; } out.append(value.substring(start)); return PythonString.valueOf(out.toString()); } public PythonLikeList<PythonString> split() { return Arrays.stream(value.stripLeading().split("\\s+")) .map(PythonString::valueOf) .collect(Collectors.toCollection(PythonLikeList::new)); } public PythonLikeList<PythonString> split(PythonNone ignored) { return split(); } public PythonLikeList<PythonString> split(PythonString seperator) { return Arrays.stream(value.split(Pattern.quote(seperator.value), -1)) .map(PythonString::valueOf) .collect(Collectors.toCollection(PythonLikeList::new)); } public PythonLikeList<PythonString> split(PythonString seperator, PythonInteger maxSplits) { int maxSplitsAsInt = maxSplits.value.intValueExact(); if (maxSplitsAsInt == -1) { return split(seperator); } return Arrays.stream(value.split(Pattern.quote(seperator.value), maxSplitsAsInt + 1)) .map(PythonString::valueOf) .collect(Collectors.toCollection(PythonLikeList::new)); } public PythonLikeList<PythonString> split(PythonNone ignored, PythonInteger maxSplits) { int maxSplitsAsInt = maxSplits.value.intValueExact(); if (maxSplitsAsInt == -1) { return split(); } return Arrays.stream(value.stripLeading().split("\\s+", maxSplitsAsInt + 1)) .map(PythonString::valueOf) .collect(Collectors.toCollection(PythonLikeList::new)); } public PythonLikeList<PythonString> rightSplit() { return split(); } public PythonLikeList<PythonString> rightSplit(PythonNone ignored) { return split(); } public PythonLikeList<PythonString> rightSplit(PythonString seperator) { return split(seperator); } public PythonLikeList<PythonString> rightSplit(PythonString seperator, PythonInteger maxSplits) { int maxSplitsAsInt = maxSplits.value.intValueExact(); if (maxSplitsAsInt == -1) { return split(seperator); } String reversedValue = new StringBuilder(value.stripTrailing()).reverse().toString(); String reversedSeperator = new StringBuilder(seperator.value).reverse().toString(); return Arrays.stream(reversedValue.split(Pattern.quote(reversedSeperator), maxSplitsAsInt + 1)) .map(reversedPart -> PythonString.valueOf(new StringBuilder(reversedPart).reverse().toString())) .collect(Collectors.collectingAndThen(Collectors.toCollection(PythonLikeList::new), l -> { Collections.reverse(l); return l; })); } public PythonLikeList<PythonString> rightSplit(PythonNone ignored, PythonInteger maxSplits) { int maxSplitsAsInt = maxSplits.value.intValueExact(); if (maxSplitsAsInt == -1) { return split(); } String reversedValue = new StringBuilder(value.stripTrailing()).reverse().toString(); return Arrays.stream(reversedValue.split("\\s+", maxSplitsAsInt + 1)) .map(reversedPart -> PythonString.valueOf(new StringBuilder(reversedPart).reverse().toString())) .collect(Collectors.collectingAndThen(Collectors.toCollection(PythonLikeList::new), l -> { Collections.reverse(l); return l; })); } public PythonLikeList<PythonString> splitLines() { if (value.isEmpty()) { return new PythonLikeList<>(); } return Arrays.stream(value.split("\\R")) .map(PythonString::valueOf) .collect(Collectors.toCollection(PythonLikeList::new)); } public PythonLikeList<PythonString> splitLines(PythonBoolean keepEnds) { if (!keepEnds.getBooleanValue()) { return splitLines(); } // Use lookahead so the newline is included in the result return Arrays.stream(value.split("(?<=\\R)")) .map(PythonString::valueOf) .collect(Collectors.collectingAndThen(Collectors.toCollection(PythonLikeList::new), l -> { int i; for (i = 0; i < l.size() - 1; i++) { // lookbehind cause it to split \r\n into two seperate // lines; need to combine consecutive lines where the first ends with \r // and the second starts with \n to get expected behavior if (l.get(i).value.endsWith("\r") && l.get(i + 1).value.startsWith("\n")) { l.set(i, PythonString.valueOf(l.get(i).value + l.remove(i + 1).value)); i--; } } // Remove trailing empty string // i = l.size() - 1 if (!l.isEmpty() && l.get(i).value.isEmpty()) { l.remove(i); } return l; })); } public PythonString translate(PythonLikeObject object) { return PythonString.valueOf(value.codePoints() .flatMap(codePoint -> { try { PythonLikeObject translated = BinaryDunderBuiltin.GET_ITEM.invoke(object, PythonInteger.valueOf(codePoint)); if (translated == PythonNone.INSTANCE) { return IntStream.empty(); } if (translated instanceof PythonInteger) { return IntStream.of(((PythonInteger) translated).value.intValueExact()); } if (translated instanceof PythonString) { return ((PythonString) translated).value.codePoints(); } throw new TypeError("character mapping must return integer, None or str"); } catch (LookupError e) { return IntStream.of(codePoint); } }).collect(StringBuilder::new, StringBuilder::appendCodePoint, StringBuilder::append).toString()); } public PythonString zfill(PythonInteger width) { int widthAsInt = width.value.intValueExact(); if (widthAsInt <= value.length()) { return this; } int leftPadding = widthAsInt - value.length(); if (!value.isEmpty() && (value.charAt(0) == '+' || value.charAt(0) == '-')) { return PythonString.valueOf(value.charAt(0) + "0".repeat(leftPadding) + value.substring(1)); } else { return PythonString.valueOf("0".repeat(leftPadding) + value); } } @Override public int compareTo(PythonString pythonString) { return value.compareTo(pythonString.value); } @Override public PythonString $method$__format__(PythonLikeObject specObject) { PythonString spec; if (specObject == PythonNone.INSTANCE) { return formatSelf(); } else if (specObject instanceof PythonString) { spec = (PythonString) specObject; } else { throw new TypeError("__format__ argument 0 has incorrect type (expecting str or None)"); } return formatSelf(spec); } public PythonString repr() { return PythonString.valueOf("'" + value.codePoints() .flatMap(character -> { if (character == '\\') { return IntStream.of('\\', '\\'); } if (isCharacterPrintable(character)) { return IntStream.of(character); } else { switch (character) { case '\r': return IntStream.of('\\', 'r'); case '\n': return IntStream.of('\\', 'n'); case '\t': return IntStream.of('\\', 't'); default: { if (character < 0xFFFF) { return String.format("u%04x", character).codePoints(); } else { return String.format("U%08x", character).codePoints(); } } } } }) .collect(StringBuilder::new, StringBuilder::appendCodePoint, StringBuilder::append) .toString() + "'"); } public PythonString asString() { return this; } @Override public PythonString $method$__str__() { return this; } @Override public String toString() { return value; } @Override public boolean equals(Object o) { if (o instanceof String s) { return s.equals(value); } else if (o instanceof PythonString s) { return s.value.equals(value); } else { return false; } } @Override public int hashCode() { return value.hashCode(); } @Override public PythonInteger $method$__hash__() { return PythonInteger.valueOf(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/types/PythonSuperObject.java
package ai.timefold.jpyinterpreter.types; import java.util.List; import java.util.Map; import ai.timefold.jpyinterpreter.PythonClassTranslator; import ai.timefold.jpyinterpreter.PythonLikeObject; import ai.timefold.jpyinterpreter.PythonTernaryOperator; import ai.timefold.jpyinterpreter.builtins.TernaryDunderBuiltin; import ai.timefold.jpyinterpreter.types.errors.AttributeError; public class PythonSuperObject extends AbstractPythonLikeObject { public static final PythonLikeType $TYPE = BuiltinTypes.SUPER_TYPE; public final PythonLikeType previousType; public final PythonLikeObject instance; public PythonSuperObject(PythonLikeType previousType) { super(BuiltinTypes.SUPER_TYPE); this.previousType = previousType; this.instance = null; } public PythonSuperObject(PythonLikeType previousType, PythonLikeObject instance) { super(BuiltinTypes.SUPER_TYPE); this.previousType = previousType; this.instance = instance; } @Override public PythonLikeObject $method$__getattribute__(PythonString pythonName) { List<PythonLikeType> mro; if (instance != null) { if (instance instanceof PythonLikeType) { mro = ((PythonLikeType) instance).MRO; } else { mro = instance.$getType().MRO; } } else { mro = previousType.MRO; } String name = pythonName.value; for (int currentIndex = mro.indexOf(previousType) + 1; currentIndex < mro.size(); currentIndex++) { PythonLikeType candidate = mro.get(currentIndex); PythonLikeObject typeResult = candidate.$getAttributeOrNull(name); if (typeResult != null) { if (typeResult instanceof PythonLikeFunction && !(typeResult instanceof PythonLikeType)) { try { Object methodInstance = candidate.getJavaClass().getField(PythonClassTranslator.getJavaMethodHolderName(name)) .get(null); typeResult = new GeneratedFunctionMethodReference(methodInstance, methodInstance.getClass().getDeclaredMethods()[0], Map.of(), typeResult.$getType()); } catch (ClassNotFoundException | NoSuchFieldException | IllegalAccessException e) { // ignore } } PythonLikeObject maybeDescriptor = typeResult.$getAttributeOrNull(PythonTernaryOperator.GET.dunderMethod); if (maybeDescriptor == null) { maybeDescriptor = typeResult.$getType().$getAttributeOrNull(PythonTernaryOperator.GET.dunderMethod); } if (maybeDescriptor != null) { if (!(maybeDescriptor instanceof PythonLikeFunction)) { throw new UnsupportedOperationException("'" + maybeDescriptor.$getType() + "' is not callable"); } return TernaryDunderBuiltin.GET_DESCRIPTOR.invoke(typeResult, (instance != null) ? instance : PythonNone.INSTANCE, candidate); } return typeResult; } } throw new AttributeError("Cannot find attribute " + pythonName.repr() + " in super(" + previousType + ")."); } }
0
java-sources/ai/timefold/solver/jpyinterpreter/1.24.0/ai/timefold/jpyinterpreter/types
java-sources/ai/timefold/solver/jpyinterpreter/1.24.0/ai/timefold/jpyinterpreter/types/collections/DelegatePythonIterator.java
package ai.timefold.jpyinterpreter.types.collections; import java.util.Iterator; import ai.timefold.jpyinterpreter.PythonLikeObject; import ai.timefold.jpyinterpreter.PythonOverloadImplementor; import ai.timefold.jpyinterpreter.PythonUnaryOperator; import ai.timefold.jpyinterpreter.types.AbstractPythonLikeObject; import ai.timefold.jpyinterpreter.types.BuiltinTypes; import ai.timefold.jpyinterpreter.types.PythonLikeType; import ai.timefold.jpyinterpreter.types.errors.StopIteration; public class DelegatePythonIterator<T> extends AbstractPythonLikeObject implements PythonIterator<T> { static { PythonOverloadImplementor.deferDispatchesFor(DelegatePythonIterator::registerMethods); } private static PythonLikeType registerMethods() throws NoSuchMethodException { BuiltinTypes.ITERATOR_TYPE.addUnaryMethod(PythonUnaryOperator.NEXT, PythonIterator.class.getMethod("nextPythonItem")); BuiltinTypes.ITERATOR_TYPE.addUnaryMethod(PythonUnaryOperator.ITERATOR, PythonIterator.class.getMethod("getIterator")); return BuiltinTypes.ITERATOR_TYPE; } private final Iterator<T> delegate; public DelegatePythonIterator(Iterator<T> delegate) { super(BuiltinTypes.ITERATOR_TYPE); this.delegate = delegate; } public DelegatePythonIterator(PythonLikeType type) { super(type); this.delegate = this; } @Override public boolean hasNext() { return delegate.hasNext(); } @Override public T next() { if (!delegate.hasNext()) { throw new StopIteration(); } return delegate.next(); } public PythonLikeObject nextPythonItem() { if (!delegate.hasNext()) { throw new StopIteration(); } return (PythonLikeObject) delegate.next(); } public DelegatePythonIterator<T> getIterator() { return this; } }
0
java-sources/ai/timefold/solver/jpyinterpreter/1.24.0/ai/timefold/jpyinterpreter/types
java-sources/ai/timefold/solver/jpyinterpreter/1.24.0/ai/timefold/jpyinterpreter/types/collections/PythonIterator.java
package ai.timefold.jpyinterpreter.types.collections; import java.util.Iterator; import ai.timefold.jpyinterpreter.PythonLikeObject; public interface PythonIterator<T> extends PythonLikeObject, Iterator<T> { PythonLikeObject nextPythonItem(); PythonIterator<T> getIterator(); }
0
java-sources/ai/timefold/solver/jpyinterpreter/1.24.0/ai/timefold/jpyinterpreter/types
java-sources/ai/timefold/solver/jpyinterpreter/1.24.0/ai/timefold/jpyinterpreter/types/collections/PythonLikeDict.java
package ai.timefold.jpyinterpreter.types.collections; import java.util.Collection; import java.util.Collections; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; import java.util.stream.Stream; import ai.timefold.jpyinterpreter.PythonBinaryOperator; import ai.timefold.jpyinterpreter.PythonLikeObject; import ai.timefold.jpyinterpreter.PythonOverloadImplementor; import ai.timefold.jpyinterpreter.PythonTernaryOperator; import ai.timefold.jpyinterpreter.PythonUnaryOperator; import ai.timefold.jpyinterpreter.builtins.UnaryDunderBuiltin; import ai.timefold.jpyinterpreter.types.AbstractPythonLikeObject; 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.collections.view.DictItemView; import ai.timefold.jpyinterpreter.types.collections.view.DictKeyView; import ai.timefold.jpyinterpreter.types.collections.view.DictValueView; import ai.timefold.jpyinterpreter.types.errors.ValueError; import ai.timefold.jpyinterpreter.types.errors.lookup.KeyError; import ai.timefold.jpyinterpreter.types.numeric.PythonBoolean; import ai.timefold.jpyinterpreter.types.numeric.PythonInteger; import ai.timefold.jpyinterpreter.util.JavaStringMapMirror; import ai.timefold.solver.core.impl.domain.solution.cloner.PlanningCloneable; import org.apache.commons.collections4.OrderedMap; import org.apache.commons.collections4.map.LinkedMap; public class PythonLikeDict<K extends PythonLikeObject, V extends PythonLikeObject> extends AbstractPythonLikeObject implements Map<K, V>, PlanningCloneable<PythonLikeDict<K, V>>, Iterable<PythonLikeObject> { public final OrderedMap delegate; static { PythonOverloadImplementor.deferDispatchesFor(PythonLikeDict::registerMethods); } private static PythonLikeType registerMethods() throws NoSuchMethodException { BuiltinTypes.DICT_TYPE.setConstructor(((positionalArguments, namedArguments, callerInstance) -> { PythonLikeDict out = new PythonLikeDict(); if (positionalArguments.isEmpty()) { out.putAll(namedArguments); return out; } else if (positionalArguments.size() == 1) { PythonLikeObject from = positionalArguments.get(0); if (from instanceof Map) { out.putAll((Map) from); } else { Iterator iterator = (Iterator) UnaryDunderBuiltin.ITERATOR.invoke(from); while (iterator.hasNext()) { List item = (List) iterator.next(); out.put((PythonLikeObject) item.get(0), (PythonLikeObject) item.get(1)); } } out.putAll(namedArguments); return out; } else { throw new ValueError("dict takes 0 or 1 positional arguments, got " + positionalArguments.size()); } })); // Unary operators BuiltinTypes.DICT_TYPE.addUnaryMethod(PythonUnaryOperator.ITERATOR, PythonLikeDict.class.getMethod("getKeyIterator")); BuiltinTypes.DICT_TYPE.addUnaryMethod(PythonUnaryOperator.LENGTH, PythonLikeDict.class.getMethod("getSize")); BuiltinTypes.DICT_TYPE.addUnaryMethod(PythonUnaryOperator.REVERSED, PythonLikeDict.class.getMethod("reversed")); // Binary operators BuiltinTypes.DICT_TYPE.addBinaryMethod(PythonBinaryOperator.GET_ITEM, PythonLikeDict.class.getMethod("getItemOrError", PythonLikeObject.class)); BuiltinTypes.DICT_TYPE.addBinaryMethod(PythonBinaryOperator.DELETE_ITEM, PythonLikeDict.class.getMethod("removeItemOrError", PythonLikeObject.class)); BuiltinTypes.DICT_TYPE.addBinaryMethod(PythonBinaryOperator.CONTAINS, PythonLikeDict.class.getMethod("isKeyInDict", PythonLikeObject.class)); BuiltinTypes.DICT_TYPE.addBinaryMethod(PythonBinaryOperator.OR, PythonLikeDict.class.getMethod("binaryOr", PythonLikeDict.class)); BuiltinTypes.DICT_TYPE.addBinaryMethod(PythonBinaryOperator.INPLACE_OR, PythonLikeDict.class.getMethod("binaryInplaceOr", PythonLikeDict.class)); // Ternary operators BuiltinTypes.DICT_TYPE.addTernaryMethod(PythonTernaryOperator.SET_ITEM, PythonLikeDict.class.getMethod("setItem", PythonLikeObject.class, PythonLikeObject.class)); // Other BuiltinTypes.DICT_TYPE.addMethod("clear", PythonLikeDict.class.getMethod("clearDict")); BuiltinTypes.DICT_TYPE.addMethod("copy", PythonLikeDict.class.getMethod("copy")); BuiltinTypes.DICT_TYPE.addMethod("get", PythonLikeDict.class.getMethod("getItemOrNone", PythonLikeObject.class)); BuiltinTypes.DICT_TYPE.addMethod("get", PythonLikeDict.class.getMethod("getItemOrDefault", PythonLikeObject.class, PythonLikeObject.class)); BuiltinTypes.DICT_TYPE.addMethod("items", PythonLikeDict.class.getMethod("getItems")); BuiltinTypes.DICT_TYPE.addMethod("keys", PythonLikeDict.class.getMethod("getKeyView")); BuiltinTypes.DICT_TYPE.addMethod("pop", PythonLikeDict.class.getMethod("popItemOrError", PythonLikeObject.class)); BuiltinTypes.DICT_TYPE.addMethod("pop", PythonLikeDict.class.getMethod("popItemOrDefault", PythonLikeObject.class, PythonLikeObject.class)); BuiltinTypes.DICT_TYPE.addMethod("popitem", PythonLikeDict.class.getMethod("popLast")); BuiltinTypes.DICT_TYPE.addMethod("setdefault", PythonLikeDict.class.getMethod("setIfAbsent", PythonLikeObject.class)); BuiltinTypes.DICT_TYPE.addMethod("setdefault", PythonLikeDict.class.getMethod("setIfAbsent", PythonLikeObject.class, PythonLikeObject.class)); BuiltinTypes.DICT_TYPE.addMethod("update", PythonLikeDict.class.getMethod("update", PythonLikeDict.class)); BuiltinTypes.DICT_TYPE.addMethod("update", PythonLikeDict.class.getMethod("update", PythonLikeObject.class)); // TODO: Keyword update BuiltinTypes.DICT_TYPE.addMethod("values", PythonLikeDict.class.getMethod("getValueView")); return BuiltinTypes.DICT_TYPE; } public PythonLikeDict() { super(BuiltinTypes.DICT_TYPE); delegate = new LinkedMap<>(); } public PythonLikeDict(int size) { super(BuiltinTypes.DICT_TYPE); delegate = new LinkedMap<>(size); } public PythonLikeDict(OrderedMap<PythonLikeObject, PythonLikeObject> source) { super(BuiltinTypes.DICT_TYPE); delegate = source; } @Override public PythonLikeDict<K, V> createNewInstance() { return new PythonLikeDict<>(); } public static PythonLikeDict<PythonString, PythonLikeObject> mirror(Map<String, PythonLikeObject> globals) { return new PythonLikeDict<>(new JavaStringMapMirror(globals)); } public PythonLikeTuple toFlattenKeyValueTuple() { return PythonLikeTuple.fromItems((PythonLikeObject[]) delegate.entrySet().stream() .flatMap(entry -> { var mapEntry = (Map.Entry<K, V>) entry; return Stream.of(mapEntry.getKey(), mapEntry.getValue()); }) .toArray(PythonLikeObject[]::new)); } public PythonLikeDict<K, V> copy() { return new PythonLikeDict<>(new LinkedMap<>(delegate)); } public PythonLikeDict concatToNew(PythonLikeDict other) { PythonLikeDict result = new PythonLikeDict(); result.putAll(delegate); result.putAll(other); return result; } public PythonLikeDict concatToSelf(PythonLikeDict other) { this.putAll(other); return this; } public PythonInteger getSize() { return PythonInteger.valueOf(delegate.size()); } public DelegatePythonIterator<PythonLikeObject> getKeyIterator() { return new DelegatePythonIterator<>(delegate.keySet().iterator()); } public PythonLikeObject getItemOrError(PythonLikeObject key) { PythonLikeObject out = (PythonLikeObject) delegate.get(key); if (out == null) { throw new KeyError(key.toString()); } return out; } public PythonLikeObject getItemOrNone(PythonLikeObject key) { var out = (PythonLikeObject) delegate.get(key); if (out == null) { return PythonNone.INSTANCE; } return out; } public PythonLikeObject getItemOrDefault(PythonLikeObject key, PythonLikeObject defaultValue) { PythonLikeObject out = (PythonLikeObject) delegate.get(key); if (out == null) { return defaultValue; } return out; } public DictItemView getItems() { return new DictItemView(this); } public DictKeyView getKeyView() { return new DictKeyView(this); } public PythonNone setItem(PythonLikeObject key, PythonLikeObject value) { delegate.put(key, value); return PythonNone.INSTANCE; } public PythonNone removeItemOrError(PythonLikeObject key) { if (delegate.remove(key) == null) { throw new KeyError(key.toString()); } return PythonNone.INSTANCE; } public PythonBoolean isKeyInDict(PythonLikeObject key) { return PythonBoolean.valueOf(delegate.containsKey(key)); } public PythonNone clearDict() { delegate.clear(); return PythonNone.INSTANCE; } public PythonLikeObject popItemOrError(PythonLikeObject key) { var out = (PythonLikeObject) delegate.remove(key); if (out == null) { throw new KeyError(key.toString()); } return out; } public PythonLikeObject popItemOrDefault(PythonLikeObject key, PythonLikeObject defaultValue) { var out = (PythonLikeObject) delegate.remove(key); if (out == null) { return defaultValue; } return out; } public PythonLikeObject popLast() { if (delegate.isEmpty()) { throw new KeyError("popitem(): dictionary is empty"); } var lastKey = (K) delegate.lastKey(); return PythonLikeTuple.fromItems(lastKey, (V) delegate.remove(lastKey)); } public DelegatePythonIterator<PythonLikeObject> reversed() { if (delegate.isEmpty()) { return new DelegatePythonIterator<>(Collections.emptyIterator()); } final var lastKey = (PythonLikeObject) delegate.lastKey(); return new DelegatePythonIterator<>(new Iterator<>() { PythonLikeObject current = lastKey; @Override public boolean hasNext() { return current != null; } @Override public PythonLikeObject next() { var out = current; current = (PythonLikeObject) delegate.previousKey(current); return out; } }); } public PythonLikeObject setIfAbsent(PythonLikeObject key) { var value = (PythonLikeObject) delegate.get(key); if (value != null) { return value; } delegate.put(key, PythonNone.INSTANCE); return PythonNone.INSTANCE; } public PythonLikeObject setIfAbsent(PythonLikeObject key, PythonLikeObject defaultValue) { var value = (V) delegate.get(key); if (value != null) { return value; } delegate.put(key, defaultValue); return defaultValue; } public PythonNone update(PythonLikeDict other) { delegate.putAll(other.delegate); return PythonNone.INSTANCE; } public PythonNone update(PythonLikeObject iterable) { Iterator<List<PythonLikeObject>> iterator = (Iterator<List<PythonLikeObject>>) UnaryDunderBuiltin.ITERATOR.invoke(iterable); while (iterator.hasNext()) { List<PythonLikeObject> keyValuePair = iterator.next(); delegate.put(keyValuePair.get(0), keyValuePair.get(1)); } return PythonNone.INSTANCE; } public DictValueView getValueView() { return new DictValueView(this); } public PythonLikeDict<K, V> binaryOr(PythonLikeDict<K, V> other) { var out = new PythonLikeDict<K, V>(); out.delegate.putAll(delegate); out.delegate.putAll(other.delegate); return out; } public PythonLikeDict<K, V> binaryInplaceOr(PythonLikeDict<K, V> other) { delegate.putAll(other.delegate); return this; } @Override public int size() { return delegate.size(); } @Override public boolean isEmpty() { return delegate.isEmpty(); } @Override public boolean containsKey(Object key) { return delegate.containsKey(key); } @Override public boolean containsValue(Object value) { return delegate.containsValue(value); } @Override public V get(Object key) { return (V) delegate.get(key); } @Override public PythonLikeObject put(PythonLikeObject key, PythonLikeObject value) { return (PythonLikeObject) delegate.put(key, value); } @Override public V remove(Object o) { return (V) delegate.remove(o); } @Override public void putAll(Map<? extends K, ? extends V> map) { delegate.putAll(map); } @Override public void clear() { delegate.clear(); } @Override public Set<K> keySet() { return delegate.keySet(); } @Override public Collection<V> values() { return delegate.values(); } @Override public Set<Entry<K, V>> entrySet() { return delegate.entrySet(); } @Override public Iterator<PythonLikeObject> iterator() { return delegate.keySet().iterator(); } @Override public boolean equals(Object o) { if (o instanceof Map<?, ?> other) { if (other.size() != this.size()) { return false; } return this.entrySet().containsAll(other.entrySet()); } return false; } @Override public int hashCode() { return delegate.hashCode(); } @Override public PythonString $method$__str__() { return PythonString.valueOf(toString()); } @Override public String toString() { return delegate.toString(); } }
0
java-sources/ai/timefold/solver/jpyinterpreter/1.24.0/ai/timefold/jpyinterpreter/types
java-sources/ai/timefold/solver/jpyinterpreter/1.24.0/ai/timefold/jpyinterpreter/types/collections/PythonLikeFrozenSet.java
package ai.timefold.jpyinterpreter.types.collections; import java.util.Collection; import java.util.Collections; import java.util.HashSet; import java.util.Iterator; import java.util.Set; import java.util.function.Predicate; import ai.timefold.jpyinterpreter.PythonBinaryOperator; import ai.timefold.jpyinterpreter.PythonLikeObject; import ai.timefold.jpyinterpreter.PythonOverloadImplementor; import ai.timefold.jpyinterpreter.PythonUnaryOperator; import ai.timefold.jpyinterpreter.builtins.UnaryDunderBuiltin; import ai.timefold.jpyinterpreter.types.AbstractPythonLikeObject; import ai.timefold.jpyinterpreter.types.BuiltinTypes; import ai.timefold.jpyinterpreter.types.PythonLikeType; import ai.timefold.jpyinterpreter.types.errors.ValueError; import ai.timefold.jpyinterpreter.types.numeric.PythonBoolean; import ai.timefold.jpyinterpreter.types.numeric.PythonInteger; // issubclass(set, frozenset) and issubclass(frozenset, set) are both False in Python public class PythonLikeFrozenSet extends AbstractPythonLikeObject implements Set<PythonLikeObject> { public final Set<PythonLikeObject> delegate; static { PythonOverloadImplementor.deferDispatchesFor(PythonLikeFrozenSet::registerMethods); } private static PythonLikeType registerMethods() throws NoSuchMethodException { // Constructor BuiltinTypes.FROZEN_SET_TYPE.setConstructor((positionalArguments, namedArguments, callerInstance) -> { if (positionalArguments.size() == 0) { return new PythonLikeFrozenSet(); } else if (positionalArguments.size() == 1) { return new PythonLikeFrozenSet(positionalArguments.get(0)); } else { throw new ValueError("frozenset expects 0 or 1 arguments, got " + positionalArguments.size()); } }); // Unary BuiltinTypes.FROZEN_SET_TYPE.addUnaryMethod(PythonUnaryOperator.LENGTH, PythonLikeFrozenSet.class.getMethod("getLength")); BuiltinTypes.FROZEN_SET_TYPE.addUnaryMethod(PythonUnaryOperator.ITERATOR, PythonLikeFrozenSet.class.getMethod("getIterator")); // Binary BuiltinTypes.FROZEN_SET_TYPE.addBinaryMethod(PythonBinaryOperator.CONTAINS, PythonLikeFrozenSet.class.getMethod("containsItem", PythonLikeObject.class)); // Other BuiltinTypes.FROZEN_SET_TYPE.addMethod("isdisjoint", PythonLikeFrozenSet.class.getMethod("isDisjoint", PythonLikeSet.class)); BuiltinTypes.FROZEN_SET_TYPE.addMethod("isdisjoint", PythonLikeFrozenSet.class.getMethod("isDisjoint", PythonLikeFrozenSet.class)); BuiltinTypes.FROZEN_SET_TYPE.addMethod("issubset", PythonLikeFrozenSet.class.getMethod("isSubset", PythonLikeSet.class)); BuiltinTypes.FROZEN_SET_TYPE.addBinaryMethod(PythonBinaryOperator.LESS_THAN_OR_EQUAL, PythonLikeFrozenSet.class.getMethod("isSubset", PythonLikeSet.class)); BuiltinTypes.FROZEN_SET_TYPE.addBinaryMethod(PythonBinaryOperator.LESS_THAN, PythonLikeFrozenSet.class.getMethod("isStrictSubset", PythonLikeSet.class)); BuiltinTypes.FROZEN_SET_TYPE.addMethod("issubset", PythonLikeFrozenSet.class.getMethod("isSubset", PythonLikeFrozenSet.class)); BuiltinTypes.FROZEN_SET_TYPE.addBinaryMethod(PythonBinaryOperator.LESS_THAN_OR_EQUAL, PythonLikeFrozenSet.class.getMethod("isSubset", PythonLikeFrozenSet.class)); BuiltinTypes.FROZEN_SET_TYPE.addBinaryMethod(PythonBinaryOperator.LESS_THAN, PythonLikeFrozenSet.class.getMethod("isStrictSubset", PythonLikeFrozenSet.class)); BuiltinTypes.FROZEN_SET_TYPE.addMethod("issuperset", PythonLikeFrozenSet.class.getMethod("isSuperset", PythonLikeSet.class)); BuiltinTypes.FROZEN_SET_TYPE.addBinaryMethod(PythonBinaryOperator.GREATER_THAN_OR_EQUAL, PythonLikeFrozenSet.class.getMethod("isSuperset", PythonLikeSet.class)); BuiltinTypes.FROZEN_SET_TYPE.addBinaryMethod(PythonBinaryOperator.GREATER_THAN, PythonLikeFrozenSet.class.getMethod("isStrictSuperset", PythonLikeSet.class)); BuiltinTypes.FROZEN_SET_TYPE.addMethod("issuperset", PythonLikeFrozenSet.class.getMethod("isSuperset", PythonLikeFrozenSet.class)); BuiltinTypes.FROZEN_SET_TYPE.addBinaryMethod(PythonBinaryOperator.GREATER_THAN_OR_EQUAL, PythonLikeFrozenSet.class.getMethod("isSuperset", PythonLikeFrozenSet.class)); BuiltinTypes.FROZEN_SET_TYPE.addBinaryMethod(PythonBinaryOperator.GREATER_THAN, PythonLikeFrozenSet.class.getMethod("isStrictSuperset", PythonLikeFrozenSet.class)); BuiltinTypes.FROZEN_SET_TYPE.addMethod("union", PythonLikeFrozenSet.class.getMethod("union", PythonLikeSet.class)); BuiltinTypes.FROZEN_SET_TYPE.addMethod("union", PythonLikeFrozenSet.class.getMethod("union", PythonLikeFrozenSet.class)); BuiltinTypes.FROZEN_SET_TYPE.addBinaryMethod(PythonBinaryOperator.OR, PythonLikeFrozenSet.class.getMethod("union", PythonLikeSet.class)); BuiltinTypes.FROZEN_SET_TYPE.addBinaryMethod(PythonBinaryOperator.OR, PythonLikeFrozenSet.class.getMethod("union", PythonLikeFrozenSet.class)); BuiltinTypes.FROZEN_SET_TYPE.addMethod("intersection", PythonLikeFrozenSet.class.getMethod("intersection", PythonLikeSet.class)); BuiltinTypes.FROZEN_SET_TYPE.addMethod("intersection", PythonLikeFrozenSet.class.getMethod("intersection", PythonLikeFrozenSet.class)); BuiltinTypes.FROZEN_SET_TYPE.addBinaryMethod(PythonBinaryOperator.AND, PythonLikeFrozenSet.class.getMethod("intersection", PythonLikeSet.class)); BuiltinTypes.FROZEN_SET_TYPE.addBinaryMethod(PythonBinaryOperator.AND, PythonLikeFrozenSet.class.getMethod("intersection", PythonLikeFrozenSet.class)); BuiltinTypes.FROZEN_SET_TYPE.addMethod("difference", PythonLikeFrozenSet.class.getMethod("difference", PythonLikeSet.class)); BuiltinTypes.FROZEN_SET_TYPE.addMethod("difference", PythonLikeFrozenSet.class.getMethod("difference", PythonLikeFrozenSet.class)); BuiltinTypes.FROZEN_SET_TYPE.addBinaryMethod(PythonBinaryOperator.SUBTRACT, PythonLikeFrozenSet.class.getMethod("difference", PythonLikeSet.class)); BuiltinTypes.FROZEN_SET_TYPE.addBinaryMethod(PythonBinaryOperator.SUBTRACT, PythonLikeFrozenSet.class.getMethod("difference", PythonLikeFrozenSet.class)); BuiltinTypes.FROZEN_SET_TYPE.addMethod("symmetric_difference", PythonLikeFrozenSet.class.getMethod("symmetricDifference", PythonLikeSet.class)); BuiltinTypes.FROZEN_SET_TYPE.addMethod("symmetric_difference", PythonLikeFrozenSet.class.getMethod("symmetricDifference", PythonLikeFrozenSet.class)); BuiltinTypes.FROZEN_SET_TYPE.addBinaryMethod(PythonBinaryOperator.XOR, PythonLikeFrozenSet.class.getMethod("symmetricDifference", PythonLikeSet.class)); BuiltinTypes.FROZEN_SET_TYPE.addBinaryMethod(PythonBinaryOperator.XOR, PythonLikeFrozenSet.class.getMethod("symmetricDifference", PythonLikeFrozenSet.class)); BuiltinTypes.FROZEN_SET_TYPE.addMethod("copy", PythonLikeFrozenSet.class.getMethod("copy")); return BuiltinTypes.FROZEN_SET_TYPE; } private static UnsupportedOperationException modificationError() { return new UnsupportedOperationException("frozenset cannot be modified once created"); } public PythonLikeFrozenSet() { super(BuiltinTypes.FROZEN_SET_TYPE); delegate = new HashSet<>(); } public PythonLikeFrozenSet(PythonLikeObject iterable) { super(BuiltinTypes.FROZEN_SET_TYPE); Iterator<PythonLikeObject> iterator = (Iterator<PythonLikeObject>) UnaryDunderBuiltin.ITERATOR.invoke(iterable); delegate = new HashSet<>(); iterator.forEachRemaining(delegate::add); } // Required for bytecode generation @SuppressWarnings("unused") public void reverseAdd(PythonLikeObject item) { delegate.add(item); } public PythonInteger getLength() { return PythonInteger.valueOf(delegate.size()); } public PythonBoolean containsItem(PythonLikeObject query) { return PythonBoolean.valueOf(delegate.contains(query)); } public DelegatePythonIterator getIterator() { return new DelegatePythonIterator(delegate.iterator()); } public PythonBoolean isDisjoint(PythonLikeSet other) { return PythonBoolean.valueOf(Collections.disjoint(delegate, other.delegate)); } public PythonBoolean isDisjoint(PythonLikeFrozenSet other) { return PythonBoolean.valueOf(Collections.disjoint(delegate, other.delegate)); } public PythonBoolean isSubset(PythonLikeSet other) { return PythonBoolean.valueOf(other.delegate.containsAll(delegate)); } public PythonBoolean isSubset(PythonLikeFrozenSet other) { return PythonBoolean.valueOf(other.delegate.containsAll(delegate)); } public PythonBoolean isStrictSubset(PythonLikeSet other) { return PythonBoolean.valueOf(other.delegate.containsAll(delegate) && !delegate.containsAll(other.delegate)); } public PythonBoolean isStrictSubset(PythonLikeFrozenSet other) { return PythonBoolean.valueOf(other.delegate.containsAll(delegate) && !delegate.containsAll(other.delegate)); } public PythonBoolean isSuperset(PythonLikeSet other) { return PythonBoolean.valueOf(delegate.containsAll(other.delegate)); } public PythonBoolean isSuperset(PythonLikeFrozenSet other) { return PythonBoolean.valueOf(delegate.containsAll(other.delegate)); } public PythonBoolean isStrictSuperset(PythonLikeSet other) { return PythonBoolean.valueOf(delegate.containsAll(other.delegate) && !other.delegate.containsAll(delegate)); } public PythonBoolean isStrictSuperset(PythonLikeFrozenSet other) { return PythonBoolean.valueOf(delegate.containsAll(other.delegate) && !other.delegate.containsAll(delegate)); } public PythonLikeFrozenSet union(PythonLikeSet other) { PythonLikeFrozenSet out = new PythonLikeFrozenSet(); out.delegate.addAll(delegate); out.delegate.addAll(other.delegate); return out; } public PythonLikeFrozenSet union(PythonLikeFrozenSet other) { PythonLikeFrozenSet out = new PythonLikeFrozenSet(); out.delegate.addAll(delegate); out.delegate.addAll(other.delegate); return out; } public PythonLikeFrozenSet intersection(PythonLikeSet other) { PythonLikeFrozenSet out = new PythonLikeFrozenSet(); out.delegate.addAll(delegate); out.delegate.retainAll(other.delegate); return out; } public PythonLikeFrozenSet intersection(PythonLikeFrozenSet other) { PythonLikeFrozenSet out = new PythonLikeFrozenSet(); out.delegate.addAll(delegate); out.delegate.retainAll(other.delegate); return out; } public PythonLikeFrozenSet difference(PythonLikeSet other) { PythonLikeFrozenSet out = new PythonLikeFrozenSet(); out.delegate.addAll(delegate); out.delegate.removeAll(other.delegate); return out; } public PythonLikeFrozenSet difference(PythonLikeFrozenSet other) { PythonLikeFrozenSet out = new PythonLikeFrozenSet(); out.delegate.addAll(delegate); out.delegate.removeAll(other.delegate); return out; } public PythonLikeFrozenSet symmetricDifference(PythonLikeSet other) { PythonLikeFrozenSet out = new PythonLikeFrozenSet(); out.delegate.addAll(delegate); other.delegate.stream() // for each item in other .filter(Predicate.not(out.delegate::add)) // add each item .forEach(out.delegate::remove); // add return false iff item already in set, so this remove // all items in both this and other return out; } public PythonLikeFrozenSet symmetricDifference(PythonLikeFrozenSet other) { PythonLikeFrozenSet out = new PythonLikeFrozenSet(); out.delegate.addAll(delegate); other.delegate.stream() // for each item in other .filter(Predicate.not(out.delegate::add)) // add each item .forEach(out.delegate::remove); // add return false iff item already in set, so this remove // all items in both this and other return out; } public PythonLikeFrozenSet copy() { return this; // frozenset are immutable, thus copy return self to duplicate behavior in Python } @Override public int size() { return delegate.size(); } @Override public boolean isEmpty() { return delegate.isEmpty(); } @Override public boolean contains(Object o) { return delegate.contains(o); } @Override public Iterator<PythonLikeObject> iterator() { return delegate.iterator(); } @Override public Object[] toArray() { return delegate.toArray(); } @Override public <T> T[] toArray(T[] ts) { return delegate.toArray(ts); } @Override public boolean containsAll(Collection<?> collection) { return delegate.containsAll(collection); } @Override public boolean add(PythonLikeObject pythonLikeObject) { throw modificationError(); } @Override public boolean remove(Object o) { throw modificationError(); } @Override public boolean addAll(Collection<? extends PythonLikeObject> collection) { throw modificationError(); } @Override public boolean removeAll(Collection<?> collection) { throw modificationError(); } @Override public boolean retainAll(Collection<?> collection) { throw modificationError(); } @Override public void clear() { throw modificationError(); } @Override public boolean equals(Object o) { if (o instanceof Set<?> other) { if (other.size() != this.size()) { return false; } return containsAll(other) && other.containsAll(this); } return false; } @Override public int hashCode() { return delegate.hashCode(); } @Override public PythonInteger $method$__hash__() { return PythonInteger.valueOf(hashCode()); } }
0
java-sources/ai/timefold/solver/jpyinterpreter/1.24.0/ai/timefold/jpyinterpreter/types
java-sources/ai/timefold/solver/jpyinterpreter/1.24.0/ai/timefold/jpyinterpreter/types/collections/PythonLikeList.java
package ai.timefold.jpyinterpreter.types.collections; import java.math.BigInteger; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.Iterator; import java.util.List; import java.util.ListIterator; import java.util.Objects; import java.util.RandomAccess; import ai.timefold.jpyinterpreter.PythonBinaryOperator; import ai.timefold.jpyinterpreter.PythonLikeObject; import ai.timefold.jpyinterpreter.PythonOverloadImplementor; import ai.timefold.jpyinterpreter.PythonTernaryOperator; import ai.timefold.jpyinterpreter.PythonUnaryOperator; import ai.timefold.jpyinterpreter.builtins.UnaryDunderBuiltin; import ai.timefold.jpyinterpreter.types.AbstractPythonLikeObject; import ai.timefold.jpyinterpreter.types.BuiltinTypes; 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.errors.ValueError; import ai.timefold.jpyinterpreter.types.errors.lookup.IndexError; import ai.timefold.jpyinterpreter.types.numeric.PythonBoolean; import ai.timefold.jpyinterpreter.types.numeric.PythonInteger; import ai.timefold.solver.core.impl.domain.solution.cloner.PlanningCloneable; public class PythonLikeList<T> extends AbstractPythonLikeObject implements List<T>, PlanningCloneable<PythonLikeList<T>>, RandomAccess { final List delegate; private int remainderToAdd; static { PythonOverloadImplementor.deferDispatchesFor(PythonLikeList::registerMethods); } private static PythonLikeType registerMethods() throws NoSuchMethodException { // Constructor BuiltinTypes.LIST_TYPE.setConstructor((positionalArguments, namedArguments, callerInstance) -> { if (positionalArguments.size() == 0) { return new PythonLikeList(); } else if (positionalArguments.size() == 1) { PythonLikeList out = new PythonLikeList(); out.extend(positionalArguments.get(0)); return out; } else { throw new ValueError("list expects 0 or 1 arguments, got " + positionalArguments.size()); } }); // Unary methods BuiltinTypes.LIST_TYPE.addUnaryMethod(PythonUnaryOperator.LENGTH, PythonLikeList.class.getMethod("length")); BuiltinTypes.LIST_TYPE.addUnaryMethod(PythonUnaryOperator.ITERATOR, PythonLikeList.class.getMethod("getIterator")); BuiltinTypes.LIST_TYPE.addUnaryMethod(PythonUnaryOperator.REPRESENTATION, PythonLikeList.class.getMethod("getRepresentation")); // Binary methods BuiltinTypes.LIST_TYPE.addBinaryMethod(PythonBinaryOperator.ADD, PythonLikeList.class.getMethod("concatToNew", PythonLikeList.class)); BuiltinTypes.LIST_TYPE.addBinaryMethod(PythonBinaryOperator.INPLACE_ADD, PythonLikeList.class.getMethod("concatToSelf", PythonLikeList.class)); BuiltinTypes.LIST_TYPE.addBinaryMethod(PythonBinaryOperator.MULTIPLY, PythonLikeList.class.getMethod("multiplyToNew", PythonInteger.class)); BuiltinTypes.LIST_TYPE.addBinaryMethod(PythonBinaryOperator.INPLACE_MULTIPLY, PythonLikeList.class.getMethod("multiplyToSelf", PythonInteger.class)); BuiltinTypes.LIST_TYPE.addBinaryMethod(PythonBinaryOperator.GET_ITEM, PythonLikeList.class.getMethod("getItem", PythonInteger.class)); BuiltinTypes.LIST_TYPE.addBinaryMethod(PythonBinaryOperator.GET_ITEM, PythonLikeList.class.getMethod("getSlice", PythonSlice.class)); BuiltinTypes.LIST_TYPE.addBinaryMethod(PythonBinaryOperator.DELETE_ITEM, PythonLikeList.class.getMethod("deleteItem", PythonInteger.class)); BuiltinTypes.LIST_TYPE.addBinaryMethod(PythonBinaryOperator.DELETE_ITEM, PythonLikeList.class.getMethod("deleteSlice", PythonSlice.class)); BuiltinTypes.LIST_TYPE.addBinaryMethod(PythonBinaryOperator.CONTAINS, PythonLikeList.class.getMethod("containsItem", PythonLikeObject.class)); // Ternary methods BuiltinTypes.LIST_TYPE.addTernaryMethod(PythonTernaryOperator.SET_ITEM, PythonLikeList.class.getMethod("setItem", PythonInteger.class, PythonLikeObject.class)); BuiltinTypes.LIST_TYPE.addTernaryMethod(PythonTernaryOperator.SET_ITEM, PythonLikeList.class.getMethod("setSlice", PythonSlice.class, PythonLikeObject.class)); // Other BuiltinTypes.LIST_TYPE.addMethod("append", PythonLikeList.class.getMethod("append", PythonLikeObject.class)); BuiltinTypes.LIST_TYPE.addMethod("extend", PythonLikeList.class.getMethod("extend", PythonLikeObject.class)); BuiltinTypes.LIST_TYPE.addMethod("insert", PythonLikeList.class.getMethod("insert", PythonInteger.class, PythonLikeObject.class)); BuiltinTypes.LIST_TYPE.addMethod("remove", PythonLikeList.class.getMethod("remove", PythonLikeObject.class)); BuiltinTypes.LIST_TYPE.addMethod("clear", PythonLikeList.class.getMethod("clearList")); BuiltinTypes.LIST_TYPE.addMethod("copy", PythonLikeList.class.getMethod("copy")); BuiltinTypes.LIST_TYPE.addMethod("count", PythonLikeList.class.getMethod("count", PythonLikeObject.class)); BuiltinTypes.LIST_TYPE.addMethod("index", PythonLikeList.class.getMethod("index", PythonLikeObject.class)); BuiltinTypes.LIST_TYPE.addMethod("index", PythonLikeList.class.getMethod("index", PythonLikeObject.class, PythonInteger.class)); BuiltinTypes.LIST_TYPE.addMethod("index", PythonLikeList.class.getMethod("index", PythonLikeObject.class, PythonInteger.class, PythonInteger.class)); BuiltinTypes.LIST_TYPE.addMethod("pop", PythonLikeList.class.getMethod("pop")); BuiltinTypes.LIST_TYPE.addMethod("pop", PythonLikeList.class.getMethod("pop", PythonInteger.class)); BuiltinTypes.LIST_TYPE.addMethod("reverse", PythonLikeList.class.getMethod("reverse")); BuiltinTypes.LIST_TYPE.addMethod("sort", PythonLikeList.class.getMethod("sort")); return BuiltinTypes.LIST_TYPE; } public PythonLikeList() { super(BuiltinTypes.LIST_TYPE); delegate = new ArrayList<>(); remainderToAdd = 0; } public PythonLikeList(int size) { super(BuiltinTypes.LIST_TYPE); delegate = new ArrayList<>(size); remainderToAdd = size; for (int i = 0; i < size; i++) { delegate.add(null); } } public PythonLikeList(List delegate) { super(BuiltinTypes.LIST_TYPE); this.delegate = delegate; remainderToAdd = 0; } @Override public PythonLikeList<T> createNewInstance() { return new PythonLikeList<>(); } // Required for bytecode generation @SuppressWarnings("unused") public void reverseAdd(PythonLikeObject object) { delegate.set(remainderToAdd - 1, object); remainderToAdd--; } public DelegatePythonIterator getIterator() { return new DelegatePythonIterator(delegate.iterator()); } public PythonLikeList copy() { PythonLikeList copy = new PythonLikeList(); copy.addAll(delegate); return copy; } public PythonLikeList concatToNew(PythonLikeList other) { PythonLikeList result = new PythonLikeList(); result.addAll(delegate); result.addAll(other); return result; } public PythonLikeList concatToSelf(PythonLikeList other) { this.addAll(other); return this; } public PythonLikeList multiplyToNew(PythonInteger times) { if (times.value.compareTo(BigInteger.ZERO) <= 0) { return new PythonLikeList(); } PythonLikeList result = new PythonLikeList(); int timesAsInt = times.value.intValueExact(); for (int i = 0; i < timesAsInt; i++) { result.addAll(delegate); } return result; } public PythonLikeList multiplyToSelf(PythonInteger times) { if (times.value.compareTo(BigInteger.ZERO) <= 0) { delegate.clear(); return this; } List<PythonLikeObject> copy = new ArrayList<>(delegate); int timesAsInt = times.value.intValueExact() - 1; for (int i = 0; i < timesAsInt; i++) { delegate.addAll(copy); } return this; } public PythonInteger length() { return PythonInteger.valueOf(delegate.size()); } public PythonInteger index(PythonLikeObject item) { int result = delegate.indexOf(item); if (result != -1) { return PythonInteger.valueOf(result); } else { throw new ValueError(item + " is not in list"); } } public PythonInteger index(PythonLikeObject item, PythonInteger start) { int startAsInt = start.value.intValueExact(); if (startAsInt < 0) { startAsInt = delegate.size() + startAsInt; } List<PythonLikeObject> searchList = delegate.subList(startAsInt, delegate.size()); int result = searchList.indexOf(item); if (result != -1) { return PythonInteger.valueOf(startAsInt + result); } else { throw new ValueError(item + " is not in list"); } } public PythonInteger index(PythonLikeObject item, PythonInteger start, PythonInteger end) { int startAsInt = start.value.intValueExact(); int endAsInt = end.value.intValueExact(); if (startAsInt < 0) { startAsInt = delegate.size() + startAsInt; } if (endAsInt < 0) { endAsInt = delegate.size() + endAsInt; } List<PythonLikeObject> searchList = delegate.subList(startAsInt, endAsInt); int result = searchList.indexOf(item); if (result != -1) { return PythonInteger.valueOf(startAsInt + result); } else { throw new ValueError(item + " is not in list"); } } public PythonLikeObject getItem(PythonInteger index) { int indexAsInt = index.value.intValueExact(); if (indexAsInt < 0) { indexAsInt = delegate.size() + index.value.intValueExact(); } if (indexAsInt < 0 || indexAsInt >= delegate.size()) { throw new IndexError("list index out of range"); } return (PythonLikeObject) delegate.get(indexAsInt); } public PythonLikeList getSlice(PythonSlice slice) { int length = delegate.size(); PythonLikeList out = new PythonLikeList(); slice.iterate(length, (i, processed) -> { out.add(delegate.get(i)); }); return out; } public PythonLikeObject setItem(PythonInteger index, PythonLikeObject value) { int indexAsInt = index.value.intValueExact(); if (indexAsInt < 0) { indexAsInt = delegate.size() + index.value.intValueExact(); } if (indexAsInt < 0 || indexAsInt >= delegate.size()) { throw new IndexError("list index out of range"); } delegate.set(indexAsInt, value); return PythonNone.INSTANCE; } public PythonLikeObject setSlice(PythonSlice slice, PythonLikeObject iterable) { int length = delegate.size(); int start = slice.getStartIndex(length); int stop = slice.getStopIndex(length); int step = slice.getStrideLength(); Iterator<PythonLikeObject> iterator = (Iterator<PythonLikeObject>) UnaryDunderBuiltin.ITERATOR.invoke(iterable); if (step == 1) { delegate.subList(start, stop).clear(); int offset = 0; while (iterator.hasNext()) { PythonLikeObject item = iterator.next(); delegate.add(start + offset, item); offset++; } } else { List<PythonLikeObject> temp = new ArrayList<>(); iterator.forEachRemaining(temp::add); if (temp.size() != slice.getSliceSize(length)) { throw new ValueError("attempt to assign sequence of size " + temp.size() + " to extended slice of size " + slice.getSliceSize(length)); } slice.iterate(length, (i, processed) -> { delegate.set(i, temp.get(processed)); }); } return PythonNone.INSTANCE; } public PythonNone deleteItem(PythonInteger index) { if (index.value.compareTo(BigInteger.ZERO) < 0) { delegate.remove(delegate.size() + index.value.intValueExact()); } else { delegate.remove(index.value.intValueExact()); } return PythonNone.INSTANCE; } public PythonNone deleteSlice(PythonSlice slice) { int length = delegate.size(); int start = slice.getStartIndex(length); int stop = slice.getStopIndex(length); int step = slice.getStrideLength(); if (step == 1) { delegate.subList(start, stop).clear(); } else { if (step > 0) { // need to account for removed items because we are moving up the list, // (as removing items shift elements down) slice.iterate(length, (i, processed) -> { delegate.remove(i - processed); }); } else { // Since we are moving down the list (starting at the higher value), // the elements being removed stay in the same place, so we do not need // to account for processed elements slice.iterate(length, (i, processed) -> { delegate.remove(i); }); } } return PythonNone.INSTANCE; } public PythonNone remove(PythonLikeObject item) { if (!delegate.remove(item)) { throw new ValueError("list.remove(x): x not in list"); } return PythonNone.INSTANCE; } public PythonNone insert(PythonInteger index, PythonLikeObject item) { int indexAsInt = PythonSlice.asIntIndexForLength(index, delegate.size()); if (indexAsInt < 0) { indexAsInt = 0; } if (indexAsInt > delegate.size()) { indexAsInt = delegate.size(); } delegate.add(indexAsInt, item); return PythonNone.INSTANCE; } public PythonLikeObject pop() { if (delegate.isEmpty()) { throw new IndexError("pop from empty list"); } return (PythonLikeObject) delegate.remove(delegate.size() - 1); } public PythonLikeObject pop(PythonInteger index) { if (delegate.isEmpty()) { throw new IndexError("pop from empty list"); } int indexAsInt = index.value.intValueExact(); if (indexAsInt < 0) { indexAsInt = delegate.size() + indexAsInt; } if (indexAsInt >= delegate.size() || indexAsInt < 0) { throw new IndexError("pop index out of range"); } return (PythonLikeObject) delegate.remove(indexAsInt); } public PythonBoolean containsItem(PythonLikeObject item) { return PythonBoolean.valueOf(delegate.contains(item)); } public PythonInteger count(PythonLikeObject search) { long count = 0; for (Object x : delegate) { if (Objects.equals(search, x)) { count++; } } return new PythonInteger(count); } public PythonNone append(PythonLikeObject item) { delegate.add(item); return PythonNone.INSTANCE; } public PythonNone extend(PythonLikeObject item) { if (item instanceof Collection) { delegate.addAll((List) item); } else { Iterator iterator = (Iterator) UnaryDunderBuiltin.ITERATOR.invoke(item); iterator.forEachRemaining(this::add); } return PythonNone.INSTANCE; } public PythonNone reverse() { Collections.reverse(delegate); return PythonNone.INSTANCE; } public PythonNone sort() { Collections.sort(delegate); return PythonNone.INSTANCE; } public PythonNone clearList() { delegate.clear(); return PythonNone.INSTANCE; } public PythonString getRepresentation() { return PythonString.valueOf(toString()); } @Override public int size() { return delegate.size(); } @Override public boolean isEmpty() { return delegate.isEmpty(); } @Override public boolean contains(Object o) { return delegate.contains(o); } @Override public Iterator<T> iterator() { return delegate.iterator(); } @Override public Object[] toArray() { return delegate.toArray(); } public Object[] toArray(Object[] ts) { return delegate.toArray(ts); } @Override public boolean add(Object pythonLikeObject) { return delegate.add(pythonLikeObject); } @Override public boolean remove(Object o) { return delegate.remove(o); } @Override public boolean containsAll(Collection collection) { return delegate.containsAll(collection); } @Override public boolean addAll(Collection collection) { return delegate.addAll(collection); } @Override public boolean addAll(int i, Collection collection) { return delegate.addAll(i, collection); } @Override public boolean removeAll(Collection collection) { return delegate.removeAll(collection); } @Override public boolean retainAll(Collection collection) { return delegate.retainAll(collection); } @Override public void clear() { delegate.clear(); } @Override public T get(int i) { return (T) delegate.get(i); } @Override public Object set(int i, Object pythonLikeObject) { return delegate.set(i, pythonLikeObject); } @Override public void add(int i, Object pythonLikeObject) { delegate.add(i, pythonLikeObject); } @Override public T remove(int i) { return (T) delegate.remove(i); } @Override public int indexOf(Object o) { return delegate.indexOf(o); } @Override public int lastIndexOf(Object o) { return delegate.lastIndexOf(o); } @Override public ListIterator<T> listIterator() { return delegate.listIterator(); } @Override public ListIterator<T> listIterator(int i) { return delegate.listIterator(i); } @Override public List<T> subList(int i, int i1) { return delegate.subList(i, i1); } @Override public PythonString $method$__str__() { return PythonString.valueOf(toString()); } @Override public String toString() { StringBuilder out = new StringBuilder(); out.append('['); for (int i = 0; i < delegate.size() - 1; i++) { out.append(UnaryDunderBuiltin.REPRESENTATION.invoke((PythonLikeObject) delegate.get(i))); out.append(", "); } if (!delegate.isEmpty()) { out.append(UnaryDunderBuiltin.REPRESENTATION.invoke((PythonLikeObject) delegate.get(delegate.size() - 1))); } out.append(']'); return out.toString(); } @Override public boolean equals(Object o) { if (o instanceof List<?> other) { if (other.size() != delegate.size()) { return false; } int itemCount = delegate.size(); for (int i = 0; i < itemCount; i++) { if (!Objects.equals(get(i), other.get(i))) { return false; } } return true; } return false; } @Override public int hashCode() { return delegate.hashCode(); } public List getDelegate() { return delegate; } }
0
java-sources/ai/timefold/solver/jpyinterpreter/1.24.0/ai/timefold/jpyinterpreter/types
java-sources/ai/timefold/solver/jpyinterpreter/1.24.0/ai/timefold/jpyinterpreter/types/collections/PythonLikeSet.java
package ai.timefold.jpyinterpreter.types.collections; import java.util.Collection; import java.util.Collections; import java.util.HashSet; import java.util.Iterator; import java.util.Objects; import java.util.Set; import java.util.function.Predicate; import ai.timefold.jpyinterpreter.PythonBinaryOperator; import ai.timefold.jpyinterpreter.PythonLikeObject; import ai.timefold.jpyinterpreter.PythonOverloadImplementor; import ai.timefold.jpyinterpreter.PythonUnaryOperator; import ai.timefold.jpyinterpreter.builtins.UnaryDunderBuiltin; import ai.timefold.jpyinterpreter.types.AbstractPythonLikeObject; import ai.timefold.jpyinterpreter.types.BuiltinTypes; import ai.timefold.jpyinterpreter.types.PythonLikeType; import ai.timefold.jpyinterpreter.types.PythonNone; import ai.timefold.jpyinterpreter.types.errors.ValueError; import ai.timefold.jpyinterpreter.types.errors.lookup.KeyError; import ai.timefold.jpyinterpreter.types.numeric.PythonBoolean; import ai.timefold.jpyinterpreter.types.numeric.PythonInteger; import ai.timefold.solver.core.impl.domain.solution.cloner.PlanningCloneable; public class PythonLikeSet<T extends PythonLikeObject> extends AbstractPythonLikeObject implements Set<T>, PlanningCloneable<PythonLikeSet<T>> { public final Set delegate; static { PythonOverloadImplementor.deferDispatchesFor(PythonLikeSet::registerMethods); } private static PythonLikeType registerMethods() throws NoSuchMethodException { // Constructor BuiltinTypes.SET_TYPE.setConstructor((positionalArguments, namedArguments, callerInstance) -> { if (positionalArguments.size() == 0) { return new PythonLikeSet(); } else if (positionalArguments.size() == 1) { PythonLikeSet out = new PythonLikeSet(); out.update(positionalArguments.get(0)); return out; } else { throw new ValueError("set expects 0 or 1 arguments, got " + positionalArguments.size()); } }); // Unary BuiltinTypes.SET_TYPE.addUnaryMethod(PythonUnaryOperator.LENGTH, PythonLikeSet.class.getMethod("getLength")); BuiltinTypes.SET_TYPE.addUnaryMethod(PythonUnaryOperator.ITERATOR, PythonLikeSet.class.getMethod("getIterator")); // Binary BuiltinTypes.SET_TYPE.addBinaryMethod(PythonBinaryOperator.CONTAINS, PythonLikeSet.class.getMethod("containsItem", PythonLikeObject.class)); // Other BuiltinTypes.SET_TYPE.addMethod("isdisjoint", PythonLikeSet.class.getMethod("isDisjoint", PythonLikeSet.class)); BuiltinTypes.SET_TYPE.addMethod("isdisjoint", PythonLikeSet.class.getMethod("isDisjoint", PythonLikeFrozenSet.class)); BuiltinTypes.SET_TYPE.addMethod("issubset", PythonLikeSet.class.getMethod("isSubset", PythonLikeSet.class)); BuiltinTypes.SET_TYPE.addBinaryMethod(PythonBinaryOperator.LESS_THAN_OR_EQUAL, PythonLikeSet.class.getMethod("isSubset", PythonLikeSet.class)); BuiltinTypes.SET_TYPE.addBinaryMethod(PythonBinaryOperator.LESS_THAN, PythonLikeSet.class.getMethod("isStrictSubset", PythonLikeSet.class)); BuiltinTypes.SET_TYPE.addMethod("issubset", PythonLikeSet.class.getMethod("isSubset", PythonLikeFrozenSet.class)); BuiltinTypes.SET_TYPE.addBinaryMethod(PythonBinaryOperator.LESS_THAN_OR_EQUAL, PythonLikeSet.class.getMethod("isSubset", PythonLikeFrozenSet.class)); BuiltinTypes.SET_TYPE.addBinaryMethod(PythonBinaryOperator.LESS_THAN, PythonLikeSet.class.getMethod("isStrictSubset", PythonLikeFrozenSet.class)); BuiltinTypes.SET_TYPE.addMethod("issuperset", PythonLikeSet.class.getMethod("isSuperset", PythonLikeSet.class)); BuiltinTypes.SET_TYPE.addBinaryMethod(PythonBinaryOperator.GREATER_THAN_OR_EQUAL, PythonLikeSet.class.getMethod("isSuperset", PythonLikeSet.class)); BuiltinTypes.SET_TYPE.addBinaryMethod(PythonBinaryOperator.GREATER_THAN, PythonLikeSet.class.getMethod("isStrictSuperset", PythonLikeSet.class)); BuiltinTypes.SET_TYPE.addMethod("issuperset", PythonLikeSet.class.getMethod("isSuperset", PythonLikeFrozenSet.class)); BuiltinTypes.SET_TYPE.addBinaryMethod(PythonBinaryOperator.GREATER_THAN_OR_EQUAL, PythonLikeSet.class.getMethod("isSuperset", PythonLikeFrozenSet.class)); BuiltinTypes.SET_TYPE.addBinaryMethod(PythonBinaryOperator.GREATER_THAN, PythonLikeSet.class.getMethod("isStrictSuperset", PythonLikeFrozenSet.class)); BuiltinTypes.SET_TYPE.addMethod("union", PythonLikeSet.class.getMethod("union", PythonLikeSet.class)); BuiltinTypes.SET_TYPE.addMethod("union", PythonLikeSet.class.getMethod("union", PythonLikeFrozenSet.class)); BuiltinTypes.SET_TYPE.addBinaryMethod(PythonBinaryOperator.OR, PythonLikeSet.class.getMethod("union", PythonLikeSet.class)); BuiltinTypes.SET_TYPE.addBinaryMethod(PythonBinaryOperator.OR, PythonLikeSet.class.getMethod("union", PythonLikeFrozenSet.class)); BuiltinTypes.SET_TYPE.addMethod("intersection", PythonLikeSet.class.getMethod("intersection", PythonLikeSet.class)); BuiltinTypes.SET_TYPE.addMethod("intersection", PythonLikeSet.class.getMethod("intersection", PythonLikeFrozenSet.class)); BuiltinTypes.SET_TYPE.addBinaryMethod(PythonBinaryOperator.AND, PythonLikeSet.class.getMethod("intersection", PythonLikeSet.class)); BuiltinTypes.SET_TYPE.addBinaryMethod(PythonBinaryOperator.AND, PythonLikeSet.class.getMethod("intersection", PythonLikeFrozenSet.class)); BuiltinTypes.SET_TYPE.addMethod("difference", PythonLikeSet.class.getMethod("difference", PythonLikeSet.class)); BuiltinTypes.SET_TYPE.addMethod("difference", PythonLikeSet.class.getMethod("difference", PythonLikeFrozenSet.class)); BuiltinTypes.SET_TYPE.addBinaryMethod(PythonBinaryOperator.SUBTRACT, PythonLikeSet.class.getMethod("difference", PythonLikeSet.class)); BuiltinTypes.SET_TYPE.addBinaryMethod(PythonBinaryOperator.SUBTRACT, PythonLikeSet.class.getMethod("difference", PythonLikeFrozenSet.class)); BuiltinTypes.SET_TYPE.addMethod("symmetric_difference", PythonLikeSet.class.getMethod("symmetricDifference", PythonLikeSet.class)); BuiltinTypes.SET_TYPE.addMethod("symmetric_difference", PythonLikeSet.class.getMethod("symmetricDifference", PythonLikeFrozenSet.class)); BuiltinTypes.SET_TYPE.addBinaryMethod(PythonBinaryOperator.XOR, PythonLikeSet.class.getMethod("symmetricDifference", PythonLikeSet.class)); BuiltinTypes.SET_TYPE.addBinaryMethod(PythonBinaryOperator.XOR, PythonLikeSet.class.getMethod("symmetricDifference", PythonLikeFrozenSet.class)); BuiltinTypes.SET_TYPE.addMethod("update", PythonLikeSet.class.getMethod("update", PythonLikeObject.class)); BuiltinTypes.SET_TYPE.addBinaryMethod(PythonBinaryOperator.INPLACE_OR, PythonLikeSet.class.getMethod("updateWithResult", PythonLikeObject.class)); BuiltinTypes.SET_TYPE.addMethod("intersection_update", PythonLikeSet.class.getMethod("intersectionUpdate", PythonLikeObject.class)); BuiltinTypes.SET_TYPE.addBinaryMethod(PythonBinaryOperator.INPLACE_AND, PythonLikeSet.class.getMethod("intersectionUpdateWithResult", PythonLikeObject.class)); BuiltinTypes.SET_TYPE.addMethod("difference_update", PythonLikeSet.class.getMethod("differenceUpdate", PythonLikeObject.class)); BuiltinTypes.SET_TYPE.addBinaryMethod(PythonBinaryOperator.INPLACE_SUBTRACT, PythonLikeSet.class.getMethod("differenceUpdateWithResult", PythonLikeObject.class)); BuiltinTypes.SET_TYPE.addMethod("symmetric_difference_update", PythonLikeSet.class.getMethod("symmetricDifferenceUpdate", PythonLikeObject.class)); BuiltinTypes.SET_TYPE.addBinaryMethod(PythonBinaryOperator.INPLACE_XOR, PythonLikeSet.class.getMethod("symmetricDifferenceUpdateWithResult", PythonLikeObject.class)); BuiltinTypes.SET_TYPE.addMethod("add", PythonLikeSet.class.getMethod("addItem", PythonLikeObject.class)); BuiltinTypes.SET_TYPE.addMethod("remove", PythonLikeSet.class.getMethod("removeOrError", PythonLikeObject.class)); BuiltinTypes.SET_TYPE.addMethod("discard", PythonLikeSet.class.getMethod("discard", PythonLikeObject.class)); BuiltinTypes.SET_TYPE.addMethod("pop", PythonLikeSet.class.getMethod("pop")); BuiltinTypes.SET_TYPE.addMethod("clear", PythonLikeSet.class.getMethod("clearSet")); BuiltinTypes.SET_TYPE.addMethod("copy", PythonLikeSet.class.getMethod("copy")); return BuiltinTypes.SET_TYPE; } public PythonLikeSet() { super(BuiltinTypes.SET_TYPE); delegate = new HashSet<>(); } public PythonLikeSet(int size) { super(BuiltinTypes.SET_TYPE); delegate = new HashSet<>(size); } @Override public PythonLikeSet<T> createNewInstance() { return new PythonLikeSet<>(); } // Required for bytecode generation @SuppressWarnings("unused") public void reverseAdd(T item) { delegate.add(item); } public PythonBoolean isDisjoint(PythonLikeSet other) { return PythonBoolean.valueOf(Collections.disjoint(delegate, other.delegate)); } public PythonBoolean isDisjoint(PythonLikeFrozenSet other) { return PythonBoolean.valueOf(Collections.disjoint(delegate, other.delegate)); } public PythonBoolean isSubset(PythonLikeSet other) { return PythonBoolean.valueOf(other.delegate.containsAll(delegate)); } public PythonBoolean isSubset(PythonLikeFrozenSet other) { return PythonBoolean.valueOf(other.delegate.containsAll(delegate)); } public PythonBoolean isStrictSubset(PythonLikeSet other) { return PythonBoolean.valueOf(other.delegate.containsAll(delegate) && !delegate.containsAll(other.delegate)); } public PythonBoolean isStrictSubset(PythonLikeFrozenSet other) { return PythonBoolean.valueOf(other.delegate.containsAll(delegate) && !delegate.containsAll(other.delegate)); } public PythonBoolean isSuperset(PythonLikeSet other) { return PythonBoolean.valueOf(delegate.containsAll(other.delegate)); } public PythonBoolean isSuperset(PythonLikeFrozenSet other) { return PythonBoolean.valueOf(delegate.containsAll(other.delegate)); } public PythonBoolean isStrictSuperset(PythonLikeSet other) { return PythonBoolean.valueOf(delegate.containsAll(other.delegate) && !other.delegate.containsAll(delegate)); } public PythonBoolean isStrictSuperset(PythonLikeFrozenSet other) { return PythonBoolean.valueOf(delegate.containsAll(other.delegate) && !other.delegate.containsAll(delegate)); } public PythonLikeSet<T> union(PythonLikeSet<T> other) { var out = new PythonLikeSet<T>(); out.delegate.addAll(delegate); out.delegate.addAll(other.delegate); return out; } public PythonLikeSet<T> union(PythonLikeFrozenSet other) { var out = new PythonLikeSet<T>(); out.delegate.addAll(delegate); out.delegate.addAll(other.delegate); return out; } public PythonLikeSet<T> intersection(PythonLikeSet<T> other) { var out = new PythonLikeSet<T>(); out.delegate.addAll(delegate); out.delegate.retainAll(other.delegate); return out; } public PythonLikeSet<T> intersection(PythonLikeFrozenSet other) { var out = new PythonLikeSet<T>(); out.delegate.addAll(delegate); out.delegate.retainAll(other.delegate); return out; } public PythonLikeSet difference(PythonLikeSet other) { PythonLikeSet out = new PythonLikeSet(); out.delegate.addAll(delegate); out.delegate.removeAll(other.delegate); return out; } public PythonLikeSet difference(PythonLikeFrozenSet other) { PythonLikeSet out = new PythonLikeSet(); out.delegate.addAll(delegate); out.delegate.removeAll(other.delegate); return out; } public PythonLikeSet symmetricDifference(PythonLikeSet other) { PythonLikeSet out = new PythonLikeSet(); out.delegate.addAll(delegate); other.delegate.stream() // for each item in other .filter(Predicate.not(out.delegate::add)) // add each item .forEach(out.delegate::remove); // add return false iff item already in set, so this remove // all items in both this and other return out; } public PythonLikeSet<T> symmetricDifference(PythonLikeFrozenSet other) { var out = new PythonLikeSet<T>(); out.delegate.addAll(delegate); other.delegate.stream() // for each item in other .filter(Predicate.not(item -> out.delegate.add(item))) // add each item .forEach(out.delegate::remove); // add return false iff item already in set, so this remove // all items in both this and other return out; } public PythonLikeSet<T> updateWithResult(PythonLikeObject collection) { if (collection instanceof Collection) { delegate.addAll((Collection<? extends PythonLikeObject>) collection); } else { Iterator<PythonLikeObject> iterator = (Iterator<PythonLikeObject>) UnaryDunderBuiltin.ITERATOR.invoke(collection); iterator.forEachRemaining(delegate::add); } return this; } public PythonNone update(PythonLikeObject collection) { updateWithResult(collection); return PythonNone.INSTANCE; } public PythonLikeSet intersectionUpdateWithResult(PythonLikeObject collection) { if (collection instanceof Collection) { delegate.retainAll((Collection<? extends PythonLikeObject>) collection); } else { Iterator<PythonLikeObject> iterator = (Iterator<PythonLikeObject>) UnaryDunderBuiltin.ITERATOR.invoke(collection); Set<PythonLikeObject> temp = new HashSet<>(); iterator.forEachRemaining(temp::add); delegate.retainAll(temp); } return this; } public PythonNone intersectionUpdate(PythonLikeObject collection) { intersectionUpdateWithResult(collection); return PythonNone.INSTANCE; } public PythonLikeSet differenceUpdateWithResult(PythonLikeObject collection) { if (collection instanceof Collection) { delegate.removeAll((Collection<? extends PythonLikeObject>) collection); } else { Iterator<PythonLikeObject> iterator = (Iterator<PythonLikeObject>) UnaryDunderBuiltin.ITERATOR.invoke(collection); iterator.forEachRemaining(delegate::remove); } return this; } public PythonNone differenceUpdate(PythonLikeObject collection) { differenceUpdateWithResult(collection); return PythonNone.INSTANCE; } public PythonLikeSet symmetricDifferenceUpdateWithResult(PythonLikeObject collection) { if (collection instanceof Collection) { Collection<PythonLikeObject> otherSet = (Collection<PythonLikeObject>) collection; Set<PythonLikeObject> temp = new HashSet<>(delegate); temp.retainAll(otherSet); delegate.addAll(otherSet); delegate.removeAll(temp); } else { Iterator<PythonLikeObject> iterator = (Iterator<PythonLikeObject>) UnaryDunderBuiltin.ITERATOR.invoke(collection); Set<PythonLikeObject> encountered = new HashSet<>(delegate); while (iterator.hasNext()) { PythonLikeObject item = iterator.next(); if (encountered.contains(item)) { continue; } if (delegate.contains(item)) { delegate.remove(item); } else { delegate.add(item); } encountered.add(item); } } return this; } public PythonNone symmetricDifferenceUpdate(PythonLikeObject collection) { symmetricDifferenceUpdateWithResult(collection); return PythonNone.INSTANCE; } public PythonNone addItem(PythonLikeObject pythonLikeObject) { delegate.add(pythonLikeObject); return PythonNone.INSTANCE; } public PythonNone discard(PythonLikeObject object) { delegate.remove(object); return PythonNone.INSTANCE; } public PythonNone removeOrError(PythonLikeObject object) { if (!delegate.remove(object)) { throw new KeyError("set (" + this + ") does not contain the specified element (" + object + ")."); } return PythonNone.INSTANCE; } public PythonLikeObject pop() { if (delegate.isEmpty()) { throw new KeyError("set (" + this + ") is empty."); } PythonLikeObject out = (PythonLikeObject) delegate.iterator().next(); delegate.remove(out); return out; } public PythonLikeSet copy() { PythonLikeSet copy = new PythonLikeSet(); copy.addAll(delegate); return copy; } public PythonNone clearSet() { delegate.clear(); return PythonNone.INSTANCE; } public PythonInteger getLength() { return PythonInteger.valueOf(delegate.size()); } public PythonBoolean containsItem(PythonLikeObject query) { return PythonBoolean.valueOf(delegate.contains(query)); } // Java Set methods @Override public int size() { return delegate.size(); } @Override public boolean isEmpty() { return delegate.isEmpty(); } @Override public boolean contains(Object o) { return delegate.contains(o); } @Override public Iterator<T> iterator() { return delegate.iterator(); } public DelegatePythonIterator getIterator() { return new DelegatePythonIterator(delegate.iterator()); } @Override public Object[] toArray() { return delegate.toArray(); } @Override public <T> T[] toArray(T[] ts) { return (T[]) delegate.toArray(ts); } @Override public boolean add(PythonLikeObject pythonLikeObject) { return delegate.add(pythonLikeObject); } @Override public boolean remove(Object o) { return delegate.remove(o); } @Override public boolean containsAll(Collection<?> collection) { return delegate.containsAll(collection); } @Override public boolean addAll(Collection<? extends T> collection) { return delegate.addAll(collection); } @Override public boolean removeAll(Collection<?> collection) { return delegate.removeAll(collection); } @Override public boolean retainAll(Collection<?> collection) { return delegate.retainAll(collection); } @Override public void clear() { delegate.clear(); } @Override public boolean equals(Object o) { if (o instanceof Set<?> other) { if (other.size() != this.size()) { return false; } return containsAll(other) && other.containsAll(this); } return false; } @Override public int hashCode() { return Objects.hash(delegate); } }
0
java-sources/ai/timefold/solver/jpyinterpreter/1.24.0/ai/timefold/jpyinterpreter/types
java-sources/ai/timefold/solver/jpyinterpreter/1.24.0/ai/timefold/jpyinterpreter/types/collections/PythonLikeTuple.java
package ai.timefold.jpyinterpreter.types.collections; import java.math.BigInteger; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.Iterator; import java.util.List; import java.util.ListIterator; import java.util.Objects; import java.util.RandomAccess; import ai.timefold.jpyinterpreter.PythonBinaryOperator; import ai.timefold.jpyinterpreter.PythonLikeObject; import ai.timefold.jpyinterpreter.PythonOverloadImplementor; import ai.timefold.jpyinterpreter.PythonUnaryOperator; import ai.timefold.jpyinterpreter.builtins.UnaryDunderBuiltin; import ai.timefold.jpyinterpreter.types.AbstractPythonLikeObject; import ai.timefold.jpyinterpreter.types.BuiltinTypes; import ai.timefold.jpyinterpreter.types.PythonLikeComparable; import ai.timefold.jpyinterpreter.types.PythonLikeType; import ai.timefold.jpyinterpreter.types.PythonSlice; import ai.timefold.jpyinterpreter.types.PythonString; import ai.timefold.jpyinterpreter.types.errors.TypeError; import ai.timefold.jpyinterpreter.types.errors.ValueError; import ai.timefold.jpyinterpreter.types.errors.lookup.IndexError; import ai.timefold.jpyinterpreter.types.numeric.PythonBoolean; import ai.timefold.jpyinterpreter.types.numeric.PythonInteger; import ai.timefold.solver.core.impl.domain.solution.cloner.PlanningCloneable; import ai.timefold.solver.core.impl.domain.solution.cloner.PlanningImmutable; public class PythonLikeTuple<T extends PythonLikeObject> extends AbstractPythonLikeObject implements List<T>, PlanningCloneable<PythonLikeTuple<T>>, PythonLikeComparable<PythonLikeTuple>, PlanningImmutable, RandomAccess { public static PythonLikeTuple EMPTY = PythonLikeTuple.fromList(Collections.emptyList()); final List delegate; private int remainderToAdd; static { PythonOverloadImplementor.deferDispatchesFor(PythonLikeTuple::registerMethods); } private static PythonLikeType registerMethods() throws NoSuchMethodException { // Constructor BuiltinTypes.TUPLE_TYPE.setConstructor((positionalArguments, namedArguments, callerInstance) -> { if (positionalArguments.isEmpty()) { return new PythonLikeTuple(); } else if (positionalArguments.size() == 1) { PythonLikeTuple out = new PythonLikeTuple(); PythonLikeObject iterable = positionalArguments.get(0); if (iterable instanceof Collection) { out.delegate.addAll((Collection<? extends PythonLikeObject>) iterable); } else { Iterator<PythonLikeObject> iterator = (Iterator<PythonLikeObject>) UnaryDunderBuiltin.ITERATOR.invoke(iterable); iterator.forEachRemaining(out.delegate::add); } return out; } else { throw new ValueError("tuple takes 0 or 1 arguments, got " + positionalArguments.size()); } }); // Unary BuiltinTypes.TUPLE_TYPE.addUnaryMethod(PythonUnaryOperator.LENGTH, PythonLikeTuple.class.getMethod("getLength")); BuiltinTypes.TUPLE_TYPE.addUnaryMethod(PythonUnaryOperator.ITERATOR, PythonLikeTuple.class.getMethod("getIterator")); // Binary BuiltinTypes.TUPLE_TYPE.addBinaryMethod(PythonBinaryOperator.ADD, PythonLikeTuple.class.getMethod("concatToNew", PythonLikeTuple.class)); BuiltinTypes.TUPLE_TYPE.addBinaryMethod(PythonBinaryOperator.MULTIPLY, PythonLikeTuple.class.getMethod("multiplyToNew", PythonInteger.class)); BuiltinTypes.TUPLE_TYPE.addBinaryMethod(PythonBinaryOperator.GET_ITEM, PythonLikeTuple.class.getMethod("getItem", PythonInteger.class)); BuiltinTypes.TUPLE_TYPE.addBinaryMethod(PythonBinaryOperator.GET_ITEM, PythonLikeTuple.class.getMethod("getSlice", PythonSlice.class)); BuiltinTypes.TUPLE_TYPE.addBinaryMethod(PythonBinaryOperator.CONTAINS, PythonLikeTuple.class.getMethod("containsItem", PythonLikeObject.class)); // Comparisons PythonLikeComparable.setup(BuiltinTypes.TUPLE_TYPE); // Other BuiltinTypes.TUPLE_TYPE.addMethod("index", PythonLikeTuple.class.getMethod("index", PythonLikeObject.class)); BuiltinTypes.TUPLE_TYPE.addMethod("index", PythonLikeTuple.class.getMethod("index", PythonLikeObject.class, PythonInteger.class)); BuiltinTypes.TUPLE_TYPE.addMethod("index", PythonLikeTuple.class.getMethod("index", PythonLikeObject.class, PythonInteger.class, PythonInteger.class)); BuiltinTypes.TUPLE_TYPE.addMethod("count", PythonLikeTuple.class.getMethod("count", PythonLikeObject.class)); return BuiltinTypes.TUPLE_TYPE; } public PythonLikeTuple() { super(BuiltinTypes.TUPLE_TYPE); delegate = new ArrayList<>(); remainderToAdd = 0; } public PythonLikeTuple(int size) { super(BuiltinTypes.TUPLE_TYPE); delegate = new ArrayList<>(size); remainderToAdd = size; for (int i = 0; i < size; i++) { delegate.add(null); } } @Override public PythonLikeTuple<T> createNewInstance() { return new PythonLikeTuple<>(); } public static <T extends PythonLikeObject> PythonLikeTuple<T> fromItems(T... items) { PythonLikeTuple<T> result = new PythonLikeTuple<>(); Collections.addAll(result, items); return result; } public static <T extends PythonLikeObject> PythonLikeTuple<T> fromList(List<T> other) { PythonLikeTuple<T> result = new PythonLikeTuple<>(); result.addAll(other); return result; } public PythonLikeTuple concatToNew(PythonLikeTuple other) { if (delegate.isEmpty()) { return other; } else if (other.delegate.isEmpty()) { return this; } PythonLikeTuple result = new PythonLikeTuple(); result.addAll(delegate); result.addAll(other); return result; } public PythonLikeTuple multiplyToNew(PythonInteger times) { if (times.value.compareTo(BigInteger.ZERO) <= 0) { if (delegate.isEmpty()) { return this; } return new PythonLikeTuple(); } if (times.value.equals(BigInteger.ONE)) { return this; } PythonLikeTuple result = new PythonLikeTuple(); int timesAsInt = times.value.intValueExact(); for (int i = 0; i < timesAsInt; i++) { result.addAll(delegate); } return result; } public PythonInteger getLength() { return PythonInteger.valueOf(delegate.size()); } public PythonBoolean containsItem(PythonLikeObject item) { return PythonBoolean.valueOf(delegate.contains(item)); } public DelegatePythonIterator<T> getIterator() { return new DelegatePythonIterator<T>(delegate.iterator()); } public DelegatePythonIterator getReversedIterator() { final ListIterator<PythonLikeObject> listIterator = delegate.listIterator(delegate.size()); return new DelegatePythonIterator<>(new Iterator<>() { @Override public boolean hasNext() { return listIterator.hasPrevious(); } @Override public Object next() { return listIterator.previous(); } }); } public PythonLikeObject getItem(PythonInteger index) { int indexAsInt = index.value.intValueExact(); if (indexAsInt < 0) { indexAsInt = delegate.size() + index.value.intValueExact(); } if (indexAsInt < 0 || indexAsInt >= delegate.size()) { throw new IndexError("list index out of range"); } return (PythonLikeObject) delegate.get(indexAsInt); } public PythonLikeTuple getSlice(PythonSlice slice) { int length = delegate.size(); PythonLikeTuple out = new PythonLikeTuple(); slice.iterate(length, (i, processed) -> { out.add((PythonLikeObject) delegate.get(i)); }); return out; } public PythonInteger count(PythonLikeObject search) { long count = 0; for (var x : delegate) { if (Objects.equals(search, x)) { count++; } } return new PythonInteger(count); } public PythonInteger index(PythonLikeObject item) { int result = delegate.indexOf(item); if (result != -1) { return PythonInteger.valueOf(result); } else { throw new ValueError(item + " is not in list"); } } public PythonInteger index(PythonLikeObject item, PythonInteger start) { int startAsInt = start.value.intValueExact(); if (startAsInt < 0) { startAsInt = delegate.size() + startAsInt; } List<PythonLikeObject> searchList = delegate.subList(startAsInt, delegate.size()); int result = searchList.indexOf(item); if (result != -1) { return PythonInteger.valueOf(startAsInt + result); } else { throw new ValueError(item + " is not in list"); } } public PythonInteger index(PythonLikeObject item, PythonInteger start, PythonInteger end) { int startAsInt = start.value.intValueExact(); int endAsInt = end.value.intValueExact(); if (startAsInt < 0) { startAsInt = delegate.size() + startAsInt; } if (endAsInt < 0) { endAsInt = delegate.size() + endAsInt; } List<PythonLikeObject> searchList = delegate.subList(startAsInt, endAsInt); int result = searchList.indexOf(item); if (result != -1) { return PythonInteger.valueOf(startAsInt + result); } else { throw new ValueError(item + " is not in list"); } } public void reverseAdd(PythonLikeObject object) { delegate.set(remainderToAdd - 1, object); remainderToAdd--; } @Override public int size() { return delegate.size(); } @Override public boolean isEmpty() { return delegate.isEmpty(); } @Override public boolean contains(Object o) { return delegate.contains(o); } @Override public Iterator<T> iterator() { return delegate.iterator(); } @Override public Object[] toArray() { return delegate.toArray(); } @Override public <T> T[] toArray(T[] ts) { return (T[]) delegate.toArray(ts); } @Override public boolean add(PythonLikeObject pythonLikeObject) { return delegate.add(pythonLikeObject); } @Override public boolean remove(Object o) { return delegate.remove(o); } @Override public boolean containsAll(Collection<?> collection) { return delegate.containsAll(collection); } @Override public boolean addAll(Collection<? extends T> collection) { return delegate.addAll(collection); } @Override public boolean addAll(int i, Collection<? extends T> collection) { return delegate.addAll(i, collection); } @Override public boolean removeAll(Collection<?> collection) { return delegate.removeAll(collection); } @Override public boolean retainAll(Collection<?> collection) { return delegate.retainAll(collection); } @Override public void clear() { delegate.clear(); } @Override public T get(int i) { return (T) delegate.get(i); } @Override public T set(int i, T pythonLikeObject) { return (T) delegate.set(i, pythonLikeObject); } @Override public void add(int i, PythonLikeObject pythonLikeObject) { delegate.add(i, pythonLikeObject); } @Override public T remove(int i) { return (T) delegate.remove(i); } @Override public int indexOf(Object o) { return delegate.indexOf(o); } @Override public int lastIndexOf(Object o) { return delegate.lastIndexOf(o); } @Override public ListIterator<T> listIterator() { return delegate.listIterator(); } @Override public ListIterator<T> listIterator(int i) { return delegate.listIterator(i); } @Override public List<T> subList(int i, int i1) { return delegate.subList(i, i1); } @Override public boolean equals(Object o) { if (o instanceof List<?> other) { if (other.size() != this.size()) { return false; } int itemCount = size(); for (int i = 0; i < itemCount; i++) { if (!Objects.equals(get(i), other.get(i))) { return false; } } return true; } return false; } @Override @SuppressWarnings({ "rawtypes", "unchecked" }) public int compareTo(PythonLikeTuple other) { int ownLength = delegate.size(); int otherLength = other.size(); int commonLength = Math.min(ownLength, otherLength); for (int i = 0; i < commonLength; i++) { Object ownItem = delegate.get(i); Object otherItem = other.delegate.get(i); if (ownItem instanceof Comparable ownComparable) { if (otherItem instanceof Comparable otherComparable) { int result = ownComparable.compareTo(otherComparable); if (result != 0) { return result; } } else { throw new TypeError("Tuple %s does not support comparisons since item (%s) at index (%d) is not comparable." .formatted(other, otherItem, i)); } } else { throw new TypeError("Tuple %s does not support comparisons since item (%s) at index (%d) is not comparable." .formatted(this, ownItem, i)); } } return ownLength - otherLength; } @Override public int hashCode() { return delegate.hashCode(); } @Override public PythonInteger $method$__hash__() { return PythonInteger.valueOf(hashCode()); } @Override public PythonString $method$__str__() { return PythonString.valueOf(toString()); } @Override public String toString() { return delegate.toString(); } }
0
java-sources/ai/timefold/solver/jpyinterpreter/1.24.0/ai/timefold/jpyinterpreter/types/collections
java-sources/ai/timefold/solver/jpyinterpreter/1.24.0/ai/timefold/jpyinterpreter/types/collections/view/DictItemView.java
package ai.timefold.jpyinterpreter.types.collections.view; import java.util.AbstractMap; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Map; import java.util.Set; import java.util.function.Predicate; import ai.timefold.jpyinterpreter.PythonBinaryOperator; import ai.timefold.jpyinterpreter.PythonLikeObject; import ai.timefold.jpyinterpreter.PythonOverloadImplementor; import ai.timefold.jpyinterpreter.PythonUnaryOperator; import ai.timefold.jpyinterpreter.builtins.UnaryDunderBuiltin; import ai.timefold.jpyinterpreter.types.AbstractPythonLikeObject; import ai.timefold.jpyinterpreter.types.BuiltinTypes; import ai.timefold.jpyinterpreter.types.PythonLikeType; import ai.timefold.jpyinterpreter.types.PythonString; import ai.timefold.jpyinterpreter.types.collections.DelegatePythonIterator; import ai.timefold.jpyinterpreter.types.collections.PythonLikeDict; import ai.timefold.jpyinterpreter.types.collections.PythonLikeSet; import ai.timefold.jpyinterpreter.types.collections.PythonLikeTuple; import ai.timefold.jpyinterpreter.types.numeric.PythonBoolean; import ai.timefold.jpyinterpreter.types.numeric.PythonInteger; import ai.timefold.jpyinterpreter.util.IteratorUtils; public class DictItemView extends AbstractPythonLikeObject { public final static PythonLikeType $TYPE = BuiltinTypes.DICT_ITEM_VIEW_TYPE; final PythonLikeDict<PythonLikeObject, PythonLikeObject> mapping; final Set<Map.Entry<PythonLikeObject, PythonLikeObject>> entrySet; static { PythonOverloadImplementor.deferDispatchesFor(DictItemView::registerMethods); } private static PythonLikeType registerMethods() throws NoSuchMethodException { // Unary BuiltinTypes.DICT_ITEM_VIEW_TYPE.addUnaryMethod(PythonUnaryOperator.LENGTH, DictItemView.class.getMethod("getItemsSize")); BuiltinTypes.DICT_ITEM_VIEW_TYPE.addUnaryMethod(PythonUnaryOperator.ITERATOR, DictItemView.class.getMethod("getItemsIterator")); BuiltinTypes.DICT_ITEM_VIEW_TYPE.addUnaryMethod(PythonUnaryOperator.REVERSED, DictItemView.class.getMethod("getReversedItemIterator")); BuiltinTypes.DICT_ITEM_VIEW_TYPE.addUnaryMethod(PythonUnaryOperator.AS_STRING, DictItemView.class.getMethod("toRepresentation")); BuiltinTypes.DICT_ITEM_VIEW_TYPE.addUnaryMethod(PythonUnaryOperator.REPRESENTATION, DictItemView.class.getMethod("toRepresentation")); // Binary BuiltinTypes.DICT_ITEM_VIEW_TYPE.addBinaryMethod(PythonBinaryOperator.CONTAINS, DictItemView.class.getMethod("containsItem", PythonLikeObject.class)); // Set methods BuiltinTypes.DICT_ITEM_VIEW_TYPE.addMethod("isdisjoint", DictItemView.class.getMethod("isDisjoint", DictItemView.class)); BuiltinTypes.DICT_ITEM_VIEW_TYPE.addBinaryMethod(PythonBinaryOperator.LESS_THAN_OR_EQUAL, DictItemView.class.getMethod("isSubset", DictItemView.class)); BuiltinTypes.DICT_ITEM_VIEW_TYPE.addBinaryMethod(PythonBinaryOperator.LESS_THAN, DictItemView.class.getMethod("isStrictSubset", DictItemView.class)); BuiltinTypes.DICT_ITEM_VIEW_TYPE.addBinaryMethod(PythonBinaryOperator.GREATER_THAN_OR_EQUAL, DictItemView.class.getMethod("isSuperset", DictItemView.class)); BuiltinTypes.DICT_ITEM_VIEW_TYPE.addBinaryMethod(PythonBinaryOperator.GREATER_THAN, DictItemView.class.getMethod("isStrictSuperset", DictItemView.class)); BuiltinTypes.DICT_ITEM_VIEW_TYPE.addBinaryMethod(PythonBinaryOperator.OR, DictItemView.class.getMethod("union", DictItemView.class)); BuiltinTypes.DICT_ITEM_VIEW_TYPE.addBinaryMethod(PythonBinaryOperator.AND, DictItemView.class.getMethod("intersection", DictItemView.class)); BuiltinTypes.DICT_ITEM_VIEW_TYPE.addBinaryMethod(PythonBinaryOperator.SUBTRACT, DictItemView.class.getMethod("difference", DictItemView.class)); BuiltinTypes.DICT_ITEM_VIEW_TYPE.addBinaryMethod(PythonBinaryOperator.XOR, DictItemView.class.getMethod("symmetricDifference", DictItemView.class)); return BuiltinTypes.DICT_ITEM_VIEW_TYPE; } public DictItemView(PythonLikeDict mapping) { super(BuiltinTypes.DICT_ITEM_VIEW_TYPE); this.mapping = mapping; this.entrySet = mapping.delegate.entrySet(); $setAttribute("mapping", mapping); } private List<PythonLikeObject> getEntriesAsTuples() { List<PythonLikeObject> out = new ArrayList<>(entrySet.size()); for (Map.Entry<PythonLikeObject, PythonLikeObject> entry : entrySet) { out.add(PythonLikeTuple.fromItems(entry.getKey(), entry.getValue())); } return out; } public PythonInteger getItemsSize() { return PythonInteger.valueOf(entrySet.size()); } public DelegatePythonIterator<PythonLikeObject> getItemsIterator() { return new DelegatePythonIterator<>( IteratorUtils.iteratorMap(entrySet.iterator(), entry -> PythonLikeTuple.fromItems(entry.getKey(), entry.getValue()))); } public PythonBoolean containsItem(PythonLikeObject o) { if (o instanceof PythonLikeTuple) { PythonLikeTuple item = (PythonLikeTuple) o; if (item.size() != 2) { return PythonBoolean.FALSE; } Map.Entry<PythonLikeObject, PythonLikeObject> entry = new AbstractMap.SimpleEntry<>(item.get(0), item.get(1)); return PythonBoolean.valueOf(entrySet.contains(entry)); } else { return PythonBoolean.FALSE; } } public DelegatePythonIterator<PythonLikeObject> getReversedItemIterator() { return new DelegatePythonIterator<>(IteratorUtils.iteratorMap(mapping.reversed(), key -> PythonLikeTuple.fromItems(key, (PythonLikeObject) mapping.delegate.get(key)))); } public PythonBoolean isDisjoint(DictItemView other) { return PythonBoolean.valueOf(Collections.disjoint(entrySet, other.entrySet)); } public PythonBoolean isSubset(DictItemView other) { return PythonBoolean.valueOf(other.entrySet.containsAll(entrySet)); } public PythonBoolean isStrictSubset(DictItemView other) { return PythonBoolean.valueOf(other.entrySet.containsAll(entrySet) && !entrySet.containsAll(other.entrySet)); } public PythonBoolean isSuperset(DictItemView other) { return PythonBoolean.valueOf(entrySet.containsAll(other.entrySet)); } public PythonBoolean isStrictSuperset(DictItemView other) { return PythonBoolean.valueOf(entrySet.containsAll(other.entrySet) && !other.entrySet.containsAll(entrySet)); } public PythonLikeSet union(DictItemView other) { PythonLikeSet out = new PythonLikeSet(); out.delegate.addAll(getEntriesAsTuples()); out.delegate.addAll(other.getEntriesAsTuples()); return out; } public PythonLikeSet intersection(DictItemView other) { PythonLikeSet out = new PythonLikeSet(); out.delegate.addAll(getEntriesAsTuples()); out.delegate.retainAll(other.getEntriesAsTuples()); return out; } public PythonLikeSet difference(DictItemView other) { PythonLikeSet out = new PythonLikeSet(); out.delegate.addAll(getEntriesAsTuples()); other.getEntriesAsTuples().forEach(out.delegate::remove); return out; } public PythonLikeSet symmetricDifference(DictItemView other) { PythonLikeSet out = new PythonLikeSet(); out.delegate.addAll(getEntriesAsTuples()); other.getEntriesAsTuples().stream() // for each item in other .filter(Predicate.not(item -> out.delegate.add(item))) // add each item .forEach(out.delegate::remove); // add return false iff item already in set, so this remove // all items in both this and other return out; } @Override public boolean equals(Object o) { if (o instanceof DictItemView other) { return entrySet.equals(other.entrySet); } return false; } @Override public int hashCode() { return entrySet.hashCode(); } public PythonString toRepresentation() { return PythonString.valueOf(toString()); } @Override public String toString() { StringBuilder out = new StringBuilder("dict_items(["); for (Map.Entry<PythonLikeObject, PythonLikeObject> entry : entrySet) { out.append("("); out.append(UnaryDunderBuiltin.REPRESENTATION.invoke(entry.getKey())); out.append(", "); out.append(UnaryDunderBuiltin.REPRESENTATION.invoke(entry.getValue())); out.append("), "); } out.delete(out.length() - 2, out.length()); out.append("])"); return out.toString(); } }
0
java-sources/ai/timefold/solver/jpyinterpreter/1.24.0/ai/timefold/jpyinterpreter/types/collections
java-sources/ai/timefold/solver/jpyinterpreter/1.24.0/ai/timefold/jpyinterpreter/types/collections/view/DictKeyView.java
package ai.timefold.jpyinterpreter.types.collections.view; import java.util.Collections; import java.util.Set; import java.util.function.Predicate; import ai.timefold.jpyinterpreter.PythonBinaryOperator; import ai.timefold.jpyinterpreter.PythonLikeObject; import ai.timefold.jpyinterpreter.PythonOverloadImplementor; import ai.timefold.jpyinterpreter.PythonUnaryOperator; import ai.timefold.jpyinterpreter.builtins.UnaryDunderBuiltin; import ai.timefold.jpyinterpreter.types.AbstractPythonLikeObject; import ai.timefold.jpyinterpreter.types.BuiltinTypes; import ai.timefold.jpyinterpreter.types.PythonLikeType; import ai.timefold.jpyinterpreter.types.PythonString; import ai.timefold.jpyinterpreter.types.collections.DelegatePythonIterator; import ai.timefold.jpyinterpreter.types.collections.PythonLikeDict; import ai.timefold.jpyinterpreter.types.collections.PythonLikeSet; import ai.timefold.jpyinterpreter.types.numeric.PythonBoolean; import ai.timefold.jpyinterpreter.types.numeric.PythonInteger; public class DictKeyView extends AbstractPythonLikeObject { public final static PythonLikeType $TYPE = BuiltinTypes.DICT_KEY_VIEW_TYPE; final PythonLikeDict mapping; final Set<PythonLikeObject> keySet; static { PythonOverloadImplementor.deferDispatchesFor(DictKeyView::registerMethods); } private static PythonLikeType registerMethods() throws NoSuchMethodException { // Unary BuiltinTypes.DICT_KEY_VIEW_TYPE.addUnaryMethod(PythonUnaryOperator.LENGTH, DictKeyView.class.getMethod("getKeysSize")); BuiltinTypes.DICT_KEY_VIEW_TYPE.addUnaryMethod(PythonUnaryOperator.ITERATOR, DictKeyView.class.getMethod("getKeysIterator")); BuiltinTypes.DICT_KEY_VIEW_TYPE.addUnaryMethod(PythonUnaryOperator.REVERSED, DictKeyView.class.getMethod("getReversedKeyIterator")); BuiltinTypes.DICT_KEY_VIEW_TYPE.addUnaryMethod(PythonUnaryOperator.AS_STRING, DictKeyView.class.getMethod("toRepresentation")); BuiltinTypes.DICT_KEY_VIEW_TYPE.addUnaryMethod(PythonUnaryOperator.REPRESENTATION, DictKeyView.class.getMethod("toRepresentation")); // Binary BuiltinTypes.DICT_KEY_VIEW_TYPE.addBinaryMethod(PythonBinaryOperator.CONTAINS, DictKeyView.class.getMethod("containsKey", PythonLikeObject.class)); // Set methods BuiltinTypes.DICT_KEY_VIEW_TYPE.addMethod("isdisjoint", DictKeyView.class.getMethod("isDisjoint", DictKeyView.class)); BuiltinTypes.DICT_KEY_VIEW_TYPE.addBinaryMethod(PythonBinaryOperator.LESS_THAN_OR_EQUAL, DictKeyView.class.getMethod("isSubset", DictKeyView.class)); BuiltinTypes.DICT_KEY_VIEW_TYPE.addBinaryMethod(PythonBinaryOperator.LESS_THAN, DictKeyView.class.getMethod("isStrictSubset", DictKeyView.class)); BuiltinTypes.DICT_KEY_VIEW_TYPE.addBinaryMethod(PythonBinaryOperator.GREATER_THAN_OR_EQUAL, DictKeyView.class.getMethod("isSuperset", DictKeyView.class)); BuiltinTypes.DICT_KEY_VIEW_TYPE.addBinaryMethod(PythonBinaryOperator.GREATER_THAN, DictKeyView.class.getMethod("isStrictSuperset", DictKeyView.class)); BuiltinTypes.DICT_KEY_VIEW_TYPE.addBinaryMethod(PythonBinaryOperator.OR, DictKeyView.class.getMethod("union", DictKeyView.class)); BuiltinTypes.DICT_KEY_VIEW_TYPE.addBinaryMethod(PythonBinaryOperator.AND, DictKeyView.class.getMethod("intersection", DictKeyView.class)); BuiltinTypes.DICT_KEY_VIEW_TYPE.addBinaryMethod(PythonBinaryOperator.SUBTRACT, DictKeyView.class.getMethod("difference", DictKeyView.class)); BuiltinTypes.DICT_KEY_VIEW_TYPE.addBinaryMethod(PythonBinaryOperator.XOR, DictKeyView.class.getMethod("symmetricDifference", DictKeyView.class)); return BuiltinTypes.DICT_KEY_VIEW_TYPE; } public DictKeyView(PythonLikeDict mapping) { super(BuiltinTypes.DICT_KEY_VIEW_TYPE); this.mapping = mapping; this.keySet = mapping.delegate.keySet(); $setAttribute("mapping", mapping); } public PythonInteger getKeysSize() { return PythonInteger.valueOf(keySet.size()); } public DelegatePythonIterator<PythonLikeObject> getKeysIterator() { return new DelegatePythonIterator<>(keySet.iterator()); } public PythonBoolean containsKey(PythonLikeObject key) { return PythonBoolean.valueOf(keySet.contains(key)); } public DelegatePythonIterator<PythonLikeObject> getReversedKeyIterator() { return mapping.reversed(); } public PythonBoolean isDisjoint(DictKeyView other) { return PythonBoolean.valueOf(Collections.disjoint(keySet, other.keySet)); } public PythonBoolean isSubset(DictKeyView other) { return PythonBoolean.valueOf(other.keySet.containsAll(keySet)); } public PythonBoolean isStrictSubset(DictKeyView other) { return PythonBoolean.valueOf(other.keySet.containsAll(keySet) && !keySet.containsAll(other.keySet)); } public PythonBoolean isSuperset(DictKeyView other) { return PythonBoolean.valueOf(keySet.containsAll(other.keySet)); } public PythonBoolean isStrictSuperset(DictKeyView other) { return PythonBoolean.valueOf(keySet.containsAll(other.keySet) && !other.keySet.containsAll(keySet)); } public PythonLikeSet union(DictKeyView other) { PythonLikeSet out = new PythonLikeSet(); out.delegate.addAll(keySet); out.delegate.addAll(other.keySet); return out; } public PythonLikeSet intersection(DictKeyView other) { PythonLikeSet out = new PythonLikeSet(); out.delegate.addAll(keySet); out.delegate.retainAll(other.keySet); return out; } public PythonLikeSet difference(DictKeyView other) { PythonLikeSet out = new PythonLikeSet(); out.delegate.addAll(keySet); out.delegate.removeAll(other.keySet); return out; } public PythonLikeSet symmetricDifference(DictKeyView other) { var out = new PythonLikeSet<>(); out.delegate.addAll(keySet); other.keySet.stream() // for each item in other .filter(Predicate.not(e -> out.delegate.add(e))) // add each item .forEach(out.delegate::remove); // add return false iff item already in set, so this remove // all items in both this and other return out; } @Override public boolean equals(Object o) { if (o instanceof DictKeyView other) { return keySet.equals(other.keySet); } return false; } @Override public int hashCode() { return keySet.hashCode(); } public PythonString toRepresentation() { return PythonString.valueOf(toString()); } @Override public String toString() { StringBuilder out = new StringBuilder("dict_keys(["); for (PythonLikeObject key : keySet) { out.append(UnaryDunderBuiltin.REPRESENTATION.invoke(key)); out.append(", "); } out.delete(out.length() - 2, out.length()); out.append("])"); return out.toString(); } }
0
java-sources/ai/timefold/solver/jpyinterpreter/1.24.0/ai/timefold/jpyinterpreter/types/collections
java-sources/ai/timefold/solver/jpyinterpreter/1.24.0/ai/timefold/jpyinterpreter/types/collections/view/DictValueView.java
package ai.timefold.jpyinterpreter.types.collections.view; import java.util.Collection; import ai.timefold.jpyinterpreter.PythonBinaryOperator; import ai.timefold.jpyinterpreter.PythonLikeObject; import ai.timefold.jpyinterpreter.PythonOverloadImplementor; import ai.timefold.jpyinterpreter.PythonUnaryOperator; import ai.timefold.jpyinterpreter.builtins.UnaryDunderBuiltin; import ai.timefold.jpyinterpreter.types.AbstractPythonLikeObject; import ai.timefold.jpyinterpreter.types.BuiltinTypes; import ai.timefold.jpyinterpreter.types.PythonLikeType; import ai.timefold.jpyinterpreter.types.PythonString; import ai.timefold.jpyinterpreter.types.collections.DelegatePythonIterator; import ai.timefold.jpyinterpreter.types.collections.PythonLikeDict; import ai.timefold.jpyinterpreter.types.numeric.PythonBoolean; import ai.timefold.jpyinterpreter.types.numeric.PythonInteger; import ai.timefold.jpyinterpreter.util.IteratorUtils; public class DictValueView extends AbstractPythonLikeObject { public final static PythonLikeType $TYPE = BuiltinTypes.DICT_VALUE_VIEW_TYPE; final PythonLikeDict mapping; final Collection<PythonLikeObject> valueCollection; static { PythonOverloadImplementor.deferDispatchesFor(DictValueView::registerMethods); } private static PythonLikeType registerMethods() throws NoSuchMethodException { // Unary BuiltinTypes.DICT_VALUE_VIEW_TYPE.addUnaryMethod(PythonUnaryOperator.LENGTH, DictValueView.class.getMethod("getValuesSize")); BuiltinTypes.DICT_VALUE_VIEW_TYPE.addUnaryMethod(PythonUnaryOperator.ITERATOR, DictValueView.class.getMethod("getValueIterator")); BuiltinTypes.DICT_VALUE_VIEW_TYPE.addUnaryMethod(PythonUnaryOperator.REVERSED, DictValueView.class.getMethod("getReversedValueIterator")); BuiltinTypes.DICT_VALUE_VIEW_TYPE.addUnaryMethod(PythonUnaryOperator.AS_STRING, DictValueView.class.getMethod("toRepresentation")); BuiltinTypes.DICT_VALUE_VIEW_TYPE.addUnaryMethod(PythonUnaryOperator.REPRESENTATION, DictValueView.class.getMethod("toRepresentation")); // Binary BuiltinTypes.DICT_VALUE_VIEW_TYPE.addBinaryMethod(PythonBinaryOperator.CONTAINS, DictValueView.class.getMethod("containsValue", PythonLikeObject.class)); return BuiltinTypes.DICT_VALUE_VIEW_TYPE; } public DictValueView(PythonLikeDict mapping) { super(BuiltinTypes.DICT_VALUE_VIEW_TYPE); this.mapping = mapping; this.valueCollection = mapping.delegate.values(); $setAttribute("mapping", mapping); } public PythonInteger getValuesSize() { return PythonInteger.valueOf(valueCollection.size()); } public DelegatePythonIterator<PythonLikeObject> getValueIterator() { return new DelegatePythonIterator<>(valueCollection.iterator()); } public PythonBoolean containsValue(PythonLikeObject value) { return PythonBoolean.valueOf(valueCollection.contains(value)); } public DelegatePythonIterator<PythonLikeObject> getReversedValueIterator() { return new DelegatePythonIterator<>(IteratorUtils.iteratorMap(mapping.reversed(), mapping::get)); } public PythonString toRepresentation() { return PythonString.valueOf(toString()); } @Override public String toString() { StringBuilder out = new StringBuilder("dict_values(["); for (PythonLikeObject value : valueCollection) { out.append(UnaryDunderBuiltin.REPRESENTATION.invoke(value)); out.append(", "); } out.delete(out.length() - 2, out.length()); out.append("])"); return out.toString(); } }
0
java-sources/ai/timefold/solver/jpyinterpreter/1.24.0/ai/timefold/jpyinterpreter/types
java-sources/ai/timefold/solver/jpyinterpreter/1.24.0/ai/timefold/jpyinterpreter/types/datetime/PythonDate.java
package ai.timefold.jpyinterpreter.types.datetime; import static ai.timefold.jpyinterpreter.types.datetime.PythonDateTime.DATE_TIME_TYPE; import java.time.Duration; import java.time.Instant; import java.time.LocalDate; import java.time.LocalDateTime; import java.time.LocalTime; import java.time.YearMonth; import java.time.ZoneId; import java.time.format.DateTimeFormatter; import java.time.temporal.IsoFields; import ai.timefold.jpyinterpreter.PythonBinaryOperator; import ai.timefold.jpyinterpreter.PythonLikeObject; import ai.timefold.jpyinterpreter.PythonOverloadImplementor; import ai.timefold.jpyinterpreter.PythonUnaryOperator; import ai.timefold.jpyinterpreter.types.AbstractPythonLikeObject; import ai.timefold.jpyinterpreter.types.PythonLikeComparable; import ai.timefold.jpyinterpreter.types.PythonLikeType; import ai.timefold.jpyinterpreter.types.PythonNone; import ai.timefold.jpyinterpreter.types.PythonString; import ai.timefold.jpyinterpreter.types.collections.PythonLikeTuple; import ai.timefold.jpyinterpreter.types.errors.TypeError; import ai.timefold.jpyinterpreter.types.errors.ValueError; 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.util.arguments.ArgumentSpec; import ai.timefold.solver.core.impl.domain.solution.cloner.PlanningImmutable; /** * Python docs: <a href="https://docs.python.org/3/library/datetime.html#datetime.date">date objects</a> */ public class PythonDate<T extends PythonDate<?>> extends AbstractPythonLikeObject implements PythonLikeComparable<T>, PlanningImmutable { static final long EPOCH_ORDINAL_OFFSET = Duration.between(LocalDateTime.of(LocalDate.of(0, 12, 31), LocalTime.MIDNIGHT), LocalDateTime.of(LocalDate.ofEpochDay(0), LocalTime.MIDNIGHT)).toDays(); // Ex: Wed Jun 9 04:26:40 1993 static final DateTimeFormatter C_TIME_FORMATTER = DateTimeFormatter.ofPattern("EEE MMM ppd HH:mm:ss yyyy"); public static PythonLikeType DATE_TYPE = new PythonLikeType("date", PythonDate.class); public static PythonLikeType $TYPE = DATE_TYPE; static { try { PythonLikeComparable.setup(DATE_TYPE); registerMethods(); DATE_TYPE.$setAttribute("min", new PythonDate(LocalDate.of(1, 1, 1))); DATE_TYPE.$setAttribute("max", new PythonDate(LocalDate.of(9999, 12, 31))); DATE_TYPE.$setAttribute("resolution", new PythonTimeDelta(Duration.ofDays(1))); PythonOverloadImplementor.createDispatchesFor(DATE_TYPE); } catch (NoSuchMethodException e) { throw new RuntimeException(e); } } private static void registerMethods() throws NoSuchMethodException { // Constructor DATE_TYPE.addConstructor(ArgumentSpec.forFunctionReturning("date", PythonDate.class.getName()) .addArgument("year", PythonInteger.class.getName()) .addArgument("month", PythonInteger.class.getName()) .addArgument("day", PythonInteger.class.getName()) .asStaticPythonFunctionSignature(PythonDate.class.getMethod("of", PythonInteger.class, PythonInteger.class, PythonInteger.class))); // Unary Operators DATE_TYPE.addUnaryMethod(PythonUnaryOperator.AS_STRING, PythonDate.class.getMethod("toPythonString")); // Binary Operators DATE_TYPE.addBinaryMethod(PythonBinaryOperator.ADD, PythonDate.class.getMethod("add_time_delta", PythonTimeDelta.class)); DATE_TYPE.addBinaryMethod(PythonBinaryOperator.SUBTRACT, PythonDate.class.getMethod("subtract_time_delta", PythonTimeDelta.class)); DATE_TYPE.addBinaryMethod(PythonBinaryOperator.SUBTRACT, PythonDate.class.getMethod("subtract_date", PythonDate.class)); // Methods DATE_TYPE.addMethod("replace", ArgumentSpec.forFunctionReturning("replace", PythonDate.class.getName()) .addNullableArgument("year", PythonInteger.class.getName()) .addNullableArgument("month", PythonInteger.class.getName()) .addNullableArgument("day", PythonInteger.class.getName()) .asPythonFunctionSignature(PythonDate.class.getMethod("replace", PythonInteger.class, PythonInteger.class, PythonInteger.class))); DATE_TYPE.addMethod("timetuple", PythonDate.class.getMethod("timetuple")); // TODO: use time.struct_time type DATE_TYPE.addMethod("toordinal", PythonDate.class.getMethod("to_ordinal")); DATE_TYPE.addMethod("weekday", PythonDate.class.getMethod("weekday")); DATE_TYPE.addMethod("isoweekday", PythonDate.class.getMethod("iso_weekday")); DATE_TYPE.addMethod("isoweekday", PythonDate.class.getMethod("iso_weekday")); DATE_TYPE.addMethod("isocalendar", PythonDate.class.getMethod("iso_calendar")); DATE_TYPE.addMethod("isoformat", PythonDate.class.getMethod("iso_format")); DATE_TYPE.addMethod("strftime", ArgumentSpec.forFunctionReturning("strftime", PythonString.class.getName()) .addArgument("format", PythonString.class.getName()) .asPythonFunctionSignature(PythonDate.class.getMethod("strftime", PythonString.class))); DATE_TYPE.addMethod("ctime", PythonDate.class.getMethod("ctime")); // Class methods DATE_TYPE.addMethod("today", ArgumentSpec.forFunctionReturning("today", PythonDate.class.getName()) .addArgument("date_type", PythonLikeType.class.getName()) .asClassPythonFunctionSignature(PythonDate.class.getMethod("today", PythonLikeType.class))); DATE_TYPE.addMethod("fromtimestamp", ArgumentSpec.forFunctionReturning("fromtimestamp", PythonDate.class.getName()) .addArgument("date_type", PythonLikeType.class.getName()) .addArgument("timestamp", PythonNumber.class.getName()) .asClassPythonFunctionSignature(PythonDate.class.getMethod("from_timestamp", PythonLikeType.class, PythonNumber.class))); DATE_TYPE.addMethod("fromordinal", ArgumentSpec.forFunctionReturning("fromordinal", PythonDate.class.getName()) .addArgument("date_type", PythonLikeType.class.getName()) .addArgument("ordinal", PythonInteger.class.getName()) .asClassPythonFunctionSignature(PythonDate.class.getMethod("from_ordinal", PythonLikeType.class, PythonInteger.class))); DATE_TYPE.addMethod("fromisoformat", ArgumentSpec.forFunctionReturning("fromisoformat", PythonDate.class.getName()) .addArgument("date_type", PythonLikeType.class.getName()) .addArgument("date_string", PythonString.class.getName()) .asClassPythonFunctionSignature(PythonDate.class.getMethod("from_iso_format", PythonLikeType.class, PythonString.class))); DATE_TYPE.addMethod("fromisocalendar", ArgumentSpec.forFunctionReturning("fromisocalendar", PythonDate.class.getName()) .addArgument("date_type", PythonLikeType.class.getName()) .addArgument("year", PythonInteger.class.getName()) .addArgument("month", PythonInteger.class.getName()) .addArgument("day", PythonInteger.class.getName()) .asClassPythonFunctionSignature(PythonDate.class.getMethod("from_iso_calendar", PythonLikeType.class, PythonInteger.class, PythonInteger.class, PythonInteger.class))); } final LocalDate localDate; public final PythonInteger year; public final PythonInteger month; public final PythonInteger day; public PythonDate(LocalDate localDate) { this(DATE_TYPE, localDate); } public PythonDate(PythonLikeType type, LocalDate localDate) { super(type); this.localDate = localDate; this.year = PythonInteger.valueOf(localDate.getYear()); this.month = PythonInteger.valueOf(localDate.getMonthValue()); this.day = PythonInteger.valueOf(localDate.getDayOfMonth()); } public static PythonDate of(PythonInteger year, PythonInteger month, PythonInteger day) { return of(year.value.intValueExact(), month.value.intValueExact(), day.value.intValueExact()); } public static PythonDate of(int year, int month, int day) { if (month < 1 || month > 12) { throw new ValueError("month must be between 1 and 12"); } if (!YearMonth.of(year, month).isValidDay(day)) { throw new ValueError("day must be between 1 and " + YearMonth.of(year, month).lengthOfMonth()); } return new PythonDate(LocalDate.of(year, month, day)); } @Override public PythonLikeObject $getAttributeOrNull(String name) { switch (name) { case "year": return year; case "month": return month; case "day": return day; default: return super.$getAttributeOrNull(name); } } public static PythonDate today() { return new PythonDate(LocalDate.now()); } public static PythonDate today(PythonLikeType dateType) { if (dateType == DATE_TYPE) { return today(); } else if (dateType == DATE_TIME_TYPE) { return today(); } else { throw new TypeError("Unknown date type: " + dateType); } } public static PythonDate from_timestamp(PythonLikeType dateType, PythonNumber timestamp) { if (dateType == DATE_TYPE) { if (timestamp instanceof PythonInteger) { return from_timestamp((PythonInteger) timestamp); } else { return from_timestamp((PythonFloat) timestamp); } } else if (dateType == DATE_TIME_TYPE) { return PythonDateTime.from_timestamp(dateType, timestamp, PythonNone.INSTANCE); } else { throw new TypeError("Unknown date type: " + dateType); } } // Python timestamp is in the current System timezone public static PythonDate from_timestamp(PythonInteger timestamp) { return new PythonDate(LocalDate.ofInstant(Instant.ofEpochSecond(timestamp.getValue().longValue()), ZoneId.systemDefault())); } public static PythonDate from_timestamp(PythonFloat timestamp) { return new PythonDate(LocalDate.ofInstant(Instant.ofEpochMilli( Math.round(timestamp.getValue().doubleValue() * 1000)), ZoneId.systemDefault())); } public static PythonDate from_ordinal(PythonLikeType dateType, PythonInteger ordinal) { if (dateType == DATE_TYPE) { return from_ordinal(ordinal); } else if (dateType == DATE_TIME_TYPE) { return PythonDateTime.from_ordinal(ordinal); } else { throw new TypeError("Unknown date type: " + dateType); } } public static PythonDate from_ordinal(PythonInteger ordinal) { return new PythonDate(LocalDate.ofEpochDay(ordinal.getValue().longValue() - EPOCH_ORDINAL_OFFSET)); } public static PythonDate from_iso_format(PythonLikeType dateType, PythonString dateString) { if (dateType == DATE_TYPE) { return from_iso_format(dateString); } else if (dateType == DATE_TIME_TYPE) { return PythonDateTime.from_iso_format(dateString); } else { throw new TypeError("Unknown date type: " + dateType); } } public static PythonDate from_iso_format(PythonString dateString) { return new PythonDate(LocalDate.parse(dateString.getValue())); } public static PythonDate from_iso_calendar(PythonLikeType dateType, PythonInteger year, PythonInteger week, PythonInteger day) { if (dateType == DATE_TYPE) { return from_iso_calendar(year, week, day); } else if (dateType == DATE_TIME_TYPE) { return PythonDateTime.from_iso_calendar(year, week, day); } else { throw new TypeError("Unknown date type: " + dateType); } } public static PythonDate from_iso_calendar(PythonInteger year, PythonInteger week, PythonInteger day) { int isoYear = year.getValue().intValue(); int dayInIsoYear = (week.getValue().intValue() * 7) + day.getValue().intValue(); int correction = LocalDate.of(isoYear, 1, 4).getDayOfWeek().getValue() + 3; int ordinalDate = dayInIsoYear - correction; if (ordinalDate <= 0) { int daysInYear = LocalDate.ofYearDay(isoYear - 1, 1).lengthOfYear(); return new PythonDate(LocalDate.ofYearDay(isoYear - 1, ordinalDate + daysInYear)); } else if (ordinalDate > LocalDate.ofYearDay(isoYear, 1).lengthOfYear()) { int daysInYear = LocalDate.ofYearDay(isoYear, 1).lengthOfYear(); return new PythonDate(LocalDate.ofYearDay(isoYear + 1, ordinalDate - daysInYear)); } else { return new PythonDate(LocalDate.ofYearDay(isoYear, ordinalDate)); } } public PythonDate add_time_delta(PythonTimeDelta summand) { return new PythonDate(localDate.plusDays(summand.duration.toDays())); } public PythonDate subtract_time_delta(PythonTimeDelta subtrahend) { return new PythonDate(localDate.minusDays(subtrahend.duration.toDays())); } public PythonTimeDelta subtract_date(PythonDate subtrahend) { return new PythonTimeDelta(Duration.ofDays(localDate.toEpochDay() - subtrahend.localDate.toEpochDay())); } public PythonDate replace(PythonInteger year, PythonInteger month, PythonInteger day) { if (year == null) { year = this.year; } if (month == null) { month = this.month; } if (day == null) { day = this.day; } return new PythonDate(LocalDate.of(year.getValue().intValue(), month.getValue().intValue(), day.getValue().intValue())); } public PythonLikeTuple timetuple() { PythonInteger yday = to_ordinal().subtract(PythonDate.of(year.value.intValueExact(), 1, 1).to_ordinal()).add(PythonInteger.ONE); return PythonLikeTuple.fromItems(year, month, day, PythonInteger.ZERO, PythonInteger.ZERO, PythonInteger.ZERO, weekday(), yday, PythonInteger.valueOf(-1)); } public PythonInteger to_ordinal() { return PythonInteger.valueOf(localDate.toEpochDay() + EPOCH_ORDINAL_OFFSET); } public PythonInteger weekday() { return PythonInteger.valueOf(localDate.getDayOfWeek().getValue() - 1); } public PythonInteger iso_weekday() { return PythonInteger.valueOf(localDate.getDayOfWeek().getValue()); } public PythonLikeTuple iso_calendar() { PythonInteger year = PythonInteger.valueOf(IsoFields.WEEK_BASED_YEAR.getFrom(localDate)); PythonInteger week = PythonInteger.valueOf(IsoFields.WEEK_OF_WEEK_BASED_YEAR.getFrom(localDate)); PythonInteger day = PythonInteger.valueOf(localDate.getDayOfWeek().getValue()); return PythonLikeTuple.fromItems(year, week, day); } public PythonString iso_format() { return new PythonString(localDate.toString()); } public PythonString toPythonString() { return new PythonString(toString()); } public PythonString ctime() { return new PythonString(localDate.atStartOfDay().format(C_TIME_FORMATTER).replaceAll("(\\D)\\.", "$1")); } public PythonString strftime(PythonString format) { var formatter = PythonDateTimeFormatter.getDateTimeFormatter(format.value); return PythonString.valueOf(formatter.format(localDate)); } @Override public int compareTo(T date) { return localDate.compareTo(date.localDate); } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } PythonDate<?> that = (PythonDate<?>) o; return localDate.equals(that.localDate); } @Override public String toString() { return iso_format().value; } @Override public int hashCode() { return localDate.hashCode(); } @Override public PythonInteger $method$__hash__() { return PythonInteger.valueOf(hashCode()); } @Override public PythonString $method$__str__() { return iso_format(); } }
0
java-sources/ai/timefold/solver/jpyinterpreter/1.24.0/ai/timefold/jpyinterpreter/types
java-sources/ai/timefold/solver/jpyinterpreter/1.24.0/ai/timefold/jpyinterpreter/types/datetime/PythonDateTime.java
package ai.timefold.jpyinterpreter.types.datetime; import java.time.Clock; import java.time.DateTimeException; import java.time.Duration; import java.time.Instant; import java.time.LocalDate; import java.time.LocalDateTime; import java.time.LocalTime; import java.time.YearMonth; import java.time.ZoneId; import java.time.ZoneOffset; import java.time.ZonedDateTime; import java.time.format.DateTimeFormatter; import java.time.format.TextStyle; import java.time.temporal.Temporal; import java.time.temporal.TemporalQuery; import java.util.List; import java.util.Locale; import java.util.regex.Matcher; import java.util.regex.Pattern; import ai.timefold.jpyinterpreter.PythonBinaryOperator; import ai.timefold.jpyinterpreter.PythonLikeObject; import ai.timefold.jpyinterpreter.PythonOverloadImplementor; import ai.timefold.jpyinterpreter.PythonUnaryOperator; import ai.timefold.jpyinterpreter.types.PythonLikeComparable; import ai.timefold.jpyinterpreter.types.PythonLikeType; import ai.timefold.jpyinterpreter.types.PythonNone; import ai.timefold.jpyinterpreter.types.PythonString; import ai.timefold.jpyinterpreter.types.collections.PythonLikeTuple; import ai.timefold.jpyinterpreter.types.errors.TypeError; import ai.timefold.jpyinterpreter.types.errors.ValueError; 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.util.arguments.ArgumentSpec; import ai.timefold.solver.core.impl.domain.solution.cloner.PlanningImmutable; /** * Python docs: <a href="https://docs.python.org/3/library/datetime.html#datetime.datetime">datetime objects</a> */ public class PythonDateTime extends PythonDate<PythonDateTime> implements PlanningImmutable { // Taken from https://docs.python.org/3/library/datetime.html#datetime.datetime.fromisoformat private static final Pattern ISO_FORMAT_PATTERN = Pattern.compile("^(?<year>\\d\\d\\d\\d)-(?<month>\\d\\d)-(?<day>\\d\\d)" + "(.(?<hour>\\d\\d)" + "(:(?<minute>\\d\\d)" + "(:(?<second>\\d\\d)" + "(\\.(?<microHigh>\\d\\d\\d)" + "(?<microLow>\\d\\d\\d)?" + ")?)?)?)?" + "(\\+(?<timezoneHour>\\d\\d):(?<timezoneMinute>\\d\\d)" + "(:(?<timezoneSecond>\\d\\d)" + "(\\.(?<timezoneMicro>\\d\\d\\d\\d\\d\\d)" + ")?)?)?$"); private static final int NANOS_PER_SECOND = 1_000_000_000; public static PythonLikeType DATE_TIME_TYPE = new PythonLikeType("datetime", PythonDateTime.class, List.of(DATE_TYPE)); public static PythonLikeType $TYPE = DATE_TIME_TYPE; static { try { PythonLikeComparable.setup(DATE_TIME_TYPE); registerMethods(); DATE_TIME_TYPE.$setAttribute("min", new PythonDateTime(LocalDate.of(1, 1, 1), LocalTime.MAX)); DATE_TIME_TYPE.$setAttribute("max", new PythonDateTime(LocalDate.of(9999, 12, 31), LocalTime.MIN)); DATE_TIME_TYPE.$setAttribute("resolution", new PythonTimeDelta(Duration.ofNanos(1000L))); PythonOverloadImplementor.createDispatchesFor(DATE_TIME_TYPE); } catch (NoSuchMethodException e) { throw new RuntimeException(e); } } private static void registerMethods() throws NoSuchMethodException { // Constructor DATE_TIME_TYPE.addConstructor(ArgumentSpec.forFunctionReturning("datetime", PythonDateTime.class.getName()) .addArgument("year", PythonInteger.class.getName()) .addArgument("month", PythonInteger.class.getName()) .addArgument("day", PythonInteger.class.getName()) .addArgument("hour", PythonInteger.class.getName(), PythonInteger.ZERO) .addArgument("minute", PythonInteger.class.getName(), PythonInteger.ZERO) .addArgument("second", PythonInteger.class.getName(), PythonInteger.ZERO) .addArgument("microsecond", PythonInteger.class.getName(), PythonInteger.ZERO) .addArgument("tzinfo", PythonLikeObject.class.getName(), PythonNone.INSTANCE) .addKeywordOnlyArgument("fold", PythonInteger.class.getName(), PythonInteger.ZERO) .asPythonFunctionSignature( PythonDateTime.class.getMethod("of", PythonInteger.class, PythonInteger.class, PythonInteger.class, PythonInteger.class, PythonInteger.class, PythonInteger.class, PythonInteger.class, PythonLikeObject.class, PythonInteger.class))); // Class methods // Date handles today, DATE_TIME_TYPE.addMethod("now", ArgumentSpec.forFunctionReturning("now", PythonDateTime.class.getName()) .addArgument("datetime_type", PythonLikeType.class.getName()) .addArgument("tzinfo", PythonLikeObject.class.getName(), PythonNone.INSTANCE) .asClassPythonFunctionSignature( PythonDateTime.class.getMethod("now", PythonLikeType.class, PythonLikeObject.class))); DATE_TIME_TYPE.addMethod("utcnow", ArgumentSpec.forFunctionReturning("now", PythonDateTime.class.getName()) .addArgument("datetime_type", PythonLikeType.class.getName()) .asClassPythonFunctionSignature( PythonDateTime.class.getMethod("utc_now", PythonLikeType.class))); DATE_TIME_TYPE.addMethod("fromtimestamp", ArgumentSpec.forFunctionReturning("fromtimestamp", PythonDate.class.getName()) .addArgument("date_type", PythonLikeType.class.getName()) .addArgument("timestamp", PythonNumber.class.getName()) .addArgument("tzinfo", PythonLikeObject.class.getName(), PythonNone.INSTANCE) .asClassPythonFunctionSignature(PythonDateTime.class.getMethod("from_timestamp", PythonLikeType.class, PythonNumber.class, PythonLikeObject.class))); DATE_TIME_TYPE.addMethod("strptime", ArgumentSpec.forFunctionReturning("strptime", PythonDateTime.class.getName()) .addArgument("datetime_type", PythonLikeType.class.getName()) .addArgument("date_string", PythonString.class.getName()) .addArgument("format", PythonString.class.getName()) .asClassPythonFunctionSignature(PythonDateTime.class.getMethod("strptime", PythonLikeType.class, PythonString.class, PythonString.class))); DATE_TIME_TYPE.addMethod("utcfromtimestamp", ArgumentSpec.forFunctionReturning("utcfromtimestamp", PythonDate.class.getName()) .addArgument("date_type", PythonLikeType.class.getName()) .addArgument("timestamp", PythonNumber.class.getName()) .asClassPythonFunctionSignature(PythonDateTime.class.getMethod("utc_from_timestamp", PythonLikeType.class, PythonNumber.class))); DATE_TIME_TYPE.addMethod("combine", ArgumentSpec.forFunctionReturning("combine", PythonDateTime.class.getName()) .addArgument("datetime_type", PythonLikeType.class.getName()) .addArgument("date", PythonDate.class.getName()) .addArgument("time", PythonTime.class.getName()) .addNullableArgument("tzinfo", PythonLikeObject.class.getName()) .asClassPythonFunctionSignature( PythonDateTime.class.getMethod("combine", PythonLikeType.class, PythonDate.class, PythonTime.class, PythonLikeObject.class))); // Unary Operators DATE_TIME_TYPE.addUnaryMethod(PythonUnaryOperator.AS_STRING, PythonDateTime.class.getMethod("toPythonString")); // Binary Operators DATE_TIME_TYPE.addBinaryMethod(PythonBinaryOperator.ADD, PythonDateTime.class.getMethod("add_time_delta", PythonTimeDelta.class)); DATE_TIME_TYPE.addBinaryMethod(PythonBinaryOperator.SUBTRACT, PythonDateTime.class.getMethod("subtract_time_delta", PythonTimeDelta.class)); DATE_TIME_TYPE.addBinaryMethod(PythonBinaryOperator.SUBTRACT, PythonDateTime.class.getMethod("subtract_date_time", PythonDateTime.class)); // Instance methods DATE_TIME_TYPE.addMethod("replace", ArgumentSpec.forFunctionReturning("replace", PythonDate.class.getName()) .addNullableArgument("year", PythonInteger.class.getName()) .addNullableArgument("month", PythonInteger.class.getName()) .addNullableArgument("day", PythonInteger.class.getName()) .addNullableArgument("hour", PythonInteger.class.getName()) .addNullableArgument("minute", PythonInteger.class.getName()) .addNullableArgument("second", PythonInteger.class.getName()) .addNullableArgument("microsecond", PythonInteger.class.getName()) .addNullableArgument("tzinfo", PythonLikeObject.class.getName()) .addNullableKeywordOnlyArgument("fold", PythonInteger.class.getName()) .asPythonFunctionSignature(PythonDateTime.class.getMethod("replace", PythonInteger.class, PythonInteger.class, PythonInteger.class, PythonInteger.class, PythonInteger.class, PythonInteger.class, PythonInteger.class, PythonLikeObject.class, PythonInteger.class))); DATE_TIME_TYPE.addMethod("timetuple", PythonDateTime.class.getMethod("timetuple")); // TODO: use time.struct_time type DATE_TIME_TYPE.addMethod("utctimetuple", PythonDateTime.class.getMethod("utctimetuple")); // TODO: use time.struct_time type DATE_TIME_TYPE.addMethod("date", PythonDateTime.class.getMethod("date")); DATE_TIME_TYPE.addMethod("time", PythonDateTime.class.getMethod("time")); DATE_TIME_TYPE.addMethod("timetz", PythonDateTime.class.getMethod("timetz")); DATE_TIME_TYPE.addMethod("astimezone", PythonDateTime.class.getMethod("astimezone", PythonTzinfo.class)); DATE_TIME_TYPE.addMethod("timestamp", PythonDateTime.class.getMethod("timestamp")); DATE_TIME_TYPE.addMethod("tzname", PythonDateTime.class.getMethod("tzname")); DATE_TIME_TYPE.addMethod("utcoffset", PythonDateTime.class.getMethod("utcoffset")); DATE_TIME_TYPE.addMethod("dst", PythonDateTime.class.getMethod("dst")); DATE_TIME_TYPE.addMethod("isoformat", ArgumentSpec.forFunctionReturning("isoformat", PythonString.class.getName()) .addArgument("sep", PythonString.class.getName(), PythonString.valueOf("T")) .addArgument("timespec", PythonString.class.getName(), PythonString.valueOf("auto")) .asPythonFunctionSignature( PythonDateTime.class.getMethod("iso_format", PythonString.class, PythonString.class))); DATE_TIME_TYPE.addMethod("strftime", ArgumentSpec.forFunctionReturning("strftime", PythonString.class.getName()) .addArgument("format", PythonString.class.getName()) .asPythonFunctionSignature(PythonDateTime.class.getMethod("strftime", PythonString.class))); DATE_TIME_TYPE.addMethod("ctime", PythonDateTime.class.getMethod("ctime")); // The following virtual methods are inherited from date: // toordinal, weekday, isoweekday, isocalendar } final Temporal dateTime; final ZoneId zoneId; public final PythonInteger hour; public final PythonInteger minute; public final PythonInteger second; public final PythonInteger microsecond; public final PythonInteger fold; public final PythonLikeObject tzinfo; public PythonDateTime(ZonedDateTime zonedDateTime) { this(zonedDateTime.toLocalDate(), zonedDateTime.toLocalTime(), zonedDateTime.getZone(), zonedDateTime.equals(zonedDateTime.withEarlierOffsetAtOverlap()) ? 0 : 1); } public PythonDateTime(LocalDateTime localDateTime) { this(localDateTime.toLocalDate(), localDateTime.toLocalTime(), (ZoneId) null, 0); } public PythonDateTime(LocalDate localDate, LocalTime localTime) { this(localDate, localTime, (ZoneId) null, 0); } public PythonDateTime(LocalDate localDate, LocalTime localTime, ZoneId zoneId) { this(localDate, localTime, zoneId, 0); } public PythonDateTime(LocalDate localDate, LocalTime localTime, PythonLikeObject tzinfo, int fold) { this(localDate, localTime, (tzinfo instanceof PythonTzinfo) ? ((PythonTzinfo) tzinfo).zoneId : null, fold); } public PythonDateTime(LocalDate localDate, LocalTime localTime, ZoneId zoneId, int fold) { super(DATE_TIME_TYPE, localDate); this.zoneId = zoneId; if (zoneId == null) { dateTime = LocalDateTime.of(localDate, localTime); } else { dateTime = ZonedDateTime.of(localDate, localTime, zoneId); } hour = PythonInteger.valueOf(localTime.getHour()); minute = PythonInteger.valueOf(localTime.getMinute()); second = PythonInteger.valueOf(localTime.getSecond()); microsecond = PythonInteger.valueOf(localTime.getNano() / 1000); // Micro = Nano // 1000 tzinfo = zoneId == null ? PythonNone.INSTANCE : new PythonTzinfo(zoneId); this.fold = PythonInteger.valueOf(fold); } public static PythonDateTime of(PythonInteger year, PythonInteger month, PythonInteger day, PythonInteger hour, PythonInteger minute, PythonInteger second, PythonInteger microsecond, PythonLikeObject tzinfo, PythonInteger fold) { if (month.value.intValueExact() < 1 || month.value.intValueExact() > 12) { throw new ValueError("month must be between 1 and 12"); } if (!YearMonth.of(year.value.intValueExact(), month.value.intValueExact()).isValidDay(day.value.intValueExact())) { throw new ValueError("day must be between 1 and " + YearMonth.of(year.value.intValueExact(), month.value.intValueExact()).lengthOfMonth()); } if (hour.value.intValueExact() < 0 || hour.value.intValueExact() >= 24) { throw new ValueError("hour must be in range 0 <= hour < 24"); } if (minute.value.intValueExact() < 0 || minute.value.intValueExact() >= 60) { throw new ValueError("minute must be in range 0 <= minute < 60"); } if (second.value.intValueExact() < 0 || second.value.intValueExact() >= 60) { throw new ValueError("second must be in range 0 <= second < 60"); } if (microsecond.value.intValueExact() < 0 || microsecond.value.intValueExact() >= 1000000) { throw new ValueError("microsecond must be in range 0 <= microsecond < 1000000"); } if (fold.value.intValueExact() != 0 && fold.value.intValueExact() != 1) { throw new ValueError("fold must be in [0, 1]"); } return new PythonDateTime( LocalDate.of(year.value.intValueExact(), month.value.intValueExact(), day.value.intValueExact()), LocalTime.of(hour.value.intValueExact(), minute.value.intValueExact(), second.value.intValueExact(), microsecond.value.intValueExact() * 1000), (tzinfo != PythonNone.INSTANCE) ? ((PythonTzinfo) tzinfo).zoneId : null, fold.value.intValueExact()); } public static PythonDateTime of(int year, int month, int day, int hour, int minute, int second, int microsecond, String tzname, int fold) { return new PythonDateTime(LocalDate.of(year, month, day), LocalTime.of(hour, minute, second, microsecond * 1000), (tzname != null) ? ZoneId.of(tzname) : null, fold); } @Override public PythonLikeObject $getAttributeOrNull(String name) { switch (name) { case "hour": return hour; case "minute": return minute; case "second": return second; case "microsecond": return microsecond; case "fold": return fold; case "tzinfo": return tzinfo; default: return super.$getAttributeOrNull(name); } } public static PythonDateTime now(PythonLikeType type, PythonLikeObject tzinfo) { if (type != DATE_TIME_TYPE) { throw new TypeError("Unknown datetime type: " + type); } LocalDateTime result = LocalDateTime.now(); return new PythonDateTime(result.toLocalDate(), result.toLocalTime(), tzinfo == PythonNone.INSTANCE ? null : ((PythonTzinfo) tzinfo).zoneId); } public static PythonDateTime utc_now(PythonLikeType type) { if (type != DATE_TIME_TYPE) { throw new TypeError("Unknown datetime type: " + type); } LocalDateTime result = LocalDateTime.now(Clock.systemUTC()); return new PythonDateTime(result.toLocalDate(), result.toLocalTime(), null); } public static PythonDateTime from_ordinal(PythonInteger ordinal) { return new PythonDateTime(LocalDate.ofEpochDay(ordinal.getValue().longValue() - EPOCH_ORDINAL_OFFSET), LocalTime.MIDNIGHT, null); } public static PythonDateTime from_timestamp(PythonLikeType type, PythonNumber timestamp, PythonLikeObject tzinfo) { if (type != DATE_TIME_TYPE) { throw new TypeError("Unknown datetime type: " + type); } if (timestamp instanceof PythonInteger) { return from_timestamp((PythonInteger) timestamp, tzinfo); } else { return from_timestamp((PythonFloat) timestamp, tzinfo); } } public static PythonDateTime from_timestamp(PythonInteger timestamp, PythonLikeObject tzinfo) { Instant instant = Instant.ofEpochSecond(timestamp.getValue().longValue()); if (tzinfo == PythonNone.INSTANCE) { LocalDateTime result = instant.atZone(ZoneId.systemDefault()).toLocalDateTime(); return new PythonDateTime(result); } else { ZoneId zoneId = ((PythonTzinfo) tzinfo).zoneId; LocalDateTime result = instant.atZone(zoneId).toLocalDateTime(); return new PythonDateTime(result.toLocalDate(), result.toLocalTime(), zoneId); } } public static PythonDateTime from_timestamp(PythonFloat timestamp, PythonLikeObject tzinfo) { long epochSeconds = (long) Math.floor(timestamp.getValue().doubleValue()); double remainder = timestamp.getValue().doubleValue() - epochSeconds; int nanos = (int) Math.round(remainder * NANOS_PER_SECOND); Instant instant = Instant.ofEpochSecond(timestamp.getValue().longValue(), nanos); if (tzinfo == PythonNone.INSTANCE) { LocalDateTime result = instant.atZone(ZoneId.systemDefault()).toLocalDateTime(); return new PythonDateTime(result); } else { ZoneId zoneId = ((PythonTzinfo) tzinfo).zoneId; LocalDateTime result = instant.atZone(zoneId).toLocalDateTime(); return new PythonDateTime(result.toLocalDate(), result.toLocalTime(), zoneId); } } public static PythonDateTime utc_from_timestamp(PythonLikeType type, PythonNumber timestamp) { if (type != DATE_TIME_TYPE) { throw new TypeError("Unknown datetime type: " + type); } if (timestamp instanceof PythonInteger) { return utc_from_timestamp((PythonInteger) timestamp); } else { return utc_from_timestamp((PythonFloat) timestamp); } } public static PythonDateTime utc_from_timestamp(PythonInteger timestamp) { return new PythonDateTime(LocalDateTime.ofEpochSecond(timestamp.getValue().longValue(), 0, ZoneOffset.UTC)); } public static PythonDateTime utc_from_timestamp(PythonFloat timestamp) { long epochSeconds = (long) Math.floor(timestamp.getValue().doubleValue()); double remainder = timestamp.getValue().doubleValue() - epochSeconds; int nanos = (int) Math.round(remainder * 1_000_000_000); return new PythonDateTime(LocalDateTime.ofEpochSecond(timestamp.getValue().longValue(), nanos, ZoneOffset.UTC)); } public static PythonDateTime combine(PythonLikeType type, PythonDate pythonDate, PythonTime pythonTime, PythonLikeObject tzinfo) { if (type != DATE_TIME_TYPE) { throw new TypeError("Unknown datetime type " + type.getTypeName()); } if (tzinfo == null) { tzinfo = pythonTime.tzinfo; } return new PythonDateTime(pythonDate.localDate, pythonTime.localTime, tzinfo, pythonTime.fold.getValue().intValue()); } public static PythonDateTime from_iso_format(PythonString dateString) { Matcher matcher = ISO_FORMAT_PATTERN.matcher(dateString.getValue()); if (!matcher.find()) { throw new IllegalArgumentException("String \"" + dateString.getValue() + "\" is not an isoformat string"); } String year = matcher.group("year"); String month = matcher.group("month"); String day = matcher.group("day"); String hour = matcher.group("hour"); String minute = matcher.group("minute"); String second = matcher.group("second"); String microHigh = matcher.group("microHigh"); String microLow = matcher.group("microLow"); String timezoneHour = matcher.group("timezoneHour"); String timezoneMinute = matcher.group("timezoneMinute"); String timezoneSecond = matcher.group("timezoneSecond"); String timezoneMicro = matcher.group("timezoneMicro"); LocalDate date = LocalDate.of(Integer.parseInt(year), Integer.parseInt(month), Integer.parseInt(day)); int hoursPart = 0; int minutePart = 0; int secondPart = 0; int microPart = 0; if (hour != null) { hoursPart = Integer.parseInt(hour); } if (minute != null) { minutePart = Integer.parseInt(minute); } if (second != null) { secondPart = Integer.parseInt(second); } if (microHigh != null) { if (microLow != null) { microPart = Integer.parseInt(microHigh + microLow); } else { microPart = 1000 * Integer.parseInt(microHigh); } } LocalTime time = LocalTime.of(hoursPart, minutePart, secondPart, microPart * 1000); if (timezoneHour == null) { return new PythonDateTime(date, time); } int timezoneHourPart = Integer.parseInt(timezoneHour); int timezoneMinutePart = Integer.parseInt(timezoneMinute); int timezoneSecondPart = 0; int timezoneMicroPart = 0; if (timezoneSecond != null) { timezoneSecondPart = Integer.parseInt(timezoneSecond); } if (timezoneMicro != null) { timezoneMicroPart = Integer.parseInt(timezoneMicro); } // TODO: ZoneOffset does not support nanos ZoneOffset timezone = ZoneOffset.ofHoursMinutesSeconds(timezoneHourPart, timezoneMinutePart, timezoneSecondPart); return new PythonDateTime(date, time, timezone); } public static PythonDate from_iso_calendar(PythonInteger year, PythonInteger week, PythonInteger day) { int isoYear = year.getValue().intValue(); int dayInIsoYear = (week.getValue().intValue() * 7) + day.getValue().intValue(); int correction = LocalDate.of(isoYear, 1, 4).getDayOfWeek().getValue() + 3; int ordinalDate = dayInIsoYear - correction; if (ordinalDate <= 0) { int daysInYear = LocalDate.ofYearDay(isoYear - 1, 1).lengthOfYear(); return new PythonDateTime(LocalDate.ofYearDay(isoYear - 1, ordinalDate + daysInYear), LocalTime.MIN); } else if (ordinalDate > LocalDate.ofYearDay(isoYear, 1).lengthOfYear()) { int daysInYear = LocalDate.ofYearDay(isoYear, 1).lengthOfYear(); return new PythonDateTime(LocalDate.ofYearDay(isoYear + 1, ordinalDate - daysInYear), LocalTime.MIN); } else { return new PythonDateTime(LocalDate.ofYearDay(isoYear, ordinalDate), LocalTime.MIN); } } private static <T> T tryParseOrNull(DateTimeFormatter formatter, String text, TemporalQuery<T> query) { try { return formatter.parse(text, query); } catch (DateTimeException e) { return null; } } public static PythonDateTime strptime(PythonLikeType type, PythonString date_string, PythonString format) { if (type != DATE_TIME_TYPE) { throw new TypeError("Unknown datetime type (" + type + ")."); } var formatter = PythonDateTimeFormatter.getDateTimeFormatter(format.value); var asZonedDateTime = tryParseOrNull(formatter, date_string.value, ZonedDateTime::from); if (asZonedDateTime != null) { return new PythonDateTime(asZonedDateTime); } var asLocalDateTime = tryParseOrNull(formatter, date_string.value, LocalDateTime::from); if (asLocalDateTime != null) { return new PythonDateTime(asLocalDateTime); } var asLocalDate = tryParseOrNull(formatter, date_string.value, LocalDate::from); if (asLocalDate != null) { return new PythonDateTime(asLocalDate.atTime(LocalTime.MIDNIGHT)); } var asLocalTime = tryParseOrNull(formatter, date_string.value, LocalTime::from); if (asLocalTime != null) { return new PythonDateTime(asLocalTime.atDate(LocalDate.of(1900, 1, 1))); } throw new ValueError("data " + date_string.repr() + " does not match the format " + format.repr()); } public PythonDateTime add_time_delta(PythonTimeDelta summand) { if (dateTime instanceof LocalDateTime) { return new PythonDateTime(((LocalDateTime) dateTime).plus(summand.duration)); } else { return new PythonDateTime(((ZonedDateTime) dateTime).plus(summand.duration)); } } public PythonDateTime subtract_time_delta(PythonTimeDelta subtrahend) { if (dateTime instanceof LocalDateTime) { return new PythonDateTime(((LocalDateTime) dateTime).minus(subtrahend.duration)); } else { return new PythonDateTime(((ZonedDateTime) dateTime).minus(subtrahend.duration)); } } public PythonTimeDelta subtract_date_time(PythonDateTime subtrahend) { return new PythonTimeDelta(Duration.between(subtrahend.dateTime, dateTime)); } @Override public int compareTo(PythonDateTime other) { if (dateTime instanceof LocalDateTime) { return ((LocalDateTime) dateTime).compareTo((LocalDateTime) other.dateTime); } else { return ((ZonedDateTime) dateTime).compareTo((ZonedDateTime) other.dateTime); } } public PythonDate<PythonDate<?>> date() { if (dateTime instanceof LocalDateTime) { return new PythonDate<>(((LocalDateTime) dateTime).toLocalDate()); } else { return new PythonDate<>(((ZonedDateTime) dateTime).toLocalDate()); } } public PythonTime time() { if (dateTime instanceof LocalDateTime) { return new PythonTime(((LocalDateTime) dateTime).toLocalTime(), null, fold.getValue().intValue()); } else { return new PythonTime(((ZonedDateTime) dateTime).toLocalTime(), null, fold.getValue().intValue()); } } public PythonTime timetz() { if (dateTime instanceof LocalDateTime) { return new PythonTime(((LocalDateTime) dateTime).toLocalTime(), null, fold.getValue().intValue()); } else { ZonedDateTime zonedDateTime = (ZonedDateTime) dateTime; return new PythonTime(zonedDateTime.toLocalTime(), zonedDateTime.getZone(), fold.getValue().intValue()); } } public PythonDateTime replace(PythonInteger year, PythonInteger month, PythonInteger day, PythonInteger hour, PythonInteger minute, PythonInteger second, PythonInteger microsecond, PythonLikeObject tzinfo, PythonInteger fold) { if (year == null) { year = this.year; } if (month == null) { month = this.month; } if (day == null) { day = this.day; } if (hour == null) { hour = this.hour; } if (minute == null) { minute = this.minute; } if (second == null) { second = this.second; } if (microsecond == null) { microsecond = this.microsecond; } if (tzinfo == null) { tzinfo = this.tzinfo; } if (fold == null) { fold = this.fold; } return new PythonDateTime(LocalDate.of(year.getValue().intValue(), month.getValue().intValue(), day.getValue().intValue()), LocalTime.of(hour.getValue().intValue(), minute.getValue().intValue(), second.getValue().intValue(), microsecond.getValue().intValue() * 1000), tzinfo, fold.getValue().intValue()); } public PythonDateTime astimezone(PythonTzinfo zoneId) { throw new UnsupportedOperationException(); // TODO } public PythonLikeObject utcoffset() { if (zoneId == null) { return PythonNone.INSTANCE; } return new PythonTimeDelta(Duration.ofSeconds( zoneId.getRules().getOffset(((ZonedDateTime) dateTime).toInstant()).getTotalSeconds())); } public PythonLikeObject dst() { if (zoneId == null) { return PythonNone.INSTANCE; } return new PythonTimeDelta(zoneId.getRules().getDaylightSavings(((ZonedDateTime) dateTime).toInstant())); } public PythonLikeObject tzname() { if (zoneId == null) { return PythonNone.INSTANCE; } return PythonString.valueOf(zoneId.getRules().getOffset(((ZonedDateTime) dateTime).toInstant()) .getDisplayName(TextStyle.FULL_STANDALONE, Locale.getDefault())); } @Override public PythonLikeTuple timetuple() { PythonInteger yday = to_ordinal().subtract(PythonDate.of(year.value.intValueExact(), 1, 1).to_ordinal()).add(PythonInteger.ONE); PythonInteger dst; if (zoneId != null) { dst = zoneId.getRules().isDaylightSavings(((ZonedDateTime) dateTime).toInstant()) ? PythonInteger.ONE : PythonInteger.ZERO; } else { dst = PythonInteger.valueOf(-1); } return PythonLikeTuple.fromItems( year, month, day, hour, minute, second, weekday(), yday, dst); } public PythonLikeTuple utctimetuple() { if (zoneId == null) { return timetuple(); } else { ZonedDateTime utcDateTime = ((ZonedDateTime) dateTime).withZoneSameInstant(ZoneOffset.UTC); return new PythonDateTime(utcDateTime.toLocalDateTime()).timetuple(); } } public PythonFloat timestamp() { if (dateTime instanceof LocalDateTime) { LocalDateTime localDateTime = (LocalDateTime) dateTime; return PythonFloat.valueOf(localDateTime.toInstant(ZoneId.systemDefault() .getRules() .getOffset(localDateTime)) .toEpochMilli() / 1000.0); } else { return PythonFloat.valueOf(((ZonedDateTime) dateTime).toInstant().toEpochMilli() / 1000.0); } } public PythonString iso_format() { return iso_format(PythonString.valueOf("T"), PythonString.valueOf("auto")); } public PythonString iso_format(PythonString sep, PythonString timespec) { return new PythonString(localDate.toString() + sep.value + time().isoformat(timespec).value); } @Override public PythonString toPythonString() { return iso_format(PythonString.valueOf(" "), PythonString.valueOf("auto")); } @Override public PythonString ctime() { if (dateTime instanceof LocalDateTime) { return new PythonString(((LocalDateTime) dateTime).format(C_TIME_FORMATTER).replaceAll("(\\D)\\.", "$1")); } else { return new PythonString(((ZonedDateTime) dateTime).format(C_TIME_FORMATTER).replaceAll("(\\D)\\.", "$1")); } } @Override public PythonString strftime(PythonString format) { var formatter = PythonDateTimeFormatter.getDateTimeFormatter(format.value); return PythonString.valueOf(formatter.format(dateTime)); } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } PythonDateTime that = (PythonDateTime) o; return dateTime.equals(that.dateTime); } @Override public int hashCode() { return dateTime.hashCode(); } @Override public PythonInteger $method$__hash__() { return PythonInteger.valueOf(hashCode()); } }
0
java-sources/ai/timefold/solver/jpyinterpreter/1.24.0/ai/timefold/jpyinterpreter/types
java-sources/ai/timefold/solver/jpyinterpreter/1.24.0/ai/timefold/jpyinterpreter/types/datetime/PythonDateTimeFormatter.java
package ai.timefold.jpyinterpreter.types.datetime; import java.time.DayOfWeek; import java.time.format.DateTimeFormatter; import java.time.format.DateTimeFormatterBuilder; import java.time.format.FormatStyle; import java.time.format.TextStyle; import java.time.temporal.ChronoField; import java.time.temporal.WeekFields; import java.util.regex.Pattern; import ai.timefold.jpyinterpreter.types.errors.ValueError; /** * Based on the format specified * <a href="https://docs.python.org/3.11/library/datetime.html#strftime-and-strptime-format-codes">in * the datetime documentation</a>. */ public class PythonDateTimeFormatter { private final static Pattern DIRECTIVE_PATTERN = Pattern.compile("([^%]*)%(.)"); static DateTimeFormatter getDateTimeFormatter(String pattern) { DateTimeFormatterBuilder builder = new DateTimeFormatterBuilder(); var matcher = DIRECTIVE_PATTERN.matcher(pattern); int endIndex = 0; while (matcher.find()) { var literalPart = matcher.group(1); builder.appendLiteral(literalPart); endIndex = matcher.end(); char directive = matcher.group(2).charAt(0); switch (directive) { case 'a' -> { builder.appendText(ChronoField.DAY_OF_WEEK, TextStyle.SHORT); } case 'A' -> { builder.appendText(ChronoField.DAY_OF_WEEK, TextStyle.FULL); } case 'w' -> { builder.appendValue(ChronoField.DAY_OF_WEEK); } case 'd' -> { builder.appendValue(ChronoField.DAY_OF_MONTH, 2); } case 'b' -> { builder.appendText(ChronoField.MONTH_OF_YEAR, TextStyle.SHORT); } case 'B' -> { builder.appendText(ChronoField.MONTH_OF_YEAR, TextStyle.FULL); } case 'm' -> { builder.appendValue(ChronoField.MONTH_OF_YEAR, 2); } case 'y' -> { builder.appendPattern("uu"); } case 'Y' -> { builder.appendValue(ChronoField.YEAR); } case 'H' -> { builder.appendValue(ChronoField.HOUR_OF_DAY, 2); } case 'I' -> { builder.appendValue(ChronoField.HOUR_OF_AMPM, 2); } case 'p' -> { builder.appendText(ChronoField.AMPM_OF_DAY); } case 'M' -> { builder.appendValue(ChronoField.MINUTE_OF_HOUR, 2); } case 'S' -> { builder.appendValue(ChronoField.SECOND_OF_MINUTE, 2); } case 'f' -> { builder.appendValue(ChronoField.MICRO_OF_SECOND, 6); } case 'z' -> { builder.appendOffset("+HHmmss", ""); } case 'Z' -> { builder.appendZoneOrOffsetId(); } case 'j' -> { builder.appendValue(ChronoField.DAY_OF_YEAR, 3); } case 'U' -> { builder.appendValue(WeekFields.of(DayOfWeek.SUNDAY, 7).weekOfYear(), 2); } case 'W' -> { builder.appendValue(WeekFields.of(DayOfWeek.MONDAY, 7).weekOfYear(), 2); } case 'c' -> { builder.appendLocalized(FormatStyle.MEDIUM, FormatStyle.MEDIUM); } case 'x' -> { builder.appendLocalized(FormatStyle.MEDIUM, null); } case 'X' -> { builder.appendLocalized(null, FormatStyle.MEDIUM); } case '%' -> { builder.appendLiteral("%"); } case 'G' -> { builder.appendValue(WeekFields.of(DayOfWeek.MONDAY, 4).weekBasedYear()); } case 'u' -> { builder.appendValue(WeekFields.of(DayOfWeek.MONDAY, 4).dayOfWeek(), 1); } case 'V' -> { builder.appendValue(WeekFields.of(DayOfWeek.MONDAY, 4).weekOfYear(), 2); } default -> { throw new ValueError("Invalid directive (" + directive + ") in format string (" + pattern + ")."); } } } builder.appendLiteral(pattern.substring(endIndex)); return builder.toFormatter(); } }
0
java-sources/ai/timefold/solver/jpyinterpreter/1.24.0/ai/timefold/jpyinterpreter/types
java-sources/ai/timefold/solver/jpyinterpreter/1.24.0/ai/timefold/jpyinterpreter/types/datetime/PythonTime.java
package ai.timefold.jpyinterpreter.types.datetime; import java.math.BigInteger; import java.time.Duration; import java.time.Instant; import java.time.LocalTime; import java.time.ZoneId; import java.time.ZoneOffset; import java.time.format.TextStyle; import java.time.temporal.ChronoField; import java.util.Locale; import java.util.regex.Matcher; import java.util.regex.Pattern; import ai.timefold.jpyinterpreter.PythonLikeObject; import ai.timefold.jpyinterpreter.PythonOverloadImplementor; import ai.timefold.jpyinterpreter.types.AbstractPythonLikeObject; import ai.timefold.jpyinterpreter.types.PythonLikeType; import ai.timefold.jpyinterpreter.types.PythonNone; import ai.timefold.jpyinterpreter.types.PythonString; import ai.timefold.jpyinterpreter.types.errors.ValueError; import ai.timefold.jpyinterpreter.types.numeric.PythonInteger; import ai.timefold.jpyinterpreter.util.arguments.ArgumentSpec; import ai.timefold.solver.core.impl.domain.solution.cloner.PlanningImmutable; public class PythonTime extends AbstractPythonLikeObject implements PlanningImmutable { // Taken from https://docs.python.org/3/library/datetime.html#datetime.time.fromisoformat private static final Pattern ISO_FORMAT_PATTERN = Pattern.compile("^(?<hour>\\d\\d)" + "(:(?<minute>\\d\\d)" + "(:(?<second>\\d\\d)" + "(\\.(?<microHigh>\\d\\d\\d)" + "(?<microLow>\\d\\d\\d)?" + ")?)?)?" + "(\\+(?<timezoneHour>\\d\\d):(?<timezoneMinute>\\d\\d)" + "(:(?<timezoneSecond>\\d\\d)" + "(:\\.(?<timezoneMicro>\\d\\d\\d\\d\\d\\d)" + ")?)?)?$"); public static PythonLikeType TIME_TYPE = new PythonLikeType("time", PythonTime.class); public static PythonLikeType $TYPE = TIME_TYPE; static { try { registerMethods(); TIME_TYPE.$setAttribute("min", new PythonTime(LocalTime.MAX)); TIME_TYPE.$setAttribute("max", new PythonTime(LocalTime.MIN)); TIME_TYPE.$setAttribute("resolution", new PythonTimeDelta(Duration.ofNanos(1000L))); PythonOverloadImplementor.createDispatchesFor(TIME_TYPE); } catch (NoSuchMethodException e) { throw new RuntimeException(e); } } private static void registerMethods() throws NoSuchMethodException { TIME_TYPE.addConstructor(ArgumentSpec.forFunctionReturning("datetime.time", PythonTime.class.getName()) .addArgument("hour", PythonInteger.class.getName(), PythonInteger.ZERO) .addArgument("minute", PythonInteger.class.getName(), PythonInteger.ZERO) .addArgument("second", PythonInteger.class.getName(), PythonInteger.ZERO) .addArgument("microsecond", PythonInteger.class.getName(), PythonInteger.ZERO) .addArgument("tzinfo", PythonLikeObject.class.getName(), PythonNone.INSTANCE) .addKeywordOnlyArgument("fold", PythonInteger.class.getName(), PythonInteger.ZERO) .asPythonFunctionSignature( PythonTime.class.getMethod("of", PythonInteger.class, PythonInteger.class, PythonInteger.class, PythonInteger.class, PythonLikeObject.class, PythonInteger.class))); TIME_TYPE.addMethod("fromisoformat", ArgumentSpec.forFunctionReturning("fromisoformat", PythonTime.class.getName()) .addArgument("time_string", PythonString.class.getName()) .asStaticPythonFunctionSignature(PythonTime.class.getMethod("from_iso_format", PythonString.class))); TIME_TYPE.addMethod("replace", ArgumentSpec.forFunctionReturning("replace", PythonTime.class.getName()) .addNullableArgument("hour", PythonInteger.class.getName()) .addNullableArgument("minute", PythonInteger.class.getName()) .addNullableArgument("second", PythonInteger.class.getName()) .addNullableArgument("microsecond", PythonInteger.class.getName()) .addNullableArgument("tzinfo", PythonLikeObject.class.getName()) .addNullableKeywordOnlyArgument("fold", PythonInteger.class.getName()) .asPythonFunctionSignature(PythonTime.class.getMethod("replace", PythonInteger.class, PythonInteger.class, PythonInteger.class, PythonInteger.class, PythonLikeObject.class, PythonInteger.class))); TIME_TYPE.addMethod("isoformat", ArgumentSpec.forFunctionReturning("isoformat", PythonString.class.getName()) .addArgument("timespec", PythonString.class.getName(), PythonString.valueOf("auto")) .asPythonFunctionSignature(PythonTime.class.getMethod("isoformat", PythonString.class))); TIME_TYPE.addMethod("strftime", ArgumentSpec.forFunctionReturning("strftime", PythonString.class.getName()) .addArgument("format", PythonString.class.getName()) .asPythonFunctionSignature(PythonTime.class.getMethod("strftime", PythonString.class))); TIME_TYPE.addMethod("tzname", PythonTime.class.getMethod("tzname")); TIME_TYPE.addMethod("utcoffset", PythonTime.class.getMethod("utcoffset")); TIME_TYPE.addMethod("dst", PythonTime.class.getMethod("dst")); } final LocalTime localTime; final ZoneId zoneId; public final PythonInteger hour; public final PythonInteger minute; public final PythonInteger second; public final PythonInteger microsecond; public final PythonInteger fold; public final PythonLikeObject tzinfo; public PythonTime(LocalTime localTime) { this(localTime, null, 0); } public PythonTime(LocalTime localTime, ZoneId zoneId) { this(localTime, zoneId, 0); } public PythonTime(LocalTime localTime, ZoneId zoneId, int fold) { super(TIME_TYPE); this.localTime = localTime; this.zoneId = zoneId; hour = PythonInteger.valueOf(localTime.getHour()); minute = PythonInteger.valueOf(localTime.getMinute()); second = PythonInteger.valueOf(localTime.getSecond()); microsecond = PythonInteger.valueOf(localTime.getNano() / 1000); // Micro = Nano // 1000 tzinfo = zoneId == null ? PythonNone.INSTANCE : new PythonTzinfo(zoneId); this.fold = PythonInteger.valueOf(fold); } @Override public PythonLikeObject $getAttributeOrNull(String name) { switch (name) { case "hour": return hour; case "minute": return minute; case "second": return second; case "microsecond": return microsecond; case "tzinfo": return tzinfo; case "fold": return fold; default: return super.$getAttributeOrNull(name); } } public static PythonTime of(PythonInteger hour, PythonInteger minute, PythonInteger second, PythonInteger microsecond, PythonLikeObject tzinfo, PythonInteger fold) { return of(hour.value.intValueExact(), minute.value.intValueExact(), second.value.intValueExact(), microsecond.value.intValueExact(), (tzinfo == PythonNone.INSTANCE) ? null : ((PythonTzinfo) tzinfo).zoneId, fold.value.intValueExact()); } public static PythonTime of(int hour, int minute, int second, int microsecond, ZoneId zoneId, int fold) { if (hour < 0 || hour >= 24) { throw new ValueError("hour must be in range 0 <= hour < 24"); } if (minute < 0 || minute >= 60) { throw new ValueError("minute must be in range 0 <= minute < 60"); } if (second < 0 || second >= 60) { throw new ValueError("second must be in range 0 <= second < 60"); } if (microsecond < 0 || microsecond >= 1000000) { throw new ValueError("microsecond must be in range 0 <= microsecond < 1000000"); } if (fold != 0 && fold != 1) { throw new ValueError("fold must be in [0, 1]"); } return new PythonTime(LocalTime.of(hour, minute, second, microsecond * 1000), zoneId, fold); } public static PythonTime from_iso_format(PythonString dateString) { Matcher matcher = ISO_FORMAT_PATTERN.matcher(dateString.getValue()); if (!matcher.find()) { throw new ValueError("String \"" + dateString.getValue() + "\" is not an isoformat string"); } String hour = matcher.group("hour"); String minute = matcher.group("minute"); String second = matcher.group("second"); String microHigh = matcher.group("microHigh"); String microLow = matcher.group("microLow"); String timezoneHour = matcher.group("timezoneHour"); String timezoneMinute = matcher.group("timezoneMinute"); String timezoneSecond = matcher.group("timezoneSecond"); String timezoneMicro = matcher.group("timezoneMicro"); int hoursPart = 0; int minutePart = 0; int secondPart = 0; int microPart = 0; if (hour != null && !hour.isEmpty()) { hoursPart = Integer.parseInt(hour); } if (minute != null && !minute.isEmpty()) { minutePart = Integer.parseInt(minute); } if (second != null && !second.isEmpty()) { secondPart = Integer.parseInt(second); } if (microHigh != null && !microHigh.isEmpty()) { if (microLow != null && !microLow.isEmpty()) { microPart = Integer.parseInt(microHigh + microLow); } else { microPart = 1000 * Integer.parseInt(microHigh); } } LocalTime time = LocalTime.of(hoursPart, minutePart, secondPart, microPart * 1000); if (timezoneHour == null || timezoneHour.isEmpty()) { return new PythonTime(time); } int timezoneHourPart = Integer.parseInt(timezoneHour); int timezoneMinutePart = Integer.parseInt(timezoneMinute); int timezoneSecondPart = 0; int timezoneMicroPart = 0; if (timezoneSecond != null) { timezoneSecondPart = Integer.parseInt(timezoneSecond); } if (timezoneMicro != null) { timezoneMicroPart = Integer.parseInt(timezoneMicro); } // TODO: ZoneOffset does not support nanos ZoneOffset timezone = ZoneOffset.ofHoursMinutesSeconds(timezoneHourPart, timezoneMinutePart, timezoneSecondPart); return new PythonTime(time, timezone); } public PythonTime replace(PythonInteger hour, PythonInteger minute, PythonInteger second, PythonInteger microsecond, PythonLikeObject tzinfo, PythonInteger fold) { if (hour == null) { hour = this.hour; } if (minute == null) { minute = this.minute; } if (second == null) { second = this.second; } if (microsecond == null) { microsecond = this.microsecond; } if (tzinfo == null) { tzinfo = (zoneId != null) ? new PythonTzinfo(zoneId) : PythonNone.INSTANCE; } if (fold == null) { fold = this.fold; } return of(hour, minute, second, microsecond, tzinfo, fold); } public PythonLikeObject utcoffset() { if (zoneId == null) { return PythonNone.INSTANCE; } return new PythonTimeDelta(Duration.ofSeconds(zoneId.getRules().getOffset(Instant.ofEpochMilli(0L)).getTotalSeconds())); } public PythonLikeObject dst() { if (zoneId == null) { return PythonNone.INSTANCE; } return new PythonTimeDelta(zoneId.getRules().getDaylightSavings(Instant.ofEpochMilli(0L))); } public PythonLikeObject tzname() { if (zoneId == null) { return PythonNone.INSTANCE; } return PythonString.valueOf(zoneId.getDisplayName(TextStyle.FULL_STANDALONE, Locale.getDefault())); } public PythonString isoformat(PythonString formatSpec) { final String result; switch (formatSpec.value) { case "auto": if (microsecond.value.equals(BigInteger.ZERO)) { result = String.format("%02d:%02d:%02d", localTime.getHour(), localTime.getMinute(), localTime.getSecond()); } else { result = String.format("%02d:%02d:%02d.%06d", localTime.getHour(), localTime.getMinute(), localTime.getSecond(), localTime.get(ChronoField.MICRO_OF_SECOND)); } break; case "hours": result = String.format("%02d", localTime.getHour()); break; case "minutes": result = String.format("%02d:%02d", localTime.getHour(), localTime.getMinute()); break; case "seconds": result = String.format("%02d:%02d:%02d", localTime.getHour(), localTime.getMinute(), localTime.getSecond()); break; case "milliseconds": result = String.format("%02d:%02d:%02d.%03d", localTime.getHour(), localTime.getMinute(), localTime.getSecond(), localTime.get(ChronoField.MILLI_OF_SECOND)); break; case "microseconds": result = String.format("%02d:%02d:%02d.%06d", localTime.getHour(), localTime.getMinute(), localTime.getSecond(), localTime.get(ChronoField.MICRO_OF_SECOND)); break; default: throw new ValueError("Invalid timespec: " + formatSpec.repr()); } return PythonString.valueOf(result); } public PythonString strftime(PythonString formatSpec) { var formatter = PythonDateTimeFormatter.getDateTimeFormatter(formatSpec.value); return PythonString.valueOf(formatter.format(localTime)); } @Override public PythonString $method$__str__() { return PythonString.valueOf(toString()); } @Override public String toString() { return localTime.toString(); } @Override public PythonInteger $method$__hash__() { return PythonInteger.valueOf(hashCode()); } }
0
java-sources/ai/timefold/solver/jpyinterpreter/1.24.0/ai/timefold/jpyinterpreter/types
java-sources/ai/timefold/solver/jpyinterpreter/1.24.0/ai/timefold/jpyinterpreter/types/datetime/PythonTimeDelta.java
package ai.timefold.jpyinterpreter.types.datetime; import java.math.BigInteger; import java.time.Duration; import java.time.temporal.ChronoUnit; import java.time.temporal.TemporalUnit; import ai.timefold.jpyinterpreter.PythonBinaryOperator; import ai.timefold.jpyinterpreter.PythonLikeObject; import ai.timefold.jpyinterpreter.PythonOverloadImplementor; import ai.timefold.jpyinterpreter.PythonUnaryOperator; import ai.timefold.jpyinterpreter.types.AbstractPythonLikeObject; import ai.timefold.jpyinterpreter.types.PythonLikeComparable; import ai.timefold.jpyinterpreter.types.PythonLikeType; import ai.timefold.jpyinterpreter.types.PythonString; import ai.timefold.jpyinterpreter.types.errors.ValueError; import ai.timefold.jpyinterpreter.types.errors.arithmetic.ZeroDivisionError; import ai.timefold.jpyinterpreter.types.numeric.PythonBoolean; 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.util.arguments.ArgumentSpec; import ai.timefold.solver.core.impl.domain.solution.cloner.PlanningImmutable; /** * Python docs: <a href="https://docs.python.org/3/library/datetime.html#timedelta-objects">timedelta-objects</a> */ public class PythonTimeDelta extends AbstractPythonLikeObject implements PythonLikeComparable<PythonTimeDelta>, PlanningImmutable { private static final int NANOS_IN_SECOND = 1_000_000_000; private static final int SECONDS_IN_DAY = 86400; // 24 * 60 * 60 public static PythonLikeType TIME_DELTA_TYPE = new PythonLikeType("timedelta", PythonTimeDelta.class); public static PythonLikeType $TYPE = TIME_DELTA_TYPE; static { try { PythonLikeComparable.setup(TIME_DELTA_TYPE); registerMethods(); TIME_DELTA_TYPE.$setAttribute("min", new PythonTimeDelta(Duration.ofDays(-999999999))); TIME_DELTA_TYPE.$setAttribute("max", new PythonTimeDelta(Duration.ofDays(1000000000) .minusNanos(1000))); TIME_DELTA_TYPE.$setAttribute("resolution", new PythonTimeDelta(Duration.ofNanos(1000))); PythonOverloadImplementor.createDispatchesFor(TIME_DELTA_TYPE); } catch (NoSuchMethodException e) { throw new RuntimeException(e); } } private static void registerMethods() throws NoSuchMethodException { // Constructor TIME_DELTA_TYPE.addConstructor(ArgumentSpec.forFunctionReturning("timedelta", PythonTimeDelta.class.getName()) .addArgument("days", PythonNumber.class.getName(), PythonInteger.ZERO) .addArgument("seconds", PythonNumber.class.getName(), PythonInteger.ZERO) .addArgument("microseconds", PythonNumber.class.getName(), PythonInteger.ZERO) .addArgument("milliseconds", PythonNumber.class.getName(), PythonInteger.ZERO) .addArgument("minutes", PythonNumber.class.getName(), PythonInteger.ZERO) .addArgument("hours", PythonNumber.class.getName(), PythonInteger.ZERO) .addArgument("weeks", PythonNumber.class.getName(), PythonInteger.ZERO) .asPythonFunctionSignature(PythonTimeDelta.class.getMethod("of", PythonNumber.class, PythonNumber.class, PythonNumber.class, PythonNumber.class, PythonNumber.class, PythonNumber.class, PythonNumber.class))); // Unary TIME_DELTA_TYPE.addUnaryMethod(PythonUnaryOperator.POSITIVE, PythonTimeDelta.class.getMethod("pos")); TIME_DELTA_TYPE.addUnaryMethod(PythonUnaryOperator.NEGATIVE, PythonTimeDelta.class.getMethod("negate")); TIME_DELTA_TYPE.addUnaryMethod(PythonUnaryOperator.ABS, PythonTimeDelta.class.getMethod("abs")); TIME_DELTA_TYPE.addUnaryMethod(PythonUnaryOperator.AS_BOOLEAN, PythonTimeDelta.class.getMethod("isZero")); TIME_DELTA_TYPE.addUnaryMethod(PythonUnaryOperator.AS_STRING, PythonTimeDelta.class.getMethod("toPythonString")); TIME_DELTA_TYPE.addUnaryMethod(PythonUnaryOperator.REPRESENTATION, PythonTimeDelta.class.getMethod("toPythonRepr")); // Binary TIME_DELTA_TYPE.addBinaryMethod(PythonBinaryOperator.ADD, PythonTimeDelta.class.getMethod("add_time_delta", PythonTimeDelta.class)); TIME_DELTA_TYPE.addBinaryMethod(PythonBinaryOperator.SUBTRACT, PythonTimeDelta.class.getMethod("subtract_time_delta", PythonTimeDelta.class)); TIME_DELTA_TYPE.addBinaryMethod(PythonBinaryOperator.MULTIPLY, PythonTimeDelta.class.getMethod("get_integer_multiple", PythonInteger.class)); TIME_DELTA_TYPE.addBinaryMethod(PythonBinaryOperator.MULTIPLY, PythonTimeDelta.class.getMethod("get_float_multiple", PythonFloat.class)); TIME_DELTA_TYPE.addBinaryMethod(PythonBinaryOperator.TRUE_DIVIDE, PythonTimeDelta.class.getMethod("divide_time_delta", PythonTimeDelta.class)); TIME_DELTA_TYPE.addBinaryMethod(PythonBinaryOperator.TRUE_DIVIDE, PythonTimeDelta.class.getMethod("divide_integer", PythonInteger.class)); TIME_DELTA_TYPE.addBinaryMethod(PythonBinaryOperator.TRUE_DIVIDE, PythonTimeDelta.class.getMethod("divide_float", PythonFloat.class)); TIME_DELTA_TYPE.addBinaryMethod(PythonBinaryOperator.FLOOR_DIVIDE, PythonTimeDelta.class.getMethod("floor_divide_time_delta", PythonTimeDelta.class)); TIME_DELTA_TYPE.addBinaryMethod(PythonBinaryOperator.FLOOR_DIVIDE, PythonTimeDelta.class.getMethod("floor_divide_integer", PythonInteger.class)); TIME_DELTA_TYPE.addBinaryMethod(PythonBinaryOperator.MODULO, PythonTimeDelta.class.getMethod("remainder_time_delta", PythonTimeDelta.class)); // Methods TIME_DELTA_TYPE.addMethod("total_seconds", PythonTimeDelta.class.getMethod("total_seconds")); } final Duration duration; public final PythonInteger days; public final PythonInteger seconds; public final PythonInteger microseconds; public PythonTimeDelta(Duration duration) { super(TIME_DELTA_TYPE); this.duration = duration; if (duration.isNegative()) { if (duration.getSeconds() % SECONDS_IN_DAY != 0 || duration.getNano() != 0) { days = PythonInteger.valueOf(duration.toDays() - 1); seconds = PythonInteger.valueOf((SECONDS_IN_DAY + (duration.toSeconds() % SECONDS_IN_DAY) % SECONDS_IN_DAY)); } else { days = PythonInteger.valueOf(duration.toDays()); seconds = PythonInteger.valueOf(Math.abs(duration.toSeconds() % SECONDS_IN_DAY)); } } else { days = PythonInteger.valueOf(duration.toDays()); seconds = PythonInteger.valueOf(Math.abs(duration.toSeconds() % SECONDS_IN_DAY)); } microseconds = PythonInteger.valueOf(duration.toNanosPart() / 1000); } @Override public PythonLikeObject $getAttributeOrNull(String name) { switch (name) { case "days": return days; case "seconds": return seconds; case "microseconds": return microseconds; default: return super.$getAttributeOrNull(name); } } public static PythonTimeDelta of(int days, int seconds, int microseconds) { return new PythonTimeDelta(Duration.ofDays(days).plusSeconds(seconds) .plusNanos(microseconds * 1000L)); } public static PythonTimeDelta of(PythonNumber days, PythonNumber seconds, PythonNumber microseconds, PythonNumber milliseconds, PythonNumber minutes, PythonNumber hours, PythonNumber weeks) { Duration out = Duration.ZERO; out = addToDuration(out, days, ChronoUnit.DAYS); out = addToDuration(out, seconds, ChronoUnit.SECONDS); out = addToDuration(out, microseconds, ChronoUnit.MICROS); out = addToDuration(out, milliseconds, ChronoUnit.MILLIS); out = addToDuration(out, minutes, ChronoUnit.MINUTES); out = addToDuration(out, hours, ChronoUnit.HOURS); if (weeks instanceof PythonInteger) { // weeks is an estimated duration; cannot use addToDuration out = out.plusDays(weeks.getValue().longValue() * 7); } else if (weeks instanceof PythonFloat) { out = out.plusNanos(Math.round(Duration.ofDays(7L).toNanos() * weeks.getValue().doubleValue())); } else { throw new ValueError("Amount for weeks is not a float or integer."); } return new PythonTimeDelta(out); } private static Duration addToDuration(Duration duration, PythonNumber amount, TemporalUnit temporalUnit) { if (amount instanceof PythonInteger) { return duration.plus(amount.getValue().longValue(), temporalUnit); } else if (amount instanceof PythonFloat) { return duration.plusNanos(Math.round(temporalUnit.getDuration().toNanos() * amount.getValue().doubleValue())); } else { throw new IllegalArgumentException("Amount for " + temporalUnit.toString() + " is not a float or integer."); } } public PythonFloat total_seconds() { return PythonFloat.valueOf((double) duration.toNanos() / NANOS_IN_SECOND); } public PythonTimeDelta add_time_delta(PythonTimeDelta other) { return new PythonTimeDelta(duration.plus(other.duration)); } public PythonTimeDelta subtract_time_delta(PythonTimeDelta other) { return new PythonTimeDelta(duration.minus(other.duration)); } public PythonTimeDelta get_integer_multiple(PythonInteger multiple) { return new PythonTimeDelta(duration.multipliedBy(multiple.getValue().longValue())); } public PythonTimeDelta get_float_multiple(PythonFloat multiple) { double multipleAsDouble = multiple.getValue().doubleValue(); long flooredMultiple = (long) Math.floor(multipleAsDouble); double fractionalPart = multipleAsDouble - flooredMultiple; long nanos = duration.toNanos(); double fractionalNanos = fractionalPart * nanos; long fractionalNanosInMicroResolution = Math.round(fractionalNanos / 1000) * 1000; return new PythonTimeDelta(duration.multipliedBy(flooredMultiple) .plus(Duration.ofNanos(fractionalNanosInMicroResolution))); } public PythonFloat divide_time_delta(PythonTimeDelta divisor) { if (divisor.duration.equals(Duration.ZERO)) { throw new ZeroDivisionError("timedelta division or modulo by zero"); } return PythonFloat.valueOf((double) duration.toNanos() / divisor.duration.toNanos()); } public PythonTimeDelta divide_integer(PythonInteger divisor) { if (divisor.value.equals(BigInteger.ZERO)) { throw new ZeroDivisionError("timedelta division or modulo by zero"); } return new PythonTimeDelta(duration.dividedBy(divisor.getValue().longValue())); } public PythonTimeDelta divide_float(PythonFloat divisor) { if (divisor.value == 0.0) { throw new ZeroDivisionError("timedelta division or modulo by zero"); } double fractionalNanos = duration.toNanos() / divisor.getValue().doubleValue(); return new PythonTimeDelta(Duration.ofNanos(Math.round(fractionalNanos / 1000) * 1000)); } public PythonInteger floor_divide_time_delta(PythonTimeDelta divisor) { if (divisor.duration.equals(Duration.ZERO)) { throw new ZeroDivisionError("timedelta division or modulo by zero"); } long amount = duration.dividedBy(divisor.duration); if (divisor.duration.multipliedBy(amount).equals(duration)) { // division exact return PythonInteger.valueOf(amount); } // division not exact // Java use round to zero; Python use floor // If both operands have the same sign, result is positive, and round to zero = floor // If operands have different signs, the result is negative, and round to zero = floor + 1 if (duration.isNegative() == divisor.duration.isNegative()) { // same sign return PythonInteger.valueOf(amount); } else { // different sign return PythonInteger.valueOf(amount - 1); } } public PythonTimeDelta floor_divide_integer(PythonInteger divisor) { if (divisor.value.equals(BigInteger.ZERO)) { throw new ZeroDivisionError("timedelta division or modulo by zero"); } return new PythonTimeDelta(duration.dividedBy(divisor.getValue().longValue())); } public PythonTimeDelta remainder_time_delta(PythonTimeDelta divisor) { boolean leftIsNegative = duration.isNegative(); int rightHandSign = divisor.duration.compareTo(Duration.ZERO); if (rightHandSign == 0) { throw new ZeroDivisionError("timedelta division or modulo by zero"); } long floorDivisionResult = duration.abs().dividedBy(divisor.abs().duration); Duration remainder; if (rightHandSign > 0) { // Need a positive result if (leftIsNegative) { remainder = divisor.duration.plus(duration.plus(divisor.duration.multipliedBy(floorDivisionResult))); } else { remainder = duration.minus(divisor.duration.multipliedBy(floorDivisionResult)); } } else { // Need a negative result if (leftIsNegative) { remainder = duration.minus(divisor.duration.multipliedBy(floorDivisionResult)); } else { remainder = divisor.duration.plus(duration.plus(divisor.duration.multipliedBy(floorDivisionResult))); } } return new PythonTimeDelta(remainder); } public PythonTimeDelta pos() { return this; } public PythonTimeDelta negate() { return new PythonTimeDelta(duration.negated()); } public PythonTimeDelta abs() { return new PythonTimeDelta(duration.abs()); } public PythonString toPythonString() { return new PythonString(toString()); } public PythonString toPythonRepr() { StringBuilder out = new StringBuilder("datetime.timedelta("); if (!days.value.equals(BigInteger.ZERO)) { out.append("days=").append(days); } if (!seconds.value.equals(BigInteger.ZERO)) { if (out.charAt(out.length() - 1) != '(') { out.append(", "); } out.append("seconds=").append(seconds); } if (!microseconds.value.equals(BigInteger.ZERO)) { if (out.charAt(out.length() - 1) != '(') { out.append(", "); } out.append("microseconds=").append(microseconds); } if (out.charAt(out.length() - 1) == '(') { // No content; do a attribute-less zero out.append("0"); } out.append(")"); return PythonString.valueOf(out.toString()); } public PythonBoolean isZero() { return PythonBoolean.valueOf(duration.isZero()); } @Override public PythonString $method$__str__() { return PythonString.valueOf(toString()); } @Override public String toString() { StringBuilder out = new StringBuilder(); long daysPart = duration.toDaysPart(); Duration durationAfterDay = duration.minusDays(daysPart); if (duration.isNegative() && !Duration.ofDays(1).multipliedBy(daysPart).equals(duration)) { daysPart = daysPart - 1; durationAfterDay = durationAfterDay.plus(Duration.ofDays(1)); } if (daysPart != 0) { out.append(daysPart); out.append(" day"); if (daysPart > 1 || daysPart < -1) { out.append('s'); } out.append(", "); } int hours = durationAfterDay.toHoursPart(); out.append(hours); out.append(':'); int minutes = durationAfterDay.toMinutesPart(); out.append(String.format("%02d", minutes)); out.append(':'); int seconds = durationAfterDay.toSecondsPart(); out.append(String.format("%02d", seconds)); int micros = durationAfterDay.toNanosPart() / 1000; if (micros != 0) { out.append(String.format(".%06d", micros)); } return out.toString(); } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } PythonTimeDelta that = (PythonTimeDelta) o; return duration.equals(that.duration); } @Override public int hashCode() { return duration.hashCode(); } @Override public PythonString $method$__repr__() { return toPythonRepr(); } @Override public PythonInteger $method$__hash__() { return PythonInteger.valueOf(hashCode()); } @Override public int compareTo(PythonTimeDelta pythonTimeDelta) { return duration.compareTo(pythonTimeDelta.duration); } }
0
java-sources/ai/timefold/solver/jpyinterpreter/1.24.0/ai/timefold/jpyinterpreter/types
java-sources/ai/timefold/solver/jpyinterpreter/1.24.0/ai/timefold/jpyinterpreter/types/datetime/PythonTzinfo.java
package ai.timefold.jpyinterpreter.types.datetime; import java.time.ZoneId; import ai.timefold.jpyinterpreter.MethodDescriptor; import ai.timefold.jpyinterpreter.PythonFunctionSignature; import ai.timefold.jpyinterpreter.PythonLikeObject; import ai.timefold.jpyinterpreter.PythonOverloadImplementor; import ai.timefold.jpyinterpreter.types.AbstractPythonLikeObject; import ai.timefold.jpyinterpreter.types.BuiltinTypes; import ai.timefold.jpyinterpreter.types.PythonLikeType; import ai.timefold.jpyinterpreter.types.PythonString; import ai.timefold.solver.core.impl.domain.solution.cloner.PlanningImmutable; public class PythonTzinfo extends AbstractPythonLikeObject implements PlanningImmutable { public static PythonLikeType TZ_INFO_TYPE = new PythonLikeType("tzinfo", PythonTzinfo.class); public static PythonLikeType $TYPE = TZ_INFO_TYPE; static { try { registerMethods(); PythonOverloadImplementor.createDispatchesFor(TZ_INFO_TYPE); } catch (NoSuchMethodException e) { throw new RuntimeException(e); } } private static void registerMethods() throws NoSuchMethodException { TZ_INFO_TYPE.addMethod("utcoffset", new PythonFunctionSignature(new MethodDescriptor( PythonTzinfo.class.getMethod("utcoffset", PythonLikeObject.class)), PythonTimeDelta.TIME_DELTA_TYPE, BuiltinTypes.BASE_TYPE)); TZ_INFO_TYPE.addMethod("dst", new PythonFunctionSignature(new MethodDescriptor( PythonTzinfo.class.getMethod("dst", PythonLikeObject.class)), PythonTimeDelta.TIME_DELTA_TYPE, BuiltinTypes.BASE_TYPE)); TZ_INFO_TYPE.addMethod("tzname", new PythonFunctionSignature(new MethodDescriptor( PythonTzinfo.class.getMethod("tzname", PythonLikeObject.class)), BuiltinTypes.STRING_TYPE, BuiltinTypes.BASE_TYPE)); } final ZoneId zoneId; public PythonTzinfo(ZoneId zoneId) { super(TZ_INFO_TYPE); this.zoneId = zoneId; } public PythonTimeDelta utcoffset(PythonLikeObject dateTime) { throw new UnsupportedOperationException(); // TODO } public PythonTimeDelta dst(PythonLikeObject dateTime) { throw new UnsupportedOperationException(); // TODO } public PythonString tzname(PythonLikeObject dateTime) { throw new UnsupportedOperationException(); // TODO } }
0
java-sources/ai/timefold/solver/jpyinterpreter/1.24.0/ai/timefold/jpyinterpreter/types
java-sources/ai/timefold/solver/jpyinterpreter/1.24.0/ai/timefold/jpyinterpreter/types/errors/AttributeError.java
package ai.timefold.jpyinterpreter.types.errors; import java.util.List; import ai.timefold.jpyinterpreter.PythonLikeObject; import ai.timefold.jpyinterpreter.types.PythonLikeType; public class AttributeError extends PythonException { public final static PythonLikeType ATTRIBUTE_ERROR_TYPE = new PythonLikeType("AttributeError", AttributeError.class, List.of(EXCEPTION_TYPE)), $TYPE = ATTRIBUTE_ERROR_TYPE; static { ATTRIBUTE_ERROR_TYPE.setConstructor( ((positionalArguments, namedArguments, callerInstance) -> new AttributeError(ATTRIBUTE_ERROR_TYPE, positionalArguments))); } public AttributeError() { super(ATTRIBUTE_ERROR_TYPE); } public AttributeError(String message) { super(ATTRIBUTE_ERROR_TYPE, message); } public AttributeError(PythonLikeType type, List<PythonLikeObject> args) { super(type, args); } }
0
java-sources/ai/timefold/solver/jpyinterpreter/1.24.0/ai/timefold/jpyinterpreter/types
java-sources/ai/timefold/solver/jpyinterpreter/1.24.0/ai/timefold/jpyinterpreter/types/errors/BufferError.java
package ai.timefold.jpyinterpreter.types.errors; import java.util.List; import ai.timefold.jpyinterpreter.PythonLikeObject; import ai.timefold.jpyinterpreter.types.PythonLikeType; /** * Raised when a buffer related operation cannot be performed. */ public class BufferError extends PythonException { final public static PythonLikeType BUFFER_ERROR_TYPE = new PythonLikeType("BufferError", BufferError.class, List.of(EXCEPTION_TYPE)), $TYPE = BUFFER_ERROR_TYPE; static { BUFFER_ERROR_TYPE.setConstructor( ((positionalArguments, namedArguments, callerInstance) -> new BufferError(BUFFER_ERROR_TYPE, positionalArguments))); } public BufferError(PythonLikeType type) { super(type); } public BufferError(PythonLikeType type, String message) { super(type, message); } public BufferError(PythonLikeType type, List<PythonLikeObject> args) { super(type, args); } }
0
java-sources/ai/timefold/solver/jpyinterpreter/1.24.0/ai/timefold/jpyinterpreter/types
java-sources/ai/timefold/solver/jpyinterpreter/1.24.0/ai/timefold/jpyinterpreter/types/errors/CPythonException.java
package ai.timefold.jpyinterpreter.types.errors; import java.util.List; import ai.timefold.jpyinterpreter.types.PythonLikeType; /** * Python class for general exceptions. Equivalent to Java's {@link RuntimeException} */ public class CPythonException extends PythonException { public final static PythonLikeType CPYTHON_EXCEPTION_TYPE = new PythonLikeType("CPython", CPythonException.class, List.of(EXCEPTION_TYPE)), $TYPE = CPYTHON_EXCEPTION_TYPE; public CPythonException() { super(CPYTHON_EXCEPTION_TYPE); } public CPythonException(String message) { super(CPYTHON_EXCEPTION_TYPE, message); } }
0
java-sources/ai/timefold/solver/jpyinterpreter/1.24.0/ai/timefold/jpyinterpreter/types
java-sources/ai/timefold/solver/jpyinterpreter/1.24.0/ai/timefold/jpyinterpreter/types/errors/GeneratorExit.java
package ai.timefold.jpyinterpreter.types.errors; import java.util.List; import ai.timefold.jpyinterpreter.PythonLikeObject; import ai.timefold.jpyinterpreter.types.PythonLikeType; import ai.timefold.jpyinterpreter.types.PythonNone; /** * Error thrown when a user of a generator indicates a Generator should close */ public class GeneratorExit extends PythonException { public static final PythonLikeType GENERATOR_EXIT_TYPE = new PythonLikeType("GeneratorExit", GeneratorExit.class, List.of(EXCEPTION_TYPE)), $TYPE = GENERATOR_EXIT_TYPE; static { GENERATOR_EXIT_TYPE.setConstructor( ((positionalArguments, namedArguments, callerInstance) -> new GeneratorExit(GENERATOR_EXIT_TYPE, positionalArguments))); } private final PythonLikeObject value; public GeneratorExit() { this(PythonNone.INSTANCE); } public GeneratorExit(PythonLikeObject value) { this(GENERATOR_EXIT_TYPE, List.of(value)); } public GeneratorExit(PythonLikeType type, List<PythonLikeObject> args) { super(type, args); if (args.size() > 0) { value = args.get(0); } else { value = PythonNone.INSTANCE; } } /** * This exception acts as a signal, and should be low cost * * @return this */ @Override public synchronized Throwable fillInStackTrace() { // Do nothing return this; } }
0
java-sources/ai/timefold/solver/jpyinterpreter/1.24.0/ai/timefold/jpyinterpreter/types
java-sources/ai/timefold/solver/jpyinterpreter/1.24.0/ai/timefold/jpyinterpreter/types/errors/ImportError.java
package ai.timefold.jpyinterpreter.types.errors; import java.util.List; import ai.timefold.jpyinterpreter.PythonLikeObject; import ai.timefold.jpyinterpreter.types.PythonLikeType; /** * Raised when a buffer related operation cannot be performed. */ public class ImportError extends PythonBaseException { final public static PythonLikeType IMPORT_ERROR_TYPE = new PythonLikeType("ImportError", ImportError.class, List.of(BASE_EXCEPTION_TYPE)), $TYPE = IMPORT_ERROR_TYPE; static { IMPORT_ERROR_TYPE.setConstructor( ((positionalArguments, namedArguments, callerInstance) -> new ImportError(IMPORT_ERROR_TYPE, positionalArguments))); } public ImportError(PythonLikeType type) { super(type); } public ImportError(PythonLikeType type, String message) { super(type, message); } public ImportError(PythonLikeType type, List<PythonLikeObject> args) { super(type, args); } }
0
java-sources/ai/timefold/solver/jpyinterpreter/1.24.0/ai/timefold/jpyinterpreter/types
java-sources/ai/timefold/solver/jpyinterpreter/1.24.0/ai/timefold/jpyinterpreter/types/errors/ModuleNotFoundError.java
package ai.timefold.jpyinterpreter.types.errors; import java.util.List; import ai.timefold.jpyinterpreter.PythonLikeObject; import ai.timefold.jpyinterpreter.types.PythonLikeType; /** * Raised when a buffer related operation cannot be performed. */ public class ModuleNotFoundError extends ImportError { final public static PythonLikeType MODULE_NOT_FOUND_ERROR_TYPE = new PythonLikeType("ModuleNotFoundError", ModuleNotFoundError.class, List.of(IMPORT_ERROR_TYPE)), $TYPE = MODULE_NOT_FOUND_ERROR_TYPE; static { MODULE_NOT_FOUND_ERROR_TYPE.setConstructor(((positionalArguments, namedArguments, callerInstance) -> new ModuleNotFoundError(MODULE_NOT_FOUND_ERROR_TYPE, positionalArguments))); } public ModuleNotFoundError(PythonLikeType type) { super(type); } public ModuleNotFoundError(PythonLikeType type, String message) { super(type, message); } public ModuleNotFoundError(PythonLikeType type, List<PythonLikeObject> args) { super(type, args); } }
0
java-sources/ai/timefold/solver/jpyinterpreter/1.24.0/ai/timefold/jpyinterpreter/types
java-sources/ai/timefold/solver/jpyinterpreter/1.24.0/ai/timefold/jpyinterpreter/types/errors/NameError.java
package ai.timefold.jpyinterpreter.types.errors; import java.util.List; import ai.timefold.jpyinterpreter.PythonLikeObject; import ai.timefold.jpyinterpreter.types.PythonLikeType; public class NameError extends PythonException { public final static PythonLikeType NAME_ERROR_TYPE = new PythonLikeType("NameError", NameError.class, List.of(EXCEPTION_TYPE)), $TYPE = NAME_ERROR_TYPE; static { NAME_ERROR_TYPE .setConstructor(((positionalArguments, namedArguments, callerInstance) -> new NameError(NAME_ERROR_TYPE, positionalArguments))); } public NameError() { super(NAME_ERROR_TYPE); } public NameError(String message) { super(NAME_ERROR_TYPE, message); } public NameError(PythonLikeType type, List<PythonLikeObject> args) { super(type, args); } public NameError(PythonLikeType type) { super(type); } public NameError(PythonLikeType type, String message) { super(type, message); } }
0
java-sources/ai/timefold/solver/jpyinterpreter/1.24.0/ai/timefold/jpyinterpreter/types
java-sources/ai/timefold/solver/jpyinterpreter/1.24.0/ai/timefold/jpyinterpreter/types/errors/NotImplementedError.java
package ai.timefold.jpyinterpreter.types.errors; import java.util.List; import ai.timefold.jpyinterpreter.PythonLikeObject; import ai.timefold.jpyinterpreter.types.PythonLikeType; /** * Raised when a buffer related operation cannot be performed. */ public class NotImplementedError extends RuntimeError { final public static PythonLikeType NOT_IMPLEMENTED_ERROR_TYPE = new PythonLikeType("NotImplementedError", NotImplementedError.class, List.of(RUNTIME_ERROR_TYPE)), $TYPE = NOT_IMPLEMENTED_ERROR_TYPE; static { NOT_IMPLEMENTED_ERROR_TYPE.setConstructor(((positionalArguments, namedArguments, callerInstance) -> new NotImplementedError(NOT_IMPLEMENTED_ERROR_TYPE, positionalArguments))); } public NotImplementedError() { super(NOT_IMPLEMENTED_ERROR_TYPE); } public NotImplementedError(String message) { super(NOT_IMPLEMENTED_ERROR_TYPE, message); } public NotImplementedError(PythonLikeType type) { super(type); } public NotImplementedError(PythonLikeType type, String message) { super(type, message); } public NotImplementedError(PythonLikeType type, List<PythonLikeObject> args) { super(type, args); } }
0
java-sources/ai/timefold/solver/jpyinterpreter/1.24.0/ai/timefold/jpyinterpreter/types
java-sources/ai/timefold/solver/jpyinterpreter/1.24.0/ai/timefold/jpyinterpreter/types/errors/PythonAssertionError.java
package ai.timefold.jpyinterpreter.types.errors; import java.util.List; import ai.timefold.jpyinterpreter.PythonLikeObject; import ai.timefold.jpyinterpreter.types.PythonLikeType; public class PythonAssertionError extends PythonException { public static final PythonLikeType ASSERTION_ERROR_TYPE = new PythonLikeType("AssertionError", PythonAssertionError.class, List.of(EXCEPTION_TYPE)), $TYPE = ASSERTION_ERROR_TYPE; static { ASSERTION_ERROR_TYPE.setConstructor( ((positionalArguments, namedArguments, callerInstance) -> new PythonAssertionError(ASSERTION_ERROR_TYPE, positionalArguments))); } public PythonAssertionError() { super(ASSERTION_ERROR_TYPE); } public PythonAssertionError(PythonLikeType type) { super(type); } public PythonAssertionError(PythonLikeType type, List<PythonLikeObject> args) { super(type, args); } }
0
java-sources/ai/timefold/solver/jpyinterpreter/1.24.0/ai/timefold/jpyinterpreter/types
java-sources/ai/timefold/solver/jpyinterpreter/1.24.0/ai/timefold/jpyinterpreter/types/errors/PythonBaseException.java
package ai.timefold.jpyinterpreter.types.errors; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import ai.timefold.jpyinterpreter.PythonLikeObject; import ai.timefold.jpyinterpreter.types.PythonLikeType; import ai.timefold.jpyinterpreter.types.PythonNone; import ai.timefold.jpyinterpreter.types.PythonString; import ai.timefold.jpyinterpreter.types.collections.PythonLikeTuple; import ai.timefold.jpyinterpreter.types.wrappers.JavaObjectWrapper; /** * Python base class for all exceptions. Equivalent to Java's {@link Throwable}. */ public class PythonBaseException extends RuntimeException implements PythonLikeObject { final public static PythonLikeType BASE_EXCEPTION_TYPE = new PythonLikeType("BaseException", PythonBaseException.class), $TYPE = BASE_EXCEPTION_TYPE; static { BASE_EXCEPTION_TYPE.setConstructor( ((positionalArguments, namedArguments, callerInstance) -> new PythonBaseException(BASE_EXCEPTION_TYPE, positionalArguments))); } Map<String, PythonLikeObject> dict; final PythonLikeType type; final List<PythonLikeObject> args; private static String getMessageFromArgs(List<PythonLikeObject> args) { if (args.size() < 1) { return null; } if (args.get(0) instanceof PythonString) { return ((PythonString) args.get(0)).getValue(); } return null; } public PythonBaseException(PythonLikeType type) { this(type, Collections.emptyList()); } public PythonBaseException(PythonLikeType type, List<PythonLikeObject> args) { super(getMessageFromArgs(args)); this.type = type; this.args = args; this.dict = new HashMap<>(); $setAttribute("args", PythonLikeTuple.fromList(args)); $setAttribute("__cause__", PythonNone.INSTANCE); } public PythonBaseException(PythonLikeType type, String message) { super(message); this.type = type; this.args = List.of(PythonString.valueOf(message)); this.dict = new HashMap<>(); $setAttribute("args", PythonLikeTuple.fromList(args)); $setAttribute("__cause__", PythonNone.INSTANCE); } @Override public synchronized Throwable initCause(Throwable cause) { super.initCause(cause); if (cause instanceof PythonLikeObject pythonError) { $setAttribute("__cause__", pythonError); } else { $setAttribute("__cause__", new JavaObjectWrapper(cause)); } return this; } @Override public PythonLikeObject $getAttributeOrNull(String attributeName) { return dict.get(attributeName); } @Override public void $setAttribute(String attributeName, PythonLikeObject value) { dict.put(attributeName, value); } @Override public void $deleteAttribute(String attributeName) { dict.remove(attributeName); } public PythonLikeTuple $getArgs() { return (PythonLikeTuple) $getAttributeOrError("args"); } @Override public PythonLikeType $getType() { return type; } }
0
java-sources/ai/timefold/solver/jpyinterpreter/1.24.0/ai/timefold/jpyinterpreter/types
java-sources/ai/timefold/solver/jpyinterpreter/1.24.0/ai/timefold/jpyinterpreter/types/errors/PythonException.java
package ai.timefold.jpyinterpreter.types.errors; import java.util.List; import ai.timefold.jpyinterpreter.PythonLikeObject; import ai.timefold.jpyinterpreter.types.PythonLikeType; /** * Python class for general exceptions. Equivalent to Java's {@link RuntimeException} */ public class PythonException extends PythonBaseException { final public static PythonLikeType EXCEPTION_TYPE = new PythonLikeType("Exception", PythonException.class, List.of(BASE_EXCEPTION_TYPE)), $TYPE = EXCEPTION_TYPE; static { EXCEPTION_TYPE.setConstructor( ((positionalArguments, namedArguments, callerInstance) -> new PythonException(EXCEPTION_TYPE, positionalArguments))); } public PythonException(PythonLikeType type) { super(type); } public PythonException(PythonLikeType type, List<PythonLikeObject> args) { super(type, args); } public PythonException(PythonLikeType type, String message) { super(type, message); } }