public static object __getnewargs__(CodeContext context, BigInteger self) { return(PythonTuple.MakeTuple(BigIntegerOps.__new__(context, TypeCache.BigInteger, self))); }
public static object staticmeth([ParamDictionary] IDictionary <object, object> dict, params object[] args) { return(PythonTuple.MakeTuple(null, PythonTuple.MakeTuple(args), dict)); }
/// <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 if (!(PythonOps.CallWithContext(context, getNewArgsCallable, self) is PythonTuple newArgs)) { 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; if (self is IPythonObject ipo) { 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 PythonTuple readbuffer_encode([BytesConversion] string input, string errors = null) { return(PythonTuple.MakeTuple(input, input.Length)); }
public static PythonTuple DivMod(CodeContext context, Complex x, Complex y) { Complex quotient = FloorDivide(context, x, y); return(PythonTuple.MakeTuple(quotient, x - (quotient * y))); }
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)); }
/// <summary> /// Provides nested level debugging support when SetTrace or SetProfile are used. /// /// This saves the current tracing information and then calls the provided object. /// </summary> public static void CallTracing(this ScriptEngine /*!*/ engine, object traceFunc, params object[] args) { SysModule.call_tracing(GetPythonContext(engine).SharedContext, traceFunc, PythonTuple.MakeTuple(args)); }
public PythonTuple ToTuple() { return(PythonTuple.MakeTuple(NID, ShortName, LongName, OIDString)); }
public static object escape_decode(string text, [DefaultParameterValue("strict")] string errors) { StringBuilder res = new StringBuilder(); for (int i = 0; i < text.Length; i++) { if (text[i] == '\\') { if (i == text.Length - 1) { throw PythonOps.ValueError("\\ at end of string"); } switch (text[++i]) { case 'a': res.Append((char)0x07); break; case 'b': res.Append((char)0x08); break; case 't': res.Append('\t'); break; case 'n': res.Append('\n'); break; case 'r': res.Append('\r'); break; case '\\': res.Append('\\'); break; case 'f': res.Append((char)0x0c); break; case 'v': res.Append((char)0x0b); break; case '\n': break; case 'x': int dig1, dig2; if (i >= text.Length - 2 || !CharToInt(text[i], out dig1) || !CharToInt(text[i + 1], out dig2)) { switch (errors) { case "strict": if (i >= text.Length - 2) { throw PythonOps.ValueError("invalid character value"); } else { throw PythonOps.ValueError("invalid hexadecimal digit"); } case "replace": res.Append("?"); i--; while (i < (text.Length - 1)) { res.Append(text[i++]); } continue; default: throw PythonOps.ValueError("decoding error; unknown error handling code: " + errors); } } res.Append(dig1 * 16 + dig2); i += 2; break; default: res.Append("\\" + text[i]); break; } } else { res.Append(text[i]); } } return(PythonTuple.MakeTuple(res.ToString(), text.Length)); }
private static PythonTuple DoDecode(Encoding encoding, object input, string errors, bool fAlwaysThrow) { // input should be character buffer of some form... string res; if (!Converter.TryConvertToString(input, out res)) { Bytes tempBytes = input as Bytes; if (tempBytes == null) { throw PythonOps.TypeErrorForBadInstance("argument 1 must be string, got {0}", input); } else { res = tempBytes.ToString(); } } int preOffset = CheckPreamble(encoding, res); byte[] bytes = new byte[res.Length - preOffset]; for (int i = 0; i < bytes.Length; i++) { bytes[i] = (byte)res[i + preOffset]; } #if FEATURE_ENCODING // DecoderFallback encoding = (Encoding)encoding.Clone(); ExceptionFallBack fallback = null; if (fAlwaysThrow) { StringOps.SetDecoderFallback(encoding, DecoderFallback.ExceptionFallback); } else { fallback = (encoding is UTF8Encoding && DotNet) ? // This is a workaround for a bug, see ExceptionFallbackBufferUtf8DotNet // for more details. new ExceptionFallBackUtf8DotNet(bytes): new ExceptionFallBack(bytes); StringOps.SetDecoderFallback(encoding, fallback); } #endif string decoded = encoding.GetString(bytes, 0, bytes.Length); int badByteCount = 0; #if FEATURE_ENCODING // DecoderFallback if (!fAlwaysThrow) { byte[] badBytes = fallback.buffer.badBytes; if (badBytes != null) { badByteCount = badBytes.Length; } } #endif PythonTuple tuple = PythonTuple.MakeTuple(decoded, bytes.Length - badByteCount); return(tuple); }
private static object CharmapDecodeWorker(string input, string errors, IDictionary <object, object> map, bool isDecode) { if (input.Length == 0) { return(PythonTuple.MakeTuple(String.Empty, 0)); } StringBuilder res = new StringBuilder(); for (int i = 0; i < input.Length; i++) { object val; if (map == null) { res.Append(input[i]); continue; } object charObj = ScriptingRuntimeHelpers.Int32ToObject((int)input[i]); if (!map.TryGetValue(charObj, out val)) { if (errors == "strict" && isDecode) { throw PythonOps.UnicodeDecodeError("failed to find key in mapping"); } else if (!isDecode) { throw PythonOps.UnicodeEncodeError("failed to find key in mapping"); } res.Append("\ufffd"); } else if (val == null) { if (errors == "strict" && isDecode) { throw PythonOps.UnicodeDecodeError("'charmap' codec can't decode characters at index {0} because charmap maps to None", i); } else if (!isDecode) { throw PythonOps.UnicodeEncodeError("charmap", input[i], i, "'charmap' codec can't encode characters at index {0} because charmap maps to None", i); } res.Append("\ufffd"); } else if (val is string) { res.Append((string)val); } else if (val is int) { res.Append((char)(int)val); } else { throw PythonOps.TypeError("charmap must be an int, str, or None"); } } return(PythonTuple.MakeTuple(res.ToString(), res.Length)); }
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))); }
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 classmeth(PythonType cls, [ParamDictionary] IDictionary <object, object> dict, params object[] args) { return(PythonTuple.MakeTuple(cls, PythonTuple.MakeTuple(args), dict)); }
private IEnumerator <object> Yielder(int r) { IEnumerator[] enums = new IEnumerator[r]; if (r > 0) { enums[0] = _data.GetEnumerator(); int curDepth = 0; int[] curIndices = new int[enums.Length]; do { if (enums[curDepth].MoveNext()) { curIndices[curDepth]++; int curIndex = curIndices[curDepth]; bool shouldSkip = false; for (int i = 0; i < curDepth; i++) { if (curIndices[i] >= curIndices[curDepth]) { // skip if we've already seen this index or a higher // index elsewhere shouldSkip = true; break; } } if (!shouldSkip) { if (curDepth == enums.Length - 1) { // create a new array so we don't mutate previous tuples object[] final = new object[r]; for (int j = 0; j < enums.Length; j++) { final[j] = enums[j].Current; } yield return(PythonTuple.MakeTuple(final)); } else { // going to the next depth, get a new enumerator curDepth++; enums[curDepth] = _data.GetEnumerator(); curIndices[curDepth] = 0; } } } else { // current depth exhausted, go to the previous iterator curDepth--; } } while (curDepth != -1); } else { yield return(PythonTuple.EMPTY); } }
public static object RAND_pseudo_bytes(int num) => PythonTuple.MakeTuple(PythonNT.urandom(num), true);
private static PythonTuple BuiltinModuleTuple(string name) { return(PythonTuple.MakeTuple(null, name, PythonTuple.MakeTuple("", "", CBuiltin))); }
private static PythonTuple ReduceProtocol2(CodeContext /*!*/ context, object self) { // builtin types which can't be pickled (due to tp_itemsize != 0) if (self is MemoryView) { throw PythonOps.TypeError("can't pickle memoryview objects"); } PythonType myType = DynamicHelpers.GetPythonType(self); object?state; object?[] funcArgs; var copyreg = context.LanguageContext.GetCopyRegModule(); var func = PythonOps.GetBoundAttr(context, copyreg, "__newobj__"); if (PythonOps.TryGetBoundAttr(context, myType, "__getnewargs__", out object?getNewArgsCallable)) { // TypeError will bubble up if __getnewargs__ isn't callable if (!(PythonOps.CallWithContext(context, getNewArgsCallable, self) is PythonTuple newArgs)) { 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; if (self is IPythonObject ipo) { 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 PythonTuple escape_decode([BytesConversion] IList <byte> data, string errors = "strict") { var res = new StringBuilder(); for (int i = 0; i < data.Count; i++) { if (data[i] == '\\') { if (i == data.Count - 1) { throw PythonOps.ValueError("\\ at end of string"); } switch ((char)data[++i]) { case 'a': res.Append((char)0x07); break; case 'b': res.Append((char)0x08); break; case 't': res.Append('\t'); break; case 'n': res.Append('\n'); break; case 'r': res.Append('\r'); break; case '\\': res.Append('\\'); break; case 'f': res.Append((char)0x0c); break; case 'v': res.Append((char)0x0b); break; case '\n': break; case 'x': if (++i < data.Count && CharToInt((char)data[i], out int dig1) && ++i < data.Count && CharToInt((char)data[i], out int dig2)) { res.Append((char)(dig1 * 16 + dig2)); } else { switch (errors) { case "strict": throw PythonOps.ValueError("invalid \\x escape at position {0}", i); case "replace": res.Append("?"); i--; break; default: throw PythonOps.ValueError("decoding error; unknown error handling code: " + errors); } } break; default: res.Append("\\" + (char)data[i]); break; } } else { res.Append((char)data[i]); } } return(PythonTuple.MakeTuple(Bytes.Make(res.ToString().MakeByteArray()), data.Count)); }
public static object __getnewargs__(CodeContext context, double self) { return(PythonTuple.MakeTuple(DoubleOps.__new__(context, TypeCache.Double, self))); }
public static PythonTuple readbuffer_encode([BytesConversion] IList <byte> input, string errors = null) => PythonTuple.MakeTuple(new Bytes(input), input.Count);
public static object __getnewargs__(CodeContext context, int self) { return(PythonTuple.MakeTuple(Int32Ops.__new__(context, TypeCache.Int32, self))); }
public static PythonTuple unicode_internal_encode([BytesConversion] IList <byte> input, string errors = "strict") => PythonTuple.MakeTuple(new Bytes(input), input.Count);
public static PythonTuple __divmod__(int x, int y) { return(PythonTuple.MakeTuple(Divide(x, y), Mod(x, y))); }
public static void warn_explicit(CodeContext context, object message, PythonType category, string filename, int lineno, [DefaultParameterValue(null)] string module, [DefaultParameterValue(null)] PythonDictionary registry, [DefaultParameterValue(null)] object module_globals) { PythonContext pContext = PythonContext.GetContext(context); PythonDictionary fields = (PythonDictionary)pContext.GetModuleState(_keyFields); 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; foreach (PythonTuple filter in (List)fields[_keyFilters]) { 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); } object warnings = pContext.GetWarningsModule(); if (warnings != null) { PythonCalls.Call( context, PythonOps.GetBoundAttr(context, warnings, "showwarning"), msg, category, filename, lineno, null, null); } else { showwarning(context, msg, category, filename, lineno, null, null); } }