diff --git a/eng/scripts/generate_set.py b/eng/scripts/generate_set.py index e4b8db361..ff985cab6 100644 --- a/eng/scripts/generate_set.py +++ b/eng/scripts/generate_set.py @@ -64,7 +64,7 @@ def simple_op_worker(cw, t, arg_t, name): ) def enter_multiarg_op(cw, t, name): - cw.enter_block('public %s %s([NotNone] params object[]/*!*/ sets)' % (t, name)) + cw.enter_block('public %s %s([NotNone] params object[] sets)' % (t, name)) def union_multiarg(cw, mutable): t = get_type(mutable) diff --git a/src/core/IronPython.Modules/IterTools.cs b/src/core/IronPython.Modules/IterTools.cs index e9fe0b59f..ee6ae37e5 100644 --- a/src/core/IronPython.Modules/IterTools.cs +++ b/src/core/IronPython.Modules/IterTools.cs @@ -142,7 +142,7 @@ public class chain : IterBase { private chain() { } - public chain(params object[] iterables) { + public chain([NotNone] params object[] iterables) { SetInnerEnumerator(PythonTuple.MakeTuple(iterables)); } @@ -667,7 +667,7 @@ public class zip_longest : IEnumerator { private readonly object _fill; private PythonTuple _current; - public zip_longest(params object[] iterables) { + public zip_longest([NotNone] params object[] iterables) { _iters = new IEnumerator[iterables.Length]; for (int i = 0; i < iterables.Length; i++) { @@ -675,7 +675,7 @@ public zip_longest(params object[] iterables) { } } - public zip_longest([ParamDictionary] IDictionary paramDict, params object[] iterables) { + public zip_longest([ParamDictionary] IDictionary paramDict, [NotNone] params object[] iterables) { object fill; if (paramDict.TryGetValue("fillvalue", out fill)) { @@ -762,12 +762,12 @@ private static Exception UnexpectedKeywordArgument(IDictionary p public class product : IterBase { private PythonTuple[] tuples; - public product(CodeContext context, params object[] iterables) { + public product(CodeContext context, [NotNone] params object[] iterables) { tuples = ArrayUtils.ConvertAll(iterables, x => new PythonTuple(PythonOps.GetEnumerator(x))); InnerEnumerator = Yielder(tuples); } - public product(CodeContext context, [ParamDictionary] IDictionary paramDict, params object[] iterables) { + public product(CodeContext context, [ParamDictionary] IDictionary paramDict, [NotNone] params object[] iterables) { object repeat; int iRepeat = 1; if (paramDict.TryGetValue("repeat", out repeat)) { diff --git a/src/core/IronPython.Modules/ResourceMetaPathImporter.cs b/src/core/IronPython.Modules/ResourceMetaPathImporter.cs index a3c444e2d..5730f201b 100644 --- a/src/core/IronPython.Modules/ResourceMetaPathImporter.cs +++ b/src/core/IronPython.Modules/ResourceMetaPathImporter.cs @@ -1,11 +1,17 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the Apache 2.0 License. +// See the LICENSE file in the project root for more information. + using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Reflection; + using IronPython.Runtime; using IronPython.Runtime.Exceptions; using IronPython.Zlib; + using Microsoft.Scripting; using Microsoft.Scripting.Runtime; @@ -68,7 +74,7 @@ fully qualified (dotted) module name. It returns the importer The optional 'path' argument is ignored -- it's there for compatibility with the importer protocol." )] - public object find_module(CodeContext /*!*/ context, string fullname, params object[] args) { + public object find_module(CodeContext /*!*/ context, string fullname, [NotNone] params object[] args) { var packedName = MakeFilename(fullname); foreach (var entry in SearchOrder) { @@ -131,8 +137,7 @@ public object load_module(CodeContext /*!*/ context, string fullname) { modules.Add(fullname, mod); try { script.Run(mod.Scope); - } - catch (Exception) { + } catch (Exception) { modules.Remove(fullname); throw; } @@ -175,8 +180,7 @@ private byte[] GetCodeFromData(CodeContext /*!*/ context, bool isbytecode, Packe if (data != null) { if (isbytecode) { // would put in code to unmarshal the bytecode here... - } - else { + } else { code = data; } } @@ -221,8 +225,8 @@ public static PackedResourceInfo Create(string fullName, int compress, #if DEBUG public override string ToString() { var sizeDesc = String.Format("{0} bytes", _fileSize); - if (Convert.ToDouble(_fileSize)/1024.0 > 1.0) - sizeDesc = String.Format("{0} KB", Math.Round(Convert.ToDouble(_fileSize)/1024.0, 1)); + if (Convert.ToDouble(_fileSize) / 1024.0 > 1.0) + sizeDesc = String.Format("{0} KB", Math.Round(Convert.ToDouble(_fileSize) / 1024.0, 1)); return String.Format("{0} ({1})", FullName, sizeDesc); } #endif @@ -259,26 +263,25 @@ where isPyFile let path = lineage.Take(lineage.Length - 1).ToArray() orderby fileName select new { - name = fileName, - path, - dottedPath = String.Join(".", path), - entry - }; + name = fileName, + path, + dottedPath = String.Join(".", path), + entry + }; var moduleContents = from source in parsedSources orderby source.dottedPath group source by source.dottedPath into moduleGroup select new { - moduleGroup.Key, - Items = moduleGroup.Select(item => item.entry).ToArray() - }; + moduleGroup.Key, + Items = moduleGroup.Select(item => item.entry).ToArray() + }; modules = moduleContents.ToDictionary( moduleGroup => moduleGroup.Key, moduleGroup => moduleGroup.Items); return true; - } - catch (Exception exception) { + } catch (Exception exception) { files = null; modules = null; unpackingError = String.Format("{0}: {1}", exception.GetType().Name, exception.Message); @@ -310,7 +313,7 @@ private bool ReadZipDirectory(out IDictionary result var endofCentralDir = new byte[22]; reader.BaseStream.Seek(-22, SeekOrigin.End); - var headerPosition = (int) reader.BaseStream.Position; + var headerPosition = (int)reader.BaseStream.Position; if (reader.Read(endofCentralDir, 0, 22) != 22) { unpackingError = "Can't read ZIP resource: Invalid ZIP Directory."; return false; @@ -332,8 +335,7 @@ private bool ReadZipDirectory(out IDictionary result .ToDictionary(entry => entry.FullName); return true; } - } - catch (Exception exception) { + } catch (Exception exception) { unpackingError = String.Format("{0}: {1}", exception.GetType().Name, exception.Message); return false; } @@ -410,26 +412,23 @@ public bool GetData(PackedResourceInfo tocEntry, out byte[] result, out string u byte[] rawData; try { rawData = reader.ReadBytes(compress == 0 ? dataSize : dataSize + 1); - } - catch { + } catch { unpackingError = "Can't read data"; return false; } if (compress != 0) { - rawData[dataSize] = (byte) 'Z'; + rawData[dataSize] = (byte)'Z'; } result = compress == 0 ? rawData : ZlibModule.Decompress(rawData, -15); return true; } - } - catch (Exception exception) { + } catch (Exception exception) { unpackingError = String.Format("{0}: {1}", exception.GetType().Name, exception.Message); return false; } } } - } } diff --git a/src/core/IronPython.Modules/SimpleSignalState.cs b/src/core/IronPython.Modules/SimpleSignalState.cs index c746290b3..bf5215835 100644 --- a/src/core/IronPython.Modules/SimpleSignalState.cs +++ b/src/core/IronPython.Modules/SimpleSignalState.cs @@ -1,11 +1,15 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using IronPython.Runtime; +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the Apache 2.0 License. +// See the LICENSE file in the project root for more information. + +#nullable enable #if FEATURE_PROCESS +using System; + +using IronPython.Runtime; + namespace IronPython.Modules { public static partial class PythonSignal { internal class SimpleSignalState : PythonSignalState { @@ -14,9 +18,9 @@ public SimpleSignalState(PythonContext pc) Console.CancelKeyPress += new ConsoleCancelEventHandler(Console_CancelKeyPress); } - private void Console_CancelKeyPress(object sender, ConsoleCancelEventArgs e) { + private void Console_CancelKeyPress(object? sender, ConsoleCancelEventArgs e) { int pySignal; - switch(e.SpecialKey) { + switch (e.SpecialKey) { case ConsoleSpecialKey.ControlC: pySignal = SIGINT; break; @@ -28,7 +32,7 @@ private void Console_CancelKeyPress(object sender, ConsoleCancelEventArgs e) { default: throw new InvalidOperationException("unreachable"); } - + lock (PySignalToPyHandler) { if (PySignalToPyHandler[pySignal].GetType() == typeof(int)) { int tempId = (int)PySignalToPyHandler[pySignal]; diff --git a/src/core/IronPython.Modules/_bisect.cs b/src/core/IronPython.Modules/_bisect.cs index 1468699d9..87f9e9efb 100644 --- a/src/core/IronPython.Modules/_bisect.cs +++ b/src/core/IronPython.Modules/_bisect.cs @@ -2,6 +2,8 @@ // The .NET Foundation licenses this file to you under the Apache 2.0 License. // See the LICENSE file in the project root for more information. +#nullable enable + using System; using System.Collections; using System.Reflection; @@ -29,9 +31,9 @@ common approach. #region Private Implementation Details - private static int InternalBisectLeft(CodeContext/*!*/ context, PythonList list, object item, int lo, int hi) { + private static int InternalBisectLeft(CodeContext/*!*/ context, PythonList list, object? item, int lo, int hi) { int mid; - object litem; + object? litem; if (lo < 0) { throw PythonOps.ValueError("lo must be non-negative"); @@ -52,7 +54,7 @@ private static int InternalBisectLeft(CodeContext/*!*/ context, PythonList list, return lo; } - private static int InternalBisectLeft(CodeContext/*!*/ context, object list, object item, int lo, int hi) { + private static int InternalBisectLeft(CodeContext/*!*/ context, object? list, object? item, int lo, int hi) { int mid; object litem; @@ -63,6 +65,7 @@ private static int InternalBisectLeft(CodeContext/*!*/ context, object list, obj if (hi == -1) { hi = PythonOps.Length(list); } + IComparer comparer = context.LanguageContext.GetLtComparer(GetComparisonType(context, list)); while (lo < hi) { mid = (int)(((long)lo + hi) / 2); @@ -75,8 +78,8 @@ private static int InternalBisectLeft(CodeContext/*!*/ context, object list, obj return lo; } - private static int InternalBisectRight(CodeContext/*!*/ context, PythonList list, object item, int lo, int hi) { - object litem; + private static int InternalBisectRight(CodeContext/*!*/ context, PythonList list, object? item, int lo, int hi) { + object? litem; int mid; if (lo < 0) { @@ -98,7 +101,7 @@ private static int InternalBisectRight(CodeContext/*!*/ context, PythonList list return lo; } - private static int InternalBisectRight(CodeContext/*!*/ context, object list, object item, int lo, int hi) { + private static int InternalBisectRight(CodeContext/*!*/ context, object list, object? item, int lo, int hi) { object litem; int mid; @@ -122,7 +125,7 @@ private static int InternalBisectRight(CodeContext/*!*/ context, object list, ob return lo; } - private static Type GetComparisonType(CodeContext/*!*/ context, object a) { + private static Type GetComparisonType(CodeContext/*!*/ context, object? a) { if (PythonOps.Length(a) > 0) { // use the 1st index to determine the type - we're assuming lists are // homogeneous @@ -183,7 +186,7 @@ before the leftmost x already there. Optional args lo (default 0) and hi (default len(a)) bound the slice of a to be searched. ")] - public static object bisect_left(CodeContext/*!*/ context, object a, object x, int lo = 0, int hi = -1) { + public static object bisect_left(CodeContext/*!*/ context, object? a, object? x, int lo = 0, int hi = -1) { if (a is PythonList l && l.GetType() == typeof(PythonList)) { return InternalBisectLeft(context, l, x, lo, hi); } @@ -201,7 +204,7 @@ public static object bisect_left(CodeContext/*!*/ context, object a, object x, i Optional args lo (default 0) and hi (default len(a)) bound the slice of a to be searched. ")] - public static void InsortRight(CodeContext/*!*/ context, object a, object x, int lo=0, int hi=-1) { + public static void InsortRight(CodeContext/*!*/ context, object a, object x, int lo = 0, int hi = -1) { if (a is PythonList l && l.GetType() == typeof(PythonList)) { l.Insert(InternalBisectRight(context, l, x, lo, hi), x); return; @@ -227,7 +230,7 @@ public static void InsortRight(CodeContext/*!*/ context, object a, object x, int Optional args lo (default 0) and hi (default len(a)) bound the slice of a to be searched. ")] - public static void insort_left(CodeContext/*!*/ context, object a, object x, int lo=0, int hi=-1) { + public static void insort_left(CodeContext/*!*/ context, object? a, object? x, int lo = 0, int hi = -1) { if (a is PythonList l && l.GetType() == typeof(PythonList)) { l.Insert(InternalBisectLeft(context, l, x, lo, hi), x); return; diff --git a/src/core/IronPython.Modules/_collections.cs b/src/core/IronPython.Modules/_collections.cs index 77067c319..d58d66f1d 100644 --- a/src/core/IronPython.Modules/_collections.cs +++ b/src/core/IronPython.Modules/_collections.cs @@ -10,17 +10,16 @@ using System.Runtime.CompilerServices; using System.Text; -using Microsoft.Scripting; -using Microsoft.Scripting.Actions; -using Microsoft.Scripting.Runtime; -using Microsoft.Scripting.Utils; - using IronPython.Runtime; using IronPython.Runtime.Binding; -using IronPython.Runtime.Exceptions; using IronPython.Runtime.Operations; using IronPython.Runtime.Types; +using Microsoft.Scripting; +using Microsoft.Scripting.Actions; +using Microsoft.Scripting.Runtime; +using Microsoft.Scripting.Utils; + [assembly: PythonModule("_collections", typeof(IronPython.Modules.PythonCollections))] namespace IronPython.Modules { public class PythonCollections { @@ -42,7 +41,7 @@ private deque(int maxlen) { _data = _maxLen < 0 ? new object[8] : new object[Math.Min(_maxLen, 8)]; } - public static object __new__(CodeContext/*!*/ context, PythonType cls, [ParamDictionary]IDictionary dict, params object[] args) { + public static object __new__(CodeContext/*!*/ context, PythonType cls, [ParamDictionary] IDictionary dict, [NotNone] params object[] args) { if (cls == DynamicHelpers.GetPythonTypeFromType(typeof(deque))) return new deque(); return cls.CreateInstance(context); } @@ -52,7 +51,7 @@ public void __init__() { clear(); } - public void __init__([ParamDictionary]IDictionary dict) { + public void __init__([ParamDictionary] IDictionary dict) { _maxLen = VerifyMaxLen(dict); clear(); } @@ -65,12 +64,12 @@ public void __init__(object iterable) { public void __init__(object iterable, object maxlen) { _maxLen = VerifyMaxLenValue(maxlen); - + clear(); extend(iterable); } - public void __init__(object iterable, [ParamDictionary]IDictionary dict) { + public void __init__(object iterable, [ParamDictionary] IDictionary dict) { if (VerifyMaxLen(dict) < 0) { __init__(iterable); } else { @@ -82,7 +81,7 @@ private static int VerifyMaxLen(IDictionary dict) { if (dict.Count != 1) { throw PythonOps.TypeError("deque() takes at most 1 keyword argument ({0} given)", dict.Count); } - + object value; if (!dict.TryGetValue("maxlen", out value)) { IEnumerator e = dict.Keys.GetEnumerator(); @@ -105,7 +104,7 @@ private static int VerifyMaxLenValue(object value) { Extensible ebi => (int)ebi.Value, _ => throw PythonOps.TypeError("an integer is required") }; - + if (res < 0) throw PythonOps.ValueError("maxlen must be non-negative"); return res; @@ -425,7 +424,7 @@ public void rotate(CodeContext/*!*/ context, object n) { // too bad, we got gaps, looks like we'll be doing some real work. object[] newData = new object[_itemCnt]; // we re-size to itemCnt so that future rotates don't require work int curWriteIndex = rot; - WalkDeque(delegate(int curIndex) { + WalkDeque(delegate (int curIndex) { newData[curWriteIndex] = _data[curIndex]; curWriteIndex = (curWriteIndex + 1) % _itemCnt; return true; @@ -534,7 +533,7 @@ public void __delitem__(CodeContext/*!*/ context, object index) { // we'll just recreate our data by walking the data once. object[] newData = new object[_data.Length]; int writeIndex = 0; - WalkDeque(delegate(int curIndex) { + WalkDeque(delegate (int curIndex) { if (curIndex != realIndex) { newData[writeIndex++] = _data[curIndex]; } @@ -925,7 +924,7 @@ private bool WalkDeque(DequeWalker walker) { string comma = ""; lock (_lockObj) { - WalkDeque(delegate(int index) { + WalkDeque(delegate (int index) { sb.Append(comma); sb.Append(PythonOps.Repr(context, _data[index])); comma = ", "; @@ -1157,10 +1156,10 @@ public void __init__(CodeContext/*!*/ context, object default_factory, [NotNone] } } - public void __init__(CodeContext/*!*/ context, object default_factory, [ParamDictionary, NotNone] IDictionary dict, [NotNone] params object[] args) { + public void __init__(CodeContext/*!*/ context, object default_factory, [ParamDictionary] IDictionary dict, [NotNone] params object[] args) { __init__(context, default_factory, args); - foreach (KeyValuePair kvp in dict) { + foreach (KeyValuePair kvp in dict) { this[kvp.Key] = kvp.Value; } } diff --git a/src/core/IronPython.Modules/_csv.cs b/src/core/IronPython.Modules/_csv.cs index 6d6c86ba6..e77d3b766 100644 --- a/src/core/IronPython.Modules/_csv.cs +++ b/src/core/IronPython.Modules/_csv.cs @@ -64,7 +64,7 @@ public static int field_size_limit(CodeContext/*!*/ context) { dialect = csv.register_dialect(name, dialect)")] public static void register_dialect(CodeContext/*!*/ context, [ParamDictionary] IDictionary kwArgs, - params object[] args) { + [NotNone] params object[] args) { string name = null; object dialectObj = null; Dialect dialect = null; @@ -157,7 +157,7 @@ The returned object is an iterator. Each iteration returns a row of the CSV file (which can span multiple input lines)")] public static object reader(CodeContext/*!*/ context, [ParamDictionary] IDictionary kwArgs, - params object[] args) { + [NotNone] params object[] args) { object dialectObj = null; Dialect dialect = null; IEnumerator e = null; @@ -198,7 +198,7 @@ public static object reader(CodeContext/*!*/ context, public static object writer(CodeContext/*!*/ context, [ParamDictionary] IDictionary kwArgs, - params object[] args) { + [NotNone] params object[] args) { object output_file = null; object dialectObj = null; Dialect dialect = null; @@ -416,7 +416,7 @@ private static string SetString(string name, object src, bool found, string @def public Dialect(CodeContext/*!*/ context, [ParamDictionary] IDictionary kwArgs, - params object[] args) { + [NotNone] params object[] args) { object dialect = null; object delimiter = null; object doublequote = null; @@ -507,10 +507,10 @@ public Dialect(CodeContext/*!*/ context, // CPython defines these overloads on Dialect since 3.10 [Documentation("raises an exception to avoid pickling")] - public object __reduce__(params object[] args) => throw PythonOps.TypeError("cannot pickle 'Dialect' instances"); + public object __reduce__([NotNone] params object[] args) => throw PythonOps.TypeError("cannot pickle 'Dialect' instances"); [Documentation("raises an exception to avoid pickling")] - public object __reduce_ex__(params object[] args) => throw PythonOps.TypeError("cannot pickle 'Dialect' instances"); + public object __reduce_ex__([NotNone] params object[] args) => throw PythonOps.TypeError("cannot pickle 'Dialect' instances"); public string escapechar { get { return _escapechar; } diff --git a/src/core/IronPython.Modules/_ctypes/Array.cs b/src/core/IronPython.Modules/_ctypes/Array.cs index cec1619b3..41cfb4ec4 100644 --- a/src/core/IronPython.Modules/_ctypes/Array.cs +++ b/src/core/IronPython.Modules/_ctypes/Array.cs @@ -23,7 +23,7 @@ public static partial class CTypes { [PythonType("Array")] public abstract class _Array : CData { - public void __init__(params object[] args) { + public void __init__([NotNone] params object[] args) { INativeType nativeType = NativeType; MemHolder = new MemoryHolder(nativeType.Size); diff --git a/src/core/IronPython.Modules/_ctypes/Extensions.cs b/src/core/IronPython.Modules/_ctypes/Extensions.cs index 946e5e399..1132a3356 100644 --- a/src/core/IronPython.Modules/_ctypes/Extensions.cs +++ b/src/core/IronPython.Modules/_ctypes/Extensions.cs @@ -2,6 +2,8 @@ // The .NET Foundation licenses this file to you under the Apache 2.0 License. // See the LICENSE file in the project root for more information. +#nullable enable + #if FEATURE_CTYPES using System; diff --git a/src/core/IronPython.Modules/_ctypes/INativeType.cs b/src/core/IronPython.Modules/_ctypes/INativeType.cs index 4756d3803..a3a99f166 100644 --- a/src/core/IronPython.Modules/_ctypes/INativeType.cs +++ b/src/core/IronPython.Modules/_ctypes/INativeType.cs @@ -2,6 +2,8 @@ // The .NET Foundation licenses this file to you under the Apache 2.0 License. // See the LICENSE file in the project root for more information. +#nullable enable + #if FEATURE_CTYPES using System; @@ -85,4 +87,4 @@ string TypeFormat { } } } -#endif \ No newline at end of file +#endif diff --git a/src/core/IronPython.Modules/_ctypes/LocalOrArg.cs b/src/core/IronPython.Modules/_ctypes/LocalOrArg.cs index c4eb9fa13..d8ca32341 100644 --- a/src/core/IronPython.Modules/_ctypes/LocalOrArg.cs +++ b/src/core/IronPython.Modules/_ctypes/LocalOrArg.cs @@ -2,6 +2,8 @@ // The .NET Foundation licenses this file to you under the Apache 2.0 License. // See the LICENSE file in the project root for more information. +#nullable enable + #if FEATURE_LCG using System; diff --git a/src/core/IronPython.Modules/_ctypes/Structure.cs b/src/core/IronPython.Modules/_ctypes/Structure.cs index e3711c2d6..6fac460bd 100644 --- a/src/core/IronPython.Modules/_ctypes/Structure.cs +++ b/src/core/IronPython.Modules/_ctypes/Structure.cs @@ -6,12 +6,12 @@ using System.Collections.Generic; -using Microsoft.Scripting; - using IronPython.Runtime; using IronPython.Runtime.Operations; using IronPython.Runtime.Types; +using Microsoft.Scripting; + namespace IronPython.Modules { /// /// Provides support for interop with native code from Python code. @@ -53,7 +53,7 @@ public void __init__([NotNone] params object[] args) { st.SetValueInternal(MemHolder, 0, args); } - public void __init__(CodeContext/*!*/ context, [ParamDictionary]IDictionary kwargs) { + public void __init__(CodeContext/*!*/ context, [ParamDictionary] IDictionary kwargs) { CheckAbstract(); foreach (var x in kwargs) { @@ -72,6 +72,6 @@ private void CheckAbstract() { } } } - } + #endif diff --git a/src/core/IronPython.Modules/_ctypes/_ctypes.cs b/src/core/IronPython.Modules/_ctypes/_ctypes.cs index 47f4283ad..01de2d51a 100644 --- a/src/core/IronPython.Modules/_ctypes/_ctypes.cs +++ b/src/core/IronPython.Modules/_ctypes/_ctypes.cs @@ -770,7 +770,7 @@ public class _COMError : PythonExceptions.BaseException { public _COMError(PythonType cls) : base(cls) { } - public override void __init__(params object[] args) { + public override void __init__([NotNone] params object[] args) { base.__init__(args); if (args.Length < 3) { throw PythonOps.TypeError($"COMError() takes exactly 4 arguments({args.Length} given)"); diff --git a/src/core/IronPython.Modules/_ctypes_test.cs b/src/core/IronPython.Modules/_ctypes_test.cs index 7acf17617..5f272243f 100644 --- a/src/core/IronPython.Modules/_ctypes_test.cs +++ b/src/core/IronPython.Modules/_ctypes_test.cs @@ -2,6 +2,8 @@ // The .NET Foundation licenses this file to you under the Apache 2.0 License. // See the LICENSE file in the project root for more information. +#nullable enable + #if FEATURE_CTYPES using System; diff --git a/src/core/IronPython.Modules/_datetime.cs b/src/core/IronPython.Modules/_datetime.cs index b6e72ce9f..e05d2be26 100644 --- a/src/core/IronPython.Modules/_datetime.cs +++ b/src/core/IronPython.Modules/_datetime.cs @@ -467,7 +467,7 @@ public object replace() { } // instance methods - public virtual date replace(CodeContext/*!*/ context, [NotNone, ParamDictionary] IDictionary dict) { + public virtual date replace(CodeContext/*!*/ context, [ParamDictionary] IDictionary dict) { int year2 = _dateTime.Year; int month2 = _dateTime.Month; int day2 = _dateTime.Day; @@ -862,7 +862,7 @@ public object timetz() { } [Documentation("gets a new datetime object with the fields provided as keyword arguments replaced.")] - public override date replace(CodeContext/*!*/ context, [NotNone, ParamDictionary] IDictionary dict) { + public override date replace(CodeContext/*!*/ context, [ParamDictionary] IDictionary dict) { int lyear = year; int lmonth = month; int lday = day; @@ -1037,8 +1037,7 @@ public override string strftime(CodeContext/*!*/ context, [NotNone] string dateF public double timestamp() { if (tzinfo is null) { return PythonTime.TicksToTimestamp(_dateTime.ToUniversalTime().Ticks); - } - else { + } else { return (this - new datetime(new DateTime(1970, 1, 1), timezone.utc)).total_seconds(); } } @@ -1233,7 +1232,7 @@ public object replace() { return this; } - public object replace([ParamDictionary, NotNone] IDictionary dict) { + public object replace([ParamDictionary] IDictionary dict) { int lhour = hour; int lminute = minute; int lsecond = second; @@ -1451,7 +1450,7 @@ public tzinfo() { public tzinfo([NotNone] params object?[] args) { } - public tzinfo([ParamDictionary, NotNone] PythonDictionary dict, [NotNone] params object?[] args) { + public tzinfo([ParamDictionary] PythonDictionary dict, [NotNone] params object?[] args) { } public virtual object fromutc([NotNone] datetime dt) { diff --git a/src/core/IronPython.Modules/_functools.cs b/src/core/IronPython.Modules/_functools.cs index fe2ba1fc0..9ac3df34b 100644 --- a/src/core/IronPython.Modules/_functools.cs +++ b/src/core/IronPython.Modules/_functools.cs @@ -89,14 +89,14 @@ public class partial : IWeakReferenceable { /// /// Creates a new partial object with the provided positional arguments. /// - public partial(CodeContext/*!*/ context, object? func, [NotNone] params object[]/*!*/ args) + public partial(CodeContext/*!*/ context, object? func, [NotNone] params object[] args) : this(context, func, new PythonDictionary(), args) { } /// /// Creates a new partial object with the provided positional and keyword arguments. /// - public partial(CodeContext/*!*/ context, object? func, [NotNone, ParamDictionary] IDictionary keywords, [NotNone] params object[]/*!*/ args) { + public partial(CodeContext/*!*/ context, object? func, [ParamDictionary] IDictionary keywords, [NotNone] params object[] args) { if (!PythonOps.IsCallable(context, func)) { throw PythonOps.TypeError("the first argument must be callable"); } @@ -148,7 +148,7 @@ public PythonDictionary __dict__ { get { return EnsureDict(); } - [param: NotNone] + [param: NotNone] set { _dict = value; } @@ -244,7 +244,7 @@ public string __repr__(CodeContext context) { /// Calls func with the previously provided arguments and more positional arguments and keyword arguments. /// [SpecialName] - public object? Call(CodeContext/*!*/ context, [ParamDictionary, NotNone] IDictionary dict, [NotNone] params object?[] args) { + public object? Call(CodeContext/*!*/ context, [ParamDictionary] IDictionary dict, [NotNone] params object?[] args) { IDictionary finalDict; if (_keywordArgs != null) { diff --git a/src/core/IronPython.Modules/_heapq.cs b/src/core/IronPython.Modules/_heapq.cs index 989874216..afccbc42b 100644 --- a/src/core/IronPython.Modules/_heapq.cs +++ b/src/core/IronPython.Modules/_heapq.cs @@ -2,16 +2,17 @@ // The .NET Foundation licenses this file to you under the Apache 2.0 License. // See the LICENSE file in the project root for more information. +#nullable enable + using System; using System.Collections; -using System.Collections.Generic; -using System.Text; -using Microsoft.Scripting.Runtime; + using IronPython.Runtime; -using IronPython.Runtime.Binding; using IronPython.Runtime.Operations; using IronPython.Runtime.Types; +using Microsoft.Scripting.Runtime; + [assembly: PythonModule("_heapq", typeof(IronPython.Modules.PythonHeapq))] namespace IronPython.Modules { public static class PythonHeapq { @@ -21,14 +22,14 @@ public static class PythonHeapq { #region public API [Documentation("Transform list into a heap, in-place, in O(len(heap)) time.")] - public static void heapify(CodeContext/*!*/ context, PythonList list) { + public static void heapify(CodeContext/*!*/ context, [NotNone] PythonList list) { lock (list) { DoHeapify(context, list); } } [Documentation("Pop the smallest item off the heap, maintaining the heap invariant.")] - public static object heappop(CodeContext/*!*/ context, PythonList list) { + public static object? heappop(CodeContext/*!*/ context, [NotNone] PythonList list) { lock (list) { int last = list._size - 1; if (last < 0) { @@ -42,7 +43,7 @@ public static object heappop(CodeContext/*!*/ context, PythonList list) { } [Documentation("Push item onto heap, maintaining the heap invariant.")] - public static void heappush(CodeContext/*!*/ context, PythonList list, object item) { + public static void heappush(CodeContext/*!*/ context, [NotNone] PythonList list, object? item) { lock (list) { list.AddNoLock(item); SiftUp(context, list, list._size - 1); @@ -53,7 +54,7 @@ public static void heappush(CodeContext/*!*/ context, PythonList list, object it + "from the heap. The combined action runs more efficiently than\n" + "heappush() followed by a separate call to heappop()." )] - public static object heappushpop(CodeContext/*!*/ context, PythonList list, object item) { + public static object? heappushpop(CodeContext/*!*/ context, [NotNone] PythonList list, object? item) { lock (list) { return DoPushPop(context, list, item); } @@ -67,9 +68,9 @@ public static object heappushpop(CodeContext/*!*/ context, PythonList list, obje + " if item > heap[0]:\n" + " item = heapreplace(heap, item)\n" )] - public static object heapreplace(CodeContext/*!*/ context, PythonList list, object item) { + public static object? heapreplace(CodeContext/*!*/ context, [NotNone] PythonList list, object? item) { lock (list) { - object ret = list._data[0]; + object? ret = list._data[0]; list._data[0] = item; SiftDown(context, list, 0, list._size - 1); return ret; @@ -80,7 +81,7 @@ public static object heapreplace(CodeContext/*!*/ context, PythonList list, obje [Documentation("Find the n largest elements in a dataset.\n\n" + "Equivalent to: sorted(iterable, reverse=True)[:n]\n" )] - public static PythonList nlargest(CodeContext/*!*/ context, int n, object iterable) { + public static PythonList nlargest(CodeContext/*!*/ context, int n, object? iterable) { if (n <= 0) { return new PythonList(); } @@ -113,7 +114,7 @@ public static PythonList nlargest(CodeContext/*!*/ context, int n, object iterab [Documentation("Find the n smallest elements in a dataset.\n\n" + "Equivalent to: sorted(iterable)[:n]\n" )] - public static PythonList nsmallest(CodeContext/*!*/ context, int n, object iterable) { + public static PythonList nsmallest(CodeContext/*!*/ context, int n, object? iterable) { if (n <= 0) { return new PythonList(); } @@ -146,7 +147,7 @@ public static PythonList nsmallest(CodeContext/*!*/ context, int n, object itera #region private implementation details (NOTE: thread-unsafe) - private static bool IsLessThan(CodeContext/*!*/ context, object x, object y) { + private static bool IsLessThan(CodeContext/*!*/ context, object? x, object? y) { object ret; if (PythonTypeOps.TryInvokeBinaryOperator(context, x, y, "__lt__", out ret) && !Object.ReferenceEquals(ret, NotImplementedType.Value)) { @@ -206,8 +207,8 @@ private static void DoHeapifyMax(CodeContext/*!*/ context, PythonList list) { } } - private static object DoPushPop(CodeContext/*!*/ context, PythonList heap, object item) { - object first; + private static object? DoPushPop(CodeContext/*!*/ context, PythonList heap, object? item) { + object? first; if (heap._size == 0 || !IsLessThan(context, first = heap._data[0], item)) { return item; } @@ -216,8 +217,8 @@ private static object DoPushPop(CodeContext/*!*/ context, PythonList heap, objec return first; } - private static object DoPushPopMax(CodeContext/*!*/ context, PythonList heap, object item) { - object first; + private static object? DoPushPopMax(CodeContext/*!*/ context, PythonList heap, object? item) { + object? first; if (heap._size == 0 || !IsLessThan(context, item, first = heap._data[0])) { return item; } diff --git a/src/core/IronPython.Modules/_multiprocessing.cs b/src/core/IronPython.Modules/_multiprocessing.cs index 63fcba0d5..9e3f257a9 100644 --- a/src/core/IronPython.Modules/_multiprocessing.cs +++ b/src/core/IronPython.Modules/_multiprocessing.cs @@ -2,13 +2,13 @@ // The .NET Foundation licenses this file to you under the Apache 2.0 License. // See the LICENSE file in the project root for more information. +#nullable enable + using System; using System.Net.Sockets; using System.Runtime.InteropServices; using System.Runtime.Versioning; -using Microsoft.Win32.SafeHandles; - using IronPython.Runtime; [assembly: PythonModule("_multiprocessing", typeof(IronPython.Modules.MultiProcessing))] @@ -16,13 +16,13 @@ namespace IronPython.Modules { public static class MultiProcessing { // TODO: implement SemLock and sem_unlink - public static object flags { get; set; } = new PythonDictionary(); + public static object? flags { get; set; } = new PythonDictionary(); [DllImport("ws2_32.dll", ExactSpelling = true, SetLastError = true)] private static extern SocketError closesocket([In] IntPtr socketHandle); [SupportedOSPlatform("windows"), PythonHidden(PlatformsAttribute.PlatformFamily.Unix)] - public static object closesocket(int handle) { + public static object? closesocket(int handle) { var error = closesocket(new IntPtr(handle)); // TODO: raise error return null; diff --git a/src/core/IronPython.Modules/_opcode.cs b/src/core/IronPython.Modules/_opcode.cs index 03c654010..b90dcddd1 100644 --- a/src/core/IronPython.Modules/_opcode.cs +++ b/src/core/IronPython.Modules/_opcode.cs @@ -2,19 +2,10 @@ // The .NET Foundation licenses this file to you under the Apache 2.0 License. // See the LICENSE file in the project root for more information. -using System; -using System.Collections; -using System.Collections.Generic; -using System.Diagnostics; -using System.Numerics; -using System.Text; - -using Microsoft.Scripting.Utils; +#nullable enable using IronPython.Runtime; -using IronPython.Runtime.Exceptions; using IronPython.Runtime.Operations; -using IronPython.Runtime.Types; [assembly: PythonModule("_opcode", typeof(IronPython.Modules.PythonOpcode))] namespace IronPython.Modules { @@ -156,7 +147,7 @@ public static class PythonOpcode { private const int FVS_MASK = 0x4; private const int FVS_HAVE_SPEC = 0x4; - public static int stack_effect(CodeContext context, int opcode, object oparg=null) { + public static int stack_effect(CodeContext context, int opcode, object? oparg = null) { int ioparg = 0; if (opcode >= HAVE_ARGUMENT) { diff --git a/src/core/IronPython.Modules/_operator.cs b/src/core/IronPython.Modules/_operator.cs index c10432010..9152b1299 100644 --- a/src/core/IronPython.Modules/_operator.cs +++ b/src/core/IronPython.Modules/_operator.cs @@ -112,7 +112,7 @@ public methodcaller([NotNone] params object?[] args) { _args = args.Skip(1).ToArray(); } - public methodcaller([ParamDictionary, NotNone] IDictionary kwargs, [NotNone] params object?[] args) : this(args) { + public methodcaller([ParamDictionary] IDictionary kwargs, [NotNone] params object?[] args) : this(args) { _dict = kwargs; } diff --git a/src/core/IronPython.Modules/_overlapped.cs b/src/core/IronPython.Modules/_overlapped.cs index 5a680a207..468be7c6e 100644 --- a/src/core/IronPython.Modules/_overlapped.cs +++ b/src/core/IronPython.Modules/_overlapped.cs @@ -2,6 +2,8 @@ // The .NET Foundation licenses this file to you under the Apache 2.0 License. // See the LICENSE file in the project root for more information. +#nullable enable + using System; using System.Numerics; using System.Runtime.InteropServices; diff --git a/src/core/IronPython.Modules/_posixsubprocess.cs b/src/core/IronPython.Modules/_posixsubprocess.cs index 9d5b9a68a..f5b72a286 100644 --- a/src/core/IronPython.Modules/_posixsubprocess.cs +++ b/src/core/IronPython.Modules/_posixsubprocess.cs @@ -2,6 +2,8 @@ // The .NET Foundation licenses this file to you under the Apache 2.0 License. // See the LICENSE file in the project root for more information. +#nullable enable + #if FEATURE_NATIVE using IronPython.Runtime; @@ -35,7 +37,7 @@ serialized and written to the errpipe_write fd per subprocess.py. Raises: Only on an error in the parent process. ")] - public static object fork_exec(CodeContext/*!*/ context, params object[] args) { + public static object fork_exec(CodeContext/*!*/ context, [NotNone] params object[] args) { throw PythonOps.NotImplementedError("fork_exec is currently not implemented"); } } diff --git a/src/core/IronPython.Modules/_random.RandomGen.cs b/src/core/IronPython.Modules/_random.RandomGen.cs index 542de7101..a2f2d9fe0 100644 --- a/src/core/IronPython.Modules/_random.RandomGen.cs +++ b/src/core/IronPython.Modules/_random.RandomGen.cs @@ -1,22 +1,7 @@ -// Copyright(c) .NET Foundation and Contributors -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in all -// copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -// SOFTWARE. +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. + +#nullable enable using System; diff --git a/src/core/IronPython.Modules/_random.cs b/src/core/IronPython.Modules/_random.cs index a77b7fdac..05cca0f2c 100644 --- a/src/core/IronPython.Modules/_random.cs +++ b/src/core/IronPython.Modules/_random.cs @@ -2,12 +2,15 @@ // The .NET Foundation licenses this file to you under the Apache 2.0 License. // See the LICENSE file in the project root for more information. +#nullable enable + using System; +using System.Diagnostics.CodeAnalysis; using System.Linq; -using System.Numerics; using IronPython.Runtime; using IronPython.Runtime.Operations; + using Microsoft.Scripting.Utils; [assembly: PythonModule("_random", typeof(IronPython.Modules.PythonRandom))] @@ -19,7 +22,7 @@ public static partial class PythonRandom { public class Random { private RandomGen _rnd; - public Random(object seed = null) { + public Random(object? seed = null) { this.seed(seed); } @@ -57,7 +60,8 @@ public object random() { } } - public void seed(object s = null) { + [MemberNotNull(nameof(_rnd))] + public void seed(object? s = null) { int newSeed; switch (s) { case null: @@ -79,7 +83,7 @@ public void seed(object s = null) { } } - public void setstate(PythonTuple state) { + public void setstate([NotNone] PythonTuple state) { if (state.Count != 58) throw PythonOps.ValueError("state vector is the wrong size"); var stateArray = state._data.Cast().ToArray(); lock (this) { diff --git a/src/core/IronPython.Modules/_socket.cs b/src/core/IronPython.Modules/_socket.cs index dc9515f62..a28e30843 100644 --- a/src/core/IronPython.Modules/_socket.cs +++ b/src/core/IronPython.Modules/_socket.cs @@ -36,7 +36,6 @@ public static class PythonSocket { private static readonly object _defaultBufsizeKey = new object(); private const int DefaultBufferSize = 8192; -#pragma warning disable IPY01 // Parameter which is marked not nullable does not have the NotNullAttribute [SpecialName] public static void PerformModuleReload(PythonContext/*!*/ context, PythonDictionary/*!*/ dict) { if (!context.HasModuleState(_defaultTimeoutKey)) { @@ -49,7 +48,6 @@ public static void PerformModuleReload(PythonContext/*!*/ context, PythonDiction context.EnsureModuleException("socketgaierror", error, dict, "gaierror", "socket"); context.EnsureModuleException("sockettimeout", error, dict, "timeout", "socket"); } -#pragma warning restore IPY01 // Parameter which is marked not nullable does not have the NotNullAttribute public static PythonType error => PythonExceptions.OSError; diff --git a/src/core/IronPython.Modules/_sre.cs b/src/core/IronPython.Modules/_sre.cs index c0ac29337..26f88ff33 100644 --- a/src/core/IronPython.Modules/_sre.cs +++ b/src/core/IronPython.Modules/_sre.cs @@ -2,6 +2,8 @@ // The .NET Foundation licenses this file to you under the Apache 2.0 License. // See the LICENSE file in the project root for more information. +#nullable enable + using System; using System.Globalization; @@ -17,7 +19,7 @@ public static class PythonSRegEx { public const int MAXREPEAT = 65535; public const int MAXGROUPS = int.MaxValue; - public static object getlower(CodeContext/*!*/ context, object val, object encoding) { + public static object getlower(CodeContext/*!*/ context, object? val, object? encoding) { int encInt = context.LanguageContext.ConvertToInt32(val); int charVal = context.LanguageContext.ConvertToInt32(val); @@ -28,7 +30,7 @@ public static object getlower(CodeContext/*!*/ context, object val, object encod } } - public static object compile(object a, object b, object c) { + public static object? compile(object? a, object? b, object? c) { return null; } } diff --git a/src/core/IronPython.Modules/_struct.cs b/src/core/IronPython.Modules/_struct.cs index d7b547704..6ed985086 100644 --- a/src/core/IronPython.Modules/_struct.cs +++ b/src/core/IronPython.Modules/_struct.cs @@ -57,11 +57,11 @@ internal Struct(CodeContext/*!*/ context, [NotNone] string/*!*/ fmt) { #region Python construction [Documentation("creates a new uninitialized struct object - all arguments are ignored")] - public Struct(params object[] args) { + public Struct([NotNone] params object[] args) { } [Documentation("creates a new uninitialized struct object - all arguments are ignored")] - public Struct([ParamDictionary] IDictionary kwArgs, params object[] args) { + public Struct([ParamDictionary] IDictionary kwArgs, [NotNone] params object[] args) { } [Documentation("initializes or re-initializes the compiled struct object with a new format")] @@ -84,7 +84,7 @@ public void __init__(CodeContext/*!*/ context, object fmt) { public string format { get; private set; } [Documentation("returns a string consisting of the values serialized according to the format of the struct object")] - public Bytes/*!*/ pack(CodeContext/*!*/ context, params object[] values) { + public Bytes/*!*/ pack(CodeContext/*!*/ context, [NotNone] params object[] values) { if (values.Length != _encodingCount) { throw Error(context, $"pack requires exactly {_encodingCount} arguments"); } @@ -221,7 +221,7 @@ public void __init__(CodeContext/*!*/ context, object fmt) { } [Documentation("Stores the deserialized data into the provided array")] - public void pack_into(CodeContext/*!*/ context, [NotNone] ByteArray/*!*/ buffer, int offset, params object[] args) { + public void pack_into(CodeContext/*!*/ context, [NotNone] ByteArray/*!*/ buffer, int offset, [NotNone] params object[] args) { var existing = buffer.UnsafeByteList; if (offset + size > existing.Count) { @@ -235,7 +235,7 @@ public void pack_into(CodeContext/*!*/ context, [NotNone] ByteArray/*!*/ buffer, } } - public void pack_into(CodeContext/*!*/ context, [NotNone] IBufferProtocol/*!*/ buffer, int offset, params object[] args) { + public void pack_into(CodeContext/*!*/ context, [NotNone] IBufferProtocol/*!*/ buffer, int offset, [NotNone] params object[] args) { using var existing = buffer.GetBufferNoThrow(BufferFlags.Writable) ?? throw PythonOps.TypeError("argument must be read-write bytes-like object, not {0}", PythonOps.GetPythonTypeName(buffer)); @@ -840,16 +840,16 @@ public static int calcsize(CodeContext/*!*/ context, object fmt) { } [Documentation("Return string containing values v1, v2, ... packed according to fmt.")] - public static Bytes/*!*/ pack(CodeContext/*!*/ context, object fmt/*!*/, params object[] values) { + public static Bytes/*!*/ pack(CodeContext/*!*/ context, object fmt/*!*/, [NotNone] params object[] values) { return GetStructFromCache(context, fmt).pack(context, values); } [Documentation("Pack the values v1, v2, ... according to fmt.\nWrite the packed bytes into the writable buffer buf starting at offset.")] - public static void pack_into(CodeContext/*!*/ context, object fmt, [NotNone] ByteArray/*!*/ buffer, int offset, params object[] args) { + public static void pack_into(CodeContext/*!*/ context, object fmt, [NotNone] ByteArray/*!*/ buffer, int offset, [NotNone] params object[] args) { GetStructFromCache(context, fmt).pack_into(context, buffer, offset, args); } - public static void pack_into(CodeContext/*!*/ context, object fmt, [NotNone] IBufferProtocol/*!*/ buffer, int offset, params object[] args) { + public static void pack_into(CodeContext/*!*/ context, object fmt, [NotNone] IBufferProtocol/*!*/ buffer, int offset, [NotNone] params object[] args) { GetStructFromCache(context, fmt).pack_into(context, buffer, offset, args); } diff --git a/src/core/IronPython.Modules/_sysconfigdata.cs b/src/core/IronPython.Modules/_sysconfigdata.cs index f2319c877..5df721d57 100644 --- a/src/core/IronPython.Modules/_sysconfigdata.cs +++ b/src/core/IronPython.Modules/_sysconfigdata.cs @@ -2,6 +2,8 @@ // The .NET Foundation licenses this file to you under the Apache 2.0 License. // See the LICENSE file in the project root for more information. +#nullable enable + using IronPython.Runtime; [assembly: PythonModule("_sysconfigdata", typeof(IronPython.Modules._sysconfigdata), PlatformsAttribute.PlatformFamily.Unix)] diff --git a/src/core/IronPython.Modules/_thread.cs b/src/core/IronPython.Modules/_thread.cs index e8df1f394..7515b9e0d 100644 --- a/src/core/IronPython.Modules/_thread.cs +++ b/src/core/IronPython.Modules/_thread.cs @@ -139,7 +139,7 @@ public static object _set_sentinel(CodeContext context) { #endregion [PythonType, PythonHidden] - public class @lock { + public sealed class @lock { private AutoResetEvent blockEvent; private Thread curHolder; @@ -148,7 +148,7 @@ public object __enter__() { return this; } - public void __exit__(CodeContext/*!*/ context, params object[] args) { + public void __exit__(CodeContext/*!*/ context, [NotNone] params object[] args) { release(context); } @@ -173,10 +173,6 @@ public bool acquire(bool blocking = true, float timeout = -1) { } } - public void release(CodeContext/*!*/ context, params object[] param) { - release(context); - } - public void release(CodeContext/*!*/ context) { if (Interlocked.Exchange(ref curHolder, null) == null) { throw PythonExceptions.CreateThrowable((PythonType)context.LanguageContext.GetModuleState("threaderror"), "lock isn't held", null); diff --git a/src/core/IronPython.Modules/_warnings.cs b/src/core/IronPython.Modules/_warnings.cs index e343cff9e..7e81275d8 100644 --- a/src/core/IronPython.Modules/_warnings.cs +++ b/src/core/IronPython.Modules/_warnings.cs @@ -3,20 +3,18 @@ // See the LICENSE file in the project root for more information. using System; -using System.Collections.Generic; using System.IO; using System.Numerics; using System.Runtime.CompilerServices; -using System.Runtime.InteropServices; using System.Text; -using System.Text.RegularExpressions; + using IronPython.Runtime; using IronPython.Runtime.Exceptions; using IronPython.Runtime.Operations; using IronPython.Runtime.Types; + using Microsoft.Scripting; using Microsoft.Scripting.Runtime; -using Microsoft.Scripting.Utils; [assembly: PythonModule("_warnings", typeof(IronPython.Modules.PythonWarnings))] namespace IronPython.Modules { diff --git a/src/core/IronPython.Modules/_weakref.Generated.cs b/src/core/IronPython.Modules/_weakref.Generated.cs index 5ad72dcc5..354548683 100644 --- a/src/core/IronPython.Modules/_weakref.Generated.cs +++ b/src/core/IronPython.Modules/_weakref.Generated.cs @@ -2,9 +2,9 @@ // The .NET Foundation licenses this file to you under the Apache 2.0 License. // See the LICENSE file in the project root for more information. -using IronPython.Runtime; +#nullable enable + using IronPython.Runtime.Types; -using Microsoft.Scripting; namespace IronPython.Modules { public static partial class PythonWeakRef { diff --git a/src/core/IronPython.Modules/_weakref.cs b/src/core/IronPython.Modules/_weakref.cs index 838fe71ae..ec3bf34cc 100644 --- a/src/core/IronPython.Modules/_weakref.cs +++ b/src/core/IronPython.Modules/_weakref.cs @@ -635,12 +635,12 @@ public override string ToString() { #endregion [SpecialName] - public object Call(CodeContext/*!*/ context, params object[] args) { + public object Call(CodeContext/*!*/ context, [NotNone] params object[] args) { return context.LanguageContext.CallSplat(GetObject(), args); } [SpecialName] - public object Call(CodeContext/*!*/ context, [ParamDictionary]IDictionary dict, params object[] args) { + public object Call(CodeContext/*!*/ context, [ParamDictionary]IDictionary dict, [NotNone] params object[] args) { return PythonCalls.CallWithKeywordArgs(context, GetObject(), args, dict); } @@ -804,13 +804,13 @@ public GenericMethodWrapper(string methodName, IProxyObject proxyTarget) { } [SpecialName] - public object Call(CodeContext context, params object[] args) { + public object Call(CodeContext context, [NotNone] params object[] args) { return PythonOps.Invoke(context, target.Target, name, args); } [SpecialName] - public object Call(CodeContext context, [ParamDictionary]IDictionary dict, params object[] args) { + public object Call(CodeContext context, [ParamDictionary]IDictionary dict, [NotNone] params object[] args) { object targetMethod; if (!DynamicHelpers.GetPythonType(target.Target).TryGetBoundMember(context, target.Target, name, out targetMethod)) throw PythonOps.AttributeError("type {0} has no attribute {1}", diff --git a/src/core/IronPython.Modules/atexit.cs b/src/core/IronPython.Modules/atexit.cs index c2a35aeb0..e12d07b42 100644 --- a/src/core/IronPython.Modules/atexit.cs +++ b/src/core/IronPython.Modules/atexit.cs @@ -1,14 +1,19 @@ -using System; +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the Apache 2.0 License. +// See the LICENSE file in the project root for more information. + +#nullable enable + +using System; using System.Collections.Generic; using System.Runtime.CompilerServices; -using Microsoft.Scripting; - using IronPython.Runtime; -using Microsoft.Scripting.Runtime; - -using IronPython.Runtime.Operations; using IronPython.Runtime.Exceptions; +using IronPython.Runtime.Operations; + +using Microsoft.Scripting; +using Microsoft.Scripting.Runtime; [assembly: PythonModule("atexit", typeof(IronPython.Modules.PythonAtExit))] namespace IronPython.Modules { @@ -28,15 +33,15 @@ public FunctionDescriptor(object func, IDictionary kwargs, objec } public object Func { - get; + get; } public IDictionary KeywordArgs { - get; + get; } public object[] Args { - get; + get; } } @@ -57,7 +62,7 @@ Register a function to be executed upon normal program termination\n\ kwargs - optional keyword arguments to pass to func func is returned to facilitate usage as a decorator.")] - public static object register(CodeContext context, object func, [ParamDictionary]IDictionary kwargs, params object[] args) { + public static object register(CodeContext context, object? func, [ParamDictionary] IDictionary kwargs, [NotNone] params object[] args) { if (!PythonOps.IsCallable(context, func)) { throw PythonOps.TypeError("the first argument must be callable"); } @@ -77,7 +82,7 @@ public static object register(CodeContext context, object func, [ParamDictionary atexit.register func - function to be unregistered")] - public static void unregister(CodeContext context, object func) { + public static void unregister(CodeContext context, object? func) { var functions = context.LanguageContext.GetModuleState(_registry_key) as List; if (functions != null) { lock (functions) { @@ -105,7 +110,7 @@ public static void _run_exitfuncs(CodeContext context) { var pc = context.LanguageContext; var functions = pc.GetModuleState(_registry_key) as List; if (functions != null) { - Exception lastException = null; + Exception? lastException = null; lock (functions) { for (int i = functions.Count - 1; i >= 0; i--) { var func = functions[i]; diff --git a/src/core/IronPython.Modules/audioop.cs b/src/core/IronPython.Modules/audioop.cs index 635bcbecb..4f2833e35 100644 --- a/src/core/IronPython.Modules/audioop.cs +++ b/src/core/IronPython.Modules/audioop.cs @@ -13,12 +13,10 @@ [assembly: PythonModule("audioop", typeof(IronPython.Modules.PythonAudioOp))] namespace IronPython.Modules { public static class PythonAudioOp { -#pragma warning disable IPY01 // Parameter which is marked not nullable does not have the NotNullAttribute [SpecialName] public static void PerformModuleReload(PythonContext/*!*/ context, PythonDictionary/*!*/ dict) { context.EnsureModuleException("audiooperror", dict, "error", "audioop"); } -#pragma warning restore IPY01 // Parameter which is marked not nullable does not have the NotNullAttribute private static PythonType error(CodeContext/*!*/ context) => (PythonType)context.LanguageContext.GetModuleState("audiooperror"); diff --git a/src/core/IronPython.Modules/binascii.cs b/src/core/IronPython.Modules/binascii.cs index ed4e6f7ed..6d7fe0429 100644 --- a/src/core/IronPython.Modules/binascii.cs +++ b/src/core/IronPython.Modules/binascii.cs @@ -2,6 +2,8 @@ // The .NET Foundation licenses this file to you under the Apache 2.0 License. // See the LICENSE file in the project root for more information. +#nullable enable + using System; using System.IO; using System.Numerics; @@ -318,16 +320,16 @@ static void to_hex(char ch, StringBuilder s, int index) { #region hqx - public static object a2b_hqx(object data) { + public static object a2b_hqx(object? data) { throw new NotImplementedException(); } - public static object rledecode_hqx(object data) { + public static object rledecode_hqx(object? data) { throw new NotImplementedException(); } - public static object rlecode_hqx(object data) { + public static object rlecode_hqx(object? data) { throw new NotImplementedException(); } - public static object b2a_hqx(object data) { + public static object b2a_hqx(object? data) { throw new NotImplementedException(); } @@ -649,7 +651,7 @@ private static void ProcessSuffix(CodeContext/*!*/ context, ReadOnlySpan d } private static Bytes ToBytes(this string s) { - if (StringOps.TryEncodeAscii(s, out Bytes ascii)) + if (StringOps.TryEncodeAscii(s, out Bytes? ascii)) return ascii; throw PythonOps.ValueError("string argument should contain only ASCII characters"); } diff --git a/src/core/IronPython.Modules/errno.cs b/src/core/IronPython.Modules/errno.cs index 9c8ec38d0..709091b51 100644 --- a/src/core/IronPython.Modules/errno.cs +++ b/src/core/IronPython.Modules/errno.cs @@ -2,6 +2,8 @@ // The .NET Foundation licenses this file to you under the Apache 2.0 License. // See the LICENSE file in the project root for more information. +#nullable enable + using System; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; diff --git a/src/core/IronPython.Modules/gc.cs b/src/core/IronPython.Modules/gc.cs index 87bcacbaf..29cdd3236 100644 --- a/src/core/IronPython.Modules/gc.cs +++ b/src/core/IronPython.Modules/gc.cs @@ -2,16 +2,16 @@ // The .NET Foundation licenses this file to you under the Apache 2.0 License. // See the LICENSE file in the project root for more information. +#nullable enable + using System; using System.Linq; -using Microsoft.Scripting; -using Microsoft.Scripting.Runtime; - using IronPython.Runtime; using IronPython.Runtime.Exceptions; using IronPython.Runtime.Operations; -using IronPython.Runtime.Types; + +using Microsoft.Scripting.Runtime; using SpecialName = System.Runtime.CompilerServices.SpecialNameAttribute; @@ -29,7 +29,7 @@ public static class PythonGC { private static readonly object _threadholdKey = new object(); [SpecialName] - public static void PerformModuleReload(PythonContext/*!*/ context, PythonDictionary/*!*/ dict) { + public static void PerformModuleReload(PythonContext/*!*/ context, PythonDictionary/*!*/ dict) { context.SetModuleState(_threadholdKey, PythonTuple.MakeTuple(64 * 1024, 256 * 1024, 1024 * 1024)); } @@ -52,7 +52,7 @@ public static int collect(CodeContext context) { return collect(context, GC.MaxGeneration); } - public static void set_debug(object o) { + public static void set_debug(object? o) { throw PythonOps.NotImplementedError("gc.set_debug isn't implemented"); } @@ -64,25 +64,25 @@ public static object[] get_objects() { throw PythonOps.NotImplementedError("gc.get_objects isn't implemented"); } - public static void set_threshold(CodeContext/*!*/ context, params object[] args) { - if(args.Length == 0) { + public static void set_threshold(CodeContext/*!*/ context, [NotNone] params object[] args) { + if (args.Length == 0) { throw PythonOps.TypeError("set_threshold() takes at least 1 argument (0 given)"); } - if(args.Length > 3) { + if (args.Length > 3) { throw PythonOps.TypeError("set_threshold() takes at most 3 arguments ({0} given)", args.Length); } - if(args.Any(x => x is double)) { + if (args.Any(x => x is double)) { throw PythonOps.TypeError("integer argument expected, got float"); } - if(!args.All(x => x is int)) { + if (!args.All(x => x is int)) { throw PythonOps.TypeError("an integer is required"); } PythonTuple current = get_threshold(context); - object[] threshold = args.Take(args.Length) + object?[] threshold = args.Take(args.Length) .Concat(current.ToArray().Skip(args.Length)) .ToArray(); SetThresholds(context, PythonTuple.MakeTuple(threshold)); @@ -92,11 +92,11 @@ public static PythonTuple get_threshold(CodeContext/*!*/ context) { return GetThresholds(context); } - public static object[] get_referrers(params object[] objs) { + public static object[] get_referrers([NotNone] params object[] objs) { throw PythonOps.NotImplementedError("gc.get_referrers isn't implemented"); } - public static object[] get_referents(params object[] objs) { + public static object[] get_referents([NotNone] params object[] objs) { throw PythonOps.NotImplementedError("gc.get_referents isn't implemented"); } diff --git a/src/core/IronPython.Modules/marshal.cs b/src/core/IronPython.Modules/marshal.cs index 1841e9a93..48bcb9926 100644 --- a/src/core/IronPython.Modules/marshal.cs +++ b/src/core/IronPython.Modules/marshal.cs @@ -2,6 +2,8 @@ // The .NET Foundation licenses this file to you under the Apache 2.0 License. // See the LICENSE file in the project root for more information. +#nullable enable + using System.Collections.Generic; using IronPython.Runtime; @@ -14,23 +16,23 @@ public static class PythonMarshal { #region Public marshal APIs - public static void dump(CodeContext/*!*/ context, object value, PythonIOModule._IOBase/*!*/ file, int version = PythonMarshal.version) { + public static void dump(CodeContext/*!*/ context, object? value, PythonIOModule._IOBase? file, int version = PythonMarshal.version) { if (file == null) throw PythonOps.TypeError("expected file, found None"); file.write(context, dumps(value, version)); } - public static object load(CodeContext/*!*/ context, PythonIOModule._IOBase/*!*/ file) { + public static object load(CodeContext/*!*/ context, PythonIOModule._IOBase? file) { if (file == null) throw PythonOps.TypeError("expected file, found None"); return MarshalOps.GetObject(FileEnumerator(context, file)); } - public static Bytes dumps(object value, int version = PythonMarshal.version) { + public static Bytes dumps(object? value, int version = PythonMarshal.version) { return Bytes.Make(MarshalOps.GetBytes(value, version)); } - public static object loads([BytesLike]IList bytes) { + public static object loads([BytesLike, NotNone] IList bytes) { return MarshalOps.GetObject(bytes.GetEnumerator()); } diff --git a/src/core/IronPython.Modules/math.Generated.cs b/src/core/IronPython.Modules/math.Generated.cs index 4a2c9a316..af7b6026f 100644 --- a/src/core/IronPython.Modules/math.Generated.cs +++ b/src/core/IronPython.Modules/math.Generated.cs @@ -2,6 +2,8 @@ // The .NET Foundation licenses this file to you under the Apache 2.0 License. // See the LICENSE file in the project root for more information. +#nullable enable + using System; namespace IronPython.Modules { diff --git a/src/core/IronPython.Modules/math.cs b/src/core/IronPython.Modules/math.cs index cde32f792..c2a888bd0 100644 --- a/src/core/IronPython.Modules/math.cs +++ b/src/core/IronPython.Modules/math.cs @@ -2,6 +2,8 @@ // The .NET Foundation licenses this file to you under the Apache 2.0 License. // See the LICENSE file in the project root for more information. +#nullable enable + using System; using System.Collections; using System.Collections.Generic; @@ -9,12 +11,10 @@ using System.Linq; using System.Numerics; -using Microsoft.Scripting; -using Microsoft.Scripting.Utils; - using IronPython.Runtime; using IronPython.Runtime.Operations; -using IronPython.Runtime.Types; + +using Microsoft.Scripting.Utils; [assembly: PythonModule("math", typeof(IronPython.Modules.PythonMath))] namespace IronPython.Modules { @@ -78,7 +78,7 @@ private static double sum(List partials) { return hi; } - public static double fsum(IEnumerable e) { + public static double fsum([NotNone] IEnumerable e) { // msum from https://code.activestate.com/recipes/393090/ var partials = new List(); foreach (var v in e.Cast().Select(o => Converter.ConvertToDouble(o))) { @@ -205,7 +205,7 @@ public static double log(BigInteger value) { return value.Log(); } - public static double log(object value) { + public static double log(object? value) { // CPython tries float first, then double, so we need // an explicit overload which properly matches the order here double val; @@ -227,7 +227,7 @@ public static double log(BigInteger value, double newBase) { return Check(value.Log(newBase)); } - public static double log(object value, double newBase) { + public static double log(object? value, double newBase) { // CPython tries float first, then double, so we need // an explicit overload which properly matches the order here double val; @@ -287,7 +287,7 @@ public static double log10(BigInteger value) { return value.Log10(); } - public static double log10(object value) { + public static double log10(object? value) { // CPython tries float first, then double, so we need // an explicit overload which properly matches the order here double val; @@ -320,7 +320,7 @@ public static double log1p(BigInteger value) { return log(value + BigInteger.One); } - public static double log1p(object value) { + public static double log1p(object? value) { // CPython tries float first, then double, so we need // an explicit overload which properly matches the order here double val; @@ -353,7 +353,7 @@ public static double asinh(double x) { #endif } - public static double asinh(object value) { + public static double asinh(object? value) { // CPython tries float first, then double, so we need // an explicit overload which properly matches the order here double val; @@ -385,7 +385,7 @@ public static double acosh(double x) { #endif } - public static double acosh(object value) { + public static double acosh(object? value) { // CPython tries float first, then double, so we need // an explicit overload which properly matches the order here double val; @@ -420,7 +420,7 @@ public static double atanh(BigInteger value) { } } - public static double atanh(object value) { + public static double atanh(object? value) { // CPython tries float first, then double, so we need // an explicit overload which properly matches the order here double val; @@ -448,7 +448,7 @@ public static double atan2(double v0, double v1) { return Math.Atan2(v0, v1); } - public static object ceil(CodeContext context, object x) { + public static object ceil(CodeContext context, object? x) { object val; if (PythonTypeOps.TryInvokeUnaryOperator(context, x, "__ceil__", out val)) { return val; @@ -508,7 +508,7 @@ public static object factorial(BigInteger value) { return (int)val; } - public static object factorial(object value) { + public static object factorial(object? value) { // CPython tries float first, then double, so we need // an explicit overload which properly matches the order here double val; @@ -519,7 +519,7 @@ public static object factorial(object value) { } } - public static object floor(CodeContext context, object x) { + public static object floor(CodeContext context, object? x) { object val; if (PythonTypeOps.TryInvokeUnaryOperator(context, x, "__floor__", out val)) { return val; @@ -553,8 +553,8 @@ public static double lgamma(double v0) { return Check(v0, MathUtils.LogGamma(v0)); } - public static object trunc(CodeContext/*!*/ context, object value) { - object func; + public static object? trunc(CodeContext/*!*/ context, object? value) { + object? func; if (PythonOps.TryGetBoundAttr(value, "__trunc__", out func)) { return PythonOps.CallWithContext(context, func); } else { @@ -574,7 +574,7 @@ public static bool isinf(BigInteger value) { return false; } - public static bool isinf(object value) { + public static bool isinf(object? value) { // CPython tries float first, then double, so we need // an explicit overload which properly matches the order here double val; @@ -592,7 +592,7 @@ public static bool isnan(BigInteger value) { return false; } - public static bool isnan(object value) { + public static bool isnan(object? value) { // CPython tries float first, then double, so we need // an explicit overload which properly matches the order here double val; @@ -606,7 +606,7 @@ public static double copysign(double x, double y) { return DoubleOps.CopySign(x, y); } - public static double copysign(object x, object y) { + public static double copysign(object? x, object? y) { double val, sign; if (!Converter.TryConvertToDouble(x, out val) || !Converter.TryConvertToDouble(y, out sign)) { @@ -623,10 +623,10 @@ public static object gcd(BigInteger x, BigInteger y) { return res; } - public static object gcd(object x, object y) { + public static object gcd(object? x, object? y) { return gcd(ObjectToBigInteger(x), ObjectToBigInteger(y)); - static BigInteger ObjectToBigInteger(object x) { + static BigInteger ObjectToBigInteger(object? x) { BigInteger a; switch (PythonOps.Index(x)) { case int i: diff --git a/src/core/IronPython.Modules/msvcrt.cs b/src/core/IronPython.Modules/msvcrt.cs index e81c3d119..0550b176f 100644 --- a/src/core/IronPython.Modules/msvcrt.cs +++ b/src/core/IronPython.Modules/msvcrt.cs @@ -2,11 +2,14 @@ // The .NET Foundation licenses this file to you under the Apache 2.0 License. // See the LICENSE file in the project root for more information. +#nullable enable + #if FEATURE_NATIVE using Microsoft.Win32.SafeHandles; using System; using System.ComponentModel; +using System.Diagnostics.CodeAnalysis; using System.IO; using System.Numerics; using System.Reflection; @@ -68,7 +71,7 @@ public static int open_osfhandle(CodeContext context, BigInteger os_handle, int return context.LanguageContext.FileManager.Add(new(stream)); } - private static bool TryGetFileHandle(Stream stream, out object handle) { + private static bool TryGetFileHandle(Stream stream, [NotNullWhen(true)] out object? handle) { if (stream is FileStream) { handle = ((FileStream)stream).SafeFileHandle.DangerousGetHandle().ToPython(); return true; @@ -98,7 +101,7 @@ private static bool TryGetFileHandle(Stream stream, out object handle) { public static object get_osfhandle(CodeContext context, int fd) { var sbox = context.LanguageContext.FileManager.GetStreams(fd); - object handle; + object? handle; if (TryGetFileHandle(sbox.ReadStream, out handle)) return handle; return -1; diff --git a/src/core/IronPython.Modules/nt.cs b/src/core/IronPython.Modules/nt.cs index 9746769d9..7a235f014 100644 --- a/src/core/IronPython.Modules/nt.cs +++ b/src/core/IronPython.Modules/nt.cs @@ -5,6 +5,7 @@ #nullable enable using Microsoft.Win32.SafeHandles; + using System; using System.Collections; using System.Collections.Generic; @@ -74,7 +75,7 @@ static PythonNT() { } [SpecialName] - public static void PerformModuleReload([NotNone] PythonContext context, [NotNone] PythonDictionary dict) { + public static void PerformModuleReload(PythonContext context, PythonDictionary dict) { var have_functions = new PythonList(); if (Environment.OSVersion.Platform == PlatformID.Win32NT) { have_functions.Add("MS_WINDOWS"); @@ -225,7 +226,7 @@ public static void abort() { /// R_OK | W_OK | X_OK: Check for the specific permissions. Only W_OK is respected. /// [Documentation("access(path, mode, *, dir_fd=None, effective_ids=False, follow_symlinks=True)")] - public static bool access(CodeContext/*!*/ context, [NotNone] string path, int mode, [ParamDictionary, NotNone] IDictionary kwargs) { + public static bool access(CodeContext/*!*/ context, [NotNone] string path, int mode, [ParamDictionary] IDictionary kwargs) { if (path == null) throw PythonOps.TypeError("expected string, got None"); foreach (var pair in kwargs) { @@ -274,11 +275,11 @@ public static bool access(CodeContext/*!*/ context, [NotNone] string path, int m } [Documentation("")] - public static bool access(CodeContext context, [NotNone] Bytes path, int mode, [ParamDictionary, NotNone] IDictionary kwargs) + public static bool access(CodeContext context, [NotNone] Bytes path, int mode, [ParamDictionary] IDictionary kwargs) => access(context, path.ToFsString(context), mode, kwargs); [Documentation("")] - public static bool access(CodeContext context, object? path, int mode, [ParamDictionary, NotNone] IDictionary kwargs) + public static bool access(CodeContext context, object? path, int mode, [ParamDictionary] IDictionary kwargs) => access(context, ConvertToFsString(context, path, nameof(path)), mode, kwargs); #if FEATURE_FILESYSTEM @@ -302,7 +303,7 @@ public static void chdir(CodeContext context, object? path) => chdir(ConvertToFsString(context, path, nameof(path))); [Documentation("chmod(path, mode, *, dir_fd=None, follow_symlinks=True)")] - public static void chmod([NotNone] string path, int mode, [ParamDictionary, NotNone] IDictionary kwargs) { + public static void chmod([NotNone] string path, int mode, [ParamDictionary] IDictionary kwargs) { foreach (var key in kwargs.Keys) { switch (key) { case "dir_fd": @@ -333,11 +334,11 @@ public static void chmod([NotNone] string path, int mode, [ParamDictionary, NotN } [Documentation("")] - public static void chmod(CodeContext context, [NotNone] Bytes path, int mode, [ParamDictionary, NotNone] IDictionary kwargs) + public static void chmod(CodeContext context, [NotNone] Bytes path, int mode, [ParamDictionary] IDictionary kwargs) => chmod(path.ToFsString(context), mode, kwargs); [Documentation("")] - public static void chmod(CodeContext context, object? path, int mode, [ParamDictionary, NotNone] IDictionary kwargs) + public static void chmod(CodeContext context, object? path, int mode, [ParamDictionary] IDictionary kwargs) => chmod(ConvertToFsString(context, path, nameof(path)), mode, kwargs); #endif @@ -497,7 +498,7 @@ public static int getpid() { #endif [Documentation("link(src, dst, *, src_dir_fd=None, dst_dir_fd=None, follow_symlinks=True)")] - public static void link([NotNone] string src, [NotNone] string dst, [ParamDictionary, NotNone] IDictionary kwargs) { + public static void link([NotNone] string src, [NotNone] string dst, [ParamDictionary] IDictionary kwargs) { foreach (var key in kwargs.Keys) { switch (key) { case "src_dir_fd": @@ -531,11 +532,11 @@ public static bool isatty(CodeContext context, int fd) { } [Documentation("")] - public static void link(CodeContext context, [NotNone] Bytes src, [NotNone] Bytes dst, [ParamDictionary, NotNone] IDictionary kwargs) + public static void link(CodeContext context, [NotNone] Bytes src, [NotNone] Bytes dst, [ParamDictionary] IDictionary kwargs) => link(src.ToFsString(context), dst.ToFsString(context), kwargs); [Documentation("")] - public static void link(CodeContext context, object? src, object? dst, [ParamDictionary, NotNone] IDictionary kwargs) + public static void link(CodeContext context, object? src, object? dst, [ParamDictionary] IDictionary kwargs) => link(ConvertToFsString(context, src, nameof(src)), ConvertToFsString(context, dst, nameof(dst)), kwargs); @@ -590,7 +591,7 @@ public static BigInteger lseek(CodeContext context, int fd, long offset, int whe "Like stat(), but do not follow symbolic links.\n" + "Equivalent to calling stat(...) with follow_symlinks=False.")] [LightThrowing] - public static object lstat([NotNone] string path, [ParamDictionary, NotNone] IDictionary kwargs) { + public static object lstat([NotNone] string path, [ParamDictionary] IDictionary kwargs) { if (kwargs.ContainsKey("follow_symlinks")) throw PythonOps.TypeError("'follow_symlinks' is an invalid keyword argument for lstat(...)"); @@ -599,11 +600,11 @@ public static object lstat([NotNone] string path, [ParamDictionary, NotNone] IDi } [LightThrowing, Documentation("")] - public static object lstat(CodeContext context, [NotNone] Bytes path, [ParamDictionary, NotNone] IDictionary kwargs) + public static object lstat(CodeContext context, [NotNone] Bytes path, [ParamDictionary] IDictionary kwargs) => lstat(path.ToFsString(context), kwargs); [LightThrowing, Documentation("")] - public static object lstat(CodeContext context, object? path, [ParamDictionary, NotNone] IDictionary kwargs) + public static object lstat(CodeContext context, object? path, [ParamDictionary] IDictionary kwargs) => lstat(ConvertToFsString(context, path, nameof(path)), kwargs); [PythonType] @@ -706,7 +707,7 @@ private static IEnumerable ScandirHelper(CodeContext context, st #if FEATURE_NATIVE [Documentation("symlink(src, dst, target_is_directory=False, *, dir_fd=None)")] - public static void symlink([NotNone] string src, [NotNone] string dst, [ParamDictionary, NotNone] IDictionary kwargs, [NotNone] params object[] args) { + public static void symlink([NotNone] string src, [NotNone] string dst, [ParamDictionary] IDictionary kwargs, [NotNone] params object[] args) { var numArgs = args.Length; CheckOptionalArgsCount(numRegParms: 2, numOptPosParms: 1, numKwParms: 1, numArgs, kwargs.Count); @@ -736,11 +737,11 @@ public static void symlink([NotNone] string src, [NotNone] string dst, [ParamDic } [Documentation("")] - public static void symlink(CodeContext context, [NotNone] Bytes src, [NotNone] Bytes dst, [ParamDictionary, NotNone] IDictionary kwargs, [NotNone] params object[] args) + public static void symlink(CodeContext context, [NotNone] Bytes src, [NotNone] Bytes dst, [ParamDictionary] IDictionary kwargs, [NotNone] params object[] args) => symlink(src.ToFsString(context), dst.ToFsString(context), kwargs, args); [Documentation("")] - public static void symlink(CodeContext context, object? src, object? dst, [ParamDictionary, NotNone] IDictionary kwargs, [NotNone] params object[] args) + public static void symlink(CodeContext context, object? src, object? dst, [ParamDictionary] IDictionary kwargs, [NotNone] params object[] args) => symlink(ConvertToFsString(context, src, nameof(src)), ConvertToFsString(context, dst, nameof(dst)), kwargs, args); [PythonType] @@ -778,7 +779,7 @@ public override string __repr__(CodeContext context) { #if FEATURE_FILESYSTEM [Documentation("mkdir(path, mode=511, *, dir_fd=None)")] - public static void mkdir([NotNone] string path, [ParamDictionary, NotNone] IDictionary kwargs, [NotNone] params object[] args) { + public static void mkdir([NotNone] string path, [ParamDictionary] IDictionary kwargs, [NotNone] params object[] args) { var numArgs = args.Length; CheckOptionalArgsCount(numRegParms: 1, numOptPosParms: 1, numKwParms: 1, numArgs, kwargs.Count); @@ -808,11 +809,11 @@ public static void mkdir([NotNone] string path, [ParamDictionary, NotNone] IDict } [Documentation("")] - public static void mkdir(CodeContext context, [NotNone] Bytes path, [ParamDictionary, NotNone] IDictionary kwargs, [NotNone] params object[] args) + public static void mkdir(CodeContext context, [NotNone] Bytes path, [ParamDictionary] IDictionary kwargs, [NotNone] params object[] args) => mkdir(path.ToFsString(context), kwargs, args); [Documentation("")] - public static void mkdir(CodeContext context, object? path, [ParamDictionary, NotNone] IDictionary kwargs, [NotNone] params object[] args) + public static void mkdir(CodeContext context, object? path, [ParamDictionary] IDictionary kwargs, [NotNone] params object[] args) => mkdir(ConvertToFsString(context, path, nameof(path)), kwargs, args); [Documentation(""" @@ -825,7 +826,7 @@ public static void mkdir(CodeContext context, object? path, [ParamDictionary, No dir_fd may not be implemented on your platform. If it is unavailable, using it will raise a NotImplementedError. """)] - public static object open(CodeContext/*!*/ context, [NotNone] string path, int flags, [ParamDictionary, NotNone] IDictionary kwargs, [NotNone] params object[] args) { + public static object open(CodeContext/*!*/ context, [NotNone] string path, int flags, [ParamDictionary] IDictionary kwargs, [NotNone] params object[] args) { var numArgs = args.Length; CheckOptionalArgsCount(numRegParms: 2, numOptPosParms: 1, numKwParms: 1, numArgs, kwargs.Count); @@ -906,11 +907,11 @@ public static object open(CodeContext/*!*/ context, [NotNone] string path, int f } [Documentation("")] - public static object open(CodeContext context, [NotNone] Bytes path, int flags, [ParamDictionary, NotNone] IDictionary kwargs, [NotNone] params object[] args) + public static object open(CodeContext context, [NotNone] Bytes path, int flags, [ParamDictionary] IDictionary kwargs, [NotNone] params object[] args) => open(context, path.ToFsString(context), flags, kwargs, args); [Documentation("")] - public static object open(CodeContext context, object? path, int flags, [ParamDictionary, NotNone] IDictionary kwargs, [NotNone] params object[] args) + public static object open(CodeContext context, object? path, int flags, [ParamDictionary] IDictionary kwargs, [NotNone] params object[] args) => open(context, ConvertToFsString(context, path, nameof(path)), flags, kwargs, args); private static FileOptions FileOptionsFromFlags(int flag) { @@ -983,7 +984,7 @@ public static Bytes read(CodeContext/*!*/ context, int fd, int buffersize) { } [Documentation("rename(src, dst, *, src_dir_fd=None, dst_dir_fd=None)")] - public static void rename([NotNone] string src, [NotNone] string dst, [ParamDictionary, NotNone] IDictionary kwargs) { + public static void rename([NotNone] string src, [NotNone] string dst, [ParamDictionary] IDictionary kwargs) { foreach (var key in kwargs.Keys) { switch (key) { case "src_dir_fd": @@ -1011,11 +1012,11 @@ public static void rename([NotNone] string src, [NotNone] string dst, [ParamDict } [Documentation("")] - public static void rename(CodeContext context, [NotNone] Bytes src, [NotNone] Bytes dst, [ParamDictionary, NotNone] IDictionary kwargs) + public static void rename(CodeContext context, [NotNone] Bytes src, [NotNone] Bytes dst, [ParamDictionary] IDictionary kwargs) => rename(src.ToFsString(context), dst.ToFsString(context), kwargs); [Documentation("")] - public static void rename(CodeContext context, object? src, object? dst, [ParamDictionary, NotNone] IDictionary kwargs) + public static void rename(CodeContext context, object? src, object? dst, [ParamDictionary] IDictionary kwargs) => rename(ConvertToFsString(context, src, nameof(src)), ConvertToFsString(context, dst, nameof(dst)), kwargs); private const uint MOVEFILE_REPLACE_EXISTING = 0x01; @@ -1024,7 +1025,7 @@ public static void rename(CodeContext context, object? src, object? dst, [ParamD private static extern bool MoveFileEx(string src, string dst, uint flags); [Documentation("replace(src, dst, *, src_dir_fd=None, dst_dir_fd=None)")] - public static void replace([NotNone] string src, [NotNone] string dst, [ParamDictionary, NotNone] IDictionary kwargs) { + public static void replace([NotNone] string src, [NotNone] string dst, [ParamDictionary] IDictionary kwargs) { foreach (var key in kwargs.Keys) { switch (key) { case "src_dir_fd": @@ -1048,16 +1049,16 @@ public static void replace([NotNone] string src, [NotNone] string dst, [ParamDic } [Documentation("")] - public static void replace(CodeContext context, [NotNone] Bytes src, [NotNone] Bytes dst, [ParamDictionary, NotNone] IDictionary kwargs) + public static void replace(CodeContext context, [NotNone] Bytes src, [NotNone] Bytes dst, [ParamDictionary] IDictionary kwargs) => replace(src.ToFsString(context), dst.ToFsString(context), kwargs); [Documentation("")] - public static void replace(CodeContext context, object? src, object? dst, [ParamDictionary, NotNone] IDictionary kwargs) + public static void replace(CodeContext context, object? src, object? dst, [ParamDictionary] IDictionary kwargs) => replace(ConvertToFsString(context, src, nameof(src)), ConvertToFsString(context, dst, nameof(dst)), kwargs); [Documentation("rmdir(path, *, dir_fd=None)")] - public static void rmdir([NotNone] string path, [ParamDictionary, NotNone] IDictionary kwargs) { + public static void rmdir([NotNone] string path, [ParamDictionary] IDictionary kwargs) { foreach (var key in kwargs.Keys) { switch (key) { case "dir_fd": @@ -1075,11 +1076,11 @@ public static void rmdir([NotNone] string path, [ParamDictionary, NotNone] IDict } [Documentation("")] - public static void rmdir(CodeContext context, [NotNone] Bytes path, [ParamDictionary, NotNone] IDictionary kwargs) + public static void rmdir(CodeContext context, [NotNone] Bytes path, [ParamDictionary] IDictionary kwargs) => rmdir(path.ToFsString(context), kwargs); [Documentation("")] - public static void rmdir(CodeContext context, object? path, [ParamDictionary, NotNone] IDictionary kwargs) + public static void rmdir(CodeContext context, object? path, [ParamDictionary] IDictionary kwargs) => rmdir(ConvertToFsString(context, path, nameof(path)), kwargs); #if FEATURE_PROCESS @@ -1430,7 +1431,7 @@ private struct BY_HANDLE_FILE_INFORMATION { [Documentation("stat(path, *, dir_fd=None, follow_symlinks=True) -> stat_result\n\n" + "Gathers statistics about the specified file or directory")] [LightThrowing] - public static object stat([NotNone] string path, [ParamDictionary, NotNone] IDictionary kwargs) { + public static object stat([NotNone] string path, [ParamDictionary] IDictionary kwargs) { if (path == null) { return LightExceptions.Throw(PythonOps.TypeError("expected string, got NoneType")); } @@ -1504,11 +1505,11 @@ public static object stat([NotNone] string path, [ParamDictionary, NotNone] IDic } [LightThrowing, Documentation("")] - public static object stat(CodeContext context, [NotNone] Bytes path, [ParamDictionary, NotNone] IDictionary dict) + public static object stat(CodeContext context, [NotNone] Bytes path, [ParamDictionary] IDictionary dict) => stat(path.ToFsString(context), dict); [LightThrowing, Documentation("")] - public static object stat(CodeContext context, object? path, [ParamDictionary, NotNone] IDictionary dict) { + public static object stat(CodeContext context, object? path, [ParamDictionary] IDictionary dict) { if (PythonOps.TryToIndex(path, out BigInteger bi)) { if (bi.AsInt32(out int i)) { return stat(context, i); @@ -1646,7 +1647,7 @@ public static object times() { } [Documentation("remove(path, *, dir_fd=None)")] - public static void remove([NotNone] string path, [ParamDictionary, NotNone] IDictionary kwargs) { + public static void remove([NotNone] string path, [ParamDictionary] IDictionary kwargs) { foreach (var key in kwargs.Keys) { switch (key) { case "dir_fd": @@ -1660,23 +1661,23 @@ public static void remove([NotNone] string path, [ParamDictionary, NotNone] IDic } [Documentation("")] - public static void remove(CodeContext context, [NotNone] Bytes path, [ParamDictionary, NotNone] IDictionary kwargs) + public static void remove(CodeContext context, [NotNone] Bytes path, [ParamDictionary] IDictionary kwargs) => remove(path.ToFsString(context), kwargs); [Documentation("")] - public static void remove(CodeContext context, object? path, [ParamDictionary, NotNone] IDictionary kwargs) + public static void remove(CodeContext context, object? path, [ParamDictionary] IDictionary kwargs) => remove(ConvertToFsString(context, path, nameof(path)), kwargs); [Documentation("unlink(path, *, dir_fd=None)")] - public static void unlink([NotNone] string path, [ParamDictionary, NotNone] IDictionary kwargs) + public static void unlink([NotNone] string path, [ParamDictionary] IDictionary kwargs) => remove(path, kwargs); [Documentation("")] - public static void unlink(CodeContext context, [NotNone] Bytes path, [ParamDictionary, NotNone] IDictionary kwargs) + public static void unlink(CodeContext context, [NotNone] Bytes path, [ParamDictionary] IDictionary kwargs) => unlink(path.ToFsString(context), kwargs); [Documentation("")] - public static void unlink(CodeContext context, object? path, [ParamDictionary, NotNone] IDictionary kwargs) + public static void unlink(CodeContext context, object? path, [ParamDictionary] IDictionary kwargs) => unlink(ConvertToFsString(context, path, nameof(path)), kwargs); private static void UnlinkWorker(string path) { @@ -1739,7 +1740,7 @@ public static int umask(CodeContext/*!*/ context, object? mask) #if FEATURE_FILESYSTEM [Documentation("utime(path, times=None, *[, ns], dir_fd=None, follow_symlinks=True)")] - public static void utime([NotNone] string path, [ParamDictionary, NotNone] IDictionary kwargs, [NotNone] params object[] args) { + public static void utime([NotNone] string path, [ParamDictionary] IDictionary kwargs, [NotNone] params object[] args) { var numArgs = args.Length; CheckOptionalArgsCount(numRegParms: 1, numOptPosParms: 1, numKwParms: 3, numArgs, kwargs.Count); @@ -1813,11 +1814,11 @@ public static void utime([NotNone] string path, [ParamDictionary, NotNone] IDict } [Documentation("")] - public static void utime(CodeContext context, [NotNone] Bytes path, [ParamDictionary, NotNone] IDictionary kwargs, [NotNone] params object[] args) + public static void utime(CodeContext context, [NotNone] Bytes path, [ParamDictionary] IDictionary kwargs, [NotNone] params object[] args) => utime(path.ToFsString(context), kwargs, args); [Documentation("")] - public static void utime(CodeContext context, object? path, [ParamDictionary, NotNone] IDictionary kwargs, [NotNone] params object[] args) + public static void utime(CodeContext context, object? path, [ParamDictionary] IDictionary kwargs, [NotNone] params object[] args) => utime(ConvertToFsString(context, path, nameof(path)), kwargs, args); #endif diff --git a/src/core/IronPython.Modules/pwd.cs b/src/core/IronPython.Modules/pwd.cs index 1eb3b015b..8b8087268 100644 --- a/src/core/IronPython.Modules/pwd.cs +++ b/src/core/IronPython.Modules/pwd.cs @@ -2,22 +2,22 @@ // The .NET Foundation licenses this file to you under the Apache 2.0 License. // See the LICENSE file in the project root for more information. +#nullable enable + #if FEATURE_NATIVE using System; +using System.Numerics; using System.Runtime.InteropServices; -using Microsoft.Scripting.Runtime; - -using IronPython; using IronPython.Runtime; using IronPython.Runtime.Operations; -using System.Numerics; +using Microsoft.Scripting.Runtime; [assembly: PythonModule("pwd", typeof(IronPython.Modules.PythonPwd), PlatformsAttribute.PlatformFamily.Unix)] namespace IronPython.Modules { - + public static class PythonPwd { public const string __doc__ = @"This module provides access to the Unix password database. It is available on all Unix versions. @@ -78,25 +78,25 @@ internal struct_passwd(string pw_name, string pw_passwd, int pw_uid, int pw_gid, } [Documentation("user name")] - public string pw_name => (string)_data[0]; + public string pw_name => (string)_data[0]!; [Documentation("password")] - public string pw_passwd => (string)_data[1]; + public string pw_passwd => (string)_data[1]!; [Documentation("user id")] - public int pw_uid => (int)_data[2]; + public int pw_uid => (int)_data[2]!; [Documentation("group id")] - public int pw_gid => (int)_data[3]; + public int pw_gid => (int)_data[3]!; [Documentation("real name")] - public string pw_gecos => (string)_data[4]; + public string pw_gecos => (string)_data[4]!; [Documentation("home directory")] - public string pw_dir => (string)_data[5]; + public string pw_dir => (string)_data[5]!; [Documentation("shell program")] - public string pw_shell => (string)_data[6]; + public string pw_shell => (string)_data[6]!; public override string/*!*/ __repr__(CodeContext/*!*/ context) { return $"pwd.struct_passwd(pw_name='{pw_name}', pw_passwd='{pw_passwd}', pw_uid={pw_uid}, pw_gid={pw_gid}, pw_gecos='{pw_gecos}', pw_dir='{pw_dir}', pw_shell='{pw_shell}')"; @@ -104,7 +104,7 @@ internal struct_passwd(string pw_name, string pw_passwd, int pw_uid, int pw_gid, } private static struct_passwd Make(IntPtr pwd) { - struct_passwd res = null; + struct_passwd? res = null; if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX)) { passwd_osx p = Marshal.PtrToStructure(pwd); res = new struct_passwd(p.pw_name, p.pw_passwd, p.pw_uid, p.pw_gid, p.pw_gecos, p.pw_dir, p.pw_shell); @@ -117,7 +117,7 @@ private static struct_passwd Make(IntPtr pwd) { } [Documentation("Return the password database entry for the given numeric user ID.")] - public static struct_passwd getpwuid(object uid) { + public static struct_passwd getpwuid(object? uid) { uid = PythonOps.Index(uid); if (uid is BigInteger bi) { @@ -130,20 +130,20 @@ public static struct_passwd getpwuid(object uid) { if (uid is int id) { var pwd = _getpwuid(id); - if(pwd == IntPtr.Zero) { + if (pwd == IntPtr.Zero) { throw PythonOps.KeyError($"getpwuid(): uid not found: {id}"); } - return Make(pwd); + return Make(pwd); } throw PythonOps.TypeError($"integer argument expected, got {PythonOps.GetPythonTypeName(uid)}"); } [Documentation("Return the password database entry for the given user name.")] - public static struct_passwd getpwnam(string name) { + public static struct_passwd getpwnam([NotNone] string name) { var pwd = _getpwnam(name); - if(pwd == IntPtr.Zero) { + if (pwd == IntPtr.Zero) { throw PythonOps.KeyError($"getpwname(): name not found: {name}"); } @@ -155,31 +155,32 @@ public static PythonList getpwall() { var res = new PythonList(); setpwent(); IntPtr val = getpwent(); - while(val != IntPtr.Zero) { + while (val != IntPtr.Zero) { res.Add(Make(val)); val = getpwent(); } - + return res; } #region P/Invoke Declarations - [DllImport("libc", EntryPoint="getpwuid", CallingConvention=CallingConvention.Cdecl)] + [DllImport("libc", EntryPoint = "getpwuid", CallingConvention = CallingConvention.Cdecl)] private static extern IntPtr _getpwuid(int uid); - [DllImport("libc", EntryPoint="getpwnam", CallingConvention=CallingConvention.Cdecl)] + [DllImport("libc", EntryPoint = "getpwnam", CallingConvention = CallingConvention.Cdecl)] private static extern IntPtr _getpwnam([MarshalAs(UnmanagedType.LPStr)] string name); - [DllImport("libc", CallingConvention=CallingConvention.Cdecl)] + [DllImport("libc", CallingConvention = CallingConvention.Cdecl)] private static extern void setpwent(); - [DllImport("libc", CallingConvention=CallingConvention.Cdecl)] + [DllImport("libc", CallingConvention = CallingConvention.Cdecl)] private static extern IntPtr getpwent(); #endregion } } + #endif diff --git a/src/core/IronPython.Modules/pyexpat.cs b/src/core/IronPython.Modules/pyexpat.cs index 0e68c8a06..0b7e9d8e5 100644 --- a/src/core/IronPython.Modules/pyexpat.cs +++ b/src/core/IronPython.Modules/pyexpat.cs @@ -229,22 +229,22 @@ public static string ErrorString(int errno) { return null; } - public static object ParserCreate(CodeContext context, [ParamDictionary]IDictionary kwArgs\u00F8, params object[] args\u00F8) { - var numArgs = argsø.Length + kwArgsø.Count; + public static object ParserCreate(CodeContext context, [ParamDictionary] IDictionary kwArgs, [NotNone] params object[] args) { + var numArgs = args.Length + kwArgs.Count; if (numArgs > 3) throw PythonOps.TypeError($"ParserCreate() takes at most 3 arguments ({numArgs} given)"); - object encoding = argsø.Length > 0 ? argsø[0] : null; - object namespace_separator = argsø.Length > 1 ? argsø[1] : null; - object intern = argsø.Length > 2 ? argsø[0] : new PythonDictionary(); + object encoding = args.Length > 0 ? args[0] : null; + object namespace_separator = args.Length > 1 ? args[1] : null; + object intern = args.Length > 2 ? args[0] : new PythonDictionary(); - foreach (var pair in kwArgsø) { + foreach (var pair in kwArgs) { switch (pair.Key) { case nameof(encoding): - if (argsø.Length > 0) throw PythonOps.TypeError($"Argument given by name('{nameof(encoding)}') and position(1)"); + if (args.Length > 0) throw PythonOps.TypeError($"Argument given by name('{nameof(encoding)}') and position(1)"); encoding = pair.Value; break; case nameof(namespace_separator): - if (argsø.Length > 1) throw PythonOps.TypeError($"Argument given by name('{nameof(namespace_separator)}') and position(2)"); + if (args.Length > 1) throw PythonOps.TypeError($"Argument given by name('{nameof(namespace_separator)}') and position(2)"); namespace_separator = pair.Value; break; case nameof(intern): diff --git a/src/core/IronPython.Modules/re.cs b/src/core/IronPython.Modules/re.cs index bcc9e8baf..718dd709a 100644 --- a/src/core/IronPython.Modules/re.cs +++ b/src/core/IronPython.Modules/re.cs @@ -34,7 +34,6 @@ namespace IronPython.Modules { public static class PythonRegex { private static CacheDict _cachedPatterns = new CacheDict(100); -#pragma warning disable IPY01 // Parameter which is marked not nullable does not have the NotNullAttribute [SpecialName] public static void PerformModuleReload(PythonContext/*!*/ context, PythonDictionary/*!*/ dict) { context.EnsureModuleException("reerror", dict, "error", "re"); @@ -44,7 +43,6 @@ public static void PerformModuleReload(PythonContext/*!*/ context, PythonDiction PythonOps.CallWithContext(context.SharedContext, pickle, DynamicHelpers.GetPythonTypeFromType(typeof(Pattern)), dict["_pickle"]); } } -#pragma warning restore IPY01 // Parameter which is marked not nullable does not have the NotNullAttribute private static readonly Random r = new Random(DateTime.Now.Millisecond); diff --git a/src/core/IronPython.Modules/spwd.cs b/src/core/IronPython.Modules/spwd.cs index 9445f7341..08893cf30 100644 --- a/src/core/IronPython.Modules/spwd.cs +++ b/src/core/IronPython.Modules/spwd.cs @@ -2,21 +2,21 @@ // The .NET Foundation licenses this file to you under the Apache 2.0 License. // See the LICENSE file in the project root for more information. +#nullable enable + #if FEATURE_NATIVE using System; using System.Runtime.InteropServices; -using Microsoft.Scripting.Runtime; - using IronPython.Runtime; using IronPython.Runtime.Operations; -using System.Numerics; +using Microsoft.Scripting.Runtime; [assembly: PythonModule("spwd", typeof(IronPython.Modules.PythonSpwd), PlatformsAttribute.PlatformFamily.Unix)] namespace IronPython.Modules { - + public static class PythonSpwd { public const string __doc__ = @"This module provides access to the Unix shadow password database. It is available on various Unix versions. @@ -41,7 +41,7 @@ private struct spwd { public int sp_inact; public int sp_expire; public int sp_flag; - }; + }; [PythonType("struct_spwd")] [Documentation(@"spwd.struct_spwd: Results from getsp*() routines. @@ -54,35 +54,35 @@ public class struct_spwd : PythonTuple { private const int LENGTH = 9; internal struct_spwd(string sp_nam, string sp_pwd, int sp_lstchg, int sp_min, int sp_max, int sp_warn, int sp_inact, int sp_expire, int sp_flag) : - base(new object[] { sp_nam ,sp_pwd, sp_lstchg, sp_min, sp_max, sp_warn, sp_inact, sp_expire, sp_flag }) { + base(new object[] { sp_nam, sp_pwd, sp_lstchg, sp_min, sp_max, sp_warn, sp_inact, sp_expire, sp_flag }) { } [Documentation("login name")] - public string sp_nam => (string)_data[0]; + public string sp_nam => (string)_data[0]!; [Documentation("encrypted password")] - public string sp_pwd => (string)_data[1]; + public string sp_pwd => (string)_data[1]!; [Documentation("date of last change")] - public int sp_lstchg => (int)_data[2]; + public int sp_lstchg => (int)_data[2]!; [Documentation("min #days between changes")] - public int sp_min => (int)_data[3]; + public int sp_min => (int)_data[3]!; [Documentation("max #days between changes")] - public int sp_max => (int)_data[4]; + public int sp_max => (int)_data[4]!; [Documentation("#days before pw expires to warn user about it")] - public int sp_warn => (int)_data[5]; + public int sp_warn => (int)_data[5]!; [Documentation("#days after pw expires until account is disabled")] - public int sp_inact => (int)_data[6]; + public int sp_inact => (int)_data[6]!; [Documentation("#days since 1970-01-01 when account expires")] - public int sp_expire => (int)_data[7]; + public int sp_expire => (int)_data[7]!; [Documentation("reserved")] - public int sp_flag => (int)_data[8]; + public int sp_flag => (int)_data[8]!; public override string/*!*/ __repr__(CodeContext/*!*/ context) { return $"spwd.struct_spwd(sp_name='{sp_nam}', sp_pwd='{sp_pwd}', sp_lstchg={sp_lstchg}, sp_min={sp_min}, sp_max={sp_max}, sp_warn={sp_warn}, sp_inact={sp_inact}, sp_expire={sp_expire}, sp_flag={sp_flag})"; @@ -95,9 +95,9 @@ private static struct_spwd Make(IntPtr pwd) { } [Documentation("Return the shadow password database entry for the given user name.")] - public static struct_spwd getspnam(string name) { + public static struct_spwd getspnam([NotNone] string name) { var pwd = _getspnam(name); - if(pwd == IntPtr.Zero) { + if (pwd == IntPtr.Zero) { throw PythonOps.KeyError($"getspnam(): name not found"); } @@ -109,28 +109,29 @@ public static PythonList getspall() { var res = new PythonList(); setspent(); IntPtr val = getspent(); - while(val != IntPtr.Zero) { + while (val != IntPtr.Zero) { res.Add(Make(val)); val = getspent(); } - + return res; } #region P/Invoke Declarations - [DllImport("libc", EntryPoint="getspnam", CallingConvention=CallingConvention.Cdecl)] + [DllImport("libc", EntryPoint = "getspnam", CallingConvention = CallingConvention.Cdecl)] private static extern IntPtr _getspnam([MarshalAs(UnmanagedType.LPStr)] string name); - [DllImport("libc", CallingConvention=CallingConvention.Cdecl)] + [DllImport("libc", CallingConvention = CallingConvention.Cdecl)] private static extern void setspent(); - [DllImport("libc", CallingConvention=CallingConvention.Cdecl)] + [DllImport("libc", CallingConvention = CallingConvention.Cdecl)] private static extern IntPtr getspent(); #endregion } } + #endif diff --git a/src/core/IronPython.Modules/termios.cs b/src/core/IronPython.Modules/termios.cs index ea5972921..63ee23e19 100644 --- a/src/core/IronPython.Modules/termios.cs +++ b/src/core/IronPython.Modules/termios.cs @@ -31,11 +31,9 @@ public static class PythonTermios { public const string __doc__ = "Stub of termios, just enough to support module tty."; // and also prompt_toolkit.terminal.vt100_input -#pragma warning disable IPY01 // Parameter which is marked not nullable does not have the NotNullAttribute [SpecialName] public static void PerformModuleReload(PythonContext context, PythonDictionary dict) => context.EnsureModuleException("termioserror", dict, "error", "termios"); -#pragma warning restore IPY01 // Parameter which is marked not nullable does not have the NotNullAttribute #region Generated TIOC Commands diff --git a/src/core/IronPython.Modules/time.cs b/src/core/IronPython.Modules/time.cs index 806efd26c..7a9598692 100644 --- a/src/core/IronPython.Modules/time.cs +++ b/src/core/IronPython.Modules/time.cs @@ -52,13 +52,11 @@ public static class PythonTime { public const string __doc__ = "This module provides various functions to manipulate time values."; -#pragma warning disable IPY01 // Parameter which is marked not nullable does not have the NotNullAttribute [SpecialName] public static void PerformModuleReload(PythonContext/*!*/ context, PythonDictionary/*!*/ dict) { // we depend on locale, it needs to be initialized PythonLocale.EnsureLocaleInitialized(context); } -#pragma warning restore IPY01 // Parameter which is marked not nullable does not have the NotNullAttribute static PythonTime() { // altzone, timezone are offsets from UTC in seconds, so they always fit in the diff --git a/src/core/IronPython.Modules/winsound.cs b/src/core/IronPython.Modules/winsound.cs index 045b99124..3231430cb 100644 --- a/src/core/IronPython.Modules/winsound.cs +++ b/src/core/IronPython.Modules/winsound.cs @@ -2,12 +2,11 @@ // The .NET Foundation licenses this file to you under the Apache 2.0 License. // See the LICENSE file in the project root for more information. -#if FEATURE_NATIVE - #nullable enable +#if FEATURE_NATIVE + using System; -using System.Collections.Generic; using System.Linq; using System.Runtime.InteropServices; using System.Runtime.Versioning; diff --git a/src/core/IronPython.Modules/xxsubtype.cs b/src/core/IronPython.Modules/xxsubtype.cs index 8980fc8c1..1fadc835a 100644 --- a/src/core/IronPython.Modules/xxsubtype.cs +++ b/src/core/IronPython.Modules/xxsubtype.cs @@ -2,17 +2,16 @@ // The .NET Foundation licenses this file to you under the Apache 2.0 License. // See the LICENSE file in the project root for more information. -using System; using System.Collections.Generic; -using Microsoft.Scripting; - using IronPython.Runtime; using IronPython.Runtime.Operations; using IronPython.Runtime.Types; +using Microsoft.Scripting; + [assembly: PythonModule("xxsubtype", typeof(IronPython.Modules.xxsubtype))] -namespace IronPython.Modules { +namespace IronPython.Modules { /// /// Samples on how to subtype built-in types from C# /// @@ -50,12 +49,12 @@ public void setstate(int value) { state = value; } - public static object staticmeth([ParamDictionary]IDictionary dict, params object[] args) { + public static object staticmeth([ParamDictionary] IDictionary dict, [NotNone] params object[] args) { return PythonTuple.MakeTuple(null, PythonTuple.MakeTuple(args), dict); } [ClassMethod] - public static object classmeth(PythonType cls, [ParamDictionary]IDictionary dict, params object[] args) { + public static object classmeth(PythonType cls, [ParamDictionary] IDictionary dict, [NotNone] params object[] args) { return PythonTuple.MakeTuple(cls, PythonTuple.MakeTuple(args), dict); } } diff --git a/src/core/IronPython.Modules/zipimport.cs b/src/core/IronPython.Modules/zipimport.cs index f1d97b0d2..7b120f3c7 100644 --- a/src/core/IronPython.Modules/zipimport.cs +++ b/src/core/IronPython.Modules/zipimport.cs @@ -1,4 +1,8 @@ -using System; +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the Apache 2.0 License. +// See the LICENSE file in the project root for more information. + +using System; using System.IO; using System.Collections.Generic; using System.Runtime.CompilerServices; @@ -194,7 +198,7 @@ fully qualified (dotted) module name. It returns the zipimporter The optional 'path' argument is ignored -- it's there for compatibility with the importer protocol.")] public object find_module(CodeContext/*!*/ context, string fullname, - params object[] args) { + [NotNone] params object[] args) { // there could be a path item in the args, but it is not used ModuleStatus info = GetModuleInfo(context, fullname); diff --git a/src/core/IronPython/Modules/Builtin.cs b/src/core/IronPython/Modules/Builtin.cs index 3131022e7..250a5fcb3 100644 --- a/src/core/IronPython/Modules/Builtin.cs +++ b/src/core/IronPython/Modules/Builtin.cs @@ -803,7 +803,7 @@ public static object locals(CodeContext/*!*/ context) { } - public static object? max(CodeContext/*!*/ context, object? x, [ParamDictionary, NotNone] IDictionary dict) { + public static object? max(CodeContext/*!*/ context, object? x, [ParamDictionary] IDictionary dict) { IEnumerator i = PythonOps.GetEnumerator(x); var kwargTuple = GetMaxKwArg(dict, isDefaultAllowed: true); @@ -832,7 +832,7 @@ public static object locals(CodeContext/*!*/ context) { return ret; } - public static object? max(CodeContext/*!*/ context, object? x, object? y, [ParamDictionary, NotNone] IDictionary dict) { + public static object? max(CodeContext/*!*/ context, object? x, object? y, [ParamDictionary] IDictionary dict) { var kwargTuple = GetMaxKwArg(dict, isDefaultAllowed: false); object? method = kwargTuple.Item1; @@ -842,7 +842,7 @@ public static object locals(CodeContext/*!*/ context) { return pc.GreaterThan(PythonCalls.Call(context, method, x), PythonCalls.Call(context, method, y)) ? x : y; } - public static object? max(CodeContext/*!*/ context, [ParamDictionary, NotNone] IDictionary dict, [NotNone] params object?[] args) { + public static object? max(CodeContext/*!*/ context, [ParamDictionary] IDictionary dict, [NotNone] params object?[] args) { var kwargTuple = GetMaxKwArg(dict, isDefaultAllowed: false); object? method = kwargTuple.Item1; @@ -914,7 +914,7 @@ public static object locals(CodeContext/*!*/ context) { } } - public static object? min(CodeContext/*!*/ context, object? x, [ParamDictionary, NotNone] IDictionary dict) { + public static object? min(CodeContext/*!*/ context, object? x, [ParamDictionary] IDictionary dict) { IEnumerator i = PythonOps.GetEnumerator(x); var kwargTuple = GetMinKwArg(dict, isDefaultAllowed: true); object? method = kwargTuple.Item1; @@ -941,7 +941,7 @@ public static object locals(CodeContext/*!*/ context) { return ret; } - public static object? min(CodeContext/*!*/ context, object? x, object? y, [ParamDictionary, NotNone] IDictionary dict) { + public static object? min(CodeContext/*!*/ context, object? x, object? y, [ParamDictionary] IDictionary dict) { var kwargTuple = GetMinKwArg(dict, isDefaultAllowed: false); object? method = kwargTuple.Item1; @@ -950,7 +950,7 @@ public static object locals(CodeContext/*!*/ context) { return context.LanguageContext.LessThan(PythonCalls.Call(context, method, x), PythonCalls.Call(context, method, y)) ? x : y; } - public static object? min(CodeContext/*!*/ context, [ParamDictionary, NotNone] IDictionary dict, [NotNone] params object?[] args) { + public static object? min(CodeContext/*!*/ context, [ParamDictionary] IDictionary dict, [NotNone] params object?[] args) { var kwargTuple = GetMinKwArg(dict, isDefaultAllowed: false); object? method = kwargTuple.Item1; @@ -1172,7 +1172,7 @@ public static void print(CodeContext/*!*/ context, [NotNone] params object?[] ar PrintHelper(context, " ", "\n", null, args, false); } - public static void print(CodeContext/*!*/ context, [ParamDictionary, NotNone] IDictionary kwargs, [NotNone] params object?[] args) { + public static void print(CodeContext/*!*/ context, [ParamDictionary] IDictionary kwargs, [NotNone] params object?[] args) { object? sep = AttrCollectionPop(kwargs, "sep", " "); if (sep != null && !(sep is string)) { throw PythonOps.TypeError("sep must be None or str, not {0}", PythonOps.GetPythonTypeName(sep)); @@ -1369,7 +1369,7 @@ public static void setattr(CodeContext/*!*/ context, object? o, [NotNone] string public static PythonList sorted(CodeContext/*!*/ context, object? iterable, - [ParamDictionary, NotNone] IDictionary kwArgs) { + [ParamDictionary] IDictionary kwArgs) { IEnumerator iter = PythonOps.GetEnumerator(iterable); PythonList l = new PythonList(10); @@ -1693,11 +1693,9 @@ private static CompileFlags GetCompilerFlags(int flags) { return localContext; } -#pragma warning disable IPY01 // Parameter which is marked not nullable does not have the NotNullAttribute [SpecialName] public static void PerformModuleReload(PythonContext context, PythonDictionary dict) { dict["__debug__"] = ScriptingRuntimeHelpers.BooleanToObject(!context.PythonOptions.Optimize); } -#pragma warning restore IPY01 // Parameter which is marked not nullable does not have the NotNullAttribute } } diff --git a/src/core/IronPython/Modules/_imp.cs b/src/core/IronPython/Modules/_imp.cs index 1e91700cf..044a26db1 100644 --- a/src/core/IronPython/Modules/_imp.cs +++ b/src/core/IronPython/Modules/_imp.cs @@ -139,7 +139,7 @@ public NullImporter(string path_string) { } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1822:MarkMembersAsStatic")] - public object find_module(params object[] args) { + public object find_module([NotNone] params object[] args) { return null; } } diff --git a/src/core/IronPython/Modules/_io.cs b/src/core/IronPython/Modules/_io.cs index 73396b67d..b25cda459 100644 --- a/src/core/IronPython/Modules/_io.cs +++ b/src/core/IronPython/Modules/_io.cs @@ -102,7 +102,7 @@ public _IOBase __enter__() { return this; } - public void __exit__(CodeContext/*!*/ context, params object[] excinfo) { + public void __exit__(CodeContext/*!*/ context, [NotNone] params object[] excinfo) { close(context); } @@ -635,7 +635,7 @@ internal static BufferedReader Create(CodeContext/*!*/ context, object raw, int public BufferedReader( CodeContext/*!*/ context, - params object[] args + [NotNone] params object[] args ) : base(context) { } diff --git a/src/core/IronPython/Modules/_io/BytesIO.cs b/src/core/IronPython/Modules/_io/BytesIO.cs index 637c8b76f..474003abf 100644 --- a/src/core/IronPython/Modules/_io/BytesIO.cs +++ b/src/core/IronPython/Modules/_io/BytesIO.cs @@ -40,8 +40,9 @@ internal BytesIO(CodeContext/*!*/ context) _data = new byte[DEFAULT_BUF_SIZE]; } - public BytesIO(CodeContext/*!*/ context, [ParamDictionary, NotNone] IDictionary kwArgs\u00F8, params object[] args) - : this(context) { } + public BytesIO(CodeContext/*!*/ context, [ParamDictionary] IDictionary kwArgs, [NotNone] params object[] args) + : this(context) { + } public void __init__(IBufferProtocol initial_bytes = null) { _pos = _length = 0; diff --git a/src/core/IronPython/Modules/_io/StringIO.cs b/src/core/IronPython/Modules/_io/StringIO.cs index 7518c4cc4..dbddec3f9 100644 --- a/src/core/IronPython/Modules/_io/StringIO.cs +++ b/src/core/IronPython/Modules/_io/StringIO.cs @@ -40,7 +40,7 @@ private StringIO(CodeContext context) _data = new char[DEFAULT_BUF_SIZE]; } - public StringIO(CodeContext context, [ParamDictionary, NotNone] IDictionary kwArgs\u00F8, [NotNone] params object[] args) + public StringIO(CodeContext context, [ParamDictionary] IDictionary kwArgs, [NotNone] params object[] args) : this(context) { } public void __init__(CodeContext context, string? initial_value = "", string? newline = "\n") { diff --git a/src/core/IronPython/Modules/unicodedata.cs b/src/core/IronPython/Modules/unicodedata.cs index d6b08a8e1..1ad495d48 100644 --- a/src/core/IronPython/Modules/unicodedata.cs +++ b/src/core/IronPython/Modules/unicodedata.cs @@ -39,12 +39,10 @@ public static UCD ucd_3_2_0 { public static string unidata_version => ucd.unidata_version; -#pragma warning disable IPY01 // Parameter which is marked not nullable does not have the NotNullAttribute [SpecialName] public static void PerformModuleReload(PythonContext/*!*/ context, IDictionary/*!*/ dict) { EnsureInitialized(); } -#pragma warning restore IPY01 // Parameter which is marked not nullable does not have the NotNullAttribute /// /// Ensures that the modules is initialized so that static methods don't throw. diff --git a/src/core/IronPython/Runtime/ByteArray.cs b/src/core/IronPython/Runtime/ByteArray.cs index 613b1400a..6eeab9dcc 100644 --- a/src/core/IronPython/Runtime/ByteArray.cs +++ b/src/core/IronPython/Runtime/ByteArray.cs @@ -57,7 +57,7 @@ internal ByteArray(IEnumerable bytes) { } [StaticExtensionMethod] - public static object __new__(CodeContext context, [NotNone] PythonType cls, [ParamDictionary, NotNone] IDictionary dict, [NotNone] params object[] args) { + public static object __new__(CodeContext context, [NotNone] PythonType cls, [ParamDictionary] IDictionary dict, [NotNone] params object[] args) { if (cls == TypeCache.ByteArray) return new ByteArray(); return cls.CreateInstance(context); } diff --git a/src/core/IronPython/Runtime/ClrModule.cs b/src/core/IronPython/Runtime/ClrModule.cs index 7e7b404bc..168e4da8b 100644 --- a/src/core/IronPython/Runtime/ClrModule.cs +++ b/src/core/IronPython/Runtime/ClrModule.cs @@ -113,7 +113,7 @@ public static void PerformModuleReload(PythonContext/*!*/ context, PythonDiction Assembly object, a full assembly name, or a partial assembly name. After the load the assemblies namespaces and top-level types will be available via import Namespace.")] - public static void AddReference(CodeContext/*!*/ context, params object[] references) { + public static void AddReference(CodeContext/*!*/ context, [NotNone] params object[] references) { if (references == null) throw new TypeErrorException("Expected string or Assembly, got NoneType"); if (references.Length == 0) throw new ValueErrorException("Expected at least one name, got none"); ContractUtils.RequiresNotNull(context, nameof(context)); @@ -129,7 +129,7 @@ sys.path and dependencies will be loaded from sys.path as well. The assembly name should be the filename on disk without a directory specifier and optionally including the .EXE or .DLL extension. After the load the assemblies namespaces and top-level types will be available via import Namespace.")] - public static void AddReferenceToFile(CodeContext/*!*/ context, params string[] files) { + public static void AddReferenceToFile(CodeContext/*!*/ context, [NotNone] params string[] files) { if (files == null) throw new TypeErrorException("Expected string, got NoneType"); if (files.Length == 0) throw new ValueErrorException("Expected at least one name, got none"); ContractUtils.RequiresNotNull(context, nameof(context)); @@ -142,7 +142,7 @@ public static void AddReferenceToFile(CodeContext/*!*/ context, params string[] [Documentation(@"Adds a reference to a .NET assembly. Parameters are an assembly name. After the load the assemblies namespaces and top-level types will be available via import Namespace.")] - public static void AddReferenceByName(CodeContext/*!*/ context, params string[] names) { + public static void AddReferenceByName(CodeContext/*!*/ context, [NotNone] params string[] names) { if (names == null) throw new TypeErrorException("Expected string, got NoneType"); if (names.Length == 0) throw new ValueErrorException("Expected at least one name, got none"); ContractUtils.RequiresNotNull(context, nameof(context)); @@ -155,7 +155,7 @@ public static void AddReferenceByName(CodeContext/*!*/ context, params string[] [Documentation(@"Adds a reference to a .NET assembly. Parameters are a partial assembly name. After the load the assemblies namespaces and top-level types will be available via import Namespace.")] - public static void AddReferenceByPartialName(CodeContext/*!*/ context, params string[] names) { + public static void AddReferenceByPartialName(CodeContext/*!*/ context, [NotNone] params string[] names) { if (names == null) throw new TypeErrorException("Expected string, got NoneType"); if (names.Length == 0) throw new ValueErrorException("Expected at least one name, got none"); ContractUtils.RequiresNotNull(context, nameof(context)); @@ -171,7 +171,7 @@ assembly on disk. After the load the assemblies namespaces and top-level types will be available via import Namespace.")] public static Assembly/*!*/ LoadAssemblyFromFileWithPath(CodeContext/*!*/ context, string/*!*/ file) { if (file == null) throw new TypeErrorException("LoadAssemblyFromFileWithPath: arg 1 must be a string."); - + Assembly res; if (!context.LanguageContext.TryLoadAssemblyFromFileWithPath(file, out res)) { if (!Path.IsPathRooted(file)) { @@ -253,7 +253,7 @@ public static string GetString(byte[] bytes) { [Documentation("Converts maxCount of an array of bytes to a string")] public static string GetString(byte[] bytes, int maxCount) { - int bytesToCopy = Math.Min(bytes.Length, maxCount); + int bytesToCopy = Math.Min(bytes.Length, maxCount); return Encoding.GetEncoding("iso-8859-1").GetString(bytes, 0, bytesToCopy); } @@ -516,7 +516,7 @@ be provided which are fully qualified names to the file on disk. The directory is added to sys.path and AddReferenceToFile is then called. After the load the assemblies namespaces and top-level types will be available via import Namespace.")] - public static void AddReferenceToFileAndPath(CodeContext/*!*/ context, params string[] files) { + public static void AddReferenceToFileAndPath(CodeContext/*!*/ context, [NotNone] params string[] files) { if (files == null) throw new TypeErrorException("Expected string, got NoneType"); ContractUtils.RequiresNotNull(context, nameof(context)); @@ -699,7 +699,7 @@ internal override bool GetAlwaysSucceeds { #region IFancyCallable Members [SpecialName] - public object Call(CodeContext context, [ParamDictionary]IDictionary dict, params object[] args) { + public object Call(CodeContext context, [ParamDictionary] IDictionary dict, params object[] args) { ValidateArgs(args); if (_inst != null) { @@ -794,7 +794,7 @@ internal override bool GetAlwaysSucceeds { #region IFancyCallable Members [SpecialName] - public object Call(CodeContext context, [ParamDictionary]IDictionary dict, params object[] args) { + public object Call(CodeContext context, [ParamDictionary] IDictionary dict, params object[] args) { object ret; if (_inst != null) { ret = PythonCalls.CallWithKeywordArgs(context, _func, ArrayUtils.Insert(_inst, args), dict); @@ -870,7 +870,7 @@ public static object Convert(CodeContext/*!*/ context, object o, Type toType) { /// Provides a helper for compiling a group of modules into a single assembly. The assembly can later be /// reloaded using the clr.AddReference API. /// - public static void CompileModules(CodeContext/*!*/ context, string/*!*/ assemblyName, [ParamDictionary]IDictionary kwArgs, params string/*!*/[]/*!*/ filenames) { + public static void CompileModules(CodeContext/*!*/ context, string/*!*/ assemblyName, [ParamDictionary] IDictionary kwArgs, [NotNone] params string/*!*/[]/*!*/ filenames) { ContractUtils.RequiresNotNull(assemblyName, nameof(assemblyName)); ContractUtils.RequiresNotNullItems(filenames, nameof(filenames)); @@ -966,7 +966,7 @@ public static void CompileModules(CodeContext/*!*/ context, string/*!*/ assembly /// object and an object which implements IComparable. /// /// - public static void CompileSubclassTypes(string/*!*/ assemblyName, params object[] newTypes) { + public static void CompileSubclassTypes(string/*!*/ assemblyName, [NotNone] params object[] newTypes) { if (assemblyName == null) { throw PythonOps.TypeError("CompileTypes expected str for assemblyName, got NoneType"); } @@ -996,7 +996,7 @@ public static void CompileSubclassTypes(string/*!*/ assemblyName, params object[ /// public static PythonTuple GetSubclassedTypes() { List res = new List(); - + foreach (NewTypeInfo info in NewTypeMaker._newTypes.Keys) { Type clrBaseType = info.BaseType; Type tempType = clrBaseType; @@ -1129,7 +1129,7 @@ private static void SortModules(List modules) { /// /// All times are expressed in the same unit of measure as DateTime.Ticks /// - public static PythonTuple GetProfilerData(CodeContext/*!*/ context, bool includeUnused=false) { + public static PythonTuple GetProfilerData(CodeContext/*!*/ context, bool includeUnused = false) { return new PythonTuple(Profiler.GetProfiler(context.LanguageContext).GetProfile(includeUnused)); } diff --git a/src/core/IronPython/Runtime/Descriptors.cs b/src/core/IronPython/Runtime/Descriptors.cs index d448ca334..245dcca2e 100644 --- a/src/core/IronPython/Runtime/Descriptors.cs +++ b/src/core/IronPython/Runtime/Descriptors.cs @@ -116,9 +116,9 @@ public class PythonProperty : PythonTypeDataSlot { public PythonProperty() { } - public PythonProperty(params object[] args) { } + public PythonProperty([NotNone] params object[] args) { } - public PythonProperty([ParamDictionary] IDictionary dict, params object[] args) { } + public PythonProperty([ParamDictionary] IDictionary dict, [NotNone] params object[] args) { } public void __init__(object fget = null, object fset = null, object fdel = null, object doc = null) { _fget = fget; _fset = fset; _fdel = fdel; _doc = doc; diff --git a/src/core/IronPython/Runtime/Exceptions/PythonExceptions.BaseException.cs b/src/core/IronPython/Runtime/Exceptions/PythonExceptions.BaseException.cs index 6a7bc59e5..b9bccdaf1 100644 --- a/src/core/IronPython/Runtime/Exceptions/PythonExceptions.BaseException.cs +++ b/src/core/IronPython/Runtime/Exceptions/PythonExceptions.BaseException.cs @@ -83,26 +83,25 @@ public BaseException([NotNone] PythonType/*!*/ type) { _args = PythonTuple.EMPTY; } - public static object __new__([NotNone] PythonType/*!*/ cls, [NotNone] params object?[] args\u00F8) { + public static object __new__([NotNone] PythonType/*!*/ cls, [NotNone] params object?[] args) { BaseException res; if (cls.UnderlyingSystemType == typeof(BaseException)) { res = new BaseException(cls); - } - else { + } else { res = (BaseException)Activator.CreateInstance(cls.UnderlyingSystemType, cls)!; } - res._args = new PythonTuple(args\u00F8); + res._args = new PythonTuple(args); return res; } - public static object __new__([NotNone] PythonType/*!*/ cls, [ParamDictionary, NotNone] IDictionary kwArgs\u00F8, [NotNone] params object?[] args\u00F8) - => __new__(cls, args\u00F8); + public static object __new__([NotNone] PythonType/*!*/ cls, [ParamDictionary] IDictionary kwArgs, [NotNone] params object?[] args) + => __new__(cls, args); /// /// Initializes the Exception object with an unlimited number of arguments /// - public virtual void __init__([NotNone] params object?[] args\u00F8) { - _args = PythonTuple.MakeTuple(args\u00F8 ?? new object?[] { null }); + public virtual void __init__([NotNone] params object?[] args) { + _args = PythonTuple.MakeTuple(args ?? new object?[] { null }); } /// @@ -180,8 +179,7 @@ internal set { } public override string/*!*/ ToString() { - return (_args.__len__()) switch - { + return (_args.__len__()) switch { 0 => string.Empty, 1 => PythonOps.ToString(_args[0]), _ => _args.ToString(), diff --git a/src/core/IronPython/Runtime/Exceptions/PythonExceptions.cs b/src/core/IronPython/Runtime/Exceptions/PythonExceptions.cs index 566653c29..a32f887de 100644 --- a/src/core/IronPython/Runtime/Exceptions/PythonExceptions.cs +++ b/src/core/IronPython/Runtime/Exceptions/PythonExceptions.cs @@ -59,7 +59,7 @@ public override string ToString() { return PythonOps.ToString(msg); } - public override void __init__(params object[] args) { + public override void __init__([NotNone] params object[] args) { base.__init__(args); if (args != null && args.Length != 0) { @@ -82,7 +82,7 @@ public override void __init__(params object[] args) { } public partial class _UnicodeTranslateError : BaseException { - public override void __init__(params object[] args) { + public override void __init__([NotNone] params object[] args) { if (args.Length != 4) { throw PythonOps.TypeError("function takes exactly 4 arguments ({0} given)", args.Length); } @@ -120,12 +120,12 @@ public override string ToString() { } public partial class _OSError { - public static new object __new__(PythonType cls, [ParamDictionary] IDictionary kwArgs, params object[] args) { + public static new object __new__(PythonType cls, [ParamDictionary] IDictionary kwArgs, [NotNone] params object[] args) { if (cls == OSError && args.Length >= 2 && args[0] is int errno) { if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) { if (args.Length >= 4 && args[3] is int winerror) { errno = WinErrorToErrno(winerror); - } + } } cls = ErrorEnumToPythonType(ErrnoToErrorEnum(errno)); } @@ -159,7 +159,7 @@ public object characters_written { set { _characters_written = PythonOps.Index(value); } } - public override void __init__(params object[] args) { + public override void __init__([NotNone] params object[] args) { if (args.Length >= 2 && args.Length <= 5) { errno = args[0]; strerror = args[1]; @@ -603,7 +603,7 @@ internal static int WinErrorToErrno(int winerror) { } public partial class _ImportError { - public void __init__([ParamDictionary] IDictionary kwargs, params object[] args) { + public void __init__([ParamDictionary] IDictionary kwargs, [NotNone] params object[] args) { base.__init__(args); foreach (var pair in kwargs) { @@ -726,7 +726,7 @@ public override void __init__([NotNone] params object[] args) { } public partial class _StopIteration : BaseException { - public override void __init__(params object[] args) { + public override void __init__([NotNone] params object[] args) { base.__init__(args); if (args?.Length > 0) { @@ -736,7 +736,7 @@ public override void __init__(params object[] args) { } public partial class _BlockingIOError { - public override void __init__(params object[] args) { + public override void __init__([NotNone] params object[] args) { if (args.Length >= 3) { if (PythonOps.TryToIndex(args[2], out object index)) // this is the behavior since CPython 3.8 characters_written = index; diff --git a/src/core/IronPython/Runtime/MemoryView.cs b/src/core/IronPython/Runtime/MemoryView.cs index ffd9bbaab..8da5c0a84 100644 --- a/src/core/IronPython/Runtime/MemoryView.cs +++ b/src/core/IronPython/Runtime/MemoryView.cs @@ -297,7 +297,7 @@ public object __enter__() { return this; } - public void __exit__(CodeContext/*!*/ context, params object?[]? excinfo) { + public void __exit__(CodeContext/*!*/ context, [NotNone] params object?[] excinfo) { release(context); } diff --git a/src/core/IronPython/Runtime/Method.cs b/src/core/IronPython/Runtime/Method.cs index 83e3dfaca..f285ff27c 100644 --- a/src/core/IronPython/Runtime/Method.cs +++ b/src/core/IronPython/Runtime/Method.cs @@ -45,11 +45,11 @@ public Method(object function, object self) { internal PythonType im_class { get; } // TODO: get rid of this property? [SpecialName] - public object Call(CodeContext/*!*/ context, params object[] args) + public object Call(CodeContext/*!*/ context, [NotNone] params object[] args) => context.LanguageContext.CallSplat(this, args); [SpecialName] - public object Call(CodeContext/*!*/ context, [ParamDictionary]IDictionary kwArgs, params object[] args) + public object Call(CodeContext/*!*/ context, [ParamDictionary]IDictionary kwArgs, [NotNone] params object[] args) => context.LanguageContext.CallWithKeywords(this, args, kwArgs); #region Object Overrides diff --git a/src/core/IronPython/Runtime/Operations/InstanceOps.cs b/src/core/IronPython/Runtime/Operations/InstanceOps.cs index bae065063..1d6e9233e 100644 --- a/src/core/IronPython/Runtime/Operations/InstanceOps.cs +++ b/src/core/IronPython/Runtime/Operations/InstanceOps.cs @@ -91,7 +91,7 @@ internal static BuiltinFunction CreateNonDefaultNew() { return CreateFunction("__new__", "NonDefaultNew", "NonDefaultNewKW", "NonDefaultNewKWNoParams"); } - public static object DefaultNew(CodeContext context, PythonType type\u00F8, params object[] args\u00F8) { + public static object DefaultNew(CodeContext context, PythonType type\u00F8, params object[] args) { if (type\u00F8 == null) { throw PythonOps.TypeError( "__new__ expected type object, got {0}", @@ -99,16 +99,16 @@ public static object DefaultNew(CodeContext context, PythonType type\u00F8, para ); } - CheckNewArgs(context, null, args\u00F8, type\u00F8); + CheckNewArgs(context, null, args, type\u00F8); return type\u00F8.CreateInstance(context); } - public static object DefaultNewClsKW(CodeContext context, PythonType type\u00F8, [ParamDictionary] IDictionary kwargs\u00F8, params object[] args\u00F8) { - object res = DefaultNew(context, type\u00F8, args\u00F8); + public static object DefaultNewClsKW(CodeContext context, PythonType type\u00F8, [ParamDictionary] IDictionary kwargs, params object[] args) { + object res = DefaultNew(context, type\u00F8, args); - if (kwargs\u00F8.Count > 0) { - foreach (KeyValuePair kvp in (IDictionary)kwargs\u00F8) { + if (kwargs.Count > 0) { + foreach (KeyValuePair kvp in kwargs) { PythonOps.SetAttr(context, res, kvp.Key.ToString(), @@ -118,60 +118,60 @@ public static object DefaultNewClsKW(CodeContext context, PythonType type\u00F8, return res; } - public static object OverloadedNewBasic(CodeContext context, SiteLocalStorage>> storage, BuiltinFunction overloads\u00F8, PythonType type\u00F8, params object[] args\u00F8) { + public static object OverloadedNewBasic(CodeContext context, SiteLocalStorage>> storage, BuiltinFunction overloads\u00F8, PythonType type\u00F8, params object[] args) { if (type\u00F8 == null) throw PythonOps.TypeError("__new__ expected type object, got {0}", PythonOps.Repr(context, DynamicHelpers.GetPythonType(type\u00F8))); - if (args\u00F8 == null) args\u00F8 = new object[1]; - return overloads\u00F8.Call(context, storage, null, args\u00F8); + if (args == null) args = new object[1]; + return overloads\u00F8.Call(context, storage, null, args); } - public static object OverloadedNewKW(CodeContext context, BuiltinFunction overloads\u00F8, PythonType type\u00F8, [ParamDictionary] IDictionary kwargs\u00F8) { + public static object OverloadedNewKW(CodeContext context, BuiltinFunction overloads\u00F8, PythonType type\u00F8, [ParamDictionary] IDictionary kwargs) { if (type\u00F8 == null) throw PythonOps.TypeError("__new__ expected type object, got {0}", PythonOps.Repr(context, DynamicHelpers.GetPythonType(type\u00F8))); - return overloads\u00F8.Call(context, null, null, [], kwargs\u00F8); + return overloads\u00F8.Call(context, null, null, [], kwargs); } - public static object OverloadedNewClsKW(CodeContext context, BuiltinFunction overloads\u00F8, PythonType type\u00F8, [ParamDictionary] IDictionary kwargs\u00F8, params object[] args\u00F8) { + public static object OverloadedNewClsKW(CodeContext context, BuiltinFunction overloads\u00F8, PythonType type\u00F8, [ParamDictionary] IDictionary kwargs, params object[] args) { if (type\u00F8 == null) throw PythonOps.TypeError("__new__ expected type object, got {0}", PythonOps.Repr(context, DynamicHelpers.GetPythonType(type\u00F8))); - if (args\u00F8 == null) args\u00F8 = new object[1]; + if (args == null) args = new object[1]; - return overloads\u00F8.Call(context, null, null, args\u00F8, kwargs\u00F8); + return overloads\u00F8.Call(context, null, null, args, kwargs); } - [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA1801:ReviewUnusedParameters", MessageId = "self"), System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA1801:ReviewUnusedParameters", MessageId = "context"), System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA1801:ReviewUnusedParameters", MessageId = "args\u00F8")] - public static void DefaultInit(CodeContext context, object self, params object[] args\u00F8) { + [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA1801:ReviewUnusedParameters", MessageId = "self"), System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA1801:ReviewUnusedParameters", MessageId = "context"), System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA1801:ReviewUnusedParameters", MessageId = "args")] + public static void DefaultInit(CodeContext context, object self, params object[] args) { } - [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA1801:ReviewUnusedParameters", MessageId = "self"), System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA1801:ReviewUnusedParameters", MessageId = "kwargs\u00F8"), System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA1801:ReviewUnusedParameters", MessageId = "context"), System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA1801:ReviewUnusedParameters", MessageId = "args\u00F8")] - public static void DefaultInitKW(CodeContext context, object self, [ParamDictionary] IDictionary kwargs\u00F8, params object[] args\u00F8) { + [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA1801:ReviewUnusedParameters", MessageId = "self"), System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA1801:ReviewUnusedParameters", MessageId = "kwargs"), System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA1801:ReviewUnusedParameters", MessageId = "context"), System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA1801:ReviewUnusedParameters", MessageId = "args")] + public static void DefaultInitKW(CodeContext context, object self, [ParamDictionary] IDictionary kwargs, params object[] args) { } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA1801:ReviewUnusedParameters", MessageId = "context")] [StaticExtensionMethod] - public static object NonDefaultNew(CodeContext context, PythonType type\u00F8, params object[] args\u00F8) { + public static object NonDefaultNew(CodeContext context, PythonType type\u00F8, params object[] args) { if (type\u00F8 == null) throw PythonOps.TypeError("__new__ expected type object, got {0}", PythonOps.Repr(context, DynamicHelpers.GetPythonType(type\u00F8))); - if (args\u00F8 == null) args\u00F8 = new object[1]; - return type\u00F8.CreateInstance(context, args\u00F8); + if (args == null) args = new object[1]; + return type\u00F8.CreateInstance(context, args); } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA1801:ReviewUnusedParameters", MessageId = "context")] [StaticExtensionMethod] - public static object NonDefaultNewKW(CodeContext context, PythonType type\u00F8, [ParamDictionary] IDictionary kwargs\u00F8, params object[] args\u00F8) { + public static object NonDefaultNewKW(CodeContext context, PythonType type\u00F8, [ParamDictionary] IDictionary kwargs, params object[] args) { if (type\u00F8 == null) throw PythonOps.TypeError("__new__ expected type object, got {0}", PythonOps.Repr(context, DynamicHelpers.GetPythonType(type\u00F8))); - if (args\u00F8 == null) args\u00F8 = new object[1]; + if (args == null) args = new object[1]; string[] names; - GetKeywordArgs(kwargs\u00F8, args\u00F8, out args\u00F8, out names); - return type\u00F8.CreateInstance(context, args\u00F8, names); + GetKeywordArgs(kwargs, args, out args, out names); + return type\u00F8.CreateInstance(context, args, names); } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA1801:ReviewUnusedParameters", MessageId = "context")] [StaticExtensionMethod] - public static object NonDefaultNewKWNoParams(CodeContext context, PythonType type\u00F8, [ParamDictionary] IDictionary kwargs\u00F8) { + public static object NonDefaultNewKWNoParams(CodeContext context, PythonType type\u00F8, [ParamDictionary] IDictionary kwargs) { if (type\u00F8 == null) throw PythonOps.TypeError("__new__ expected type object, got {0}", PythonOps.Repr(context, DynamicHelpers.GetPythonType(type\u00F8))); string[] names; object[] args; - GetKeywordArgs(kwargs\u00F8, [], out args, out names); + GetKeywordArgs(kwargs, [], out args, out names); return type\u00F8.CreateInstance(context, args, names); } diff --git a/src/core/IronPython/Runtime/Operations/ObjectOps.cs b/src/core/IronPython/Runtime/Operations/ObjectOps.cs index 058259ba5..bac14ec81 100644 --- a/src/core/IronPython/Runtime/Operations/ObjectOps.cs +++ b/src/core/IronPython/Runtime/Operations/ObjectOps.cs @@ -6,15 +6,13 @@ using System; using System.Collections.Generic; -using System.Numerics; using System.Reflection; using System.Threading; +using IronPython.Runtime.Types; + using Microsoft.Scripting; using Microsoft.Scripting.Runtime; -using Microsoft.Scripting.Utils; - -using IronPython.Runtime.Types; namespace IronPython.Runtime.Operations { @@ -67,15 +65,15 @@ public static void __init__(CodeContext/*!*/ context, object self) { } /// /// Initializes the object. The base class does nothing. /// - public static void __init__(CodeContext/*!*/ context, object self, [NotNone] params object[] args\u00F8) { - InstanceOps.CheckInitArgs(context, null, args\u00F8, self); + public static void __init__(CodeContext/*!*/ context, object self, [NotNone] params object[] args) { + InstanceOps.CheckInitArgs(context, null, args, self); } /// /// Initializes the object. The base class does nothing. /// - public static void __init__(CodeContext/*!*/ context, object self, [ParamDictionary]IDictionary kwargs, params object[] args\u00F8) { - InstanceOps.CheckInitArgs(context, kwargs, args\u00F8, self); + public static void __init__(CodeContext/*!*/ context, object self, [ParamDictionary] IDictionary kwargs, [NotNone] params object[] args) { + InstanceOps.CheckInitArgs(context, kwargs, args, self); } /// @@ -94,12 +92,12 @@ public static object __new__(CodeContext/*!*/ context, PythonType cls) { /// Creates a new instance of the type /// [StaticExtensionMethod] - public static object __new__(CodeContext/*!*/ context, PythonType cls, [NotNone] params object[] args\u00F8) { + public static object __new__(CodeContext/*!*/ context, PythonType cls, [NotNone] params object[] args) { if (cls == null) { throw PythonOps.TypeError("__new__ expected type object, got {0}", PythonOps.Repr(context, DynamicHelpers.GetPythonType(cls))); } - InstanceOps.CheckNewArgs(context, null, args\u00F8, cls); + InstanceOps.CheckNewArgs(context, null, args, cls); return cls.CreateInstance(context); } @@ -108,12 +106,12 @@ public static object __new__(CodeContext/*!*/ context, PythonType cls, [NotNone] /// Creates a new instance of the type /// [StaticExtensionMethod] - public static object __new__(CodeContext/*!*/ context, PythonType cls, [ParamDictionary]IDictionary kwargs\u00F8, [NotNone] params object[] args\u00F8) { + public static object __new__(CodeContext/*!*/ context, PythonType cls, [ParamDictionary] IDictionary kwargs, [NotNone] params object[] args) { if (cls == null) { throw PythonOps.TypeError("__new__ expected type object, got {0}", PythonOps.Repr(context, DynamicHelpers.GetPythonType(cls))); } - InstanceOps.CheckNewArgs(context, kwargs\u00F8, args\u00F8, cls); + InstanceOps.CheckNewArgs(context, kwargs, args, cls); return cls.CreateInstance(context); } diff --git a/src/core/IronPython/Runtime/Operations/StringOps.cs b/src/core/IronPython/Runtime/Operations/StringOps.cs index 36a2e3723..36259c804 100644 --- a/src/core/IronPython/Runtime/Operations/StringOps.cs +++ b/src/core/IronPython/Runtime/Operations/StringOps.cs @@ -16,18 +16,18 @@ using System.Numerics; using System.Reflection; using System.Runtime.InteropServices; -using System.Threading; using System.Text; +using System.Threading; + +using IronPython.Runtime.Exceptions; +using IronPython.Runtime.Types; using Microsoft.Scripting; using Microsoft.Scripting.Runtime; using Microsoft.Scripting.Utils; -using IronPython.Runtime.Exceptions; -using IronPython.Runtime.Types; - -using SpecialNameAttribute = System.Runtime.CompilerServices.SpecialNameAttribute; using NotNullAttribute = System.Diagnostics.CodeAnalysis.NotNullAttribute; +using SpecialNameAttribute = System.Runtime.CompilerServices.SpecialNameAttribute; namespace IronPython.Runtime.Operations { /// @@ -1319,12 +1319,12 @@ public static string zfill([NotNone] this string self, int width) { /// /// Conversion can be 'r' for repr or 's' for string. /// - public static string/*!*/ format(CodeContext/*!*/ context, [NotNone] string format_string\u00F8, [ParamDictionary]IDictionary kwargs\u00F8, params object[] args\u00F8) { + public static string/*!*/ format(CodeContext/*!*/ context, [NotNone] string format_string\u00F8, [ParamDictionary] IDictionary kwargs, [NotNone] params object[] args) { return NewStringFormatter.FormatString( context.LanguageContext, format_string\u00F8, - PythonTuple.MakeTuple(args\u00F8), - kwargs\u00F8 + PythonTuple.MakeTuple(args), + kwargs ); } @@ -1730,7 +1730,7 @@ private static string RawUnicodeEscapeEncode(string s, int start, int count, boo return b?.ToString() ?? s.Substring(start, count); } - private static void StringBuilderInit([NotNull]ref StringBuilder? sb, string s, int start, int end) { + private static void StringBuilderInit([NotNull] ref StringBuilder? sb, string s, int start, int end) { if (sb != null) return; sb = new StringBuilder(s.Length); @@ -1913,7 +1913,7 @@ internal static Bytes RawEncode(CodeContext/*!*/ context, string s, string encod internal static Bytes DoEncodeAscii(string s) => DoEncode(DefaultContext.Default, s, "strict", "ascii", Encoding.ASCII, includePreamble: false); - internal static bool TryEncodeAscii(string s, [NotNullWhen(true)]out Bytes? b) { + internal static bool TryEncodeAscii(string s, [NotNullWhen(true)] out Bytes? b) { try { b = DoEncodeAscii(s); return true; @@ -2092,9 +2092,9 @@ static CodecsInfo() { #if DEBUG foreach (KeyValuePair> kvp in d) { // all codecs should be stored in lowercase because we only look up from lowercase strings - #pragma warning disable CA1862 // disable warning about comparing with ToLower() +#pragma warning disable CA1862 // disable warning about comparing with ToLower() Debug.Assert(kvp.Key.ToLower(CultureInfo.InvariantCulture) == kvp.Key); - #pragma warning restore +#pragma warning restore // all codec names should use underscores instead of dashes to match lookup values Debug.Assert(kvp.Key.IndexOf('-') < 0); } @@ -2186,7 +2186,7 @@ private static PythonList SplitInternal(string self, string separator, int maxsp } } - private static void AssertStringOrTuple([NotNull]object? prefix) { + private static void AssertStringOrTuple([NotNull] object? prefix) { if (prefix == null) { throw PythonOps.TypeError("expected string or tuple, got NoneType"); } @@ -2751,7 +2751,7 @@ static string NameReplaceEncode(string s, int start, int count) { } private delegate string? DecodeErrorHandler(IList bytes, int start, ref int end); - private delegate Bytes? EncodeErrorHandler(string text, int start, ref int end); + private delegate Bytes? EncodeErrorHandler(string text, int start, ref int end); private static object SurrogateEscapeErrors(object unicodeError) { return SurrogateErrorsImpl(unicodeError, surrogateEscapeDecode, surrogateEscapeEncode); @@ -2910,7 +2910,7 @@ private static object SurrogateErrorsImpl(object unicodeError, DecodeErrorHandle int end = dfe.BytesUnknown.Length; string? res = decodeFallback(dfe.BytesUnknown, 0, ref end); if (res == null) throw dfe; - return PythonTuple.MakeTuple(res, dfe.Index + end); + return PythonTuple.MakeTuple(res, dfe.Index + end); } case EncoderFallbackException efe: { diff --git a/src/core/IronPython/Runtime/PythonDictionary.cs b/src/core/IronPython/Runtime/PythonDictionary.cs index 5fd1cff15..334f83058 100644 --- a/src/core/IronPython/Runtime/PythonDictionary.cs +++ b/src/core/IronPython/Runtime/PythonDictionary.cs @@ -245,7 +245,7 @@ public object get(object key, object defaultValue) { return DictionaryOps.get(this, key, defaultValue); } - public virtual object this[params object[] key] { + public virtual object this[[NotNone] params object[] key] { get { if (key == null) { return GetItem(null); @@ -300,7 +300,7 @@ public virtual void __delitem__(object key) { } } - public virtual void __delitem__(params object[] key) { + public virtual void __delitem__([NotNone] params object[] key) { if (key == null) { __delitem__((object)null); } else if (key.Length > 0) { @@ -356,17 +356,17 @@ public object setdefault(object key, object defaultValue) { public void update() { } - public void update(CodeContext/*!*/ context, [ParamDictionary] IDictionary other\u00F8) { - DictionaryOps.update(context, this, other\u00F8); + public void update(CodeContext/*!*/ context, [ParamDictionary] IDictionary other) { + DictionaryOps.update(context, this, other); } public void update(CodeContext/*!*/ context, object other\u00F8) { DictionaryOps.update(context, this, other\u00F8); } - public void update(CodeContext/*!*/ context, object other\u00F8, [ParamDictionary] IDictionary otherArgs\u00F8) { + public void update(CodeContext/*!*/ context, object other\u00F8, [ParamDictionary] IDictionary otherArgs) { DictionaryOps.update(context, this, other\u00F8); - DictionaryOps.update(context, this, otherArgs\u00F8); + DictionaryOps.update(context, this, otherArgs); } private static object fromkeysAny(CodeContext/*!*/ context, PythonType cls, object o, object value) { diff --git a/src/core/IronPython/Runtime/PythonFunction.cs b/src/core/IronPython/Runtime/PythonFunction.cs index a40f9378d..effde504f 100644 --- a/src/core/IronPython/Runtime/PythonFunction.cs +++ b/src/core/IronPython/Runtime/PythonFunction.cs @@ -222,11 +222,11 @@ public FunctionCode __code__ { } } - public object __call__(CodeContext/*!*/ context, params object[] args) { + public object __call__(CodeContext/*!*/ context, [NotNone] params object[] args) { return PythonCalls.Call(context, this, args); } - public object __call__(CodeContext/*!*/ context, [ParamDictionary] IDictionary dict, params object[] args) { + public object __call__(CodeContext/*!*/ context, [ParamDictionary] IDictionary dict, [NotNone] params object[] args) { return PythonCalls.CallWithKeywordArgs(context, this, args, dict); } diff --git a/src/core/IronPython/Runtime/PythonList.cs b/src/core/IronPython/Runtime/PythonList.cs index 286d55010..918f8c6e7 100644 --- a/src/core/IronPython/Runtime/PythonList.cs +++ b/src/core/IronPython/Runtime/PythonList.cs @@ -121,10 +121,10 @@ public static object __new__(CodeContext/*!*/ context, [NotNone] PythonType cls) public static object __new__(CodeContext/*!*/ context, [NotNone] PythonType cls, object? arg) => __new__(context, cls); - public static object __new__(CodeContext/*!*/ context, [NotNone] PythonType cls, [NotNone] params object[] args\u00F8) + public static object __new__(CodeContext/*!*/ context, [NotNone] PythonType cls, [NotNone] params object[] args) => __new__(context, cls); - public static object __new__(CodeContext/*!*/ context, [NotNone] PythonType cls, [ParamDictionary, NotNone] IDictionary kwArgs\u00F8, [NotNone] params object[] args\u00F8) + public static object __new__(CodeContext/*!*/ context, [NotNone] PythonType cls, [ParamDictionary] IDictionary kwArgs, [NotNone] params object[] args) => __new__(context, cls); #endregion @@ -898,7 +898,7 @@ internal void reverse(int index, int count) { } public void sort(CodeContext/*!*/ context, - [ParamDictionary, NotNone] IDictionary kwArgs) { + [ParamDictionary] IDictionary kwArgs) { object? key = null; bool reverse = false; diff --git a/src/core/IronPython/Runtime/PythonModule.cs b/src/core/IronPython/Runtime/PythonModule.cs index 377f856b3..4cad4ca6f 100755 --- a/src/core/IronPython/Runtime/PythonModule.cs +++ b/src/core/IronPython/Runtime/PythonModule.cs @@ -55,7 +55,7 @@ internal PythonModule(PythonDictionary dict) { _dict = dict; } - public static PythonModule/*!*/ __new__(CodeContext/*!*/ context, PythonType/*!*/ cls, params object[]/*!*/ args\u00F8) { + public static PythonModule/*!*/ __new__(CodeContext/*!*/ context, PythonType/*!*/ cls, [NotNone] params object[] args) { PythonModule res; if (cls == TypeCache.Module) { res = new PythonModule(); @@ -69,8 +69,8 @@ internal PythonModule(PythonDictionary dict) { } [StaticExtensionMethod] - public static PythonModule/*!*/ __new__(CodeContext/*!*/ context, PythonType/*!*/ cls, [ParamDictionary]IDictionary kwDict0, params object[]/*!*/ args\u00F8) { - return __new__(context, cls, args\u00F8); + public static PythonModule/*!*/ __new__(CodeContext/*!*/ context, PythonType/*!*/ cls, [ParamDictionary] IDictionary kwDict0, [NotNone] params object[] args) { + return __new__(context, cls, args); } public void __init__(string name) { @@ -255,7 +255,7 @@ public DynamicMetaObject GetMember(PythonGetMemberBinder member, DynamicMetaObje private DynamicMetaObject GetMemberWorker(DynamicMetaObjectBinder binder, DynamicMetaObject codeContext) { string name = GetGetMemberName(binder); - var tmp = Expression.Variable(typeof(object), "res"); + var tmp = Expression.Variable(typeof(object), "res"); return new DynamicMetaObject( Expression.Block( @@ -360,7 +360,7 @@ IList IMembersList.GetMemberNames() { } #endregion - + internal class DebugProxy { private readonly PythonModule _module; @@ -379,7 +379,5 @@ public List Members { } } } - - } } diff --git a/src/core/IronPython/Runtime/Set.cs b/src/core/IronPython/Runtime/Set.cs index 4fee48acd..9d7dab2e2 100644 --- a/src/core/IronPython/Runtime/Set.cs +++ b/src/core/IronPython/Runtime/Set.cs @@ -60,11 +60,11 @@ public static object __new__(CodeContext/*!*/ context, [NotNone] PythonType cls, return __new__(context, cls); } - public static object __new__(CodeContext/*!*/ context, [NotNone] PythonType cls, [NotNone] params object?[] args\u00F8) { + public static object __new__(CodeContext/*!*/ context, [NotNone] PythonType cls, [NotNone] params object?[] args) { return __new__(context, cls); } - public static object __new__(CodeContext/*!*/ context, [NotNone] PythonType cls, [ParamDictionary, NotNone] IDictionary kwArgs, [NotNone] params object?[] args\u00F8) { + public static object __new__(CodeContext/*!*/ context, [NotNone] PythonType cls, [ParamDictionary] IDictionary kwArgs, [NotNone] params object?[] args) { return __new__(context, cls); } @@ -248,7 +248,7 @@ public void update(object? set) { } } - public void update([NotNone] params object[]/*!*/ sets) { + public void update([NotNone] params object[] sets) { if (sets.Length == 0) { return; } @@ -291,7 +291,7 @@ public void intersection_update(object? set) { } } - public void intersection_update([NotNone] params object[]/*!*/ sets) { + public void intersection_update([NotNone] params object[] sets) { if (sets.Length == 0) { return; } @@ -336,7 +336,7 @@ public void difference_update(object? set) { } } - public void difference_update([NotNone] params object[]/*!*/ sets) { + public void difference_update([NotNone] params object[] sets) { if (sets.Length == 0) { return; } @@ -447,7 +447,7 @@ public SetCollection union(object? set) { return Make(items); } - public SetCollection union([NotNone] params object[]/*!*/ sets) { + public SetCollection union([NotNone] params object[] sets) { SetStorage res = _items.Clone(); foreach (object set in sets) { res.UnionUpdate(SetStorage.GetItems(set)); @@ -478,7 +478,7 @@ public SetCollection intersection(object? set) { return Make(items); } - public SetCollection intersection([NotNone] params object[]/*!*/ sets) { + public SetCollection intersection([NotNone] params object[] sets) { if (sets.Length == 0) { return copy(); } @@ -535,7 +535,7 @@ public SetCollection difference(object? set) { ); } - public SetCollection difference([NotNone] params object[]/*!*/ sets) { + public SetCollection difference([NotNone] params object[] sets) { if (sets.Length == 0) { return copy(); } @@ -1069,7 +1069,7 @@ public FrozenSetCollection union(object? set) { return Make(items); } - public FrozenSetCollection union([NotNone] params object[]/*!*/ sets) { + public FrozenSetCollection union([NotNone] params object[] sets) { SetStorage res = _items.Clone(); foreach (object set in sets) { res.UnionUpdate(SetStorage.GetItems(set)); @@ -1100,7 +1100,7 @@ public FrozenSetCollection intersection(object? set) { return Make(items); } - public FrozenSetCollection intersection([NotNone] params object[]/*!*/ sets) { + public FrozenSetCollection intersection([NotNone] params object[] sets) { if (sets.Length == 0) { return Make(_items); } @@ -1157,7 +1157,7 @@ public FrozenSetCollection difference(object? set) { ); } - public FrozenSetCollection difference([NotNone] params object[]/*!*/ sets) { + public FrozenSetCollection difference([NotNone] params object[] sets) { if (sets.Length == 0) { return Make(_items); } diff --git a/src/core/IronPython/Runtime/SimpleNamespace.cs b/src/core/IronPython/Runtime/SimpleNamespace.cs index 4cc1258c7..a6203481a 100644 --- a/src/core/IronPython/Runtime/SimpleNamespace.cs +++ b/src/core/IronPython/Runtime/SimpleNamespace.cs @@ -17,8 +17,8 @@ namespace IronPython.Runtime { [PythonHidden, PythonType("types.SimpleNamespace")] public class SimpleNamespace { - public SimpleNamespace([ParamDictionary, NotNone] Dictionary kwargs\u00F8) { - __dict__ = new PythonDictionary(kwargsø); + public SimpleNamespace([ParamDictionary] Dictionary kwargs) { + __dict__ = new PythonDictionary(kwargs); } public PythonDictionary __dict__ { get; } diff --git a/src/core/IronPython/Runtime/Types/BuiltinFunction.cs b/src/core/IronPython/Runtime/Types/BuiltinFunction.cs index aa3abf12c..2ee75eb28 100644 --- a/src/core/IronPython/Runtime/Types/BuiltinFunction.cs +++ b/src/core/IronPython/Runtime/Types/BuiltinFunction.cs @@ -464,7 +464,7 @@ internal static DynamicMetaObject TranslateArguments(DynamicMetaObjectBinder cal DynamicMetaObject dict = args[index]; - if (!(dict.Value is IDictionary) && dict.Value != null) { + if (dict.Value is not IDictionary) { // The DefaultBinder only handles types that implement IDictionary. Here we have an // arbitrary user-defined mapping type. We'll convert it into a PythonDictionary // and then have an embedded dynamic site pass that dictionary through to the default @@ -697,7 +697,7 @@ private bool IsBuiltinModuleMethod { } } - public object __call__(CodeContext/*!*/ context, SiteLocalStorage, object>>> storage, [ParamDictionary] IDictionary dictArgs, params object[] args) { + public object __call__(CodeContext/*!*/ context, SiteLocalStorage, object>>> storage, [ParamDictionary] IDictionary dictArgs, [NotNone] params object[] args) { return Call(context, storage, null, args, dictArgs); } diff --git a/src/core/IronPython/Runtime/Types/BuiltinMethodDescriptor.cs b/src/core/IronPython/Runtime/Types/BuiltinMethodDescriptor.cs index e9d4f07c1..41817afec 100644 --- a/src/core/IronPython/Runtime/Types/BuiltinMethodDescriptor.cs +++ b/src/core/IronPython/Runtime/Types/BuiltinMethodDescriptor.cs @@ -118,7 +118,7 @@ public string __doc__ { } } - public object __call__(CodeContext context, SiteLocalStorage, object>>> storage, [ParamDictionary]IDictionary dictArgs, params object[] args) { + public object __call__(CodeContext context, SiteLocalStorage, object>>> storage, [ParamDictionary]IDictionary dictArgs, [NotNone] params object[] args) { return _template.__call__(context, storage, dictArgs, args); } diff --git a/src/core/IronPython/Runtime/Types/PythonType.cs b/src/core/IronPython/Runtime/Types/PythonType.cs index e8c78ade8..0fb363fc7 100644 --- a/src/core/IronPython/Runtime/Types/PythonType.cs +++ b/src/core/IronPython/Runtime/Types/PythonType.cs @@ -500,11 +500,11 @@ private static bool TryReplaceExtensibleWithBase(Type curType, out Type newType) return false; } - public object __call__(CodeContext context, params object[] args) { + public object __call__(CodeContext context, [NotNone] params object[] args) { return PythonTypeOps.CallParams(context, this, args); } - public object __call__(CodeContext context, [ParamDictionary] IDictionary kwArgs, params object[] args) { + public object __call__(CodeContext context, [ParamDictionary] IDictionary kwArgs, [NotNone] params object[] args) { return PythonTypeOps.CallWorker(context, this, kwArgs, args); } @@ -538,7 +538,7 @@ public object __getattribute__(CodeContext/*!*/ context, string name) { throw PythonOps.AttributeError("type object '{0}' has no attribute '{1}'", Name, name); } - public PythonType this[params Type[] args] { + public PythonType this[[NotNone] params Type[] args] { get { if (UnderlyingSystemType == typeof(Array)) { if (args.Length == 1) { @@ -638,7 +638,7 @@ public static void Set__qualname__(PythonType type, string name) { type.QualName = name; } - public static PythonDictionary __prepare__([ParamDictionary] IDictionary kwargs, params object[] args) + public static PythonDictionary __prepare__([ParamDictionary] IDictionary kwargs, [NotNone] params object[] args) => new PythonDictionary(); public string/*!*/ __repr__(CodeContext/*!*/ context) { diff --git a/src/core/IronPython/Runtime/Types/ReflectedIndexer.cs b/src/core/IronPython/Runtime/Types/ReflectedIndexer.cs index 3d0dc2376..63fdc525e 100644 --- a/src/core/IronPython/Runtime/Types/ReflectedIndexer.cs +++ b/src/core/IronPython/Runtime/Types/ReflectedIndexer.cs @@ -80,7 +80,7 @@ public object GetValue(CodeContext context, SiteLocalStorage>> storage, params object[] key] { + public object this[SiteLocalStorage>> storage, [NotNone] params object[] key] { get { return GetValue(DefaultContext.Default, storage, key); } diff --git a/src/roslyn/IronPython.Analyzer/IronPythonDiagnosticAnalyzer.cs b/src/roslyn/IronPython.Analyzer/IronPythonDiagnosticAnalyzer.cs index bdbc354a9..7536451af 100644 --- a/src/roslyn/IronPython.Analyzer/IronPythonDiagnosticAnalyzer.cs +++ b/src/roslyn/IronPython.Analyzer/IronPythonDiagnosticAnalyzer.cs @@ -2,14 +2,11 @@ // The .NET Foundation licenses this file to you under the Apache 2.0 License. // See the LICENSE file in the project root for more information. -using System; -using System.Collections.Generic; using System.Collections.Immutable; +using System.Diagnostics; using System.Linq; -using System.Threading; + using Microsoft.CodeAnalysis; -using Microsoft.CodeAnalysis.CSharp; -using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Operations; @@ -24,9 +21,11 @@ public class IronPythonDiagnosticAnalyzer : DiagnosticAnalyzer { private static readonly DiagnosticDescriptor Rule3 = new DiagnosticDescriptor("IPY03", title: "BytesLikeAttribute used on a not supported type", messageFormat: "Parameter '{0}' declared bytes-like on unsupported type '{1}'", category: "Usage", DiagnosticSeverity.Warning, isEnabledByDefault: true, description: "BytesLikeAttribute is only allowed on parameters of type IReadOnlyList, or IList."); private static readonly DiagnosticDescriptor Rule4 = new DiagnosticDescriptor("IPY04", title: "Call to PythonTypeOps.GetName", messageFormat: "Direct call to PythonTypeOps.GetName", category: "Usage", DiagnosticSeverity.Warning, isEnabledByDefault: true, description: "To obtain a name of a python type of a given object to display to a user, use PythonOps.GetPythonTypeName."); private static readonly DiagnosticDescriptor Rule5 = new DiagnosticDescriptor("IPY05", title: "DLR NotNullAttribute accessed without an alias", messageFormat: "Microsoft.Scripting.Runtime.NotNullAttribute should be accessed though alias 'NotNone'", category: "Usage", DiagnosticSeverity.Warning, isEnabledByDefault: true, description: "NotNullAttribute is ambiguous between 'System.Diagnostics.CodeAnalysis.NotNullAttribute' and 'Microsoft.Scripting.Runtime.NotNullAttribute'. The latter should be accesses as 'NotNoneAttribute'."); + private static readonly DiagnosticDescriptor Rule6 = new DiagnosticDescriptor("IPY06", title: "Unnecessary NotNoneAttribute", messageFormat: "Parameter '{0}' has an unnecessary NotNoneAttribute", category: "Usage", DiagnosticSeverity.Warning, isEnabledByDefault: true, description: "ParamDictionary do not require a NotNoneAttribute."); + private static readonly DiagnosticDescriptor Rule7 = new DiagnosticDescriptor("IPY07", title: "Parameters with params does not have the NotNoneAttribute", messageFormat: "Parameter '{0}' does not have the NotNoneAttribute", category: "Usage", DiagnosticSeverity.Warning, isEnabledByDefault: true, description: "Parameters with params should use the NotNoneAttribute to prevent binding to null."); #pragma warning restore RS2008 // Enable analyzer release tracking - public override ImmutableArray SupportedDiagnostics { get { return ImmutableArray.Create(Rule1, Rule2, Rule3, Rule4, Rule5); } } + public override ImmutableArray SupportedDiagnostics { get { return ImmutableArray.Create(Rule1, Rule2, Rule3, Rule4, Rule5, Rule6, Rule7); } } public override void Initialize(AnalysisContext context) { context.ConfigureGeneratedCodeAnalysis(GeneratedCodeAnalysisFlags.None); @@ -62,15 +61,37 @@ private static void AnalyzeSymbol(SymbolAnalysisContext context) { var ireadOnlyListOfByteType = ireadOnlyListType.Construct(byteType); var ilistOfByteType = ilistType.Construct(byteType); + var paramDictionaryAttributeSymbol = context.Compilation.GetTypeByMetadataName("Microsoft.Scripting.ParamDictionaryAttribute"); + var paramArrayAttributeSymbol = context.Compilation.GetTypeByMetadataName("System.ParamArrayAttribute"); + + // PerformModuleReload is special and we don't need NotNone annotations + if (methodSymbol.Name == "PerformModuleReload") return; + foreach (IParameterSymbol parameterSymbol in methodSymbol.Parameters) { - if (parameterSymbol.GetAttributes().Any(x => x.AttributeClass.Equals(bytesLikeAttributeSymbol, SymbolEqualityComparer.Default)) + var attributes = parameterSymbol.GetAttributes(); + + if (attributes.Any(x => x.AttributeClass.Equals(bytesLikeAttributeSymbol, SymbolEqualityComparer.Default)) && !parameterSymbol.Type.Equals(ireadOnlyListOfByteType, SymbolEqualityComparer.Default) && !parameterSymbol.Type.Equals(ilistOfByteType, SymbolEqualityComparer.Default)) { var diagnostic = Diagnostic.Create(Rule3, parameterSymbol.Locations[0], parameterSymbol.Name, parameterSymbol.Type.MetadataName); context.ReportDiagnostic(diagnostic); continue; } - if (parameterSymbol.GetAttributes().FirstOrDefault(x => x.AttributeClass.Equals(notNoneAttributeSymbol, SymbolEqualityComparer.Default)) is AttributeData attr) { + + if (parameterSymbol.IsParams && attributes.All(x => !x.AttributeClass.Equals(notNoneAttributeSymbol, SymbolEqualityComparer.Default))) { + var diagnostic = Diagnostic.Create(Rule7, parameterSymbol.Locations[0], parameterSymbol.Name); + context.ReportDiagnostic(diagnostic); + } + + if (attributes.Any(x => x.AttributeClass.Equals(paramDictionaryAttributeSymbol, SymbolEqualityComparer.Default))) { + if (attributes.Any(x => x.AttributeClass.Equals(notNoneAttributeSymbol, SymbolEqualityComparer.Default))) { + var diagnostic = Diagnostic.Create(Rule6, parameterSymbol.Locations[0], parameterSymbol.Name); + context.ReportDiagnostic(diagnostic); + } + continue; + } + + if (attributes.FirstOrDefault(x => x.AttributeClass.Equals(notNoneAttributeSymbol, SymbolEqualityComparer.Default)) is AttributeData attr) { SyntaxNode node = attr.ApplicationSyntaxReference.GetSyntax(); // Async? if (node.GetLastToken().Text != "NotNone") { var diagnostic = Diagnostic.Create(Rule5, node.GetLocation()); @@ -81,14 +102,14 @@ private static void AnalyzeSymbol(SymbolAnalysisContext context) { if (parameterSymbol.Type.Equals(codeContextSymbol, SymbolEqualityComparer.Default)) continue; if (SymbolEqualityComparer.Default.Equals(parameterSymbol.Type.BaseType, siteLocalStorageSymbol)) continue; if (parameterSymbol.NullableAnnotation == NullableAnnotation.NotAnnotated) { - if (!parameterSymbol.GetAttributes().Any(x => x.AttributeClass.Equals(notNoneAttributeSymbol, SymbolEqualityComparer.Default)) - && !parameterSymbol.GetAttributes().Any(x => IsAllowNull(x.AttributeClass))) { + if (!attributes.Any(x => x.AttributeClass.Equals(notNoneAttributeSymbol, SymbolEqualityComparer.Default)) + && !attributes.Any(x => IsAllowNull(x.AttributeClass))) { var diagnostic = Diagnostic.Create(Rule1, parameterSymbol.Locations[0], parameterSymbol.Name); context.ReportDiagnostic(diagnostic); } } else if (parameterSymbol.NullableAnnotation == NullableAnnotation.Annotated) { - if (parameterSymbol.GetAttributes().Any(x => x.AttributeClass.Equals(notNoneAttributeSymbol, SymbolEqualityComparer.Default)) - && !parameterSymbol.GetAttributes().Any(x => IsDisallowNull(x.AttributeClass))) { + if (attributes.Any(x => x.AttributeClass.Equals(notNoneAttributeSymbol, SymbolEqualityComparer.Default)) + && !attributes.Any(x => IsDisallowNull(x.AttributeClass))) { var diagnostic = Diagnostic.Create(Rule2, parameterSymbol.Locations[0], parameterSymbol.Name); context.ReportDiagnostic(diagnostic); }