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)); } }
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 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.GetCallableAddMethod(); if (CompilerHelpers.IsVisible(add) || context.LanguageContext.DomainManager.Configuration.PrivateBinding) { _event.Tracker.AddHandler(_instance, func, context.LanguageContext.DelegateCreator); } else { throw new ArgumentTypeException("Cannot add handler to a private event."); } return(this); }
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 void __init__(object fget = null, object fset = null, object fdel = null, object doc = null) { _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 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"); }
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 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)); }
internal object CallTarget(CodeContext context, SiteLocalStorage <CallSite <Func <CallSite, CodeContext, object, object[], object> > > storage, MethodInfo[] targets, object instance, params object[] args) { BuiltinFunction target = PythonTypeOps.GetBuiltinFunction(DeclaringType, __name__, targets); return(target.Call(context, storage, instance, args)); }
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); } }
private List <OldClass> ValidateBases(object value) { PythonTuple t = value as PythonTuple; if (t == null) { throw PythonOps.TypeError("__bases__ must be a tuple object"); } List <OldClass> res = new List <OldClass>(t.__len__()); foreach (object o in t) { OldClass oc = o as OldClass; if (oc == null) { 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); }
public override BigInteger write(CodeContext /*!*/ context, [NotNull] 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 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(); if (_pos >= _length) { return(0); } var span = pythonBuffer.AsSpan(); int len = Math.Min(_length - _pos, span.Length); _data.AsSpan(_pos, len).CopyTo(span); _pos += len; return(len); }
internal override bool TryDeleteValue(CodeContext context, object instance, PythonType owner) { throw PythonOps.AttributeErrorForReadonlyAttribute(PythonTypeOps.GetName(instance), "__class__"); }
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)); } }
private void MakeSetFunc() { _setfunc = PythonTypeOps.GetBuiltinFunction(DeclaringType, __name__, _setter); }
private Func <CallSite, TSelfType, CodeContext, object> MakeGetMemberTarget <TSelfType>(string name, object target, CodeContext context) { Type type = CompilerHelpers.GetType(target); // needed for GetMember call until DynamicAction goes away if (typeof(TypeTracker).IsAssignableFrom(type)) { // no fast path for TypeTrackers PerfTrack.NoteEvent(PerfTrack.Categories.BindingSlow, "GetNoFast TypeTracker"); return(null); } MemberGroup members = Context.Binder.GetMember(MemberRequestKind.Get, type, name); if (members.Count == 0 && type.IsInterface()) { // all interfaces have object members type = typeof(object); members = Context.Binder.GetMember(MemberRequestKind.Get, type, name); } if (members.Count == 0 && typeof(IStrongBox).IsAssignableFrom(type)) { // no fast path for strong box access PerfTrack.NoteEvent(PerfTrack.Categories.BindingSlow, "GetNoFast StrongBox"); return(null); } MethodInfo getMem = Context.Binder.GetMethod(type, "GetCustomMember"); if (getMem != null && getMem.IsSpecialName) { // no fast path for custom member access PerfTrack.NoteEvent(PerfTrack.Categories.BindingSlow, "GetNoFast GetCustomMember " + type); return(null); } Expression error; TrackerTypes memberType = Context.Binder.GetMemberType(members, out error); if (error == null) { PythonType argType = DynamicHelpers.GetPythonTypeFromType(type); bool isHidden = argType.IsHiddenMember(name); if (isHidden) { PerfTrack.NoteEvent(PerfTrack.Categories.BindingSlow, "GetNoFast FilteredMember " + memberType); return(null); } switch (memberType) { case TrackerTypes.TypeGroup: case TrackerTypes.Type: object typeObj; if (members.Count == 1) { typeObj = DynamicHelpers.GetPythonTypeFromType(((TypeTracker)members[0]).Type); } else { TypeTracker typeTracker = (TypeTracker)members[0]; for (int i = 1; i < members.Count; i++) { typeTracker = TypeGroup.UpdateTypeEntity(typeTracker, (TypeTracker)members[i]); } typeObj = typeTracker; } return(new FastTypeGet <TSelfType>(type, typeObj).GetTypeObject); case TrackerTypes.Method: PythonTypeSlot slot = PythonTypeOps.GetSlot(members, name, _context.DomainManager.Configuration.PrivateBinding); if (slot is BuiltinMethodDescriptor) { return(new FastMethodGet <TSelfType>(type, (BuiltinMethodDescriptor)slot).GetMethod); } else if (slot is BuiltinFunction) { return(new FastSlotGet <TSelfType>(type, slot, DynamicHelpers.GetPythonTypeFromType(type)).GetRetSlot); } return(new FastSlotGet <TSelfType>(type, slot, DynamicHelpers.GetPythonTypeFromType(type)).GetBindSlot); case TrackerTypes.Event: if (members.Count == 1 && !((EventTracker)members[0]).IsStatic) { slot = PythonTypeOps.GetSlot(members, name, _context.DomainManager.Configuration.PrivateBinding); return(new FastSlotGet <TSelfType>(type, slot, DynamicHelpers.GetPythonTypeFromType(((EventTracker)members[0]).DeclaringType)).GetBindSlot); } PerfTrack.NoteEvent(PerfTrack.Categories.BindingSlow, "GetNoFast Event " + members.Count + " " + ((EventTracker)members[0]).IsStatic); return(null); case TrackerTypes.Property: if (members.Count == 1) { PropertyTracker pt = (PropertyTracker)members[0]; if (!pt.IsStatic && pt.GetIndexParameters().Length == 0) { MethodInfo prop = pt.GetGetMethod(); ParameterInfo[] parameters; if (prop != null && (parameters = prop.GetParameters()).Length == 0) { if (prop.ReturnType == typeof(bool)) { return(new FastPropertyGet <TSelfType>(type, CallInstruction.Create(prop, parameters).Invoke).GetPropertyBool); } else if (prop.ReturnType == typeof(int)) { return(new FastPropertyGet <TSelfType>(type, CallInstruction.Create(prop, parameters).Invoke).GetPropertyInt); } else { return(new FastPropertyGet <TSelfType>(type, CallInstruction.Create(prop, parameters).Invoke).GetProperty); } } } } PerfTrack.NoteEvent(PerfTrack.Categories.BindingSlow, "GetNoFast Property " + members.Count + " " + ((PropertyTracker)members[0]).IsStatic); return(null); case TrackerTypes.All: getMem = Context.Binder.GetMethod(type, "GetBoundMember"); if (getMem != null && getMem.IsSpecialName) { PerfTrack.NoteEvent(PerfTrack.Categories.BindingSlow, "GetNoFast GetBoundMember " + type); return(null); } if (members.Count == 0) { // we don't yet support fast bindings to extension methods members = context.ModuleContext.ExtensionMethods.GetBinder(_context).GetMember(MemberRequestKind.Get, type, name); if (members.Count == 0) { if (IsNoThrow) { return(new FastErrorGet <TSelfType>(type, name, context.ModuleContext.ExtensionMethods).GetErrorNoThrow); } else if (SupportsLightThrow) { return(new FastErrorGet <TSelfType>(type, name, context.ModuleContext.ExtensionMethods).GetErrorLightThrow); } else { return(new FastErrorGet <TSelfType>(type, name, context.ModuleContext.ExtensionMethods).GetError); } } } return(null); default: PerfTrack.NoteEvent(PerfTrack.Categories.BindingSlow, "GetNoFast " + memberType); return(null); } } else { StringBuilder sb = new StringBuilder(); foreach (MemberTracker mi in members) { if (sb.Length != 0) { sb.Append(", "); } sb.Append(mi.MemberType); sb.Append(" : "); sb.Append(mi.ToString()); } return(new FastErrorGet <TSelfType>(type, sb.ToString(), context.ModuleContext.ExtensionMethods).GetAmbiguous); } }
public bool __contains__(CodeContext /*!*/ context, object value) { if (!PythonContext.GetContext(context).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)); }
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 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 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)); }
public string GetClassName() { return(PythonTypeOps.GetName(_value)); }
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.GetCallableAddMethod(); // 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) || (add.IsProtected() /*todo: validate current context is in family*/) || 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 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 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)); }
internal static Exception CannotConvertOverflow(string name, object value) { return(PythonOps.OverflowError("Cannot convert {0}({1}) to {2}", PythonTypeOps.GetName(value), value, name)); }
/// <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(); } if (cdata is StructType st) { st.EnsureFinal(); } if (pt.Count != 3) { bitCount = null; } else { bitCount = CheckBits(cdata, pt); } }
public int seek(CodeContext /*!*/ context, object pos, [DefaultParameterValue(0)] object whence) { EnsureOpen(); if (pos == null || whence == null) { throw PythonOps.TypeError("an integer is required"); } int intPos; if (pos is int) { intPos = (int)pos; } else if (pos is Extensible <int> ) { intPos = ((Extensible <int>)pos).Value; } else if (pos is BigInteger) { intPos = (int)(BigInteger)pos; } else if (pos is Extensible <BigInteger> ) { intPos = (int)(((Extensible <BigInteger>)pos).Value); } else if (pos is double || pos is Extensible <double> ) { throw PythonOps.TypeError("position argument must be an integer"); } else if (PythonContext.GetContext(context).PythonOptions.Python30) { throw PythonOps.TypeError("'{0}' object cannot be interpreted as an integer", PythonTypeOps.GetOldName(pos)); } else { throw PythonOps.TypeError("an integer is required"); } if (whence is int) { return(seek(intPos, (int)whence)); } else if (whence is Extensible <int> ) { return(seek(intPos, ((Extensible <int>)pos).Value)); } else if (whence is BigInteger) { return(seek(intPos, (int)(BigInteger)whence)); } else if (whence is Extensible <BigInteger> ) { return(seek(intPos, (int)(((Extensible <BigInteger>)whence).Value))); } else if (whence is double || whence is Extensible <double> ) { if (PythonContext.GetContext(context).PythonOptions.Python30) { throw PythonOps.TypeError("integer argument expected, got float"); } else { PythonOps.Warn(context, PythonExceptions.DeprecationWarning, "integer argument expected, got float"); return(seek(intPos, Converter.ConvertToInt32(whence))); } } else if (PythonContext.GetContext(context).PythonOptions.Python30) { throw PythonOps.TypeError("'{0}' object cannot be interpreted as an integer", PythonTypeOps.GetOldName(whence)); } else { throw PythonOps.TypeError("an integer is required"); } }