public static Type GetNewType(string typeName, PythonTuple bases, IAttributesCollection dict) { if (bases == null) bases = PythonTuple.EMPTY; // we're really only interested in the "correct" base type pulled out of bases // and any slot information contained in dict // other info might be used for future optimizations NewTypeInfo typeInfo = GetTypeInfo(typeName, bases, GetSlots(dict)); if (typeInfo.BaseType.IsValueType) throw PythonOps.TypeError("cannot derive from {0} because it is a value type", typeInfo.BaseType.FullName); if (typeInfo.BaseType.IsSealed) throw PythonOps.TypeError("cannot derive from {0} because it is sealed", typeInfo.BaseType.FullName); Type ret = _newTypes.GetOrCreateValue(typeInfo, delegate() { if (typeInfo.InterfaceTypes.Count == 0 && typeInfo.Slots == null) { // types that the have DynamicBaseType attribute can be used as NewType's directly, no // need to create a new type unless we're adding interfaces or slots... object[] attrs = typeInfo.BaseType.GetCustomAttributes(typeof(DynamicBaseTypeAttribute), false); if (attrs.Length > 0) { return typeInfo.BaseType; } } // creation code return GetTypeMaker(bases, typeInfo).CreateNewType(); }); OptimizedScriptCode.InitializeFields(ret, true); return ret; }
private static readonly Field[] _emptyFields = new Field[0]; // fields were never initialized before a type was created public StructType(CodeContext/*!*/ context, string name, PythonTuple bases, PythonDictionary members) : base(context, name, bases, members) { foreach (PythonType pt in ResolutionOrder) { StructType st = pt as StructType; if (st != this && st != null) { st.EnsureFinal(); } UnionType ut = pt as UnionType; if (ut != null) { ut.EnsureFinal(); } } object pack; if (members.TryGetValue("_pack_", out pack)) { if (!(pack is int) || ((int)pack < 0)) { throw PythonOps.ValueError("pack must be a non-negative integer"); } _pack = (int)pack; } object fields; if (members.TryGetValue("_fields_", out fields)) { // When we support alternate endianness this should change to: //__setattr__(context, "_fields_", fields); SetFields(fields); } // TODO: _anonymous_ }
/// <summary> /// Python ctor - maps to function.__new__ /// /// y = func(x.__code__, globals(), 'foo', None, (a, )) /// </summary> public PythonFunction(CodeContext context, FunctionCode code, PythonDictionary globals, string name, PythonTuple defaults, PythonTuple closure) { if (closure != null && closure.__len__() != 0) { throw new NotImplementedException("non empty closure argument is not supported"); } if (globals == context.GlobalDict) { _module = context.Module.GetName(); _context = context; } else { _module = null; _context = new CodeContext(new PythonDictionary(), new ModuleContext(globals, DefaultContext.DefaultPythonContext)); } _defaults = defaults == null ? ArrayUtils.EmptyObjects : defaults.ToArray(); _code = code; _name = name; _doc = code._initialDoc; Closure = null; var scopeStatement = _code.PythonCode; if (scopeStatement.IsClosure) { throw new NotImplementedException("code containing closures is not supported"); } scopeStatement.RewriteBody(FunctionDefinition.ArbitraryGlobalsVisitorInstance); _compat = CalculatedCachedCompat(); }
static PythonTime() { // altzone, timezone are offsets from UTC in seconds, so they always fit in the // -13*3600 to 13*3600 range and are safe to cast to ints #if FEATURE_TIMEZONE DaylightTime dayTime = TimeZone.CurrentTimeZone.GetDaylightChanges(DateTime.Now.Year); daylight = (dayTime.Start == dayTime.End && dayTime.Start == DateTime.MinValue && dayTime.Delta.Ticks == 0) ? 0 : 1; tzname = PythonTuple.MakeTuple(TimeZone.CurrentTimeZone.StandardName, TimeZone.CurrentTimeZone.DaylightName); altzone = (int)-TimeZone.CurrentTimeZone.GetUtcOffset(DateTime.Now).TotalSeconds; timezone = altzone; if (daylight != 0) { // GetUtcOffset includes adjustments for timezones. If we're in daylight saving time then // we need to adjust timezone so it is the correct time. Otherwise we need to adjust altzone if (TimeZone.CurrentTimeZone.IsDaylightSavingTime(DateTime.Now)) { timezone += (int)dayTime.Delta.TotalSeconds; } else { altzone -= (int)dayTime.Delta.TotalSeconds; } } #else daylight = TimeZoneInfo.Local.SupportsDaylightSavingTime ? 1 : 0; tzname = PythonTuple.MakeTuple(TimeZoneInfo.Local.StandardName, TimeZoneInfo.Local.DaylightName); timezone = (int)-TimeZoneInfo.Local.BaseUtcOffset.TotalSeconds; altzone = (int)-TimeZoneInfo.Local.GetUtcOffset(DateTime.Now).TotalSeconds; #endif }
// __nonzero__ /// <summary> /// Creates a new CFuncPtr object from a tuple. The 1st element of the /// tuple is the ordinal or function name. The second is an object with /// a _handle property. The _handle property is the handle of the module /// from which the function will be loaded. /// </summary> public _CFuncPtr(PythonTuple args) { if (args == null) { throw PythonOps.TypeError("expected sequence, got None"); } else if (args.Count != 2) { throw PythonOps.TypeError("argument 1 must be a sequence of length 2, not {0}", args.Count); } object nameOrOrdinal = args[0]; object dll = args[1]; IntPtr intPtrHandle = GetHandleFromObject(dll, "the _handle attribute of the second element must be an integer"); string funcName = args[0] as string; if (funcName != null) { _addr = NativeFunctions.GetProcAddress(intPtrHandle, funcName); } else { _addr = NativeFunctions.GetProcAddress(intPtrHandle, new IntPtr((int)nameOrOrdinal)); } if (_addr == IntPtr.Zero) { if (CallingConvention == CallingConvention.StdCall && funcName != null) { // apply std call name mangling - prepend a _, append @bytes where // bytes is the number of bytes of the argument list. string mangled = "_" + funcName + "@"; for (int i = 0; i < 128 && _addr == IntPtr.Zero; i += 4) { _addr = NativeFunctions.GetProcAddress(intPtrHandle, mangled + i); } } if (_addr == IntPtr.Zero) { throw PythonOps.AttributeError("function {0} is not defined", args[0]); } } _id = Interlocked.Increment(ref _curId); }
public StructType(CodeContext/*!*/ context, string name, PythonTuple bases, IAttributesCollection members) : base(context, name, bases, members) { foreach (PythonType pt in ResolutionOrder) { StructType st = pt as StructType; if (st != this && st != null) { st.EnsureFinal(); } UnionType ut = pt as UnionType; if (ut != null) { ut.EnsureFinal(); } } object pack; if (members.TryGetValue(SymbolTable.StringToId("_pack_"), out pack)) { if (!(pack is int) || ((int)pack < 0)) { throw PythonOps.ValueError("pack must be a non-negative integer"); } _pack = (int)pack; } object fields; if (members.TryGetValue(SymbolTable.StringToId("_fields_"), out fields)) { SetFields(fields); } // TODO: _anonymous_ }
public static object load_module(CodeContext/*!*/ context, string name, PythonFile file, string filename, PythonTuple/*!*/ description) { if (description == null) { throw PythonOps.TypeError("load_module() argument 4 must be 3-item sequence, not None"); } if (description.__len__() != 3) { throw PythonOps.TypeError("load_module() argument 4 must be sequence of length 3, not {0}", description.__len__()); } PythonContext pythonContext = PythonContext.GetContext(context); // already loaded? do reload() PythonModule module = pythonContext.GetModuleByName(name); if (module != null) { Importer.ReloadModule(context, module.Scope); return module.Scope; } int type = PythonContext.GetContext(context).ConvertToInt32(description[2]); switch (type) { case PythonSource: return LoadPythonSource(pythonContext, name, file, filename); case CBuiltin: return LoadBuiltinModule(context, name); case PackageDirectory: return LoadPackageDirectory(pythonContext, name, filename); default: throw PythonOps.TypeError("don't know how to import {0}, (type code {1}", name, type); } }
/// <summary> /// Gateway into importing ... called from Ops. Performs the initial import of /// a module and returns the module. /// </summary> public static object Import(CodeContext/*!*/ context, string fullName, PythonTuple from, int level) { PythonContext pc = PythonContext.GetContext(context); if (level == -1) { // no specific level provided, call the 4 param version so legacy code continues to work return pc.OldImportSite.Target( pc.OldImportSite, context, FindImportFunction(context), fullName, Builtin.globals(context), context.Dict, from ); } // relative import or absolute import, in other words: // // from . import xyz // or // from __future__ import absolute_import return pc.ImportSite.Target( pc.ImportSite, context, FindImportFunction(context), fullName, Builtin.globals(context), context.Dict, from, level ); }
public static Type/*!*/ GetNewType(string/*!*/ typeName, PythonTuple/*!*/ bases) { Assert.NotNull(typeName, bases); NewTypeInfo typeInfo = NewTypeInfo.GetTypeInfo(typeName, bases); if (typeInfo.BaseType.IsValueType) { throw PythonOps.TypeError("cannot derive from {0} because it is a value type", typeInfo.BaseType.FullName); } else if (typeInfo.BaseType.IsSealed) { throw PythonOps.TypeError("cannot derive from {0} because it is sealed", typeInfo.BaseType.FullName); } Type ret = _newTypes.GetOrCreateValue(typeInfo, () => { if (typeInfo.InterfaceTypes.Count == 0) { // types that the have DynamicBaseType attribute can be used as NewType's directly, no // need to create a new type unless we're adding interfaces object[] attrs = typeInfo.BaseType.GetCustomAttributes(typeof(DynamicBaseTypeAttribute), false); if (attrs.Length > 0) { return typeInfo.BaseType; } } // creation code return new NewTypeMaker(typeInfo).CreateNewType(); }); return ret; }
public UnionType(CodeContext/*!*/ context, string name, PythonTuple bases, IAttributesCollection members) : base(context, name, bases, members) { object fields; if (members.TryGetValue(SymbolTable.StringToId("_fields_"), out fields)) { SetFields(fields); } }
public UnionType(CodeContext/*!*/ context, string name, PythonTuple bases, PythonDictionary members) : base(context, name, bases, members) { object fields; if (members.TryGetValue("_fields_", out fields)) { SetFields(fields); } }
/// <summary> /// Runs the formatting operation on the given format and keyword arguments /// </summary> public static string/*!*/ FormatString(PythonContext/*!*/ context, string/*!*/ format, PythonTuple/*!*/ args, IAttributesCollection/*!*/ kwArgs) { ContractUtils.RequiresNotNull(context, "context"); ContractUtils.RequiresNotNull(format, "format"); ContractUtils.RequiresNotNull(args, "args"); ContractUtils.RequiresNotNull(kwArgs, "kwArgs"); return Formatter.FormatString(context, format, args, kwArgs); }
public PointerType(CodeContext/*!*/ context, string name, PythonTuple bases, IAttributesCollection members) : base(context, name, bases, members) { object type; if (members.TryGetValue(SymbolTable.StringToId("_type_"), out type) && !(type is INativeType)) { throw PythonOps.TypeError("_type_ must be a type"); } _type = (INativeType)type; }
private static void validateRouteInfo(PythonTuple routeInfo) { if (routeInfo.Count != EXPECTED_TUPLE_LENGTH) { throw new RouteMappingException(); } if (routeInfo.Contains(null)) { throw new RouteMappingException(); } }
public ArrayType(CodeContext/*!*/ context, string name, PythonTuple bases, IAttributesCollection dict) : base(context, name, bases, dict) { object len; int iLen; if (!dict.TryGetValue(SymbolTable.StringToId("_length_"), out len) || !(len is int) || (iLen = (int)len) < 0) { throw PythonOps.AttributeError("arrays must have _length_ attribute and it must be a positive integer"); } object type; if (!dict.TryGetValue(SymbolTable.StringToId("_type_"), out type)) { throw PythonOps.AttributeError("class must define a '_type_' attribute"); } _length = iLen; _type = (INativeType)type; if (_type is SimpleType) { SimpleType st = (SimpleType)_type; if (st._type == SimpleTypeKind.Char) { // TODO: (c_int * 2).value isn't working SetCustomMember(context, SymbolTable.StringToId("value"), new ReflectedExtensionProperty( new ExtensionPropertyInfo(this, typeof(CTypes).GetMethod("GetCharArrayValue")), NameType.Property | NameType.Python ) ); SetCustomMember(context, SymbolTable.StringToId("raw"), new ReflectedExtensionProperty( new ExtensionPropertyInfo(this, typeof(CTypes).GetMethod("GetWCharArrayRaw")), NameType.Property | NameType.Python ) ); } else if (st._type == SimpleTypeKind.WChar) { SetCustomMember(context, SymbolTable.StringToId("value"), new ReflectedExtensionProperty( new ExtensionPropertyInfo(this, typeof(CTypes).GetMethod("GetWCharArrayValue")), NameType.Property | NameType.Python ) ); SetCustomMember(context, SymbolTable.StringToId("raw"), new ReflectedExtensionProperty( new ExtensionPropertyInfo(this, typeof(CTypes).GetMethod("GetWCharArrayRaw")), NameType.Property | NameType.Python ) ); } } }
public PointerType(CodeContext/*!*/ context, string name, PythonTuple bases, PythonDictionary members) : base(context, name, bases, members) { object type; if (members.TryGetValue("_type_", out type) && !(type is INativeType)) { throw PythonOps.TypeError("_type_ must be a type"); } _type = (INativeType)type; if (_type != null) { _typeFormat = _type.TypeFormat; } }
/// <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 = Type.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 ? Type.EmptyTypes : interfaceTypes.ToArray()); }
public override IntPtr PyList_AsTuple(IntPtr listPtr) { try { PythonTuple tuple = new PythonTuple(this.Retrieve(listPtr)); return this.Store(tuple); } catch (Exception e) { this.LastException = e; return IntPtr.Zero; } }
ExtractBases(IntPtr typePtr) { PythonTuple tp_bases = null; IntPtr tp_basesPtr = CPyMarshal.ReadPtrField(typePtr, typeof(PyTypeObject), "tp_bases"); if (tp_basesPtr != IntPtr.Zero) { tp_bases = (PythonTuple)this.Retrieve(tp_basesPtr); } if (tp_bases == null) { IntPtr tp_basePtr = CPyMarshal.ReadPtrField(typePtr, typeof(PyTypeObject), "tp_base"); tp_bases = new PythonTuple(new object[] { this.Retrieve(tp_basePtr) }); } return tp_bases; }
public static object __new__(CodeContext/*!*/ context, [NotNull]PythonType cls, string name, PythonTuple bases, IAttributesCollection dict) { if (cls != TypeCache.OldClass) throw PythonOps.TypeError("{0} is not a subtype of classobj", cls.Name); if (!dict.ContainsKey(Symbols.Module)) { object moduleValue; if (context.GlobalScope.TryGetVariable(Symbols.Name, out moduleValue)) { dict[Symbols.Module] = moduleValue; } } foreach (object o in bases) { if (o is PythonType) { return PythonOps.MakeClass(context, name, bases._data, String.Empty, dict); } } return new OldClass(name, bases, dict, String.Empty); }
public SimpleType(CodeContext/*!*/ context, string name, PythonTuple bases, IAttributesCollection dict) : base(context, name, bases, dict) { object val; string sVal; const string allowedTypes = "?cbBghHiIlLdfuzZqQPXOv"; if (!TryGetBoundCustomMember(context, SymbolTable.StringToId("_type_"), out val) || (sVal = StringOps.AsString(val)) == null || sVal.Length != 1 || allowedTypes.IndexOf(sVal[0]) == -1) { throw PythonOps.AttributeError("AttributeError: class must define a '_type_' attribute which must be a single character string containing one of '{0}'.", allowedTypes); } _charType = sVal[0]; switch (sVal[0]) { case '?': _type = SimpleTypeKind.Boolean; break; case 'c': _type = SimpleTypeKind.Char; break; case 'b': _type = SimpleTypeKind.SignedByte; break; case 'B': _type = SimpleTypeKind.UnsignedByte; break; case 'h': _type = SimpleTypeKind.SignedShort; break; case 'H': _type = SimpleTypeKind.UnsignedShort; break; case 'i': _type = SimpleTypeKind.SignedInt; break; case 'I': _type = SimpleTypeKind.UnsignedInt; break; case 'l': _type = SimpleTypeKind.SignedLong; break; case 'L': _type = SimpleTypeKind.UnsignedLong; break; case 'f': _type = SimpleTypeKind.Single; break; case 'g': // long double, new in 2.6 case 'd': _type = SimpleTypeKind.Double; break; case 'q': _type = SimpleTypeKind.SignedLongLong; break; case 'Q': _type = SimpleTypeKind.UnsignedLongLong; break; case 'O': _type = SimpleTypeKind.Object; break; case 'P': _type = SimpleTypeKind.Pointer; break; case 'z': _type = SimpleTypeKind.CharPointer; break; case 'Z': _type = SimpleTypeKind.WCharPointer; break; case 'u': _type = SimpleTypeKind.WChar; break; case 'p': // what are these? case 'X': case 'v': throw new NotImplementedException("simple type " + sVal); } }
public static object __new__(CodeContext/*!*/ context, [NotNull]PythonType cls, string name, PythonTuple bases, PythonDictionary/*!*/ dict) { if (dict == null) { throw PythonOps.TypeError("dict must be a dictionary"); } else if (cls != TypeCache.OldClass) { throw PythonOps.TypeError("{0} is not a subtype of classobj", cls.Name); } if (!dict.ContainsKey("__module__")) { object moduleValue; if (context.TryGetGlobalVariable("__name__", out moduleValue)) { dict["__module__"] = moduleValue; } } foreach (object o in bases) { if (o is PythonType) { return PythonOps.MakeClass(context, name, bases._data, String.Empty, dict); } } return new OldClass(name, bases, dict, String.Empty); }
/// <summary> /// Gateway into importing ... called from Ops. Performs the initial import of /// a module and returns the module. /// </summary> public static object Import(CodeContext/*!*/ context, string fullName, PythonTuple from, int level) { Exception exLast = PythonOps.SaveCurrentException(); try { PythonContext pc = PythonContext.GetContext(context); if (level == -1) { // no specific level provided, call the 4 param version so legacy code continues to work return pc.OldImportSite.Target( pc.OldImportSite, context, FindImportFunction(context), fullName, Builtin.globals(context), Builtin.LocalsAsAttributesCollection(context), from ); } // relative import or absolute import, in other words: // // from . import xyz // or // from __future__ import absolute_import return pc.ImportSite.Target( pc.ImportSite, context, FindImportFunction(context), fullName, Builtin.globals(context), Builtin.LocalsAsAttributesCollection(context), from, level ); } finally { PythonOps.RestoreCurrentException(exLast); } }
public static double mktime(CodeContext /*!*/ context, PythonTuple localTime) { return(TicksToTimestamp(GetDateTimeFromTuple(context, localTime).AddSeconds(timezone).Ticks)); }
public static string strftime(CodeContext /*!*/ context, string format, PythonTuple dateTime) { return(strftime(context, format, GetDateTimeFromTupleNoDst(context, dateTime), null)); }
public static object call_function(CodeContext context, int address, PythonTuple args) { return(call_function(context, new IntPtr(address), args)); }
public static object __getnewargs__(CodeContext context, int year, int month, int day, int hour, int minute, int second, int dayOfWeek, int dayOfYear, int isDst) { return(PythonTuple.MakeTuple(struct_time.__new__(context, _StructTimeType, year, month, day, hour, minute, second, dayOfWeek, dayOfYear, isDst))); }
private static PythonTuple SocketExceptionToTuple(SocketException e) { return(PythonTuple.MakeTuple(e.ErrorCode, e.Message)); }
public virtual void __init__([NotNull] params object?[] args\u00F8) { _args = PythonTuple.MakeTuple(args\u00F8 ?? new object?[] { null }); }
internal struct_time(PythonTuple sequence) : base(sequence) { }
internal OldClass(string name, PythonTuple bases, PythonDictionary /*!*/ dict, string instanceNames) { _bases = ValidateBases(bases); Init(name, dict, instanceNames); }
/// <summary> /// Implements the default __reduce_ex__ method as specified by PEP 307 case 3 (new-style instance, protocol 2) /// </summary> private static PythonTuple ReduceProtocol2(CodeContext /*!*/ context, object self) { PythonType myType = DynamicHelpers.GetPythonType(self); object state; object[] funcArgs; object func = context.LanguageContext.NewObject; object getNewArgsCallable; if (PythonOps.TryGetBoundAttr(context, myType, "__getnewargs__", out getNewArgsCallable)) { // TypeError will bubble up if __getnewargs__ isn't callable PythonTuple newArgs = PythonOps.CallWithContext(context, getNewArgsCallable, self) as PythonTuple; if (newArgs == null) { 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; IPythonObject ipo = self as IPythonObject; if (ipo != null) { 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 /*dict == null && initializedSlotValues != null*/ state {
public static struct_time __new__(CodeContext context, PythonType cls, [NotNull] IEnumerable sequence) { return(__new__(context, cls, PythonTuple.Make(sequence))); }
private SimpleType(CodeContext /*!*/ context, string name, PythonTuple bases, PythonDictionary dict, bool isLittleEndian) : this(context, name, bases, dict) { _format = (isLittleEndian ? '<' : '>') + _charType.ToString(); _swap = isLittleEndian != BitConverter.IsLittleEndian; }
public static object DoErrorCheck(object errCheckFunc, object result, object func, object[] arguments) { return(PythonCalls.Call(errCheckFunc, result, func, PythonTuple.Make(arguments))); }
public PythonTuple __getstate__(CodeContext context) { return(PythonTuple.MakeTuple(getvalue(), tell(context), new PythonDictionary(__dict__))); }
public BaseException([NotNull] PythonType /*!*/ type) { ContractUtils.RequiresNotNull(type, nameof(type)); _type = type; _args = PythonTuple.EMPTY; }
public static object __getnewargs__(CodeContext context, int self) { return(PythonTuple.MakeTuple(Int32Ops.__new__(context, TypeCache.Int32, self))); }
/// <summary> /// Return the System.Net.Sockets.Socket object that corresponds to the passed-in /// object. obj can be a System.Net.Sockets.Socket, a PythonSocket.SocketObj, a /// long integer (representing a socket handle), or a Python object with a fileno() /// method (whose result is used to look up an existing PythonSocket.SocketObj, /// which is in turn converted to a Socket. /// </summary> private static Socket ObjectToSocket(CodeContext context, object obj) { Socket socket; PythonSocket.socket pythonSocket = obj as PythonSocket.socket; if (pythonSocket != null) { return(pythonSocket._socket); } Int64 handle; if (!Converter.TryConvertToInt64(obj, out handle)) { object userSocket = obj; object filenoCallable = PythonOps.GetBoundAttr(context, userSocket, "fileno"); object fileno = PythonCalls.Call(context, filenoCallable); handle = Converter.ConvertToInt64(fileno); } if (handle < 0) { throw PythonOps.ValueError("file descriptor cannot be a negative number ({0})", handle); } socket = PythonSocket.socket.HandleToSocket(handle); if (socket == null) { SocketException e = new SocketException((int)SocketError.NotSocket); throw PythonExceptions.CreateThrowable((PythonType)context.LanguageContext.GetModuleState("selecterror"), PythonTuple.MakeTuple(e.ErrorCode, e.Message)); } return(socket); }
private static DateTime GetDateTimeFromTupleNoDst(CodeContext context, PythonTuple t) { int[] dummy; return(GetDateTimeFromTupleNoDst(context, t, out dummy)); }
public static object call_function(CodeContext context, BigInteger address, PythonTuple args) { return(call_function(context, new IntPtr((long)address), args)); }
public PythonTuple __reduce__() { return(PythonTuple.MakeTuple(_StructTimeType, PythonTuple.MakeTuple(tm_year, tm_mon, tm_mday, tm_hour, tm_min, tm_sec, tm_wday, tm_yday, tm_isdst))); }
public static object __new__(CodeContext /*!*/ context, [NotNull] PythonType cls, string name, PythonTuple bases, PythonDictionary /*!*/ dict) { if (dict == null) { throw PythonOps.TypeError("dict must be a dictionary"); } else if (cls != TypeCache.OldClass) { throw PythonOps.TypeError("{0} is not a subtype of classobj", cls.Name); } if (!dict.ContainsKey("__module__")) { object moduleValue; if (context.TryGetGlobalVariable("__name__", out moduleValue)) { dict["__module__"] = moduleValue; } } foreach (object o in bases) { if (o is PythonType) { return(PythonOps.MakeClass(context, name, bases._data, String.Empty, dict)); } } return(new OldClass(name, bases, dict, String.Empty)); }
public static socket create_connection(CodeContext/*!*/ context, PythonTuple address, object timeout) { string msg = "getaddrinfo returns an empty list"; string host = Converter.ConvertToString(address[0]); object port = address[1]; IEnumerator en = getaddrinfo(context, host, port, 0, SOCK_STREAM, (int)ProtocolType.IP, (int)SocketFlags.None).GetEnumerator(); while (en.MoveNext()) { PythonTuple current = (PythonTuple)en.Current; int family = Converter.ConvertToInt32(current[0]); int socktype = Converter.ConvertToInt32(current[1]); int proto = Converter.ConvertToInt32(current[2]); string name = Converter.ConvertToString(current[3]); PythonTuple sockaddress = (PythonTuple)current[4]; socket socket = null; try { socket = new socket(context, family, socktype, proto); if (timeout != _GLOBAL_DEFAULT_TIMEOUT) { socket.settimeout(timeout); } socket.connect(sockaddress); return socket; } catch (Exception ex) { if (PythonOps.CheckException(ex, error(context)) == null) { continue; } if (socket != null) { socket.close(); } msg = ex.Message; } } throw PythonExceptions.CreateThrowableForRaise(context, error(context), msg); }
public static object call_function(CodeContext context, int address, PythonTuple args) { return call_function(context, new IntPtr(address), args); }
public static object call_function(CodeContext context, IntPtr address, PythonTuple args) { CFuncPtrType funcType = GetFunctionType(context, FUNCFLAG_STDCALL); _CFuncPtr func = (_CFuncPtr)funcType.CreateInstance(context, address); return PythonOps.CallWithArgsTuple(func, new object[0], args); }
public PythonTuple ToTuple() { return(PythonTuple.MakeTuple(NID, ShortName, LongName, OIDString)); }
public BuiltinFunction /*!*/ this[PythonTuple tuple] { get { return(this[tuple._data]); } }
public SimpleType(CodeContext /*!*/ context, string name, PythonTuple bases, PythonDictionary dict) : base(context, name, bases, dict) { string sVal; const string allowedTypes = "?cbBghHiIlLdfuzZqQPXOv"; const string swappedTypes = "fdhHiIlLqQ"; if (!TryGetBoundCustomMember(context, "_type_", out object val) || (sVal = StringOps.AsString(val)) == null || sVal.Length != 1 || allowedTypes.IndexOf(sVal[0]) == -1) { throw PythonOps.AttributeError("AttributeError: class must define a '_type_' attribute which must be a single character string containing one of '{0}'.", allowedTypes); } _charType = sVal[0]; switch (_charType) { case '?': _type = SimpleTypeKind.Boolean; break; case 'c': _type = SimpleTypeKind.Char; break; case 'b': _type = SimpleTypeKind.SignedByte; break; case 'B': _type = SimpleTypeKind.UnsignedByte; break; case 'h': _type = SimpleTypeKind.SignedShort; break; case 'H': _type = SimpleTypeKind.UnsignedShort; break; case 'i': _type = SimpleTypeKind.SignedInt; break; case 'I': _type = SimpleTypeKind.UnsignedInt; break; case 'l': _type = SimpleTypeKind.SignedLong; break; case 'L': _type = SimpleTypeKind.UnsignedLong; break; case 'f': _type = SimpleTypeKind.Single; break; case 'g': // long double, new in 2.6 case 'd': _type = SimpleTypeKind.Double; break; case 'q': _type = SimpleTypeKind.SignedLongLong; break; case 'Q': _type = SimpleTypeKind.UnsignedLongLong; break; case 'O': _type = SimpleTypeKind.Object; break; case 'P': _type = SimpleTypeKind.Pointer; break; case 'z': _type = SimpleTypeKind.CharPointer; break; case 'Z': _type = SimpleTypeKind.WCharPointer; break; case 'u': _type = SimpleTypeKind.WChar; break; case 'v': _type = SimpleTypeKind.VariantBool; break; case 'X': _type = SimpleTypeKind.BStr; break; default: throw new NotImplementedException("simple type " + sVal); } if (!name.EndsWith("_be") && !name.EndsWith("_le") && swappedTypes.IndexOf(_charType) != -1) { CreateSwappedType(context, name, bases, dict); } _format = (BitConverter.IsLittleEndian ? '<' : '>') + _charType.ToString(); }
public static PythonTuple __divmod__(int x, int y) { return(PythonTuple.MakeTuple(FloorDivide(x, y), Mod(x, y))); }
public static void warn_explicit(CodeContext context, object message, PythonType category, string filename, int lineno, string module = null, PythonDictionary registry = null, object module_globals = null) { PythonContext pContext = context.LanguageContext; PythonDictionary fields = (PythonDictionary)pContext.GetModuleState(_keyFields); object warnings = pContext.GetWarningsModule(); PythonExceptions.BaseException msg; string text; // message text if (string.IsNullOrEmpty(module)) { module = (filename == null || filename == "") ? "<unknown>" : filename; if (module.EndsWith(".py")) { module = module.Substring(0, module.Length - 3); } } if (registry == null) { registry = new PythonDictionary(); } if (PythonOps.IsInstance(message, PythonExceptions.Warning)) { msg = (PythonExceptions.BaseException)message; text = msg.ToString(); category = DynamicHelpers.GetPythonType(msg); } else { text = message.ToString(); msg = PythonExceptions.CreatePythonThrowable(category, message.ToString()); } PythonTuple key = PythonTuple.MakeTuple(text, category, lineno); if (registry.ContainsKey(key)) { return; } string action = Converter.ConvertToString(fields[_keyDefaultAction]); PythonTuple last_filter = null; bool loop_break = false; PythonList filters = (PythonList)fields[_keyFilters]; if (warnings != null) { filters = PythonOps.GetBoundAttr(context, warnings, "filters") as PythonList; if (filters == null) { throw PythonOps.ValueError("_warnings.filters must be a list"); } } foreach (PythonTuple filter in filters) { last_filter = filter; action = (string)filter._data[0]; PythonRegex.RE_Pattern fMsg = (PythonRegex.RE_Pattern)filter._data[1]; PythonType fCat = (PythonType)filter._data[2]; PythonRegex.RE_Pattern fMod = (PythonRegex.RE_Pattern)filter._data[3]; int fLno; if (filter._data[4] is int) { fLno = (int)filter._data[4]; } else { fLno = (Extensible <int>)filter._data[4]; } if ((fMsg == null || fMsg.match(text) != null) && category.IsSubclassOf(fCat) && (fMod == null || fMod.match(module) != null) && (fLno == 0 || fLno == lineno)) { loop_break = true; break; } } if (!loop_break) { action = Converter.ConvertToString(fields[_keyDefaultAction]); } switch (action) { case "ignore": registry.Add(key, 1); return; case "error": throw msg.GetClrException(); case "once": registry.Add(key, 1); PythonTuple onceKey = PythonTuple.MakeTuple(text, category); PythonDictionary once_reg = (PythonDictionary)fields[_keyOnceRegistry]; if (once_reg.ContainsKey(onceKey)) { return; } once_reg.Add(key, 1); break; case "always": break; case "module": registry.Add(key, 1); PythonTuple altKey = PythonTuple.MakeTuple(text, category, 0); if (registry.ContainsKey(altKey)) { return; } registry.Add(altKey, 1); break; case "default": registry.Add(key, 1); break; default: throw PythonOps.RuntimeError("Unrecognized action ({0}) in warnings.filters:\n {1}", action, last_filter); } if (warnings != null) { object show_fxn = PythonOps.GetBoundAttr(context, warnings, "showwarning"); if (show_fxn != null) { PythonCalls.Call( context, show_fxn, msg, category, filename, lineno, null, null); } else { showwarning(context, msg, category, filename, lineno, null, null); } } else { showwarning(context, msg, category, filename, lineno, null, null); } }
private KeyValuePair <IEnumerator, IDisposable> GetTupleEnumerator(CallSite site, PythonTuple value) { return(new KeyValuePair <IEnumerator, IDisposable>(new TupleEnumerator(value), null)); }
public static socket create_connection(CodeContext/*!*/ context, PythonTuple address) { return create_connection(context, address, _GLOBAL_DEFAULT_TIMEOUT); }
private bool TupleContains(CallSite site, object other, PythonTuple value) { return(value.Contains(other)); }
public static void utime(string path, PythonTuple times) { try { FileInfo fi = new FileInfo(path); if (times == null) { fi.LastAccessTime = DateTime.Now; fi.LastWriteTime = DateTime.Now; } else if (times.__len__() == 2) { DateTime atime = new DateTime(PythonTime.TimestampToTicks(Converter.ConvertToDouble(times[0])), DateTimeKind.Utc); DateTime mtime = new DateTime(PythonTime.TimestampToTicks(Converter.ConvertToDouble(times[1])), DateTimeKind.Utc); fi.LastAccessTime = atime; fi.LastWriteTime = mtime; } else { throw PythonOps.TypeError("times value must be a 2-value tuple (atime, mtime)"); } } catch (Exception e) { throw ToPythonException(e); } }
public static PythonTuple CreateProcess( CodeContext context, string applicationName, string commandLineArgs, object pSec /*subprocess.py passes None*/, object tSec /*subprocess.py passes None*/, int?bInheritHandles, uint?dwCreationFlags, PythonDictionary lpEnvironment, string lpCurrentDirectory, object lpStartupInfo /* subprocess.py passes STARTUPINFO*/) { object dwFlags = PythonOps.GetBoundAttr(context, lpStartupInfo, "dwFlags"); //public Int32 dwFlags; object hStdInput = PythonOps.GetBoundAttr(context, lpStartupInfo, "hStdInput"); //public IntPtr hStdInput; object hStdOutput = PythonOps.GetBoundAttr(context, lpStartupInfo, "hStdOutput"); //public IntPtr hStdOutput; object hStdError = PythonOps.GetBoundAttr(context, lpStartupInfo, "hStdError"); //public IntPtr hStdError; object wShowWindow = PythonOps.GetBoundAttr(context, lpStartupInfo, "wShowWindow"); //Int16 wShowWindow; Int32 dwFlagsInt32 = dwFlags != null?Converter.ConvertToInt32(dwFlags) : 0; IntPtr hStdInputIntPtr = hStdInput != null ? new IntPtr(Converter.ConvertToInt32(hStdInput)) : IntPtr.Zero; IntPtr hStdOutputIntPtr = hStdOutput != null ? new IntPtr(Converter.ConvertToInt32(hStdOutput)) : IntPtr.Zero; IntPtr hStdErrorIntPtr = hStdError != null ? new IntPtr(Converter.ConvertToInt32(hStdError)) : IntPtr.Zero; Int16 wShowWindowInt16 = wShowWindow != null?Converter.ConvertToInt16(wShowWindow) : (short)0; STARTUPINFO startupInfo = new STARTUPINFO(); startupInfo.dwFlags = dwFlagsInt32; startupInfo.hStdInput = hStdInputIntPtr; startupInfo.hStdOutput = hStdOutputIntPtr; startupInfo.hStdError = hStdErrorIntPtr; startupInfo.wShowWindow = wShowWindowInt16; // No special security SECURITY_ATTRIBUTES pSecSA = new SECURITY_ATTRIBUTES(); pSecSA.nLength = Marshal.SizeOf(pSecSA); SECURITY_ATTRIBUTES tSecSA = new SECURITY_ATTRIBUTES(); tSecSA.nLength = Marshal.SizeOf(tSecSA); if (pSec != null) { /* If pSec paseed in from Python is not NULL * there needs to be some conversion done here...*/ } if (tSec != null) { /* If tSec paseed in from Python is not NULL * there needs to be some conversion done here...*/ } // If needed convert lpEnvironment Dictonary to lpEnvironmentIntPtr string lpEnvironmentStr = EnvironmentToNative(lpEnvironment); PROCESS_INFORMATION lpProcessInformation = new PROCESS_INFORMATION(); bool result = CreateProcessPI( String.IsNullOrEmpty(applicationName) ? null : applicationName /*applicationNameHelper*//*processStartInfo.FileName*/, String.IsNullOrEmpty(commandLineArgs) ? null : commandLineArgs /*commandLineArgsHelper*//*processStartInfo.Arguments*/, ref pSecSA, ref tSecSA, bInheritHandles.HasValue && bInheritHandles.Value > 0 ? true : false, dwCreationFlags.HasValue ? dwCreationFlags.Value : 0, lpEnvironmentStr, lpCurrentDirectory, ref startupInfo, out lpProcessInformation); if (!result) { int error = Marshal.GetLastWin32Error(); throw PythonExceptions.CreateThrowable(PythonExceptions.WindowsError, error, CTypes.FormatError(error)); } IntPtr hp = lpProcessInformation.hProcess; IntPtr ht = lpProcessInformation.hThread; int pid = lpProcessInformation.dwProcessId; int tid = lpProcessInformation.dwThreadId; return(PythonTuple.MakeTuple( new PythonSubprocessHandle(hp, true), new PythonSubprocessHandle(ht), pid, tid)); }
public static object call_function(CodeContext context, BigInteger address, PythonTuple args) { return call_function(context, new IntPtr(address.ToInt64()), args); }
public void Click(PythonTuple point) { this.Click((int)point[0], (int)point[1]); }
/// <summary> /// Verifies that the provided bit field settings are valid for this type. /// </summary> private static int CheckBits(INativeType cdata, PythonTuple pt) { int bitCount = Converter.ConvertToInt32(pt[2]); SimpleType simpType = cdata as SimpleType; if (simpType == null) { throw PythonOps.TypeError("bit fields not allowed for type {0}", ((PythonType)cdata).Name); } switch (simpType._type) { case SimpleTypeKind.Object: case SimpleTypeKind.Pointer: case SimpleTypeKind.Single: case SimpleTypeKind.Double: case SimpleTypeKind.Char: case SimpleTypeKind.CharPointer: case SimpleTypeKind.WChar: case SimpleTypeKind.WCharPointer: throw PythonOps.TypeError("bit fields not allowed for type {0}", ((PythonType)cdata).Name); } if (bitCount <= 0 || bitCount > cdata.Size * 8) { throw PythonOps.ValueError("number of bits invalid for bit field"); } return bitCount; }
public static object call_tracing(CodeContext /*!*/ context, object func, PythonTuple args) { return(context.LanguageContext.CallTracing(func, args)); }