Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions .editorconfig
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down
6 changes: 3 additions & 3 deletions eng/scripts/generate_exceptions.py
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand Down
6 changes: 3 additions & 3 deletions src/core/IronPython.Modules/_ctypes/_ctypes.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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);
}
}

Expand Down Expand Up @@ -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();
}
Expand Down
2 changes: 1 addition & 1 deletion src/core/IronPython.Modules/_datetime.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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";
Expand Down
6 changes: 3 additions & 3 deletions src/core/IronPython.Modules/msvcrt.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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");
}
}

Expand Down Expand Up @@ -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");
}
}

Expand All @@ -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");
}
}

Expand Down
2 changes: 1 addition & 1 deletion src/core/IronPython.Modules/nt.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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;
}
Expand Down
6 changes: 3 additions & 3 deletions src/core/IronPython.Modules/zipimport.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Expand Down Expand Up @@ -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
Expand All @@ -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) {
Expand Down
2 changes: 1 addition & 1 deletion src/core/IronPython/Modules/_ast.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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<int>());
}
Expand Down
46 changes: 23 additions & 23 deletions src/core/IronPython/Modules/_io.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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) {
Expand Down Expand Up @@ -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) {
Expand Down Expand Up @@ -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) {
Expand Down Expand Up @@ -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;
Expand Down Expand Up @@ -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;
Expand Down Expand Up @@ -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;
Expand Down Expand Up @@ -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;
Expand Down Expand Up @@ -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.");
}
}

Expand Down Expand Up @@ -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;
Expand Down Expand Up @@ -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);
Expand Down Expand Up @@ -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;
}
Expand Down Expand Up @@ -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 ?
Expand Down Expand Up @@ -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;
}
Expand Down Expand Up @@ -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
Expand Down
2 changes: 1 addition & 1 deletion src/core/IronPython/Modules/_io/StringIO.cs
Original file line number Diff line number Diff line change
Expand Up @@ -309,7 +309,7 @@ public void __setstate__(CodeContext context, [NotNone] PythonTuple tuple) {
null => null,
string s => s,
Extensible<string> 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);

Expand Down
6 changes: 3 additions & 3 deletions src/core/IronPython/Runtime/ClrModule.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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);
}

Expand Down Expand Up @@ -885,7 +885,7 @@ public static void CompileModules(CodeContext/*!*/ context, string/*!*/ assembly
List<SavableScriptCode> code = new List<SavableScriptCode>();
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;
Expand Down Expand Up @@ -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);
Expand Down
4 changes: 2 additions & 2 deletions src/core/IronPython/Runtime/Exceptions/TraceBack.cs
Original file line number Diff line number Diff line change
Expand Up @@ -286,10 +286,10 @@ private bool IsTopMostFrame(List<FunctionStack> pyThread) {
private static Exception BadForOrFinallyJump(int newLineNum, Dictionary<int, bool> 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'");
}
}

Expand Down
Loading