diff --git a/.editorconfig b/.editorconfig index 4a7fd19de..bf4d05b4c 100644 --- a/.editorconfig +++ b/.editorconfig @@ -40,6 +40,9 @@ dotnet_naming_style.pascal_case_style.capitalization = pascal_case dotnet_style_require_accessibility_modifiers = for_non_interface_members:error csharp_preferred_modifier_order = public, private, protected, internal, static, extern, new, virtual, abstract, sealed, override, readonly, unsafe, volatile, async:error +# CA2241: Provide correct arguments to formatting methods +dotnet_code_quality.CA2241.try_determine_additional_string_formatting_methods_automatically = true + # IPY01: Parameter which is marked not nullable does not have the NotNullAttribute dotnet_diagnostic.IPY01.severity = warning diff --git a/eng/scripts/generate_exceptions.py b/eng/scripts/generate_exceptions.py index 563f35dfe..b57a5d82f 100644 --- a/eng/scripts/generate_exceptions.py +++ b/eng/scripts/generate_exceptions.py @@ -265,9 +265,9 @@ def get_clr_name(e): return e.replace('Error', '') + 'Exception' FACTORY = """ -public static Exception %(name)s(string format, params object?[] args) { - return new %(clrname)s(string.Format(format, args)); -}""" +internal static Exception %(name)s(string message) => new %(clrname)s(message); +public static Exception %(name)s(string format, params object?[] args) => new %(clrname)s(string.Format(format, args)); +""".rstrip() def factory_gen(cw): for e in pythonExcs: diff --git a/src/core/IronPython.Modules/_ctypes/_ctypes.cs b/src/core/IronPython.Modules/_ctypes/_ctypes.cs index e0580c137..83ccefdb9 100644 --- a/src/core/IronPython.Modules/_ctypes/_ctypes.cs +++ b/src/core/IronPython.Modules/_ctypes/_ctypes.cs @@ -317,7 +317,7 @@ public static PythonTuple buffer_info(CData data) { public static void _check_HRESULT(int hresult) { if (hresult < 0) { - throw PythonOps.WindowsError("ctypes function returned failed HRESULT: {0:x}", (uint)hresult); + throw PythonOps.OSError("ctypes function returned failed HRESULT: {0:x}", (uint)hresult); } } @@ -584,12 +584,12 @@ private static void GetFieldInfo(INativeType type, object o, out string fieldNam fieldName = pt[0] as string; if (fieldName == null) { - throw PythonOps.TypeError("first item in _fields_ tuple must be a string, got", PythonOps.GetPythonTypeName(pt[0])); + throw PythonOps.TypeError("first item in _fields_ tuple must be a string, got {0}", PythonOps.GetPythonTypeName(pt[0])); } cdata = pt[1] as INativeType; if (cdata == null) { - throw PythonOps.TypeError("second item in _fields_ tuple must be a C type, got {0}", PythonOps.GetPythonTypeName(pt[0])); + throw PythonOps.TypeError("second item in _fields_ tuple must be a C type, got {0}", PythonOps.GetPythonTypeName(pt[1])); } else if (cdata == type) { throw StructureCannotContainSelf(); } diff --git a/src/core/IronPython.Modules/_datetime.cs b/src/core/IronPython.Modules/_datetime.cs index 5c6bf2ea4..5d9867e18 100644 --- a/src/core/IronPython.Modules/_datetime.cs +++ b/src/core/IronPython.Modules/_datetime.cs @@ -1571,7 +1571,7 @@ public override object fromutc([NotNone] datetime dt) { private bool IsUtc => ReferenceEquals(this, utc); public override string tzname(object? dt) { - if (dt is not null && dt is not datetime) throw PythonOps.TypeError($"tzname(dt) argument must be a datetime instance or None, not {0}", PythonOps.GetPythonTypeName(dt)); + if (dt is not null && dt is not datetime) throw PythonOps.TypeError("tzname(dt) argument must be a datetime instance or None, not {0}", PythonOps.GetPythonTypeName(dt)); if (_name is not null) return _name; if (IsUtc) return "UTC"; diff --git a/src/core/IronPython.Modules/msvcrt.cs b/src/core/IronPython.Modules/msvcrt.cs index 0550b176f..9d989c7b6 100644 --- a/src/core/IronPython.Modules/msvcrt.cs +++ b/src/core/IronPython.Modules/msvcrt.cs @@ -49,7 +49,7 @@ public static void SetErrorMode(int mode) { to the operating system. On failure, this raises IOError.")] public static void heapmin() { if (_heapmin() != 0) { - throw PythonOps.IOError(new Win32Exception()); + throw PythonOps.OSError(0, "Error"); } } @@ -178,7 +178,7 @@ public static void putwch(char @char) { it will be the next character read by getch() or getche().")] public static void ungetch(char @char) { if (_ungetch(@char) == EOF) { - throw PythonOps.IOError(new Win32Exception()); + throw PythonOps.OSError(0, "Error"); } } @@ -187,7 +187,7 @@ public static void ungetch(char @char) { Wide char variant of ungetch(), accepting a Unicode value.")] public static void ungetwch(char @char) { if (_ungetwch(@char) == WEOF) { - throw PythonOps.IOError(new Win32Exception()); + throw PythonOps.OSError(0, "Error"); } } diff --git a/src/core/IronPython.Modules/nt.cs b/src/core/IronPython.Modules/nt.cs index 15d537399..773c4634a 100644 --- a/src/core/IronPython.Modules/nt.cs +++ b/src/core/IronPython.Modules/nt.cs @@ -2233,7 +2233,7 @@ private static FileAccess FileAccessFromFlags(int flags) { if (!TryGetExecutableCommand(command, out baseCommand, out args)) { if (!TryGetShellCommand(command, out baseCommand, out args)) { if (throwException) { - throw PythonOps.WindowsError("The system can not find command '{0}'", command); + throw PythonOps.OSError("The system can not find command '{0}'", command); } else { return null; } diff --git a/src/core/IronPython.Modules/zipimport.cs b/src/core/IronPython.Modules/zipimport.cs index 7b120f3c7..a1883dbdd 100644 --- a/src/core/IronPython.Modules/zipimport.cs +++ b/src/core/IronPython.Modules/zipimport.cs @@ -292,7 +292,7 @@ public Bytes get_data(CodeContext/*!*/ context, string path) { path = path.Replace(_archive, string.Empty).TrimStart(Path.DirectorySeparatorChar); if (!__files.ContainsKey(path)) { - throw PythonOps.IOError(path); + throw PythonOps.OSError(path); } var data = GetData(context, _archive, __files[path] as PythonTuple); @@ -394,7 +394,7 @@ private byte[] GetData(CodeContext context, string archive, PythonTuple toc_entr try { fp = new BinaryReader(new FileStream(archive, FileMode.Open, FileAccess.Read)); } catch { - throw PythonOps.IOError("zipimport: can not open file {0}", archive); + throw PythonOps.OSError("zipimport: can not open file {0}", archive); } // Check to make sure the local file header is correct @@ -412,7 +412,7 @@ private byte[] GetData(CodeContext context, string archive, PythonTuple toc_entr try { raw_data = fp.ReadBytes(compress == 0 ? data_size : data_size + 1); } catch { - throw PythonOps.IOError("zipimport: can't read data"); + throw PythonOps.OSError("zipimport: can't read data"); } if (compress != 0) { diff --git a/src/core/IronPython/Modules/_ast.cs b/src/core/IronPython/Modules/_ast.cs index 42d5deabc..32edce63a 100755 --- a/src/core/IronPython/Modules/_ast.cs +++ b/src/core/IronPython/Modules/_ast.cs @@ -66,7 +66,7 @@ internal static PythonAst ConvertToPythonAst(CodeContext codeContext, AST source stmt = _ast.stmt.RevertStmts(interactive.body); printExpression = true; } else - throw PythonOps.TypeError("unsupported type of AST: {0}", (source.GetType())); + throw PythonOps.TypeError("unsupported type of AST: {0}", source.GetType()); return new PythonAst(stmt, false, ModuleOptions.ExecOrEvalCode, printExpression, compilerContext, Array.Empty()); } diff --git a/src/core/IronPython/Modules/_io.cs b/src/core/IronPython/Modules/_io.cs index 6ebf39aa1..4e449788f 100644 --- a/src/core/IronPython/Modules/_io.cs +++ b/src/core/IronPython/Modules/_io.cs @@ -435,11 +435,11 @@ internal Exception UnsupportedOperationWithMessage(CodeContext/*!*/ context, str => PythonExceptions.CreateThrowable((PythonType)context.LanguageContext.GetModuleState(_unsupportedOperationKey), msg); internal Exception AttributeError(string attrName) { - throw PythonOps.AttributeError("'{0}' object has no attribute '{1}'", PythonOps.GetPythonTypeName(this), attrName); + return PythonOps.AttributeError("'{0}' object has no attribute '{1}'", PythonOps.GetPythonTypeName(this), attrName); } internal Exception InvalidPosition(BigInteger pos) { - return PythonOps.IOError("Raw stream returned invalid position {0}", pos); + return PythonOps.OSError("Raw stream returned invalid position {0}", pos); } #endregion @@ -550,7 +550,7 @@ public virtual BigInteger readinto(CodeContext/*!*/ context, object buf) { return data.Count; } - throw PythonOps.TypeError("must be read-write buffer, not " + PythonOps.GetPythonTypeName(buf)); + throw PythonOps.TypeError("must be read-write buffer, not {0}", PythonOps.GetPythonTypeName(buf)); } public override BigInteger write(CodeContext/*!*/ context, object buf) { @@ -648,11 +648,11 @@ public void __init__( if (_rawIO != null) { if (!_rawIO.readable(context)) { - throw PythonOps.IOError("\"raw\" argument must be readable."); + throw PythonOps.OSError("\"raw\" argument must be readable."); } } else { if (PythonOps.Not(PythonOps.Invoke(context, _raw, "readable"))) { - throw PythonOps.IOError("\"raw\" argument must be readable."); + throw PythonOps.OSError("\"raw\" argument must be readable."); } } if (buffer_size <= 0) { @@ -1125,11 +1125,11 @@ public void __init__( this.raw = raw; if (_rawIO != null) { if (!_rawIO.writable(context)) { - throw PythonOps.IOError("\"raw\" argument must be writable."); + throw PythonOps.OSError("\"raw\" argument must be writable."); } } else { if (PythonOps.Not(PythonOps.Invoke(context, _raw, "writable"))) { - throw PythonOps.IOError("\"raw\" argument must be writable."); + throw PythonOps.OSError("\"raw\" argument must be writable."); } } if (buffer_size <= 0) { @@ -1332,7 +1332,7 @@ private void FlushNoLock(CodeContext/*!*/ context) { int written = GetInt(writtenObj, "write() should return integer"); if (written > _writeBuf.Count || written < 0) { - throw PythonOps.IOError("write() returned incorrect number of bytes"); + throw PythonOps.OSError("write() returned incorrect number of bytes"); } _writeBuf.RemoveRange(0, written); count += written; @@ -1450,9 +1450,9 @@ public void __init__( if (buffer_size <= 0) { throw PythonOps.ValueError("invalid buffer size (must be positive)"); } else if (!raw.readable(context)) { - throw PythonOps.IOError("\"raw\" argument must be readable."); + throw PythonOps.OSError("\"raw\" argument must be readable."); } else if (!raw.writable(context)) { - throw PythonOps.IOError("\"raw\" argument must be writable."); + throw PythonOps.OSError("\"raw\" argument must be writable."); } _bufSize = buffer_size; @@ -1744,7 +1744,7 @@ private void FlushNoLock(CodeContext/*!*/ context) { var bytes = Bytes.Make(_writeBuf.ToArray()); int written = (int)_inner.write(context, bytes); if (written > _writeBuf.Count || written < 0) { - throw PythonOps.IOError("write() returned incorrect number of bytes"); + throw PythonOps.OSError("write() returned incorrect number of bytes"); } _writeBuf.RemoveRange(0, written); count += written; @@ -1792,7 +1792,7 @@ public override BigInteger seek(CodeContext/*!*/ context, BigInteger pos, [Optio pos = _inner.seek(context, pos, whence); ResetReadBuf(); if (pos < 0) { - throw PythonOps.IOError("seek() returned invalid position"); + throw PythonOps.OSError("seek() returned invalid position"); } GC.KeepAlive(this); return pos; @@ -1863,10 +1863,10 @@ public void __init__( this.writer = writer; if (!_reader.readable(context)) { - throw PythonOps.IOError("\"reader\" object must be readable."); + throw PythonOps.OSError("\"reader\" object must be readable."); } if (!_writer.writable(context)) { - throw PythonOps.IOError("\"writer\" object must be writable."); + throw PythonOps.OSError("\"writer\" object must be writable."); } } @@ -2027,7 +2027,7 @@ public void __init__( case "\r\n": break; default: - throw PythonOps.ValueError(string.Format("illegal newline value: " + newline)); + throw PythonOps.ValueError("illegal newline value: {0}", newline); } encoding ??= context.LanguageContext.PythonOptions.Utf8Mode ? "UTF-8" : PythonLocale.PreferredEncoding; @@ -2193,10 +2193,10 @@ public override BigInteger write(CodeContext/*!*/ context, object s) { public override BigInteger tell(CodeContext/*!*/ context) { if (!_seekable) { - throw PythonOps.IOError("underlying stream is not seekable"); + throw PythonOps.OSError("underlying stream is not seekable"); } if (!_telling) { - throw PythonOps.IOError("telling position disabled by next() call"); + throw PythonOps.OSError("telling position disabled by next() call"); } flush(context); @@ -2285,7 +2285,7 @@ public override BigInteger tell(CodeContext/*!*/ context) { } if (charsDecoded < skip) { - throw PythonOps.IOError("can't reconstruct logical file position"); + throw PythonOps.OSError("can't reconstruct logical file position"); } break; } @@ -2347,21 +2347,21 @@ public override BigInteger seek(CodeContext/*!*/ context, BigInteger cookie, [Op throw PythonOps.ValueError("tell on closed file"); } if (!_seekable) { - throw PythonOps.IOError("underlying stream is not seekable"); + throw PythonOps.OSError("underlying stream is not seekable"); } IncrementalNewlineDecoder typedDecoder; if (whenceInt == 1) { // seek relative to the current position if (cookie != 0) { - throw PythonOps.IOError("can't do nonzero cur-relative seeks"); + throw PythonOps.OSError("can't do nonzero cur-relative seeks"); } whenceInt = 0; cookie = tell(context); } else if (whenceInt == 2) { // seek relative to the end of the stream if (cookie != 0) { - throw PythonOps.IOError("can't do nonzero end-relative seeks"); + throw PythonOps.OSError("can't do nonzero end-relative seeks"); } flush(context); BigInteger pos = _bufferTyped != null ? @@ -2452,7 +2452,7 @@ public override BigInteger seek(CodeContext/*!*/ context, BigInteger cookie, [Op // skip appropriate number of decoded chars if (_decodedChars.Length < skip) { - throw PythonOps.IOError("can't restore logical file position"); + throw PythonOps.OSError("can't restore logical file position"); } _decodedCharsUsed = skip; } @@ -3218,7 +3218,7 @@ private static bool TryGetInt(object? i, out int value) { return Bytes.Make(s.MakeByteArray()); } - throw PythonOps.TypeError("'" + name + "' should have returned bytes"); + throw PythonOps.TypeError($"'{name}' should have returned bytes"); } #nullable restore diff --git a/src/core/IronPython/Modules/_io/StringIO.cs b/src/core/IronPython/Modules/_io/StringIO.cs index dbddec3f9..1b67ed0fc 100644 --- a/src/core/IronPython/Modules/_io/StringIO.cs +++ b/src/core/IronPython/Modules/_io/StringIO.cs @@ -309,7 +309,7 @@ public void __setstate__(CodeContext context, [NotNone] PythonTuple tuple) { null => null, string s => s, Extensible es => es.Value, - _ => throw PythonOps.TypeError($"newline must be str or None, not {0}", PythonOps.GetPythonTypeName(tuple[1])), + _ => throw PythonOps.TypeError($"newline must be str or None, not {PythonOps.GetPythonTypeName(tuple[1])}"), }; CheckNewline(context, newline); diff --git a/src/core/IronPython/Runtime/ClrModule.cs b/src/core/IronPython/Runtime/ClrModule.cs index 6d3e45757..4d05e1442 100644 --- a/src/core/IronPython/Runtime/ClrModule.cs +++ b/src/core/IronPython/Runtime/ClrModule.cs @@ -540,7 +540,7 @@ private static void AddReferenceToFileAndPath(CodeContext/*!*/ context, string f list.append(path); Assembly asm = pc.LoadAssemblyFromFile(file); - if (asm == null) throw PythonOps.IOError("file does not exist: {0}", file); + if (asm == null) throw PythonOps.OSError("file does not exist: {0}", file); AddReference(context, asm); } @@ -885,7 +885,7 @@ public static void CompileModules(CodeContext/*!*/ context, string/*!*/ assembly List code = new List(); foreach (string filename in filenames) { if (!pc.DomainManager.Platform.FileExists(filename)) { - throw PythonOps.IOError($"Couldn't find file for compilation: {filename}"); + throw PythonOps.OSError($"Couldn't find file for compilation: {filename}"); } ScriptCode sc; @@ -932,7 +932,7 @@ public static void CompileModules(CodeContext/*!*/ context, string/*!*/ assembly if (kwArgs != null && kwArgs.TryGetValue("mainModule", out object mainModule)) { if (mainModule is string strModule) { if (!pc.DomainManager.Platform.FileExists(strModule)) { - throw PythonOps.IOError("Couldn't find main file for compilation: {0}", strModule); + throw PythonOps.OSError("Couldn't find main file for compilation: {0}", strModule); } SourceUnit su = pc.CreateFileUnit(strModule, pc.DefaultEncoding, SourceCodeKind.File); diff --git a/src/core/IronPython/Runtime/Exceptions/TraceBack.cs b/src/core/IronPython/Runtime/Exceptions/TraceBack.cs index 5125e115e..1700743cc 100644 --- a/src/core/IronPython/Runtime/Exceptions/TraceBack.cs +++ b/src/core/IronPython/Runtime/Exceptions/TraceBack.cs @@ -286,10 +286,10 @@ private bool IsTopMostFrame(List pyThread) { private static Exception BadForOrFinallyJump(int newLineNum, Dictionary jumpIntoLoopIds) { foreach (bool isFinally in jumpIntoLoopIds.Values) { if (isFinally) { - return PythonOps.ValueError("can't jump into 'finally block'", newLineNum); + return PythonOps.ValueError("can't jump into 'finally block'"); } } - return PythonOps.ValueError("can't jump into 'for loop'", newLineNum); + return PythonOps.ValueError("can't jump into 'for loop'"); } } diff --git a/src/core/IronPython/Runtime/Importer.cs b/src/core/IronPython/Runtime/Importer.cs index 42d81b6a2..824bdf692 100644 --- a/src/core/IronPython/Runtime/Importer.cs +++ b/src/core/IronPython/Runtime/Importer.cs @@ -149,7 +149,7 @@ public static object ImportModule(CodeContext/*!*/ context, object globals, stri 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); + throw PythonOps.ImportError("Import by filename is not supported."); } string package = null; @@ -745,8 +745,8 @@ internal static SourceUnit TryFindSourceFile(PythonContext/*!*/ context, string/ if (context.DomainManager.Platform.FileExists(fullPath)) { if (candidatePath != null) { - throw PythonOps.ImportError(String.Format("Found multiple modules of the same name '{0}': '{1}' and '{2}'", - name, candidatePath, fullPath)); + throw PythonOps.ImportError("Found multiple modules of the same name '{0}': '{1}' and '{2}'", + name, candidatePath, fullPath); } candidatePath = fullPath; diff --git a/src/core/IronPython/Runtime/MemoryView.cs b/src/core/IronPython/Runtime/MemoryView.cs index a0d78ba49..f10b3f2cb 100644 --- a/src/core/IronPython/Runtime/MemoryView.cs +++ b/src/core/IronPython/Runtime/MemoryView.cs @@ -829,7 +829,7 @@ private int GetItemOffset(PythonTuple tuple) { } if (firstOutOfRangeIndex != -1) { - PythonOps.IndexError("index out of bounds on dimension {0}", firstOutOfRangeIndex + 1); + throw PythonOps.IndexError("index out of bounds on dimension {0}", firstOutOfRangeIndex + 1); } return flatIndex; diff --git a/src/core/IronPython/Runtime/NewStringFormatter.cs b/src/core/IronPython/Runtime/NewStringFormatter.cs index 84ca824ab..fa5278f25 100644 --- a/src/core/IronPython/Runtime/NewStringFormatter.cs +++ b/src/core/IronPython/Runtime/NewStringFormatter.cs @@ -195,14 +195,14 @@ private bool ParseDoubleBracket(int lastTextStart, out string/*!*/ text) { // report the text w/ a single } at the end _index++; if (_index == _str.Length || _str[_index] != '}') { - throw PythonOps.ValueError("Single '}}' encountered in format string"); + throw PythonOps.ValueError("Single '}' encountered in format string"); } text = _str.Substring(lastTextStart, _index - lastTextStart); _index++; return true; } else if (_index == _str.Length - 1) { - throw PythonOps.ValueError("Single '{{' encountered in format string"); + throw PythonOps.ValueError("Single '{' encountered in format string"); } else if (_str[_index + 1] == '{') { // report the text w/ a single { at the end text = _str.Substring(lastTextStart, ++_index - lastTextStart); @@ -233,7 +233,7 @@ private char ParseConversion() { /// private bool CheckEnd() { if (_index == _str.Length) { - throw PythonOps.ValueError("unmatched '{{' in format spec"); + throw PythonOps.ValueError("unmatched '{' in format spec"); } else if (_str[_index] == '}') { _index++; return true; @@ -272,7 +272,7 @@ private bool CheckEnd() { end = _str.IndexOfAny(ends, end + 1); if (end == -1) { - throw PythonOps.ValueError("unmatched '{{' in format spec"); + throw PythonOps.ValueError("unmatched '{' in format spec"); } switch (_str[end]) { diff --git a/src/core/IronPython/Runtime/Operations/BigIntegerOps.cs b/src/core/IronPython/Runtime/Operations/BigIntegerOps.cs index dc7e1e203..bee93c914 100644 --- a/src/core/IronPython/Runtime/Operations/BigIntegerOps.cs +++ b/src/core/IronPython/Runtime/Operations/BigIntegerOps.cs @@ -504,7 +504,7 @@ public static object Power(BigInteger x, BigInteger y, object? z) { [SpecialName] public static object Power(BigInteger x, int y, BigInteger z) { if (y < 0) { - throw PythonOps.TypeError("power", y, "power must be >= 0"); + throw PythonOps.ValueError("power must be >= 0"); } if (z == BigInteger.Zero) { throw PythonOps.ZeroDivisionError(); @@ -523,7 +523,7 @@ public static object Power(BigInteger x, int y, BigInteger z) { [SpecialName] public static object Power(BigInteger x, BigInteger y, BigInteger z) { if (y < BigInteger.Zero) { - throw PythonOps.TypeError("power", y, "power must be >= 0"); + throw PythonOps.ValueError("power must be >= 0"); } if (z == BigInteger.Zero) { throw PythonOps.ZeroDivisionError(); diff --git a/src/core/IronPython/Runtime/Operations/PythonOps.Generated.cs b/src/core/IronPython/Runtime/Operations/PythonOps.Generated.cs index 44b377549..87b537945 100644 --- a/src/core/IronPython/Runtime/Operations/PythonOps.Generated.cs +++ b/src/core/IronPython/Runtime/Operations/PythonOps.Generated.cs @@ -17,149 +17,113 @@ public static partial class PythonOps { // generated by function: factory_gen from: generate_exceptions.py - public static Exception ImportError(string format, params object?[] args) { - return new ImportException(string.Format(format, args)); - } + internal static Exception ImportError(string message) => new ImportException(message); + public static Exception ImportError(string format, params object?[] args) => new ImportException(string.Format(format, args)); - public static Exception RuntimeError(string format, params object?[] args) { - return new RuntimeException(string.Format(format, args)); - } + internal static Exception RuntimeError(string message) => new RuntimeException(message); + public static Exception RuntimeError(string format, params object?[] args) => new RuntimeException(string.Format(format, args)); - public static Exception UnicodeTranslateError(string format, params object?[] args) { - return new UnicodeTranslateException(string.Format(format, args)); - } + internal static Exception UnicodeTranslateError(string message) => new UnicodeTranslateException(message); + public static Exception UnicodeTranslateError(string format, params object?[] args) => new UnicodeTranslateException(string.Format(format, args)); - public static Exception PendingDeprecationWarning(string format, params object?[] args) { - return new PendingDeprecationWarningException(string.Format(format, args)); - } + internal static Exception PendingDeprecationWarning(string message) => new PendingDeprecationWarningException(message); + public static Exception PendingDeprecationWarning(string format, params object?[] args) => new PendingDeprecationWarningException(string.Format(format, args)); - public static Exception LookupError(string format, params object?[] args) { - return new LookupException(string.Format(format, args)); - } + internal static Exception LookupError(string message) => new LookupException(message); + public static Exception LookupError(string format, params object?[] args) => new LookupException(string.Format(format, args)); - public static Exception OSError(string format, params object?[] args) { - return new OSException(string.Format(format, args)); - } + internal static Exception OSError(string message) => new OSException(message); + public static Exception OSError(string format, params object?[] args) => new OSException(string.Format(format, args)); - public static Exception DeprecationWarning(string format, params object?[] args) { - return new DeprecationWarningException(string.Format(format, args)); - } + internal static Exception DeprecationWarning(string message) => new DeprecationWarningException(message); + public static Exception DeprecationWarning(string format, params object?[] args) => new DeprecationWarningException(string.Format(format, args)); - public static Exception UnicodeError(string format, params object?[] args) { - return new UnicodeException(string.Format(format, args)); - } + internal static Exception UnicodeError(string message) => new UnicodeException(message); + public static Exception UnicodeError(string format, params object?[] args) => new UnicodeException(string.Format(format, args)); - public static Exception FloatingPointError(string format, params object?[] args) { - return new FloatingPointException(string.Format(format, args)); - } + internal static Exception FloatingPointError(string message) => new FloatingPointException(message); + public static Exception FloatingPointError(string format, params object?[] args) => new FloatingPointException(string.Format(format, args)); - public static Exception ReferenceError(string format, params object?[] args) { - return new ReferenceException(string.Format(format, args)); - } + internal static Exception ReferenceError(string message) => new ReferenceException(message); + public static Exception ReferenceError(string format, params object?[] args) => new ReferenceException(string.Format(format, args)); - public static Exception FutureWarning(string format, params object?[] args) { - return new FutureWarningException(string.Format(format, args)); - } + internal static Exception FutureWarning(string message) => new FutureWarningException(message); + public static Exception FutureWarning(string format, params object?[] args) => new FutureWarningException(string.Format(format, args)); - public static Exception AssertionError(string format, params object?[] args) { - return new AssertionException(string.Format(format, args)); - } + internal static Exception AssertionError(string message) => new AssertionException(message); + public static Exception AssertionError(string format, params object?[] args) => new AssertionException(string.Format(format, args)); - public static Exception RuntimeWarning(string format, params object?[] args) { - return new RuntimeWarningException(string.Format(format, args)); - } + internal static Exception RuntimeWarning(string message) => new RuntimeWarningException(message); + public static Exception RuntimeWarning(string format, params object?[] args) => new RuntimeWarningException(string.Format(format, args)); - public static Exception ImportWarning(string format, params object?[] args) { - return new ImportWarningException(string.Format(format, args)); - } + internal static Exception ImportWarning(string message) => new ImportWarningException(message); + public static Exception ImportWarning(string format, params object?[] args) => new ImportWarningException(string.Format(format, args)); - public static Exception UserWarning(string format, params object?[] args) { - return new UserWarningException(string.Format(format, args)); - } + internal static Exception UserWarning(string message) => new UserWarningException(message); + public static Exception UserWarning(string format, params object?[] args) => new UserWarningException(string.Format(format, args)); - public static Exception SyntaxWarning(string format, params object?[] args) { - return new SyntaxWarningException(string.Format(format, args)); - } + internal static Exception SyntaxWarning(string message) => new SyntaxWarningException(message); + public static Exception SyntaxWarning(string format, params object?[] args) => new SyntaxWarningException(string.Format(format, args)); - public static Exception UnicodeWarning(string format, params object?[] args) { - return new UnicodeWarningException(string.Format(format, args)); - } + internal static Exception UnicodeWarning(string message) => new UnicodeWarningException(message); + public static Exception UnicodeWarning(string format, params object?[] args) => new UnicodeWarningException(string.Format(format, args)); - public static Exception StopIteration(string format, params object?[] args) { - return new StopIterationException(string.Format(format, args)); - } + internal static Exception StopIteration(string message) => new StopIterationException(message); + public static Exception StopIteration(string format, params object?[] args) => new StopIterationException(string.Format(format, args)); - public static Exception BytesWarning(string format, params object?[] args) { - return new BytesWarningException(string.Format(format, args)); - } + internal static Exception BytesWarning(string message) => new BytesWarningException(message); + public static Exception BytesWarning(string format, params object?[] args) => new BytesWarningException(string.Format(format, args)); - public static Exception BufferError(string format, params object?[] args) { - return new BufferException(string.Format(format, args)); - } + internal static Exception BufferError(string message) => new BufferException(message); + public static Exception BufferError(string format, params object?[] args) => new BufferException(string.Format(format, args)); - public static Exception ResourceWarning(string format, params object?[] args) { - return new ResourceWarningException(string.Format(format, args)); - } + internal static Exception ResourceWarning(string message) => new ResourceWarningException(message); + public static Exception ResourceWarning(string format, params object?[] args) => new ResourceWarningException(string.Format(format, args)); - public static Exception FileExistsError(string format, params object?[] args) { - return new FileExistsException(string.Format(format, args)); - } + internal static Exception FileExistsError(string message) => new FileExistsException(message); + public static Exception FileExistsError(string format, params object?[] args) => new FileExistsException(string.Format(format, args)); - public static Exception BlockingIOError(string format, params object?[] args) { - return new BlockingIOException(string.Format(format, args)); - } + internal static Exception BlockingIOError(string message) => new BlockingIOException(message); + public static Exception BlockingIOError(string format, params object?[] args) => new BlockingIOException(string.Format(format, args)); - public static Exception NotADirectoryError(string format, params object?[] args) { - return new NotADirectoryException(string.Format(format, args)); - } + internal static Exception NotADirectoryError(string message) => new NotADirectoryException(message); + public static Exception NotADirectoryError(string format, params object?[] args) => new NotADirectoryException(string.Format(format, args)); - public static Exception InterruptedError(string format, params object?[] args) { - return new InterruptedException(string.Format(format, args)); - } + internal static Exception InterruptedError(string message) => new InterruptedException(message); + public static Exception InterruptedError(string format, params object?[] args) => new InterruptedException(string.Format(format, args)); - public static Exception ChildProcessError(string format, params object?[] args) { - return new ChildProcessException(string.Format(format, args)); - } + internal static Exception ChildProcessError(string message) => new ChildProcessException(message); + public static Exception ChildProcessError(string format, params object?[] args) => new ChildProcessException(string.Format(format, args)); - public static Exception IsADirectoryError(string format, params object?[] args) { - return new IsADirectoryException(string.Format(format, args)); - } + internal static Exception IsADirectoryError(string message) => new IsADirectoryException(message); + public static Exception IsADirectoryError(string format, params object?[] args) => new IsADirectoryException(string.Format(format, args)); - public static Exception ProcessLookupError(string format, params object?[] args) { - return new ProcessLookupException(string.Format(format, args)); - } + internal static Exception ProcessLookupError(string message) => new ProcessLookupException(message); + public static Exception ProcessLookupError(string format, params object?[] args) => new ProcessLookupException(string.Format(format, args)); - public static Exception ConnectionError(string format, params object?[] args) { - return new ConnectionException(string.Format(format, args)); - } + internal static Exception ConnectionError(string message) => new ConnectionException(message); + public static Exception ConnectionError(string format, params object?[] args) => new ConnectionException(string.Format(format, args)); - public static Exception ConnectionAbortedError(string format, params object?[] args) { - return new ConnectionAbortedException(string.Format(format, args)); - } + internal static Exception ConnectionAbortedError(string message) => new ConnectionAbortedException(message); + public static Exception ConnectionAbortedError(string format, params object?[] args) => new ConnectionAbortedException(string.Format(format, args)); - public static Exception BrokenPipeError(string format, params object?[] args) { - return new BrokenPipeException(string.Format(format, args)); - } + internal static Exception BrokenPipeError(string message) => new BrokenPipeException(message); + public static Exception BrokenPipeError(string format, params object?[] args) => new BrokenPipeException(string.Format(format, args)); - public static Exception ConnectionRefusedError(string format, params object?[] args) { - return new ConnectionRefusedException(string.Format(format, args)); - } + internal static Exception ConnectionRefusedError(string message) => new ConnectionRefusedException(message); + public static Exception ConnectionRefusedError(string format, params object?[] args) => new ConnectionRefusedException(string.Format(format, args)); - public static Exception ConnectionResetError(string format, params object?[] args) { - return new ConnectionResetException(string.Format(format, args)); - } + internal static Exception ConnectionResetError(string message) => new ConnectionResetException(message); + public static Exception ConnectionResetError(string format, params object?[] args) => new ConnectionResetException(string.Format(format, args)); - public static Exception RecursionError(string format, params object?[] args) { - return new RecursionException(string.Format(format, args)); - } + internal static Exception RecursionError(string message) => new RecursionException(message); + public static Exception RecursionError(string format, params object?[] args) => new RecursionException(string.Format(format, args)); - public static Exception StopAsyncIteration(string format, params object?[] args) { - return new StopAsyncIterationException(string.Format(format, args)); - } + internal static Exception StopAsyncIteration(string message) => new StopAsyncIterationException(message); + public static Exception StopAsyncIteration(string format, params object?[] args) => new StopAsyncIterationException(string.Format(format, args)); - public static Exception ModuleNotFoundError(string format, params object?[] args) { - return new ModuleNotFoundException(string.Format(format, args)); - } + internal static Exception ModuleNotFoundError(string message) => new ModuleNotFoundException(message); + public static Exception ModuleNotFoundError(string format, params object?[] args) => new ModuleNotFoundException(string.Format(format, args)); // *** END GENERATED CODE *** diff --git a/src/core/IronPython/Runtime/Operations/PythonOps.cs b/src/core/IronPython/Runtime/Operations/PythonOps.cs index 953a6861c..1c871d283 100644 --- a/src/core/IronPython/Runtime/Operations/PythonOps.cs +++ b/src/core/IronPython/Runtime/Operations/PythonOps.cs @@ -3930,18 +3930,13 @@ public static Exception AttributeErrorForMissingAttribute(object o, string name) return AttributeErrorForReadonlyAttribute(PythonOps.GetPythonTypeName(o), name); } + internal static Exception ValueError(string message) => new ValueErrorException(message); + public static Exception ValueError(string format, params object?[] args) => new ValueErrorException(string.Format(format, args)); - public static Exception ValueError(string format, params object?[] args) { - return new ValueErrorException(string.Format(format, args)); - } - - public static Exception KeyError(object? key) { - return PythonExceptions.CreateThrowable(PythonExceptions.KeyError, key); - } + public static Exception KeyError(object? key) => PythonExceptions.CreateThrowable(PythonExceptions.KeyError, key); - public static Exception KeyError(string format, params object?[] args) { - return new KeyNotFoundException(string.Format(format, args)); - } + internal static Exception KeyError(string message) => new KeyNotFoundException(message); + public static Exception KeyError(string format, params object?[] args) => new KeyNotFoundException(string.Format(format, args)); public static Exception UnicodeDecodeError(string message, byte[] bytesUnknown, int index) { return new DecoderFallbackException(message, bytesUnknown, index); @@ -3973,13 +3968,11 @@ internal static Exception UnicodeEncodeError(string message, int runeUnknown, in } } - public static Exception IOError(Exception inner) { - return OSError(inner.Message, inner); - } + [Obsolete("Use OSError instead")] + public static Exception IOError(Exception inner) => new OSException(inner.Message, inner); - public static Exception IOError(string format, params object?[] args) { - return OSError(format, args); - } + [Obsolete("Use OSError instead")] + public static Exception IOError(string format, params object?[] args) => OSError(format, args); internal static Exception OSError(int errno, string strerror, string? filename = null, int? winerror = null, string? filename2 = null) { if (filename2 != null) { @@ -3993,59 +3986,44 @@ internal static Exception OSError(int errno, string strerror, string? filename = } } - public static Exception EofError(string format, params object?[] args) { - return new EndOfStreamException(string.Format(format, args)); - } + internal static Exception EofError(string message) => new EndOfStreamException(message); + public static Exception EofError(string format, params object?[] args) => new EndOfStreamException(string.Format(format, args)); - public static Exception ZeroDivisionError(string format, params object?[] args) { - return new DivideByZeroException(string.Format(format, args)); - } + internal static Exception ZeroDivisionError(string message) => new DivideByZeroException(message); + public static Exception ZeroDivisionError(string format, params object?[] args) => new DivideByZeroException(string.Format(format, args)); - public static Exception SystemError(string format, params object?[] args) { - return new SystemException(string.Format(format, args)); - } + internal static Exception SystemError(string message) => new SystemException(message); + public static Exception SystemError(string format, params object?[] args) => new SystemException(string.Format(format, args)); - public static Exception TypeError(string format, params object?[] args) { - return new TypeErrorException(string.Format(format, args)); - } + internal static Exception TypeError(string message) => new TypeErrorException(message); + public static Exception TypeError(string format, params object?[] args) => new TypeErrorException(string.Format(format, args)); - public static Exception IndexError(string format, params object?[] args) { - return new IndexOutOfRangeException(string.Format(format, args)); - } + internal static Exception IndexError(string message) => new IndexOutOfRangeException(message); + public static Exception IndexError(string format, params object?[] args) => new IndexOutOfRangeException(string.Format(format, args)); public static Exception MemoryError() => new OutOfMemoryException(); - public static Exception MemoryError(string message) => new OutOfMemoryException(message); + public static Exception MemoryError(string format, params object?[] args) => new OutOfMemoryException(string.Format(format, args)); - public static Exception MemoryError(string format, params object[] args) => new OutOfMemoryException(string.Format(format, args)); + internal static Exception ArithmeticError(string message) => new ArithmeticException(message); + public static Exception ArithmeticError(string format, params object?[] args) => new ArithmeticException(string.Format(format, args)); - public static Exception ArithmeticError(string format, params object[] args) { - return new ArithmeticException(string.Format(format, args)); - } + internal static Exception NotImplementedError(string message) => new NotImplementedException(message); + public static Exception NotImplementedError(string format, params object?[] args) => new NotImplementedException(string.Format(format, args)); - public static Exception NotImplementedError(string format, params object[] args) { - return new NotImplementedException(string.Format(format, args)); - } + internal static Exception AttributeError(string message) => new MissingMemberException(message); + public static Exception AttributeError(string format, params object?[] args) => new MissingMemberException(string.Format(format, args)); - public static Exception AttributeError(string format, params object[] args) { - return new MissingMemberException(string.Format(format, args)); - } + internal static Exception OverflowError(string message) => new OverflowException(message); + public static Exception OverflowError(string format, params object?[] args) => new OverflowException(string.Format(format, args)); - public static Exception OverflowError(string format, params object[] args) { - return new OverflowException(string.Format(format, args)); - } + [Obsolete("Use OSError instead")] + public static Exception WindowsError(string format, params object?[] args) => OSError(format, args); - public static Exception WindowsError(string format, params object[] args) { - return OSError(format, args); - } + internal static Exception TimeoutError(string message) => new TimeoutException(message); + public static Exception TimeoutError(string format, params object?[] args) => new TimeoutException(string.Format(format, args)); - public static Exception TimeoutError(string format, params object[] args) { - return new TimeoutException(string.Format(format, args)); - } - - public static Exception SystemExit() { - return new SystemExitException(); - } + public static Exception SystemExit() => new SystemExitException(); public static void SyntaxWarning(string message, SourceUnit sourceUnit, SourceSpan span, int errorCode) { PythonContext pc = (PythonContext)sourceUnit.LanguageContext; @@ -4054,9 +4032,8 @@ public static void SyntaxWarning(string message, SourceUnit sourceUnit, SourceSp ShowWarning(context, PythonExceptions.SyntaxWarning, message, sourceUnit.Path, span.Start.Line); } - public static SyntaxErrorException SyntaxError(string format, params object[] args) { - return new SyntaxErrorException(string.Format(format, args)); - } + internal static Exception SyntaxError(string message) => new SyntaxErrorException(message); + public static SyntaxErrorException SyntaxError(string format, params object?[] args) => new SyntaxErrorException(string.Format(format, args)); public static SyntaxErrorException SyntaxError(string message, SourceUnit sourceUnit, SourceSpan span, int errorCode) { switch (errorCode & ErrorCodes.ErrorMask) { @@ -4138,8 +4115,7 @@ public static Exception TypeErrorForUnboundMethodCall(string methodName, PythonT // When a generator first starts, before it gets to the first yield point, you can't call generator.Send(x) where x != null. // See Pep342 for details. public static Exception TypeErrorForIllegalSend() { - string message = "can't send non-None value to a just-started generator"; - return TypeError(message); + return TypeError("can't send non-None value to a just-started generator"); } // If a method is called with an incorrect number of arguments @@ -4269,9 +4245,8 @@ public static T TypeErrorForBadEnumConversion(object? value) { return PythonOps.AttributeError("undeletable attribute"); } - public static Exception Warning(string format, params object[] args) { - return new WarningException(string.Format(format, args)); - } + internal static Exception Warning(string message) => new WarningException(message); + public static Exception Warning(string format, params object?[] args) => new WarningException(string.Format(format, args)); #endregion diff --git a/src/core/IronPython/Runtime/Types/PythonType.cs b/src/core/IronPython/Runtime/Types/PythonType.cs index 3a4f4ab2e..85c9334e0 100644 --- a/src/core/IronPython/Runtime/Types/PythonType.cs +++ b/src/core/IronPython/Runtime/Types/PythonType.cs @@ -561,7 +561,7 @@ public object this[string member] { throw PythonOps.TypeError("'type' object is not subscriptable"); } if (member == null) { - throw PythonOps.KeyError(member); + throw PythonOps.KeyError((object)member); } try { return Enum.Parse(UnderlyingSystemType, member); diff --git a/tests/suite/test_enum.py b/tests/suite/test_enum.py index 30bf52cfe..ed6620ea9 100644 --- a/tests/suite/test_enum.py +++ b/tests/suite/test_enum.py @@ -50,7 +50,7 @@ def test_from_str(self): self.assertEqual(EnumType['Weekend'], EnumType.Weekend) self.assertRaises(SystemError, lambda: EnumType[DaysInt]) - self.assertRaises(TypeError, lambda: EnumType[None]) + self.assertRaises(KeyError, lambda: EnumType[None]) self.assertRaises(TypeError, lambda: EnumType[self]) self.assertRaises(KeyError, lambda: EnumType['invalid']) diff --git a/tests/suite/test_regressions.py b/tests/suite/test_regressions.py index 37d6ce28d..29342ff5f 100644 --- a/tests/suite/test_regressions.py +++ b/tests/suite/test_regressions.py @@ -1726,5 +1726,13 @@ def test_ipy3_gh1135(self): # ensure out is the expected value and not empty self.assertEqual(out, b"aaa") + def test_errors_string_format(self): + # error formatting regressions were introduced causing SystemError instead of the expected exceptions + self.assertRaises(TypeError, lambda: ImportError(**{"{0}": 1})) + self.assertRaises(ValueError, int, "{0}") + + if is_cli: + import System + self.assertRaises(KeyError, lambda: System.DayOfWeek["{0}"]) run_test(__name__)