public static object CreateCData(IntPtr dataAddress, PythonType type) { CTypes.INativeType nativeType = (CTypes.INativeType)type; CTypes.CData data = (CTypes.CData)type.CreateInstance(type.Context.SharedContext); data._memHolder = new MemoryHolder(nativeType.Size); data._memHolder.CopyFrom(dataAddress, new IntPtr(nativeType.Size)); return data; }
public static object __new__(CodeContext/*!*/ context, PythonType cls, object x) { if (cls == TypeCache.Double) { if (x is string) { return ParseFloat((string)x); } else if (x is Extensible<string>) { object res; if (PythonTypeOps.TryInvokeUnaryOperator(context, x, "__float__", out res)) { return res; } return ParseFloat(((Extensible<string>)x).Value); } else if (x is char) { return ParseFloat(ScriptingRuntimeHelpers.CharToString((char)x)); } if (x is Complex) { throw PythonOps.TypeError("can't convert complex to float; use abs(z)"); } object d = PythonOps.CallWithContext(context, PythonOps.GetBoundAttr(context, x, "__float__")); if (d is double) { return d; } else if (d is Extensible<double>) { return ((Extensible<double>)d).Value; } throw PythonOps.TypeError("__float__ returned non-float (type {0})", PythonTypeOps.GetName(d)); } else { return cls.CreateInstance(context, x); } }
public static object CreateNativeWrapper(PythonType type, object holder) { Debug.Assert(holder is MemoryHolder); CTypes.CData data = (CTypes.CData)type.CreateInstance(type.Context.SharedContext); data._memHolder = (MemoryHolder)holder; return data; }
public static object __new__(CodeContext context, PythonType type, object o) { object reversed; if (PythonOps.TryGetBoundAttr(context, o, "__reversed__", out reversed)) { return PythonCalls.Call(context, reversed); } object boundFunc; PythonTypeSlot getitem; PythonType pt = DynamicHelpers.GetPythonType(o); if(!pt.TryResolveSlot(context, "__getitem__", out getitem) || !getitem.TryGetValue(context, o, pt, out boundFunc) || o is PythonDictionary) { throw PythonOps.TypeError("argument to reversed() must be a sequence"); } int length; if (!DynamicHelpers.GetPythonType(o).TryGetLength(context, o, out length)) { throw PythonOps.TypeError("object of type '{0}' has no len()", DynamicHelpers.GetPythonType(o).Name); } if (type.UnderlyingSystemType == typeof(ReversedEnumerator)) { return new ReversedEnumerator((int)length, boundFunc); } return type.CreateInstance(context, length, getitem); }
public static object __new__(CodeContext/*!*/ context, PythonType cls, object x) { if (cls == TypeCache.Double) { if (x is string) { return ParseFloat((string)x); } else if (x is Extensible<string>) { object res; if (PythonTypeOps.TryInvokeUnaryOperator(context, x, Symbols.ConvertToFloat, out res)) { return res; } return ParseFloat(((Extensible<string>)x).Value); } else if (x is char) { return ParseFloat(ScriptingRuntimeHelpers.CharToString((char)x)); } double doubleVal; if (Converter.TryConvertToDouble(x, out doubleVal)) return doubleVal; if (x is Complex64) throw PythonOps.TypeError("can't convert complex to float; use abs(z)"); object d = PythonOps.CallWithContext(context, PythonOps.GetBoundAttr(context, x, Symbols.ConvertToFloat)); if (d is double) return d; throw PythonOps.TypeError("__float__ returned non-float (type %s)", DynamicHelpers.GetPythonType(d)); } else { return cls.CreateInstance(context, x); } }
public static object __new__(CodeContext context, PythonType cls, object x) { Extensible<string> es; if (x is string) { return ReturnBigInteger(context, cls, ParseBigIntegerSign((string)x, 10)); } else if ((es = x as Extensible<string>) != null) { object value; if (PythonTypeOps.TryInvokeUnaryOperator(context, x, Symbols.ConvertToLong, out value)) { return ReturnBigInteger(context, cls, (BigInteger)value); } return ReturnBigInteger(context, cls, ParseBigIntegerSign(es.Value, 10)); } BigInteger intVal; if (Converter.TryConvertToBigInteger(x, out intVal)) { if (Object.Equals(intVal, null)) throw PythonOps.TypeError("can't convert {0} to long", PythonTypeOps.GetName(x)); return ReturnBigInteger(context, cls, intVal); } if (x is Complex64) throw PythonOps.TypeError("can't convert complex to long; use long(abs(z))"); throw PythonOps.ValueError("long argument must be convertible to long (string, number, or type that defines __long__, got {0})", StringOps.Quote(PythonOps.GetPythonTypeName(x))); }
internal override bool TrySetValue(CodeContext context, object instance, PythonType owner, object value) { IWeakReferenceable reference = instance as IWeakReferenceable; if (reference != null) { return reference.SetWeakRef(new WeakRefTracker(value, instance)); } return false; }
/// <summary> /// Create new dlr class /// </summary> /// <param name="scriptScope">Scope which contains the class definition and in which the instance will be created</param> /// <param name="pythonType">Python-Type instance</param> /// <param name="parameter">Arguments for the constructor</param> public DlrClass(DlrScriptScope scriptScope, PythonType pythonType, params object[] parameter) { this.scriptScope = scriptScope; // create class instance instance = scriptScope.Host.ScriptEngine.Operations.CreateInstance(pythonType, parameter); }
public IronPythonTypeWrapper(ScriptEngine engine, string name, PythonType pythonType, ObjectHandle classHandle) { Name = name; PythonType = pythonType; _engine = engine; _classHandle = classHandle; }
internal override bool TrySetValue(CodeContext context, object instance, PythonType owner, object value) { IWeakReferenceable reference; if (context.GetPythonContext().TryConvertToWeakReferenceable(instance, out reference)) { return reference.SetWeakRef(new WeakRefTracker(value, instance)); } return false; }
public static object __new__(PythonType cls, object value) { if (cls != DynamicHelpers.GetPythonTypeFromType(typeof(SByte))) { throw PythonOps.TypeError("SByte.__new__: first argument must be SByte type."); } IConvertible valueConvertible; if ((valueConvertible = value as IConvertible) != null) { switch (valueConvertible.GetTypeCode()) { case TypeCode.Byte: return (SByte)(Byte)value; case TypeCode.SByte: return (SByte)(SByte)value; case TypeCode.Int16: return (SByte)(Int16)value; case TypeCode.UInt16: return (SByte)(UInt16)value; case TypeCode.Int32: return (SByte)(Int32)value; case TypeCode.UInt32: return (SByte)(UInt32)value; case TypeCode.Int64: return (SByte)(Int64)value; case TypeCode.UInt64: return (SByte)(UInt64)value; case TypeCode.Single: return (SByte)(Single)value; case TypeCode.Double: return (SByte)(Double)value; } } if (value is String) { return SByte.Parse((String)value); } else if (value is BigInteger) { return (SByte)(BigInteger)value; } else if (value is Extensible<BigInteger>) { return (SByte)((Extensible<BigInteger>)value).Value; } else if (value is Extensible<double>) { return (SByte)((Extensible<double>)value).Value; } throw PythonOps.ValueError("invalid value for SByte.__new__"); }
public static InstanceCreator Make(PythonType type) { if (type.IsSystemType) { return new SystemInstanceCreator(type); } return new UserInstanceCreator(type); }
internal override bool TrySetValue(CodeContext context, object instance, PythonType owner, object value) { if (instance != null) { Setter(instance, value); return true; } return false; }
public BuiltinClassInfo(PythonType classObj, ProjectState projectState) : base(new LazyDotNetDict(classObj, projectState, true)) { // TODO: Get parameters from ctor // TODO: All types should be shared via projectState _type = classObj; _doc = null; }
internal override bool TryDeleteValue(CodeContext context, object instance, PythonType owner) { if (_deleter == null || instance == null) { return base.TryDeleteValue(context, instance, owner); } CallTarget(context, null, new MethodInfo[] { _deleter }, instance); return true; }
public Expression GetBoundPythonValue(RuleBuilder builder, ActionBinder binder, PythonType accessing) { return Ast.Call( typeof(PythonOps).GetMethod("SlotGetValue"), builder.Context, Ast.Constant(GetSlot(), typeof(PythonTypeSlot)), Ast.Constant(null), Ast.Constant(accessing) ); }
internal override bool TryGetValue(CodeContext context, object instance, PythonType owner, out object value) { if (Getter.Length == 0 || instance == null) { value = null; return false; } value = CallGetter(context, null, instance, ArrayUtils.EmptyObjects); return true; }
internal override bool TryGetValue(CodeContext context, object instance, PythonType owner, out object value) { try { value = PythonOps.GetUserDescriptor(Value, instance, owner); return true; } catch (MissingMemberException) { value = null; return false; } }
public static object __new__(CodeContext/*!*/ context, PythonType cls, params object[] args\u00F8) { if (cls == null) { throw PythonOps.TypeError("__new__ expected type object, got {0}", PythonOps.Repr(context, DynamicHelpers.GetPythonType(cls))); } InstanceOps.CheckInitArgs(context, null, args\u00F8, cls); return cls.CreateInstance(context); }
internal override bool TryGetValue(CodeContext context, object instance, PythonType owner, out object value) { if (Getter.Length == 0 || (instance == null && Getter[0].IsDefined(typeof(WrapperDescriptorAttribute), false))) { value = null; return false; } value = CallGetter(context, null, instance, ArrayUtils.EmptyObjects); return true; }
internal override bool TryDeleteValue(CodeContext context, object instance, PythonType owner) { IPythonObject sdo = instance as IPythonObject; if (sdo != null) { return sdo.ReplaceDict(null); } if (instance == null) throw PythonOps.TypeError("'__dict__' of '{0}' objects is not writable", owner.Name); return false; }
internal override bool TryGetValue(CodeContext context, object instance, PythonType owner, out object value) { if (instance != null) { CheckSelf(context, instance); value = UncheckedGetAttribute(instance); return true; } value = this; return true; }
public static object __new__(CodeContext context, PythonType cls, object x) { Extensible<string> es; if (x is string) { return ReturnObject(context, cls, ParseBigIntegerSign((string)x, 10)); } else if ((es = x as Extensible<string>) != null) { object value; if (PythonTypeOps.TryInvokeUnaryOperator(context, x, "__long__", out value)) { return ReturnObject(context, cls, (BigInteger)value); } return ReturnObject(context, cls, ParseBigIntegerSign(es.Value, 10)); } if (x is double) return ReturnObject(context, cls, DoubleOps.__long__((double)x)); if (x is int) return ReturnObject(context, cls, (BigInteger)(int)x); if (x is BigInteger) return ReturnObject(context, cls, x); if (x is Complex) throw PythonOps.TypeError("can't convert complex to long; use long(abs(z))"); if (x is decimal) { return ReturnObject(context, cls, (BigInteger)(decimal)x); } object result; int intRes; BigInteger bigintRes; if (PythonTypeOps.TryInvokeUnaryOperator(context, x, "__long__", out result) && !Object.ReferenceEquals(result, NotImplementedType.Value) || x is OldInstance && PythonTypeOps.TryInvokeUnaryOperator(context, x, "__int__", out result) && !Object.ReferenceEquals(result, NotImplementedType.Value)) { if (result is int || result is BigInteger || result is Extensible<int> || result is Extensible<BigInteger>) { return ReturnObject(context, cls, result); } else { throw PythonOps.TypeError("__long__ returned non-long (type {0})", PythonTypeOps.GetOldName(result)); } } else if (PythonOps.TryGetBoundAttr(context, x, "__trunc__", out result)) { result = PythonOps.CallWithContext(context, result); if (Converter.TryConvertToInt32(result, out intRes)) { return ReturnObject(context, cls, (BigInteger)intRes); } else if (Converter.TryConvertToBigInteger(result, out bigintRes)) { return ReturnObject(context, cls, bigintRes); } else { throw PythonOps.TypeError("__trunc__ returned non-Integral (type {0})", PythonTypeOps.GetOldName(result)); } } if (x is OldInstance) { throw PythonOps.AttributeError("{0} instance has no attribute '__trunc__'", ((OldInstance)x)._class.Name); } else { throw PythonOps.TypeError("long() argument must be a string or a number, not '{0}'", DynamicHelpers.GetPythonType(x).Name); } }
public static NameType TryGetName(PythonType dt, PropertyInfo pi, MethodInfo prop, out string name) { if (pi.IsDefined(typeof(PythonHiddenAttribute), false)) { name = null; return NameType.None; } name = pi.Name; return GetNameFromMethod(dt, prop, NameType.Property, ref name); }
private static void InitModuleExceptions(PythonContext context, PythonDictionary dict) { ZipImportError = context.EnsureModuleException( "zipimport.ZipImportError", PythonExceptions.ImportError, typeof(PythonExceptions.BaseException), dict, "ZipImportError", "zipimport", msg => new ImportException(msg)); }
internal override bool TryGetValue(CodeContext context, object instance, PythonType owner, out object value) { if (instance != null) { value = Getter(instance); PythonOps.CheckInitializedAttribute(value, instance, _name); return true; } value = this; return true; }
internal static object CallWorker(CodeContext/*!*/ context, PythonType dt, object[] args) { object newObject = PythonOps.CallWithContext(context, GetTypeNew(context, dt), ArrayUtils.Insert<object>(dt, args)); if (ShouldInvokeInit(dt, DynamicHelpers.GetPythonType(newObject), args.Length)) { PythonOps.CallWithContext(context, GetInitMethod(context, dt, newObject), args); AddFinalizer(context, dt, newObject); } return newObject; }
public static PythonModule/*!*/ __new__(CodeContext/*!*/ context, PythonType/*!*/ cls, params object[]/*!*/ args\u00F8) { PythonModule res; if (cls == TypeCache.Module) { res = new PythonModule(); } else if (cls.IsSubclassOf(TypeCache.Module)) { res = (PythonModule)cls.CreateInstance(context); } else { throw PythonOps.TypeError("{0} is not a subtype of module", cls.Name); } return res; }
internal override bool TrySetValue(CodeContext context, object instance, PythonType owner, object value) { IPythonObject sdo = instance as IPythonObject; if (sdo != null) { if (!(value is IAttributesCollection)) throw PythonOps.TypeError("__dict__ must be set to a dictionary, not '{0}'", owner.Name); return sdo.ReplaceDict((IAttributesCollection)value); } if (instance == null) throw PythonOps.AttributeError("'__dict__' of '{0}' objects is not writable", owner.Name); return false; }
public static object __new__(CodeContext context, PythonType cls, string s, int radix) { if (radix == 16 || radix == 8 || radix == 2) { s = Int32Ops.TrimRadix(s, radix); } if (cls == TypeCache.BigInteger) { return ParseBigIntegerSign(s, radix); } else { BigInteger res = ParseBigIntegerSign(s, radix); return cls.CreateInstance(context, res); } }
public SystemInstanceCreator(PythonType /*!*/ type) : base(type) { }
internal override bool TrySetValue(CodeContext context, object instance, PythonType owner, object value) { return(PythonOps.TrySetUserDescriptor(Value, instance, value)); }
internal override bool TryDeleteValue(CodeContext context, object instance, PythonType owner) { throw PythonOps.AttributeErrorForReadonlyAttribute(PythonTypeOps.GetName(instance), "__class__"); }
internal override bool IsSetDescriptor(CodeContext context, PythonType owner) { return(Setter.Length != 0); }
internal override bool TryDeleteValue(CodeContext context, object instance, PythonType owner) { return(TrySetValue(context, instance, owner, Uninitialized.Instance)); }
private MissingMemberException /*!*/ ReadOnlyException(PythonType /*!*/ dt) { Assert.NotNull(dt); return(new MissingMemberException(String.Format("attribute '{1}' of '{0}' object is read-only", dt.Name, _tracker.Name))); }
internal override bool TrySetValue(CodeContext /*!*/ context, object instance, PythonType owner, object value) { Assert.NotNull(context); if (!(value is BoundEvent et) || EventInfosDiffer(et)) { if (value is BadEventChange bea) { if (bea.Owner is PythonType dt) { if (bea.Instance == null) { throw new MissingMemberException(String.Format("attribute '{1}' of '{0}' object is read-only", dt.Name, _tracker.Name)); } else { throw new MissingMemberException(String.Format("'{0}' object has no attribute '{1}'", dt.Name, _tracker.Name)); } } } throw ReadOnlyException(DynamicHelpers.GetPythonTypeFromType(Info.DeclaringType)); } return(true); }
protected InstanceCreator(PythonType type) { Assert.NotNull(type); _type = type; }
public UserInstanceCreator(PythonType /*!*/ type) : base(type) { }
internal override bool IsSetDescriptor(CodeContext context, PythonType owner) { return(true); }
/// <summary> /// "bases" contains a set of PythonTypes. These can include types defined in Python (say cpy1, cpy2), /// CLI types (say cCLI1, cCLI2), and CLI interfaces (say iCLI1, iCLI2). Here are some /// examples of how this works: /// /// (bases) => baseType, {interfaceTypes} /// /// (cpy1) => System.Object, {} /// (cpy1, cpy2) => System.Object, {} /// (cpy1, cCLI1, iCLI1, iCLI2) => cCLI1, {iCLI1, iCLI2} /// [some type that satisfies the line above] => /// cCLI1, {iCLI1, iCLI2} /// (cCLI1, cCLI2) => error /// </summary> public static NewTypeInfo GetTypeInfo(string typeName, PythonTuple bases) { List <Type> interfaceTypes = new List <Type>(); Type baseCLIType = typeof(object); // Pure Python object instances inherit from System.Object PythonType basePythonType = null; foreach (PythonType curBasePythonType in GetPythonTypes(typeName, bases)) { // discover the initial base/interfaces IList <Type> baseInterfaces = ReflectionUtils.EmptyTypes; Type curTypeToExtend = curBasePythonType.ExtensionType; if (curBasePythonType.ExtensionType.IsInterface) { baseInterfaces = new Type[] { curTypeToExtend }; curTypeToExtend = typeof(object); } else if (NewTypeMaker.IsInstanceType(curTypeToExtend)) { baseInterfaces = new List <Type>(); curTypeToExtend = GetBaseTypeFromUserType(curBasePythonType, baseInterfaces, curTypeToExtend.BaseType); } if (curTypeToExtend == null || typeof(BuiltinFunction).IsAssignableFrom(curTypeToExtend) || typeof(PythonFunction).IsAssignableFrom(curTypeToExtend)) { throw PythonOps.TypeError(typeName + ": {0} is not an acceptable base type", curBasePythonType.Name); } if (curTypeToExtend.ContainsGenericParameters) { throw PythonOps.TypeError(typeName + ": cannot inhert from open generic instantiation {0}. Only closed instantiations are supported.", curBasePythonType); } foreach (Type interfaceType in baseInterfaces) { if (interfaceType.ContainsGenericParameters) { throw PythonOps.TypeError(typeName + ": cannot inhert from open generic instantiation {0}. Only closed instantiations are supported.", interfaceType); } // collecting all the interfaces because we override them all. interfaceTypes.Add(interfaceType); } // if we're not extending something already in our existing base classes type hierarchy // then we better be in some esoteric __slots__ situation if (!baseCLIType.IsSubclassOf(curTypeToExtend)) { if (baseCLIType != typeof(object) && baseCLIType != curTypeToExtend && (!baseCLIType.IsDefined(typeof(DynamicBaseTypeAttribute), false) && !curTypeToExtend.IsSubclassOf(baseCLIType))) { throw PythonOps.TypeError( typeName + ": can only extend one CLI or builtin type, not both {0} (for {1}) and {2} (for {3})", baseCLIType.FullName, basePythonType, curTypeToExtend.FullName, curBasePythonType); } // we have a new base type baseCLIType = curTypeToExtend; basePythonType = curBasePythonType; } } return(new NewTypeInfo(baseCLIType, interfaceTypes.Count == 0 ? ReflectionUtils.EmptyTypes : interfaceTypes.ToArray())); }
internal override bool IsSetDescriptor(CodeContext context, PythonType owner) { object dummy; return(PythonOps.TryGetBoundAttr(context, Value, "__set__", out dummy)); }
internal override bool TryDeleteValue(CodeContext context, object instance, PythonType owner) { return(PythonOps.TryDeleteUserDescriptor(Value, instance)); }
internal override bool TryDeleteValue(CodeContext /*!*/ context, object instance, PythonType owner) { Assert.NotNull(context, owner); throw ReadOnlyException(DynamicHelpers.GetPythonTypeFromType(Info.DeclaringType)); }
/// <summary> /// Deletes the value stored in the slot from the instance. /// </summary> /// <returns>true if the value was deleted, false if it can't be deleted</returns> internal virtual bool TryDeleteValue(CodeContext context, object instance, PythonType owner) { return(false); }
internal override bool TryGetValue(CodeContext /*!*/ context, object instance, PythonType owner, out object value) { Assert.NotNull(context, owner); value = new BoundEvent(this, instance, owner); return(true); }
/// <summary> /// Sets the value of the slot for the given instance. /// </summary> /// <returns>true if the value was set, false if it can't be set</returns> internal virtual bool TrySetValue(CodeContext context, object instance, PythonType owner, object value) { return(false); }
public BadEventChange(PythonType /*!*/ ownerType, object instance) { _ownerType = ownerType; _instance = instance; }
internal override bool TryDeleteValue(CodeContext context, object instance, PythonType owner) { throw PythonOps.TypeError("__weakref__ attribute cannot be deleted"); }
internal static object GetOldStyleDescriptor(CodeContext context, object self, object instance, PythonType type) { PythonTypeSlot dts = self as PythonTypeSlot; object callable; if (dts != null && dts.TryGetValue(context, instance, type, out callable)) { return(callable); } return(PythonOps.GetUserDescriptor(self, instance, type)); }
internal virtual bool IsSetDescriptor(CodeContext context, PythonType owner) { return(false); }
internal override bool TryDeleteValue(CodeContext context, object instance, PythonType owner) { __delete__(instance); return(true); }
public PythonTypeWeakRefSlot(PythonType parent) { _type = parent; }