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> /// 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(); }
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"); } else 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, file); return(module); } 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); } }
StoreTyped(PythonType _type) { uint typeSize = (uint)Marshal.SizeOf(typeof(PyTypeObject)); IntPtr typePtr = this.allocator.Alloc(typeSize); CPyMarshal.Zero(typePtr, typeSize); CPyMarshal.WriteIntField(typePtr, typeof(PyTypeObject), "ob_refcnt", 2); object ob_type = PythonCalls.Call(this.scratchContext, Builtin.type, new object[] { _type }); CPyMarshal.WritePtrField(typePtr, typeof(PyTypeObject), "ob_type", this.Store(ob_type)); string tp_name = (string)_type.__getattribute__(this.scratchContext, "__name__"); CPyMarshal.WritePtrField(typePtr, typeof(PyTypeObject), "tp_name", this.Store(tp_name)); PythonTuple tp_bases = (PythonTuple)_type.__getattribute__(this.scratchContext, "__bases__"); object tp_base = tp_bases[0]; CPyMarshal.WritePtrField(typePtr, typeof(PyTypeObject), "tp_base", this.Store(tp_base)); if (tp_bases.__len__() > 1) { CPyMarshal.WritePtrField(typePtr, typeof(PyTypeObject), "tp_bases", this.Store(tp_bases)); } this.scratchModule.Get__dict__()["_ironclad_bases"] = tp_bases; this.scratchModule.Get__dict__()["_ironclad_metaclass"] = ob_type; this.ExecInModule(CodeSnippets.CLASS_STUB_CODE, this.scratchModule); this.classStubs[typePtr] = this.scratchModule.Get__dict__()["_ironclad_class_stub"]; this.actualisableTypes[typePtr] = new ActualiseDelegate(this.ActualiseArbitraryObject); this.map.Associate(typePtr, _type); this.PyType_Ready(typePtr); return(typePtr); }
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); } }
/// <summary> /// Convert a (host, port) tuple [IPv4] (host, port, flowinfo, scopeid) tuple [IPv6] /// to its corresponding IPEndPoint. /// /// Throws gaierror if host is not a valid address. /// Throws ArgumentTypeException if any of the following are true: /// - address does not have exactly two elements /// - address[0] is not a string /// - address[1] is not an int /// </summary> private static IPEndPoint TupleToEndPoint(CodeContext/*!*/ context, PythonTuple address, AddressFamily family, out string host) { if (address.__len__() != 2 && address.__len__() != 4) { throw PythonOps.TypeError("address tuple must have exactly 2 (IPv4) or exactly 4 (IPv6) elements"); } try { host = Converter.ConvertToString(address[0]); } catch (ArgumentTypeException) { throw PythonOps.TypeError("host must be string"); } int port; try { port = PythonContext.GetContext(context).ConvertToInt32(address[1]); } catch (ArgumentTypeException) { throw PythonOps.TypeError("port must be integer"); } IPAddress ip = HostToAddress(context, host, family); if (address.__len__() == 2) { return new IPEndPoint(ip, port); } else { try { Converter.ConvertToInt64(address[2]); } catch (ArgumentTypeException) { throw PythonOps.TypeError("flowinfo must be integer"); } // We don't actually do anything with flowinfo right now, but we validate it // in case we want to do something in the future. long scopeId; try { scopeId = Converter.ConvertToInt64(address[3]); } catch (ArgumentTypeException) { throw PythonOps.TypeError("scopeid must be integer"); } IPEndPoint endPoint = new IPEndPoint(ip, port); endPoint.Address.ScopeId = scopeId; return endPoint; } }
public static object getnameinfo(CodeContext/*!*/ context, PythonTuple socketAddr, int flags) { if (socketAddr.__len__() < 2 || socketAddr.__len__() > 4) { throw PythonOps.TypeError("socket address must be a 2-tuple (IPv4 or IPv6) or 4-tuple (IPv6)"); } if ((flags & (int)NI_NUMERICSERV) == 0) { throw PythonOps.NotImplementedError("getnameinfo() required the NI_NUMERICSERV flag (see docstring)"); } string host = Converter.ConvertToString(socketAddr[0]); if (host == null) throw PythonOps.TypeError("argument 1 must be string"); int port = 0; try { port = (int)socketAddr[1]; } catch (InvalidCastException) { throw PythonOps.TypeError("an integer is required"); } string resultHost = null; string resultPort = null; // Host IPHostEntry hostEntry = null; try { // Do double lookup to force reverse DNS lookup to match CPython behavior hostEntry = Dns.GetHostEntry(host); if (hostEntry.AddressList.Length < 1) { throw PythonExceptions.CreateThrowable(error(context), "sockaddr resolved to zero addresses"); } hostEntry = Dns.GetHostEntry(hostEntry.AddressList[0]); } catch (SocketException e) { throw PythonExceptions.CreateThrowable(gaierror(context), e.ErrorCode, e.Message); } catch (IndexOutOfRangeException) { throw PythonExceptions.CreateThrowable(gaierror(context), "sockaddr resolved to zero addresses"); } IList<IPAddress> addrs = hostEntry.AddressList; if (addrs.Count > 1) { // ignore non-IPV4 addresses List<IPAddress> newAddrs = new List<IPAddress>(addrs.Count); foreach (IPAddress addr in hostEntry.AddressList) { if (addr.AddressFamily == AddressFamily.InterNetwork) { newAddrs.Add(addr); } } if (newAddrs.Count > 1) { throw PythonExceptions.CreateThrowable(error(context), "sockaddr resolved to multiple addresses"); } addrs = newAddrs; } if (addrs.Count < 1) { throw PythonExceptions.CreateThrowable(error(context), "sockaddr resolved to zero addresses"); } if ((flags & (int)NI_NUMERICHOST) != 0) { resultHost = addrs[0].ToString(); } else if ((flags & (int)NI_NOFQDN) != 0) { resultHost = RemoveLocalDomain(hostEntry.HostName); } else { resultHost = hostEntry.HostName; } // Port // We don't branch on NI_NUMERICSERV here since we throw above if it's not set resultPort = port.ToString(); return PythonTuple.MakeTuple(resultHost, resultPort); }
/// <summary> /// Initializes the Exception object with an unlimited number of arguments /// </summary> public virtual void __init__(params object[] args\u00F8) { _args = PythonTuple.MakeTuple(args\u00F8 ?? new object[] { null }); if (_args.__len__() == 1) { _message = _args[0]; } }
private void ExpandArgsTuple(List<string> names, PythonTuple toExpand) { for (int i = 0; i < toExpand.__len__(); i++) { if (toExpand[i] is PythonTuple) { ExpandArgsTuple(names, toExpand[i] as PythonTuple); } else { names.Add(toExpand[i] as string); } } }
public static PythonType GetItem(TypeGroup self, PythonTuple tuple) { if (tuple.__len__() == 0) { return DynamicHelpers.GetPythonTypeFromType(self.NonGenericType); } return GetItem(self, tuple._data); }
private static int[] ValidateDateTimeTuple(CodeContext/*!*/ context, PythonTuple t) { if (t.__len__() != MaxIndex) throw PythonOps.TypeError("expected tuple of length {0}", MaxIndex); int[] ints = new int[MaxIndex]; for (int i = 0; i < MaxIndex; i++) { ints[i] = PythonContext.GetContext(context).ConvertToInt32(t[i]); } int year = ints[YearIndex]; if (accept2dyear && (year >= 0 && year <= 99)) { if (year > 68) { year += 1900; } else { year += 2000; } } if (year < DateTime.MinValue.Year || year <= minYear) throw PythonOps.ValueError("year is too low"); if (year > DateTime.MaxValue.Year) throw PythonOps.ValueError("year is too high"); if (ints[WeekdayIndex] < 0 || ints[WeekdayIndex] >= 7) throw PythonOps.ValueError("day of week is outside of 0-6 range"); return ints; }
public static object getnameinfo(CodeContext/*!*/ context, PythonTuple socketAddr, int flags) { if (socketAddr.__len__() < 2 || socketAddr.__len__() > 4) { throw PythonOps.TypeError("socket address must be a 2-tuple (IPv4 or IPv6) or 4-tuple (IPv6)"); } string host = Converter.ConvertToString(socketAddr[0]); if (host == null) throw PythonOps.TypeError("argument 1 must be string"); int port = 0; try { port = (int)socketAddr[1]; } catch (InvalidCastException) { throw PythonOps.TypeError("an integer is required"); } string resultHost = null; string resultPort = null; // Host IList<IPAddress> addrs = null; try { addrs = HostToAddresses(context, host, AddressFamily.InterNetwork); if (addrs.Count < 1) { throw PythonExceptions.CreateThrowable(error(context), "sockaddr resolved to zero addresses"); } } catch (SocketException e) { throw PythonExceptions.CreateThrowable(gaierror(context), e.ErrorCode, e.Message); } catch (IndexOutOfRangeException) { throw PythonExceptions.CreateThrowable(gaierror(context), "sockaddr resolved to zero addresses"); } if (addrs.Count > 1) { // ignore non-IPV4 addresses List<IPAddress> newAddrs = new List<IPAddress>(addrs.Count); foreach (IPAddress addr in addrs) { if (addr.AddressFamily == AddressFamily.InterNetwork) { newAddrs.Add(addr); } } if (newAddrs.Count > 1) { throw PythonExceptions.CreateThrowable(error(context), "sockaddr resolved to multiple addresses"); } addrs = newAddrs; } if (addrs.Count < 1) { throw PythonExceptions.CreateThrowable(error(context), "sockaddr resolved to zero addresses"); } IPHostEntry hostEntry = null; try { hostEntry = Dns.GetHostEntry(addrs[0]); } catch (SocketException e) { throw PythonExceptions.CreateThrowable(gaierror(context), e.ErrorCode, e.Message); } if ((flags & (int)NI_NUMERICHOST) != 0) { resultHost = addrs[0].ToString(); } else if ((flags & (int)NI_NOFQDN) != 0) { resultHost = RemoveLocalDomain(hostEntry.HostName); } else { resultHost = hostEntry.HostName; } // Port if ((flags & (int)NI_NUMERICSERV) == 0) { //call the servbyport to translate port if not just use the port.ToString as the result try{ resultPort = getservbyport(context, port,null); } catch{ resultPort = port.ToString(); } flags = flags | (int)NI_NUMERICSERV; } else resultPort = port.ToString(); return PythonTuple.MakeTuple(resultHost, resultPort); }
StoreTyped(PythonTuple tuple) { int length = tuple.__len__(); IntPtr tuplePtr = this.CreateTuple(length); IntPtr itemPtr = CPyMarshal.Offset( tuplePtr, Marshal.OffsetOf(typeof(PyTupleObject), "ob_item")); for (int i = 0; i < length; i++) { CPyMarshal.WritePtr(itemPtr, this.Store(tuple[i])); itemPtr = CPyMarshal.Offset(itemPtr, CPyMarshal.PtrSize); } this.map.Associate(tuplePtr, tuple); return tuplePtr; }