#nullable enable
using System;
using System.Collections.Generic;
using System.Reflection;
using System.Threading;
using IronPython.Runtime.Types;
using Microsoft.Scripting;
using Microsoft.Scripting.Runtime;
namespace IronPython.Runtime.Operations {
public static class ObjectOps {
[MultiRuntimeAware]
private static HashSet<PythonType>? _nativelyPickleableTypes;
[SlotField]
public static PythonTypeSlot __class__ = new PythonTypeTypeSlot();
public static void __delattr__(CodeContext context, object self, string name) {
if (self is PythonType) {
throw PythonOps.TypeError("can't apply this __delattr__ to type object");
}
PythonOps.ObjectDeleteAttribute(context, self, name);
}
public static int __hash__(object self) {
if (self == null) return NoneTypeOps.NoneHashCode;
return self.GetHashCode();
}
public static object __getattribute__(CodeContext context, object self, string name) {
return PythonOps.ObjectGetAttribute(context, self, name);
}
public static void __init__(CodeContext context, object self) { }
public static void __init__(CodeContext context, object self, [NotNone] params object[] args) {
InstanceOps.CheckInitArgs(context, null, args, self);
}
public static void __init__(CodeContext context, object self, [ParamDictionary] IDictionary<object, object> kwargs, [NotNone] params object[] args) {
InstanceOps.CheckInitArgs(context, kwargs, args, self);
}
[StaticExtensionMethod]
public static object __new__(CodeContext context, PythonType cls) {
if (cls == null) {
throw PythonOps.TypeError("__new__ expected type object, got {0}", PythonOps.Repr(context, DynamicHelpers.GetPythonType(cls)));
}
return cls.CreateInstance(context);
}
[StaticExtensionMethod]
public static object __new__(CodeContext context, PythonType cls, [NotNone] params object[] args) {
if (cls == null) {
throw PythonOps.TypeError("__new__ expected type object, got {0}", PythonOps.Repr(context, DynamicHelpers.GetPythonType(cls)));
}
InstanceOps.CheckNewArgs(context, null, args, cls);
return cls.CreateInstance(context);
}
[StaticExtensionMethod]
public static object __new__(CodeContext context, PythonType cls, [ParamDictionary] IDictionary<object, object> kwargs, [NotNone] params object[] args) {
if (cls == null) {
throw PythonOps.TypeError("__new__ expected type object, got {0}", PythonOps.Repr(context, DynamicHelpers.GetPythonType(cls)));
}
InstanceOps.CheckNewArgs(context, kwargs, args, cls);
return cls.CreateInstance(context);
}
public static object? __reduce__(CodeContext context, object self) {
return __reduce_ex__(context, self, 0);
}
public static object? __reduce_ex__(CodeContext context, object self) {
return __reduce_ex__(context, self, 0);
}
public static object? __reduce_ex__(CodeContext context, object self, object protocol) {
object objectReduce = PythonOps.GetBoundAttr(context, TypeCache.Object, "__reduce__");
if (PythonOps.TryGetBoundAttr(context, DynamicHelpers.GetPythonType(self), "__reduce__", out object? myReduce)) {
if (!PythonOps.IsRetBool(myReduce, objectReduce)) {
return PythonOps.CallWithContext(context, myReduce, self)!;
}
}
if (context.LanguageContext.ConvertToInt32(protocol) < 2) {
return ReduceProtocol0(context, self);
} else {
return ReduceProtocol2(context, self);
}
}
public static string __repr__(object self) {
return $"<{PythonOps.GetPythonTypeName(self)} object at {PythonOps.HexId(self)}>";
}
public static void __setattr__(CodeContext context, object self, string name, object value) {
if (self is PythonType) {
throw PythonOps.TypeError("can't apply this __setattr__ to type object");
}
PythonOps.ObjectSetAttribute(context, self, name, value);
}
private static int AdjustPointerSize(int size) {
if (IntPtr.Size == 4) {
return size;
}
return size * 2;
}
public static int __sizeof__(object self) {
int res = AdjustPointerSize(8);
if (self is IPythonObject) {
res += AdjustPointerSize(12);
}
Type t = DynamicHelpers.GetPythonType(self).FinalSystemType;
res += GetTypeSize(t);
return res;
}
private static int GetTypeSize(Type t) {
FieldInfo[] fields = t.GetFields(System.Reflection.BindingFlags.FlattenHierarchy | System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Public);
int res = 0;
foreach (FieldInfo fi in fields) {
if (fi.FieldType.IsClass || fi.FieldType.IsInterface) {
res += AdjustPointerSize(4);
} else if (fi.FieldType.IsPrimitive) {
return System.Runtime.InteropServices.Marshal.SizeOf(fi.FieldType);
} else {
res += GetTypeSize(fi.FieldType);
}
}
return res;
}
public static string __str__(CodeContext context, object o) {
try {
PythonOps.FunctionPushFrame(context.LanguageContext);
return PythonOps.Repr(context, o);
} finally {
PythonOps.FunctionPopFrame();
}
}
public static NotImplementedType __subclasshook__(params object[] args) {
return NotImplementedType.Value;
}
[return: MaybeNotImplemented]
public static object __eq__(object self, object value) {
if (ReferenceEquals(self, value)) return ScriptingRuntimeHelpers.True;
return NotImplementedType.Value;
}
[return: MaybeNotImplemented]
public static object __ne__(CodeContext context, object self, object other) {
if (PythonTypeOps.TryInvokeBinaryOperator(context, self, other, "__eq__", out object res)) {
if (res is NotImplementedType) {
return NotImplementedType.Value;
}
return !PythonOps.IsTrue(res);
}
return NotImplementedType.Value;
}
[return: MaybeNotImplemented]
public static NotImplementedType __gt__(object self, object value) => NotImplementedType.Value;
[return: MaybeNotImplemented]
public static NotImplementedType __lt__(object self, object value) => NotImplementedType.Value;
[return: MaybeNotImplemented]
public static NotImplementedType __ge__(object self, object value) => NotImplementedType.Value;
[return: MaybeNotImplemented]
public static NotImplementedType __le__(object self, object value) => NotImplementedType.Value;
public static string __format__(CodeContext context, object self, [NotNone] string formatSpec) {
if (formatSpec != string.Empty)
throw PythonOps.TypeError("unsupported format string passed to {0}.__format__", PythonOps.GetPythonTypeName(self));
return PythonOps.ToString(context, self);
}
#region Pickle helpers
private static HashSet<PythonType> NativelyPickleableTypes {
get {
if (_nativelyPickleableTypes == null) {
var hashSet = new HashSet<PythonType> {
TypeCache.Null,
TypeCache.Boolean,
TypeCache.Int32,
TypeCache.BigInteger,
TypeCache.Double,
TypeCache.Complex,
TypeCache.String,
TypeCache.PythonTuple,
TypeCache.PythonList,
TypeCache.Dict,
TypeCache.Function
};
Thread.MemoryBarrier();
_nativelyPickleableTypes = hashSet;
}
return _nativelyPickleableTypes;
}
}
private static PythonDictionary? GetInitializedSlotValues(object obj) {
PythonDictionary initializedSlotValues = new PythonDictionary();
IList<PythonType> mro = DynamicHelpers.GetPythonType(obj).ResolutionOrder;
foreach (object type in mro) {
if (PythonOps.TryGetBoundAttr(type, "__slots__", out object? slots)) {
List<string> slotNames = PythonType.SlotsToList(slots);
foreach (string slotName in slotNames) {
if (slotName == "__dict__") continue;
if (initializedSlotValues.__contains__(slotName)) continue;
if (PythonOps.TryGetBoundAttr(obj, slotName, out object? slotValue)) {
initializedSlotValues[slotName] = slotValue;
}
}
}
}
if (initializedSlotValues.Count == 0) return null;
return initializedSlotValues;
}
internal static object? ReduceProtocol0(CodeContext context, object self) {
var copyreg = context.LanguageContext.GetCopyRegModule();
var _reduce_ex = PythonOps.GetBoundAttr(context, copyreg, "_reduce_ex");
return PythonOps.CallWithContext(context, _reduce_ex, self, 0);
}
private static PythonTuple ReduceProtocol2(CodeContext context, object self) {
if (self is MemoryView) {
throw PythonOps.TypeError("can't pickle memoryview objects");
}
PythonType myType = DynamicHelpers.GetPythonType(self);
object? state;
object?[] funcArgs;
var copyreg = context.LanguageContext.GetCopyRegModule();
var func = PythonOps.GetBoundAttr(context, copyreg, "__newobj__");
if (PythonOps.TryGetBoundAttr(context, myType, "__getnewargs__", out object? getNewArgsCallable)) {
if (!(PythonOps.CallWithContext(context, getNewArgsCallable, self) is PythonTuple newArgs)) {
throw PythonOps.TypeError("__getnewargs__ should return a tuple");
}
funcArgs = new object[1 + newArgs.Count];
funcArgs[0] = myType;
for (int i = 0; i < newArgs.Count; i++) funcArgs[i + 1] = newArgs[i];
} else {
funcArgs = new object[] { myType };
}
if (!PythonTypeOps.TryInvokeUnaryOperator(context,
self,
"__getstate__",
out state)) {
object? dict;
if (self is IPythonObject ipo) {
dict = ipo.Dict;
} else if (!PythonOps.TryGetBoundAttr(context, self, "__dict__", out dict)) {
dict = null;
}
PythonDictionary? initializedSlotValues = GetInitializedSlotValues(self);
if (initializedSlotValues != null && initializedSlotValues.Count == 0) {
initializedSlotValues = null;
}
if (dict == null && initializedSlotValues == null) state = null;
else if (dict != null && initializedSlotValues == null) state = dict;
else if (dict != null && initializedSlotValues != null) state = PythonTuple.MakeTuple(dict, initializedSlotValues);
else state = PythonTuple.MakeTuple(null, initializedSlotValues);
}
object? listIterator = null;
if (self is PythonList) {
listIterator = PythonOps.GetEnumerator(context, self);
}
object? dictIterator = null;
if (self is PythonDictionary) {
dictIterator = Modules.Builtin.iter(context, PythonOps.Invoke(context, self, nameof(PythonDictionary.items)));
}
if (state is PythonDictionary d && d.Count == 0) state = null;
return PythonTuple.MakeTuple(func, PythonTuple.MakeTuple(funcArgs), state, listIterator, dictIterator);
}
#endregion
}
}