public object InPlaceAdd(CodeContext /*!*/ context, object func) { if (func == null || !PythonOps.IsCallable(context, func)) { throw PythonOps.TypeError("event addition expected callable object, got {0}", PythonTypeOps.GetName(func)); } if (_event.Tracker.IsStatic) { if (_ownerType != DynamicHelpers.GetPythonTypeFromType(_event.Tracker.DeclaringType)) { // mutating static event, only allow this from the type we're mutating, not sub-types return(new BadEventChange(_ownerType, _instance)); } } MethodInfo add = _event.Tracker.GetAddMethod(); // TODO (tomat): this used to use event.ReflectedType, is it still correct? if (_instance != null) { add = CompilerHelpers.TryGetCallableMethod(_instance.GetType(), add); } if (CompilerHelpers.IsVisible(add) || context.LanguageContext.DomainManager.Configuration.PrivateBinding) { _event.Tracker.AddHandler(_instance, func, context.LanguageContext.DelegateCreator); } else { throw new TypeErrorException("Cannot add handler to a private event."); } return(this); }
public static string hex(CodeContext /*!*/ context, object number) { if (number is int) { return(Int32Ops.__hex__((int)number)); } else if (number is BigInteger) { BigInteger x = (BigInteger)number; if (x < 0) { return("-0x" + (-x).ToString(16).ToLower()); } else { return("0x" + x.ToString(16).ToLower()); } } object value; if (PythonTypeOps.TryInvokeUnaryOperator(context, number, "__index__", out value)) { if (!(value is int) && !(value is BigInteger)) { throw PythonOps.TypeError("index returned non-(int, long), got '{0}'", PythonTypeOps.GetName(value)); } return(hex(context, value)); } throw PythonOps.TypeError("hex() argument cannot be interpreted as an index"); }
public static object ParserCreate(object encoding, object namespace_separator, object intern) { var encoding_str = encoding == null ? null : (encoding as string ?? throw PythonOps.TypeError($"ParserCreate() argument 1 must be string or None, not {PythonTypeOps.GetName(encoding)}")); var namespace_separator_str = namespace_separator == null ? null : (namespace_separator as string ?? throw PythonOps.TypeError($"ParserCreate() argument 2 must be string or None, not {PythonTypeOps.GetName(namespace_separator)}")); return(ParserCreateImpl(encoding_str, namespace_separator_str, intern)); }
public static object decode(CodeContext /*!*/ context, object?obj, [NotNull, DisallowNull] string?encoding = null, [NotNull] string errors = "strict") { if (encoding == null) { if (obj is IList <byte> bytesLikeObj) { PythonContext lc = context.LanguageContext; return(StringOps.DoDecode(context, bytesLikeObj, errors, lc.GetDefaultEncodingName(), lc.DefaultEncoding)); } else { throw PythonOps.TypeError("expected bytes-like object, got {0}", PythonTypeOps.GetName(obj)); } } else { object?decoder = lookup(context, encoding)[DecoderIndex]; if (!PythonOps.IsCallable(context, decoder)) { throw PythonOps.TypeError("decoding with '{0}' codec failed; decoder must be callable ('{1}' object is not callable)", encoding, PythonTypeOps.GetName(decoder)); } return(PythonOps.GetIndex(context, PythonCalls.Call(context, decoder, obj, errors), 0)); } }
public BigInteger readinto([NotNull] IBufferProtocol buffer) { EnsureReadable(); using var pythonBuffer = buffer.GetBufferNoThrow(BufferFlags.Writable) ?? throw PythonOps.TypeError("readinto() argument must be read-write bytes-like object, not {0}", PythonTypeOps.GetName(buffer)); _checkClosed(); var span = pythonBuffer.AsSpan(); for (int i = 0; i < span.Length; i++) { int b = _readStream.ReadByte(); if (b == -1) { return(i); } span[i] = (byte)b; } return(span.Length); }
public int __cmp__(object other) { if (!(other is ClosureCell cc)) { throw PythonOps.TypeError("cell.__cmp__(x,y) expected cell, got {0}", PythonTypeOps.GetName(other)); } return(PythonOps.Compare(Value, cc.Value)); }
private List <OldClass> ValidateBases(object value) { if (!(value is PythonTuple t)) { throw PythonOps.TypeError("__bases__ must be a tuple object"); } List <OldClass> res = new List <OldClass>(t.__len__()); foreach (object o in t) { if (!(o is OldClass oc)) { throw PythonOps.TypeError("__bases__ items must be classes (got {0})", PythonTypeOps.GetName(o)); } if (oc.IsSubclassOf(this)) { throw PythonOps.TypeError("a __bases__ item causes an inheritance cycle"); } res.Add(oc); } return(res); }
private static void TestBothSequence(object a, object b) { if (!isSequenceType(a)) { throw PythonOps.TypeError("'{0}' object cannot be concatenated", PythonTypeOps.GetName(a)); } else if (!isSequenceType(b)) { throw PythonOps.TypeError("cannot concatenate '{0}' and '{1} objects", PythonTypeOps.GetName(a), PythonTypeOps.GetName(b)); } }
public static object trunc(CodeContext /*!*/ context, object value) { object func; if (PythonOps.TryGetBoundAttr(value, "__trunc__", out func)) { return(PythonOps.CallWithContext(context, func)); } else { throw PythonOps.TypeError("type {0} doesn't define __trunc__ method", PythonTypeOps.GetName(value)); } }
public string GetClassName() { return(PythonTypeOps.GetName(_value)); }
public SetCollection InPlaceExclusiveOr(object s) { ISet set = s as ISet; if (set == null) { throw PythonOps.TypeError("unsupported operand type(s) for ^=: '{0}' and '{1}'", PythonTypeOps.GetName(s), PythonTypeOps.GetName(this)); } symmetric_difference_update(set); return(this); }
public SetCollection InPlaceBitwiseOr(object s) { ISet set = s as ISet; if (set == null) { throw PythonOps.TypeError("unsupported operand type(s) for |=: '{0}' and '{1}'", PythonTypeOps.GetName(s), PythonTypeOps.GetName(this)); } update(set); return(this); }
public static object encode(CodeContext /*!*/ context, object?obj, [NotNull, DisallowNull] string?encoding = null, [NotNull] string errors = "strict") { if (encoding == null) { if (obj is string str) { PythonContext lc = context.LanguageContext; return(StringOps.DoEncode(context, str, errors, lc.GetDefaultEncodingName(), lc.DefaultEncoding, includePreamble: true)); } else { throw PythonOps.TypeError("expected str, got {0}", PythonTypeOps.GetName(obj)); } } else { object?encoder = lookup(context, encoding)[EncoderIndex]; if (!PythonOps.IsCallable(context, encoder)) { throw PythonOps.TypeError("encoding with '{0}' codec failed; encoder must be callable ('{1}' object is not callable)", encoding, PythonTypeOps.GetName(encoder)); } return(PythonOps.GetIndex(context, PythonCalls.Call(context, encoder, obj, errors), 0)); } }
public static string oct(CodeContext context, object number) { if (number is int) { number = (BigInteger)(int)number; } if (number is BigInteger) { BigInteger x = (BigInteger)number; if (x == 0) { return("0o0"); } else if (x > 0) { return("0o" + x.ToString(8)); } else { return("-0o" + (-x).ToString(8)); } } object value; if (PythonTypeOps.TryInvokeUnaryOperator(context, number, "__index__", out value)) { if (!(value is int) && !(value is BigInteger)) { throw PythonOps.TypeError("index returned non-(int, long), got '{0}'", PythonTypeOps.GetName(value)); } return(oct(context, value)); } throw PythonOps.TypeError("oct() argument cannot be interpreted as an index"); }
/// <summary> /// Shared helper between struct and union for getting field info and validating it. /// </summary> private static void GetFieldInfo(INativeType type, object o, out string fieldName, out INativeType cdata, out int?bitCount) { PythonTuple pt = o as PythonTuple; if (pt.Count != 2 && pt.Count != 3) { throw PythonOps.AttributeError("'_fields_' must be a sequence of pairs"); } fieldName = pt[0] as string; if (fieldName == null) { throw PythonOps.TypeError("first item in _fields_ tuple must be a string, got", PythonTypeOps.GetName(pt[0])); } cdata = pt[1] as INativeType; if (cdata == null) { throw PythonOps.TypeError("second item in _fields_ tuple must be a C type, got {0}", PythonTypeOps.GetName(pt[0])); } else if (cdata == type) { throw StructureCannotContainSelf(); } StructType st = cdata as StructType; if (st != null) { st.EnsureFinal(); } if (pt.Count != 3) { bitCount = null; } else { bitCount = CheckBits(cdata, pt); } }
internal static Exception CannotConvertOverflow(string name, object value) { return(PythonOps.OverflowError("Cannot convert {0}({1}) to {2}", PythonTypeOps.GetName(value), value, name)); }
public BigInteger readinto([NotNull] IBufferProtocol buffer) { using var pythonBuffer = buffer.GetBufferNoThrow(BufferFlags.Writable) ?? throw PythonOps.TypeError("readinto() argument must be read-write bytes-like object, not {0}", PythonTypeOps.GetName(buffer)); _checkClosed(); var span = pythonBuffer.AsSpan(); int len = Math.Min(_length - _pos, span.Length); _data.AsSpan(_pos, len).CopyTo(span); _pos += len; return(len); }
public bool __contains__(CodeContext /*!*/ context, object value) { if (value is Extensible <int> ) { return(IndexOf(((Extensible <int>)value).Value.ToByteChecked()) != -1); } else if (value is BigInteger) { return(IndexOf(((BigInteger)value).ToByteChecked()) != -1); } else if (value is Extensible <BigInteger> ) { return(IndexOf(((Extensible <BigInteger>)value).Value.ToByteChecked()) != -1); } throw PythonOps.TypeError("Type {0} doesn't support the buffer API", PythonContext.GetContext(context).PythonOptions.Python30 ? PythonTypeOps.GetOldName(value) : PythonTypeOps.GetName(value)); }
public override BigInteger write(CodeContext /*!*/ context, object bytes) { _checkClosed(); if (bytes is IBufferProtocol bufferProtocol) { return(DoWrite(bufferProtocol)); } throw PythonOps.TypeError("a bytes-like object is required, not '{0}'", PythonTypeOps.GetName(bytes)); }
public void __init__([DefaultParameterValue(null)] object fget, [DefaultParameterValue(null)] object fset, [DefaultParameterValue(null)] object fdel, [DefaultParameterValue(null)] object doc) { _fget = fget; _fset = fset; _fdel = fdel; _doc = doc; if (GetType() != typeof(PythonProperty) && _fget is PythonFunction) { // http://bugs.python.org/issue5890 PythonDictionary dict = UserTypeOps.GetDictionary((IPythonObject)this); if (dict == null) { throw PythonOps.AttributeError("{0} object has no __doc__ attribute", PythonTypeOps.GetName(this)); } dict["__doc__"] = ((PythonFunction)_fget).__doc__; } }
public void __init__(PythonType type, object obj) { if (obj != null) { PythonType dt = obj as PythonType; if (PythonOps.IsInstance(obj, type)) { this._thisClass = type; this._self = obj; this._selfClass = DynamicHelpers.GetPythonType(obj); } else if (dt != null && dt.IsSubclassOf(type)) { this._thisClass = type; this._selfClass = obj; this._self = obj; } else { throw PythonOps.TypeError("super(type, obj): obj must be an instance or subtype of type {1}, not {0}", PythonTypeOps.GetName(obj), type.Name); } } else { this._thisClass = type; this._self = null; this._selfClass = null; } }
public bool __contains__(CodeContext /*!*/ context, object value) { if (value is Extensible <string> ) { return(__contains__(PythonOps.MakeBytes(((Extensible <string>)value).Value.MakeByteArray()))); } if (!context.LanguageContext.PythonOptions.Python30) { throw PythonOps.TypeError("'in <bytes>' requires string or bytes as left operand, not {0}", PythonTypeOps.GetName(value)); } if (value is Extensible <int> ) { return(IndexOf(((Extensible <int>)value).Value.ToByteChecked()) != -1); } else if (value is BigInteger) { return(IndexOf(((BigInteger)value).ToByteChecked()) != -1); } else if (value is Extensible <BigInteger> ) { return(IndexOf(((Extensible <BigInteger>)value).Value.ToByteChecked()) != -1); } // 3.0 error message throw PythonOps.TypeError("Type {0} doesn't support the buffer API", PythonTypeOps.GetOldName(value)); }
internal override bool TryDeleteValue(CodeContext context, object instance, PythonType owner) { throw PythonOps.AttributeErrorForReadonlyAttribute(PythonTypeOps.GetName(instance), "__class__"); }
public int __cmp__(object other) { BuiltinMethodDescriptor bmd = other as BuiltinMethodDescriptor; if (bmd == null) { throw PythonOps.TypeError("instancemethod.__cmp__(x,y) requires y to be a 'instancemethod', not a {0}", PythonTypeOps.GetName(other)); } long result = PythonOps.Id(__objclass__) - PythonOps.Id(bmd.__objclass__); if (result != 0) { return((result > 0) ? 1 : -1); } return(StringOps.Compare(__name__, bmd.__name__)); }
public void __setstate__(CodeContext context, PythonTuple tuple) { _checkClosed(); if (tuple.__len__() != 3) { throw PythonOps.TypeError("_io.BytesIO.__setstate__ argument should be 3-tuple, got tuple"); } var initial_bytes = tuple[0] as IBufferProtocol; if (!(tuple[0] is IBufferProtocol)) { throw PythonOps.TypeError($"'{PythonTypeOps.GetName(tuple[0])}' does not support the buffer interface"); } if (!(tuple[1] is int i)) { throw PythonOps.TypeError($"second item of state must be an integer, not {PythonTypeOps.GetName(tuple[1])}"); } if (i < 0) { throw PythonOps.ValueError("position value cannot be negative"); } var dict = tuple[2] as PythonDictionary; if (!(tuple[2] is PythonDictionary || tuple[2] is null)) { throw PythonOps.TypeError($"third item of state should be a dict, got a {PythonTypeOps.GetName(tuple[2])}"); } __init__(initial_bytes); _pos = i; if (!(dict is null)) { __dict__.update(context, dict); } }