public static bool isCallable(CodeContext /*!*/ context, object o) { return(PythonOps.IsCallable(context, o)); }
public static PythonTuple lookup(CodeContext /*!*/ context, string encoding) => PythonOps.LookupEncoding(context, encoding);
public static void register(CodeContext /*!*/ context, object search_function) => PythonOps.RegisterEncoding(context, search_function);
public static object DeleteWCharArrayValue(_Array arr) { throw PythonOps.TypeError("cannot delete wchar array value"); }
/// <summary> /// Read a possible mapping key for %(key)s. /// </summary> /// <returns>The key name enclosed between the '%(key)s', /// or null if there are no paranthesis such as '%s'.</returns> private string ReadMappingKey() { // Caller has set _curCh to the character past the %, and // _index to 2 characters past the original '%'. Debug.Assert(_curCh == _str[_index - 1]); Debug.Assert(_str[_index - 2] == '%'); if (_curCh != '(') { // No parenthesized key. return(null); } // CPython supports nested parenthesis (See "S3.6.2:String Formatting Operations"). // Keywords inbetween %(...)s can contain parenthesis. // // For example, here are the keys returned for various format strings: // %(key)s - return 'key' // %((key))s - return '(key)' // %()s - return '' // %((((key))))s - return '(((key)))' // %((%)s)s - return '(%)s' // %((%s))s - return (%s) // %(a(b)c)s - return a(b)c // %((a)s)s - return (a)s // %(((a)s))s - return ((a)s) // Use a counter rule. int nested = 1; // already passed the 1st '(' int start = _index; // character index after 1st opening '(' int end = start; while (end < _str.Length) { if (_str[end] == '(') { nested++; } else if (_str[end] == ')') { nested--; } if (nested == 0) { // Found final matching closing parent string key = _str.Substring(_index, end - start); // Update fields _index = end + 1; if (_index == _str.Length) { // This error could happen with a format string like '%((key))' throw PythonOps.ValueError("incomplete format"); } _curCh = _str[_index++]; return(key); } end++; } // Error: missing closing ')'. // This could happen with '%((key)s' throw PythonOps.ValueError("incomplete format key"); }
public string __repr__(CodeContext context) { return(String.Format("<memory at {0}>", PythonOps.Id(this))); }
private static Exception StructureCannotContainSelf() { return(PythonOps.AttributeError("Structure or union cannot contain itself")); }
int IValueEquality.GetValueHashCode() { throw PythonOps.TypeError("unhashable type: cell"); }
public static void exit() { PythonOps.SystemExit(); }
IList <string> IMembersList.GetMemberNames() { return(PythonOps.GetStringMemberList(this)); }
public string /*!*/ __repr__(CodeContext /*!*/ context) { return(string.Format("<function {0} at {1}>", func_name, PythonOps.HexId(this))); }
public void Deletefunc_globals() { throw PythonOps.TypeError("readonly attribute"); }
public static bool _compare_digest(object a, object b) { if (a is string && b is string) { string aStr = a as string; string bStr = b as string; return(CompareBytes(aStr.MakeByteArray(), bStr.MakeByteArray())); } else if (a is IBufferProtocol && b is IBufferProtocol) { IBufferProtocol aBuf = a as IBufferProtocol; IBufferProtocol bBuf = b as IBufferProtocol; if (aBuf.NumberDimensions > 1 || bBuf.NumberDimensions > 1) { throw PythonOps.BufferError("Buffer must be single dimension"); } return(CompareBytes(aBuf.ToBytes(0, null), bBuf.ToBytes(0, null))); } throw PythonOps.TypeError("unsupported operand types(s) or combination of types: '{0}' and '{1}", PythonOps.GetPythonTypeName(a), PythonOps.GetPythonTypeName(b)); }
public static object isMappingType(CodeContext context, object o) { return(PythonOps.IsMappingType(context, o)); }
/// <summary> /// Interrogates the importing module for __name__ and __path__, which determine /// whether the imported module (whose name is 'name') is being imported as nested /// module (__path__ is present) or as sibling. /// /// For sibling import, the full name of the imported module is parent.sibling /// For nested import, the full name of the imported module is parent.module.nested /// where parent.module is the mod.__name__ /// </summary> /// <param name="context"></param> /// <param name="globals">the globals dictionary</param> /// <param name="name">Name of the module to be imported</param> /// <param name="full">Output - full name of the module being imported</param> /// <param name="path">Path to use to search for "full"</param> /// <param name="level">the import level for relaive imports</param> /// <param name="parentMod">the parent module</param> /// <param name="package">the global __package__ value</param> /// <returns></returns> private static bool TryGetNameAndPath(CodeContext /*!*/ context, object globals, string name, int level, string package, out string full, out PythonList path, out PythonModule parentMod) { Debug.Assert(level > 0); // shouldn't be here for absolute imports // Unless we can find enough information to perform relative import, // we are going to import the module whose name we got full = name; path = null; parentMod = null; // We need to get __name__ to find the name of the imported module. // If absent, fall back to absolute import object attribute; if (!(globals is PythonDictionary pyGlobals) || !pyGlobals._storage.TryGetName(out attribute)) { return(false); } // And the __name__ needs to be string if (!(attribute is string modName)) { return(false); } string pn; if (package == null) { // If the module has __path__ (and __path__ is list), nested module is being imported // otherwise, importing sibling to the importing module if (pyGlobals._storage.TryGetPath(out attribute) && (path = attribute as PythonList) != null) { // found __path__, importing nested module. The actual name of the nested module // is the name of the mod plus the name of the imported module if (String.IsNullOrEmpty(name)) { // relative import of ancestor full = (StringOps.rsplit(modName, ".", level - 1)[0] as string); } else { // relative import of some ancestors child string parentName = (StringOps.rsplit(modName, ".", level - 1)[0] as string); full = parentName + "." + name; object parentModule; if (context.LanguageContext.SystemStateModules.TryGetValue(parentName, out parentModule)) { parentMod = parentModule as PythonModule; } } return(true); } // importing sibling. The name of the imported module replaces // the last element in the importing module name int lastDot = modName.LastIndexOf('.'); if (lastDot == -1) { // name doesn't include dot, only absolute import possible if (level > 0) { throw PythonOps.SystemError("Parent module '{0}' not loaded, cannot perform relative import", string.Empty); } return(false); } // need to remove more than one name int tmpLevel = level; while (tmpLevel > 1 && lastDot != -1) { lastDot = modName.LastIndexOf('.', lastDot - 1); tmpLevel--; } if (lastDot == -1) { pn = modName; } else { pn = modName.Substring(0, lastDot); } } else { // __package__ doesn't include module name, so level is - 1. pn = GetParentPackageName(level - 1, package.Split('.')); } path = GetParentPathAndModule(context, pn, out parentMod); if (path != null) { if (String.IsNullOrEmpty(name)) { full = pn; } else { full = pn + "." + name; } return(true); } if (level > 0) { throw PythonOps.SystemError("Parent module '{0}' not loaded, cannot perform relative import", pn); } // not enough information - absolute import return(false); }
// returns object array containing 2 elements: DateTime and DayOfWeek internal static object[] _strptime(CodeContext /*!*/ context, string @string, string format) { bool postProc; FoundDateComponents foundDateComp; List <FormatInfo> formatInfo = PythonFormatToCLIFormat(format, true, out postProc, out foundDateComp); DateTime res; if (postProc) { int doyIndex = FindFormat(formatInfo, "\\%j"); int dowMIndex = FindFormat(formatInfo, "\\%W"); int dowSIndex = FindFormat(formatInfo, "\\%U"); if (doyIndex != -1 && dowMIndex == -1 && dowSIndex == -1) { res = new DateTime(1900, 1, 1); res = res.AddDays(Int32.Parse(@string)); } else if (dowMIndex != -1 && doyIndex == -1 && dowSIndex == -1) { res = new DateTime(1900, 1, 1); res = res.AddDays(Int32.Parse(@string) * 7); } else if (dowSIndex != -1 && doyIndex == -1 && dowMIndex == -1) { res = new DateTime(1900, 1, 1); res = res.AddDays(Int32.Parse(@string) * 7); } else { throw PythonOps.ValueError("cannot parse %j, %W, or %U w/ other values"); } } else { var fIdx = -1; string[] formatParts = new string[formatInfo.Count]; for (int i = 0; i < formatInfo.Count; i++) { switch (formatInfo[i].Type) { case FormatInfoType.UserText: formatParts[i] = "'" + formatInfo[i].Text + "'"; break; case FormatInfoType.SimpleFormat: formatParts[i] = formatInfo[i].Text; break; case FormatInfoType.CustomFormat: if (formatInfo[i].Text == "f") { fIdx = i; } // include % if we only have one specifier to mark that it's a custom // specifier if (formatInfo.Count == 1 && formatInfo[i].Text.Length == 1) { formatParts[i] = "%" + formatInfo[i].Text; } else { formatParts[i] = formatInfo[i].Text; } break; } } var formats = fIdx == -1 ? new [] { String.Join("", formatParts) } : ExpandMicrosecondFormat(fIdx, formatParts); try { if (!StringUtils.TryParseDateTimeExact(@string, formats, PythonLocale.GetLocaleInfo(context).Time.DateTimeFormat, DateTimeStyles.AllowWhiteSpaces | DateTimeStyles.NoCurrentDateDefault, out res)) { throw PythonOps.ValueError("time data does not match format" + Environment.NewLine + "data=" + @string + ", fmt=" + format + ", to: " + formats[0]); } } catch (FormatException e) { throw PythonOps.ValueError(e.Message + Environment.NewLine + "data=" + @string + ", fmt=" + format + ", to: " + formats[0]); } } DayOfWeek?dayOfWeek = null; if ((foundDateComp & FoundDateComponents.DayOfWeek) != 0) { dayOfWeek = res.DayOfWeek; } if ((foundDateComp & FoundDateComponents.Year) == 0) { res = new DateTime(1900, res.Month, res.Day, res.Hour, res.Minute, res.Second, res.Millisecond, res.Kind); } return(new object[] { res, dayOfWeek }); }
private DynamicMetaObject /*!*/ MakeConvertRuleForCall(DynamicMetaObjectBinder /*!*/ convertToAction, Type toType, DynamicMetaObject /*!*/ self, string name, string returner, Func <DynamicMetaObject> fallback, Func <Expression, Expression> resultConverter) { PythonType pt = ((IPythonObject)self.Value).PythonType; PythonTypeSlot pts; CodeContext context = PythonContext.GetPythonContext(convertToAction).SharedContext; ValidationInfo valInfo = BindingHelpers.GetValidationInfo(this, pt); if (pt.TryResolveSlot(context, name, out pts) && !IsBuiltinConversion(context, pts, name, pt)) { ParameterExpression tmp = Ast.Variable(typeof(object), "func"); Expression callExpr = resultConverter( Ast.Call( PythonOps.GetConversionHelper(returner, GetResultKind(convertToAction)), Ast.Dynamic( PythonContext.GetPythonContext(convertToAction).InvokeNone, typeof(object), PythonContext.GetCodeContext(convertToAction), tmp ) ) ); if (typeof(Extensible <>).MakeGenericType(toType).IsAssignableFrom(self.GetLimitType())) { // if we're doing a conversion to the underlying type and we're an // Extensible<T> of that type: // if an extensible type returns it's self in a conversion, then we need // to actually return the underlying value. If an extensible just keeps // returning more instances of it's self a stack overflow occurs - both // behaviors match CPython. callExpr = AstUtils.Convert(AddExtensibleSelfCheck(convertToAction, toType, self, callExpr), typeof(object)); } return(BindingHelpers.AddDynamicTestAndDefer( convertToAction, new DynamicMetaObject( Ast.Condition( MakeTryGetTypeMember( PythonContext.GetPythonContext(convertToAction), pts, self.Expression, tmp ), callExpr, AstUtils.Convert( ConversionFallback(convertToAction), typeof(object) ) ), self.Restrict(self.GetRuntimeType()).Restrictions ), new DynamicMetaObject[] { this }, valInfo, tmp )); } return(fallback()); }
private static List <FormatInfo> PythonFormatToCLIFormat(string format, bool forParse, out bool postProcess, out FoundDateComponents found) { postProcess = false; found = FoundDateComponents.None; List <FormatInfo> newFormat = new List <FormatInfo>(); for (int i = 0; i < format.Length; i++) { if (format[i] == '%') { if (i + 1 == format.Length) { throw PythonOps.ValueError("badly formatted string"); } switch (format[++i]) { case 'a': found |= FoundDateComponents.DayOfWeek; newFormat.Add(new FormatInfo("ddd")); break; case 'A': found |= FoundDateComponents.DayOfWeek; newFormat.Add(new FormatInfo("dddd")); break; case 'b': newFormat.Add(new FormatInfo("MMM")); break; case 'B': newFormat.Add(new FormatInfo("MMMM")); break; case 'c': found |= FoundDateComponents.Date; AddDate(newFormat); newFormat.Add(new FormatInfo(FormatInfoType.UserText, " ")); AddTime(newFormat); break; case 'd': // if we're parsing we want to use the less-strict // d format and which doesn't require both digits. if (forParse) { newFormat.Add(new FormatInfo(FormatInfoType.CustomFormat, "d")); } else { newFormat.Add(new FormatInfo("dd")); } break; case 'H': newFormat.Add(new FormatInfo(forParse ? "H" : "HH")); break; case 'I': newFormat.Add(new FormatInfo(forParse ? "h" : "hh")); break; case 'm': newFormat.Add(new FormatInfo(forParse ? "M" : "MM")); break; case 'M': newFormat.Add(new FormatInfo(forParse ? "m" : "mm")); break; case 'p': newFormat.Add(new FormatInfo(FormatInfoType.CustomFormat, "t")); newFormat.Add(new FormatInfo(FormatInfoType.UserText, "M")); break; case 'S': newFormat.Add(new FormatInfo("ss")); break; case 'x': found |= FoundDateComponents.Date; AddDate(newFormat); break; case 'X': AddTime(newFormat); break; case 'y': found |= FoundDateComponents.Year; newFormat.Add(new FormatInfo("yy")); break; case 'Y': found |= FoundDateComponents.Year; newFormat.Add(new FormatInfo("yyyy")); break; case '%': newFormat.Add(new FormatInfo("\\%")); break; // format conversions not defined by the CLR. We leave // them as \\% and then replace them by hand later case 'j': // day of year newFormat.Add(new FormatInfo("\\%j")); postProcess = true; break; case 'f': if (forParse) { newFormat.Add(new FormatInfo(FormatInfoType.CustomFormat, "f")); } else { postProcess = true; newFormat.Add(new FormatInfo(FormatInfoType.UserText, "%f")); } break; case 'W': newFormat.Add(new FormatInfo("\\%W")); postProcess = true; break; case 'U': newFormat.Add(new FormatInfo("\\%U")); postProcess = true; break; // week number case 'w': newFormat.Add(new FormatInfo("\\%w")); postProcess = true; break; // weekday number case 'z': case 'Z': // !!!TODO: // 'z' for offset // 'Z' for time zone name; could be from PythonTimeZoneInformation newFormat.Add(new FormatInfo(FormatInfoType.UserText, "")); break; default: newFormat.Add(new FormatInfo(FormatInfoType.UserText, "")); break; } } else { if (newFormat.Count == 0 || newFormat[newFormat.Count - 1].Type != FormatInfoType.UserText) { newFormat.Add(new FormatInfo(FormatInfoType.UserText, format[i].ToString())); } else { newFormat[newFormat.Count - 1].Text = newFormat[newFormat.Count - 1].Text + format[i]; } } } return(newFormat); }
private static CFuncPtrType GetFunctionType(CodeContext context, int flags) { // Ideally we should cache these... SimpleType resType = new SimpleType( context, "int", PythonTuple.MakeTuple(DynamicHelpers.GetPythonTypeFromType(typeof(SimpleCData))), PythonOps.MakeHomogeneousDictFromItems(new object[] { "i", "_type_" })); CFuncPtrType funcType = new CFuncPtrType( context, "func", PythonTuple.MakeTuple(DynamicHelpers.GetPythonTypeFromType(typeof(_CFuncPtr))), PythonOps.MakeHomogeneousDictFromItems(new object[] { FUNCFLAG_STDCALL, "_flags_", resType, "_restype_" })); return(funcType); }
public static IntPtr GetPointer(object value) { if (value is int) { int iVal = (int)value; if (iVal >= 0) { return(new IntPtr(iVal)); } } if (value is BigInteger) { return(new IntPtr((long)(BigInteger)value)); } if (value is Int64) { return(new IntPtr((Int64)value)); } if (value == null) { return(IntPtr.Zero); } object asParam; if (PythonOps.TryGetBoundAttr(value, "_as_parameter_", out asParam)) { return(GetPointer(asParam)); } CTypes.SimpleCData sd = value as CTypes.SimpleCData; if (sd != null) { CTypes.SimpleType simpType = (CTypes.SimpleType)sd.NativeType; if (simpType._type == CTypes.SimpleTypeKind.WCharPointer || simpType._type == CTypes.SimpleTypeKind.CharPointer) { return(sd.UnsafeAddress); } else if (simpType._type == CTypes.SimpleTypeKind.Pointer) { return(sd._memHolder.ReadIntPtr(0)); } } CTypes._Array arr = value as CTypes._Array; if (arr != null) { return(arr.UnsafeAddress); } CTypes._CFuncPtr func = value as CTypes._CFuncPtr; if (func != null) { return(func.UnsafeAddress); } CTypes.Pointer pointer = value as CTypes.Pointer; if (pointer != null) { return(pointer.UnsafeAddress); } throw PythonOps.TypeErrorForTypeMismatch("pointer", value); }
public static void DeleteCharArrayValue(_Array arr, object value) { throw PythonOps.TypeError("cannot delete char array value"); }
internal static Exception CannotConvertOverflow(string name, object value) { return(PythonOps.OverflowError("Cannot convert {0}({1}) to {2}", PythonTypeOps.GetName(value), value, name)); }
public static object DeleteWCharArrayRaw(_Array arr) { throw PythonOps.TypeError("cannot delete wchar array raw"); }
private static Exception MakeTypeError(string expectedType, object o) { return(PythonOps.TypeErrorForTypeMismatch(expectedType, o)); }
public static object escape_decode(string text, string errors = "strict") { 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)); }
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, object 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 Dictionary to lpEnvironmentIntPtr string lpEnvironmentStr = EnvironmentToNative(context, 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.OSError, error, FormatError(error), null, 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 lookup_error(CodeContext /*!*/ context, string name) => PythonOps.LookupEncodingError(context, name);
/// <summary> /// Called by the __builtin__.__import__ functions (general importing) and ScriptEngine (for site.py) /// /// level indiciates whether to perform absolute or relative imports. /// 0 indicates only absolute imports should be performed /// Positive numbers indicate the # of parent directories to search relative to the calling module /// </summary> public static object ImportModule(CodeContext /*!*/ context, object globals, string /*!*/ modName, bool bottom, int level) { if (level < 0) { throw PythonOps.ValueError("level must be >= 0"); } if (modName.IndexOf(Path.DirectorySeparatorChar) != -1) { throw PythonOps.ImportError("Import by filename is not supported.", modName); } string package = null; if (globals is PythonDictionary pyGlobals) { if (pyGlobals._storage.TryGetPackage(out object attribute)) { package = attribute as string; if (package == null && attribute != null) { throw PythonOps.ValueError("__package__ set to non-string"); } } else { package = null; if (level > 0) { // explicit relative import, calculate and store __package__ object pathAttr, nameAttr; if (pyGlobals._storage.TryGetName(out nameAttr) && nameAttr is string) { if (pyGlobals._storage.TryGetPath(out pathAttr)) { pyGlobals["__package__"] = nameAttr; } else { pyGlobals["__package__"] = ((string)nameAttr).rpartition(".")[0]; } } } } } object newmod = null; string firstName; int firstDot = modName.IndexOf('.'); if (firstDot == -1) { firstName = modName; } else { firstName = modName.Substring(0, firstDot); } string finalName = null; if (level > 0) { // try a relative import // if importing a.b.c, import "a" first and then import b.c from a string name; // name of the module we are to import in relation to the current module PythonModule parentModule; PythonList path; // path to search if (TryGetNameAndPath(context, globals, firstName, level, package, out name, out path, out parentModule)) { finalName = name; var existingOrMetaPathModule = false; // import relative if (TryGetExistingModule(context, name, out newmod)) { existingOrMetaPathModule = true; } else if (TryLoadMetaPathModule(context, name, path, out newmod)) { existingOrMetaPathModule = true; if (parentModule != null && !string.IsNullOrEmpty(firstName)) { parentModule.__dict__[firstName] = newmod; } } else { newmod = ImportFromPath(context, firstName, name, path); if (newmod == null) { // add an indirection entry saying this module does not exist // see http://www.python.org/doc/essays/packages.html "Dummy Entries" context.LanguageContext.SystemStateModules[name] = null; } else if (parentModule != null) { parentModule.__dict__[firstName] = newmod; } } if (existingOrMetaPathModule && firstDot == -1) { // if we imported before having the assembly // loaded and then loaded the assembly we want // to make the assembly available now. if (newmod is NamespaceTracker) { context.ShowCls = true; } } } } if (level == 0) { // try an absolute import if (newmod == null) { object parentPkg; if (!String.IsNullOrEmpty(package) && !context.LanguageContext.SystemStateModules.TryGetValue(package, out parentPkg)) { PythonModule warnModule = new PythonModule(); warnModule.__dict__["__file__"] = package; warnModule.__dict__["__name__"] = package; ModuleContext modContext = new ModuleContext(warnModule.__dict__, context.LanguageContext); PythonOps.Warn( modContext.GlobalContext, PythonExceptions.RuntimeWarning, "Parent module '{0}' not found while handling absolute import", package); } newmod = ImportTopAbsolute(context, firstName); finalName = firstName; if (newmod == null) { return(null); } } } // now import the a.b.c etc. a needs to be included here // because the process of importing could have modified // sys.modules. string[] parts = modName.Split('.'); object next = newmod; string curName = null; for (int i = 0; i < parts.Length; i++) { curName = i == 0 ? finalName : curName + "." + parts[i]; object tmpNext; if (TryGetExistingModule(context, curName, out tmpNext)) { next = tmpNext; if (i == 0) { // need to update newmod if we pulled it out of sys.modules // just in case we're in bottom mode. newmod = next; } } else if (i != 0) { // child module isn't loaded yet, import it. next = ImportModuleFrom(context, next, parts, i); } else { // top-level module doesn't exist in sys.modules, probably // came from some weird meta path hook. newmod = next; } } return(bottom ? next : newmod); }
public static void register_error(CodeContext /*!*/ context, string name, object handler) => PythonOps.RegisterEncodingError(context, name, handler);
public static object __getslice__(CodeContext /*!*/ context, object a, object b, object c) { return(PythonOps.GetIndex(context, a, MakeSlice(b, c))); }