diff --git a/src/core/IronPython.Modules/_socket.cs b/src/core/IronPython.Modules/_socket.cs index 846a06ed3..6d36554d8 100644 --- a/src/core/IronPython.Modules/_socket.cs +++ b/src/core/IronPython.Modules/_socket.cs @@ -245,7 +245,7 @@ public void close() { var refs = System.Threading.Interlocked.Decrement(ref _referenceCount); // Don't actually close the socket if other file objects are - // still referring to this socket. + // still referring to this socket. if (refs < 1) { _close(); } @@ -329,19 +329,22 @@ private bool TryConnect(IPEndPoint remoteEP) { return true; } - public long detach() { + public object detach() { var fd = fileno(); _socket = null!; // TODO: this is wrong, no null checks on _socket anywhere! return fd; } [Documentation("fileno() -> file_handle\n\n" - + "Return the underlying system handle for this socket (a 64-bit integer)." + + "Return the underlying system handle for this socket." )] - public long fileno() { + public object fileno() { if (_closed) return -1; try { - return _socket.Handle.ToInt64(); + var handle = _socket.Handle.ToInt64(); + if (int.MinValue <= handle && handle <= int.MaxValue) + return (int)handle; + return (BigInteger)handle; } catch (Exception e) { throw MakeException(_context, e); } @@ -1737,7 +1740,7 @@ public static void setdefaulttimeout(CodeContext/*!*/ context, object? timeout) public const int RCVALL_SOCKETLEVELONLY = 2; public const int RCVALL_MAX = 3; - public const int has_ipv6 = (int)1; + public const bool has_ipv6 = true; #endregion @@ -2014,7 +2017,7 @@ private static string EncodeHostName(string host) { /// /// Return the IP address associated with host, with optional address family checking. /// host may be either a name or an IP address (in string form). - /// + /// /// If family is non-null, a gaierror will be thrown if the host's address family is /// not the same as the specified family. gaierror is also raised if the hostname cannot be /// converted to an IP address (e.g. through a name lookup failure). @@ -2026,7 +2029,7 @@ private static IPAddress HostToAddress(CodeContext/*!*/ context, string host, Ad /// /// Return the IP address associated with host, with optional address family checking. /// host may be either a name or an IP address (in string form). - /// + /// /// If family is non-null, a gaierror will be thrown if the host's address family is /// not the same as the specified family. gaierror is also raised if the hostname cannot be /// converted to an IP address (e.g. through a name lookup failure). @@ -2086,7 +2089,7 @@ private static string RemoveLocalDomain(string fqdn) { /// /// Convert a (host, port) tuple [IPv4] (host, port, flowinfo, scopeid) tuple [IPv6] /// to its corresponding IPEndPoint. - /// + /// /// Throws gaierror if host is not a valid address. /// Throws ArgumentTypeException if any of the following are true: /// - address does not have exactly two elements @@ -2155,7 +2158,7 @@ private static PythonTuple EndPointToTuple(IPEndPoint endPoint) { case AddressFamily.InterNetwork: return PythonTuple.MakeTuple(ip, port); case AddressFamily.InterNetworkV6: - long flowInfo = 0; // RFC 3493 p. 7 + long flowInfo = 0; // RFC 3493 p. 7 long scopeId = endPoint.Address.ScopeId; return PythonTuple.MakeTuple(ip, port, flowInfo, scopeId); default: diff --git a/src/core/IronPython/Compiler/Ast/FlowChecker.cs b/src/core/IronPython/Compiler/Ast/FlowChecker.cs index b2f6fe498..65995615d 100644 --- a/src/core/IronPython/Compiler/Ast/FlowChecker.cs +++ b/src/core/IronPython/Compiler/Ast/FlowChecker.cs @@ -112,7 +112,7 @@ public override bool Walk(ListExpression node) { public override bool Walk(Parameter node) { _fc.Define(node.Name); - return true; + return false; } } diff --git a/src/core/IronPython/Compiler/Ast/SetExpression.cs b/src/core/IronPython/Compiler/Ast/SetExpression.cs index 555fa3022..247f3f25b 100644 --- a/src/core/IronPython/Compiler/Ast/SetExpression.cs +++ b/src/core/IronPython/Compiler/Ast/SetExpression.cs @@ -20,6 +20,7 @@ public class SetExpression : Expression { public SetExpression(params Expression[] items) { ContractUtils.RequiresNotNull(items, nameof(items)); + ContractUtils.RequiresNotNullItems(items, nameof(items)); _items = items; } diff --git a/src/core/IronPython/Compiler/Ast/StarredExpression.cs b/src/core/IronPython/Compiler/Ast/StarredExpression.cs index de08431ee..cc7bc649d 100644 --- a/src/core/IronPython/Compiler/Ast/StarredExpression.cs +++ b/src/core/IronPython/Compiler/Ast/StarredExpression.cs @@ -48,10 +48,10 @@ public override void Walk(PythonWalker walker) { } internal class StarredExpressionChecker : PythonWalker { - private readonly CompilerContext context; + private readonly CompilerContext _context; private StarredExpressionChecker(CompilerContext context) { - this.context = context; + _context = context; } public static void Check(PythonAst ast, CompilerContext context) { @@ -122,7 +122,7 @@ public override bool Walk(StarredExpression node) { public override bool Walk(TupleExpression node) => WalkItems(node.Items); private void ReportSyntaxError(string message, Node node) { - context.Errors.Add(context.SourceUnit, message, node.Span, ErrorCodes.SyntaxError, Severity.FatalError); + _context.Errors.Add(_context.SourceUnit, message, node.Span, ErrorCodes.SyntaxError, Severity.FatalError); } private void WalkAssignmentTarget(Expression expr) { diff --git a/src/core/IronPython/Compiler/Ast/YieldFromExpression.cs b/src/core/IronPython/Compiler/Ast/YieldFromExpression.cs index 15976d816..1f33e355f 100644 --- a/src/core/IronPython/Compiler/Ast/YieldFromExpression.cs +++ b/src/core/IronPython/Compiler/Ast/YieldFromExpression.cs @@ -15,12 +15,12 @@ namespace IronPython.Compiler.Ast { using Ast = MSAst.Expression; public class YieldFromExpression : Expression { - private readonly Statement statement; - private readonly NameExpression result; + private readonly Statement _statement; + private readonly NameExpression _result; public YieldFromExpression(Expression expression) { - statement = GenYieldFromStatement(expression); - result = new NameExpression("__yieldfromprefix_r"); + _statement = GenYieldFromStatement(expression); + _result = new NameExpression("__yieldfromprefix_r"); Expression = expression; } @@ -83,16 +83,16 @@ private static Statement GenYieldFromStatement(Expression expression) { public override MSAst.Expression Reduce() { return Ast.Block( typeof(object), - statement, - AstUtils.Convert(result, typeof(object)) + _statement, + AstUtils.Convert(_result, typeof(object)) ).Reduce(); } public override void Walk(PythonWalker walker) { if (walker.Walk(this)) { // Expression is already walked as part of statement so skip it - statement.Walk(walker); - result.Walk(walker); + _statement.Walk(walker); + _result.Walk(walker); } walker.PostWalk(this); } diff --git a/src/core/IronPython/Modules/_ast.cs b/src/core/IronPython/Modules/_ast.cs index de446326f..ef18a2670 100755 --- a/src/core/IronPython/Modules/_ast.cs +++ b/src/core/IronPython/Modules/_ast.cs @@ -1000,6 +1000,11 @@ internal BoolOp(OrExpression or) } internal override AstExpression Revert() { + if (values.Count < 2) throw PythonOps.ValueError($"{nameof(BoolOp)} with less than 2 values"); + foreach (var val in values) { + if (val is null) throw PythonOps.ValueError("None disallowed in expression list"); + } + if (op == And.Instance || op is And) { AndExpression ae = new AndExpression( expr.Revert(values[0]), @@ -2564,8 +2569,9 @@ internal Set(SetExpression setExpression) internal override AstExpression Revert() { AstExpression[] e = new AstExpression[elts.Count]; int i = 0; - foreach (expr el in elts) - e[i++] = expr.Revert(el); + foreach (expr el in elts) { + e[i++] = expr.Revert(el) ?? throw PythonOps.ValueError("None disallowed in expression list"); + } return new SetExpression(e); } diff --git a/src/core/IronPython/Modules/sys.cs b/src/core/IronPython/Modules/sys.cs index 40f542f20..8c95149c5 100644 --- a/src/core/IronPython/Modules/sys.cs +++ b/src/core/IronPython/Modules/sys.cs @@ -214,7 +214,7 @@ public static int getsizeof(object o) { public static PythonTuple getwindowsversion() => windows_version.GetWindowsVersion(); - [PythonType("sys.getwindowsversion"), SupportedOSPlatform("windows"), PythonHidden] + [PythonType("getwindowsversion"), SupportedOSPlatform("windows"), PythonHidden] public sealed class windows_version : PythonTuple { internal static windows_version GetWindowsVersion() { unsafe { @@ -591,6 +591,65 @@ public override string __repr__(CodeContext context) { } } + [PythonType("version_info"), PythonHidden] + public class VersionInfo : PythonTuple { + public readonly int major; + public readonly int minor; + public readonly int micro; + public readonly string releaselevel; + public readonly int serial; + + private VersionInfo(int major, int minor, int micro, string releaselevel, int serial) + : base(new object[] { major, minor, micro, releaselevel, serial }) { + this.major = major; + this.minor = minor; + this.micro = micro; + this.releaselevel = releaselevel; + this.serial = serial; + } + + internal static VersionInfo Instance { get; } = new VersionInfo(CurrentVersion.Major, + CurrentVersion.Minor, + CurrentVersion.Micro, + CurrentVersion.ReleaseLevel, + CurrentVersion.ReleaseSerial); + + public override string __repr__(CodeContext context) { + return string.Format("sys.version_info(major={0}, minor={1}, micro={2}, releaselevel='{3}', serial={4})", + major, minor, micro, releaselevel, serial); + } + + internal int GetHexVersion() { + int hexlevel = 0; + switch (releaselevel) { + case "alpha": + hexlevel = 0xA; + break; + + case "beta": + hexlevel = 0xB; + break; + + case "candidate": + hexlevel = 0xC; + break; + + case "final": + hexlevel = 0xF; + break; + } + + return (major << 24) | + (minor << 16) | + (micro << 8) | + (hexlevel << 4) | + (serial << 0); + } + + internal string GetVersionString() + => CurrentVersion.GetVersionString(major, minor, micro, releaselevel, serial); + } + [SpecialName] public static void PerformModuleReload(PythonContext/*!*/ context, PythonDictionary/*!*/ dict) { dict["stdin"] = dict["__stdin__"]; diff --git a/src/core/IronPython/Runtime/Implementation.cs b/src/core/IronPython/Runtime/CurrentVersion.cs similarity index 53% rename from src/core/IronPython/Runtime/Implementation.cs rename to src/core/IronPython/Runtime/CurrentVersion.cs index 5d875f844..3822df68c 100644 --- a/src/core/IronPython/Runtime/Implementation.cs +++ b/src/core/IronPython/Runtime/CurrentVersion.cs @@ -8,65 +8,6 @@ using System.Reflection; namespace IronPython.Runtime { - [PythonType("sys.version_info")] - public class VersionInfo : PythonTuple { - public readonly int major; - public readonly int minor; - public readonly int micro; - public readonly string releaselevel; - public readonly int serial; - - private VersionInfo(int major, int minor, int micro, string releaselevel, int serial) - : base(new object[] { major, minor, micro, releaselevel, serial }) { - this.major = major; - this.minor = minor; - this.micro = micro; - this.releaselevel = releaselevel; - this.serial = serial; - } - - internal static VersionInfo Instance { get; } = new VersionInfo(CurrentVersion.Major, - CurrentVersion.Minor, - CurrentVersion.Micro, - CurrentVersion.ReleaseLevel, - CurrentVersion.ReleaseSerial); - - public override string __repr__(CodeContext context) { - return string.Format("sys.version_info(major={0}, minor={1}, micro={2}, releaselevel='{3}', serial={4})", - major, minor, micro, releaselevel, serial); - } - - internal int GetHexVersion() { - int hexlevel = 0; - switch (releaselevel) { - case "alpha": - hexlevel = 0xA; - break; - - case "beta": - hexlevel = 0xB; - break; - - case "candidate": - hexlevel = 0xC; - break; - - case "final": - hexlevel = 0xF; - break; - } - - return (major << 24) | - (minor << 16) | - (micro << 8) | - (hexlevel << 4) | - (serial << 0); - } - - internal string GetVersionString() - => CurrentVersion.GetVersionString(major, minor, micro, releaselevel, serial); - } - internal static class CurrentVersion { public static int Major { get; } public static int Minor { get; } diff --git a/src/core/IronPython/Runtime/PythonContext.cs b/src/core/IronPython/Runtime/PythonContext.cs index a77180ed3..793879248 100644 --- a/src/core/IronPython/Runtime/PythonContext.cs +++ b/src/core/IronPython/Runtime/PythonContext.cs @@ -1881,9 +1881,9 @@ internal void SetHostVariables(PythonDictionary dict) { } private void SetVersionVariables(PythonDictionary dict) { - dict["implementation"] = new SimpleNamespace(new Dictionary() { { "cache_tag", $"ironpython-{VersionInfo.Instance.major}{VersionInfo.Instance.minor}" }, { "name", "ironpython" }, { "version", VersionInfo.Instance }, { "hexversion", VersionInfo.Instance.GetHexVersion() } }); - dict["version_info"] = VersionInfo.Instance; - dict["hexversion"] = VersionInfo.Instance.GetHexVersion(); + dict["implementation"] = new SimpleNamespace(new Dictionary() { { "cache_tag", $"ironpython-{SysModule.VersionInfo.Instance.major}{SysModule.VersionInfo.Instance.minor}" }, { "name", "ironpython" }, { "version", SysModule.VersionInfo.Instance }, { "hexversion", SysModule.VersionInfo.Instance.GetHexVersion() } }); + dict["version_info"] = SysModule.VersionInfo.Instance; + dict["hexversion"] = SysModule.VersionInfo.Instance.GetHexVersion(); dict["version"] = _initialVersionString ?? GetVersionString(); } @@ -1903,7 +1903,7 @@ internal static string GetVersionString() { string configuration = Runtime.ClrModule.IsDebug ? " DEBUG" : string.Empty; string bitness = (IntPtr.Size * 8).ToString(); - return $"{VersionInfo.Instance.GetVersionString()}{configuration} ({Runtime.ClrModule.FileVersion})\n" + + return $"{SysModule.VersionInfo.Instance.GetVersionString()}{configuration} ({Runtime.ClrModule.FileVersion})\n" + $"[{Runtime.ClrModule.TargetFramework} on {Runtime.ClrModule.FrameworkDescription} ({bitness}-bit)]"; } diff --git a/src/core/IronPython/Runtime/Types/PythonType.cs b/src/core/IronPython/Runtime/Types/PythonType.cs index 8d4896bfc..c60cb9391 100644 --- a/src/core/IronPython/Runtime/Types/PythonType.cs +++ b/src/core/IronPython/Runtime/Types/PythonType.cs @@ -895,12 +895,7 @@ internal int Hash(object o) { } internal bool TryGetLength(CodeContext context, object o, out int length) { - CallSite> lenSite; - if (IsSystemType) { - lenSite = context.LanguageContext.GetSiteCacheForSystemType(UnderlyingSystemType).GetLenSite(context); - } else { - lenSite = _siteCache.GetLenSite(context); - } + var lenSite = GetSiteCache(context).GetLenSite(context); PythonTypeSlot lenSlot = _lenSlot; if (lenSlot == null && !PythonOps.TryResolveTypeSlot(context, this, "__len__", out lenSlot)) { @@ -935,35 +930,22 @@ internal bool EqualRetBool(object self, object other) { return _eqSite.Target(_eqSite, self, other); } - internal CallSite> GetTryGetMemberSite( - CodeContext context, string name) { - CallSite> site; - if (IsSystemType) { - site = context.LanguageContext - .GetSiteCacheForSystemType(UnderlyingSystemType) - .GetTryGetMemberSite(context, name); - } else { - site = _siteCache.GetTryGetMemberSite(context, name); - } - return site; - } + private PythonSiteCache GetSiteCache(CodeContext context) + => IsSystemType + ? context.LanguageContext.GetSiteCacheForSystemType(UnderlyingSystemType) + : _siteCache; /// /// Gets an attribute the same way the attribute access operator does, so that /// the exception raised if that fails is preserved. /// internal object GetBoundAttr(CodeContext context, object o, string name) { - PythonSiteCache siteCache = IsSystemType - ? context.LanguageContext.GetSiteCacheForSystemType(UnderlyingSystemType) - : _siteCache; - CallSite> site = siteCache.GetGetMemberSite(context, name); - + var site = GetSiteCache(context).GetGetMemberSite(context, name); return site.Target(site, o, context); } internal bool TryGetBoundAttr(CodeContext context, object o, string name, out object ret) { - CallSite> site = - GetTryGetMemberSite(context, name); + var site = GetSiteCache(context).GetTryGetMemberSite(context, name); try { ret = site.Target(site, o, context); @@ -1532,13 +1514,7 @@ internal bool TryGetBoundMember(CodeContext context, object instance, string nam } private object InvokeGetAttributeMethod(CodeContext context, string name, object getattr) { - CallSite> getAttributeSite; - if (IsSystemType) { - getAttributeSite = context.LanguageContext.GetSiteCacheForSystemType(UnderlyingSystemType).GetGetAttributeSite(context); - } else { - getAttributeSite = _siteCache.GetGetAttributeSite(context); - } - + var getAttributeSite = GetSiteCache(context).GetGetAttributeSite(context); return getAttributeSite.Target(getAttributeSite, context, getattr, name); } @@ -1613,13 +1589,7 @@ private bool TryResolveNonObjectSlot(CodeContext context, object instance, strin internal bool TrySetMember(CodeContext context, object instance, string name, object value) { object setattr; if (TryResolveNonObjectSlot(context, instance, "__setattr__", out setattr)) { - CallSite> setAttrSite; - if (IsSystemType) { - setAttrSite = context.LanguageContext.GetSiteCacheForSystemType(UnderlyingSystemType).GetSetAttrSite(context); - } else { - setAttrSite = _siteCache.GetSetAttrSite(context); - } - + var setAttrSite = GetSiteCache(context).GetSetAttrSite(context); setAttrSite.Target(setAttrSite, context, setattr, instance, name, value); return true; } @@ -1753,9 +1723,7 @@ private PythonList TryGetCustomDir(CodeContext context, object self) { if (self != null) { object dir; if (TryResolveNonObjectSlot(context, self, "__dir__", out dir)) { - CallSite> dirSite = IsSystemType - ? context.LanguageContext.GetSiteCacheForSystemType(UnderlyingSystemType).GetDirSite(context) - : _siteCache.GetDirSite(context); + var dirSite = GetSiteCache(context).GetDirSite(context); return new PythonList(context, dirSite.Target(dirSite, context, dir)); } diff --git a/tests/IronPython.Tests/Cases/CPythonCasesManifest.ini b/tests/IronPython.Tests/Cases/CPythonCasesManifest.ini index 8a04c6242..b34c8ebb2 100644 --- a/tests/IronPython.Tests/Cases/CPythonCasesManifest.ini +++ b/tests/IronPython.Tests/Cases/CPythonCasesManifest.ini @@ -788,6 +788,9 @@ Ignore=true [CPython.test_smtplib] RunCondition=NOT $(IS_POSIX) # TODO: debug +[CPython.test_smtpnet] +RetryCount=2 # smtp.gmail.com sometimes times out or resets the connection on CI + [CPython.test_socket] RunCondition=NOT $(IS_MONO) # TODO: figure out Timeout=300000 # 5 minute timeout - sometimes slow diff --git a/tests/suite/stdlib/test_pdb.py b/tests/suite/stdlib/test_pdb.py index 327d0c501..e475d060e 100644 --- a/tests/suite/stdlib/test_pdb.py +++ b/tests/suite/stdlib/test_pdb.py @@ -40,13 +40,11 @@ def load_tests(loader, standard_tests, pattern): )] if sys.version_info >= (3, 6): failing_tests += [doctests['test.test_pdb.' + name] for name in ( - # the second set_trace stops on the line after it (in CI, an order-dependent "Value cannot be null. Parameter name: del") - 'test_pdb_issue_20766', - # asyncio.new_event_loop() fails: socket.fileno() returns Int64, which selectors rejects - 'test_pdb_next_command_for_asyncgen', - 'test_pdb_next_command_for_coroutine', - 'test_pdb_return_command_for_coroutine', - 'test_pdb_until_command_for_coroutine', + 'test_pdb_issue_20766', # second set_trace stops on the wrong line + 'test_pdb_next_command_for_asyncgen', # no async generators + 'test_pdb_next_command_for_coroutine', # can't await asyncio.sleep + 'test_pdb_return_command_for_coroutine', # can't await asyncio.sleep + 'test_pdb_until_command_for_coroutine', # can't await asyncio.sleep )] if is_posix: diff --git a/tests/suite/stdlib/test_sys_settrace.py b/tests/suite/stdlib/test_sys_settrace.py index 7df0ae5e9..520f6b996 100644 --- a/tests/suite/stdlib/test_sys_settrace.py +++ b/tests/suite/stdlib/test_sys_settrace.py @@ -40,23 +40,24 @@ def load_tests(loader, standard_tests, pattern): test.test_sys_settrace.JumpTestCase('test_jump_in_nested_finally_2'), test.test_sys_settrace.JumpTestCase('test_jump_in_nested_finally_3'), test.test_sys_settrace.JumpTestCase('test_jump_out_of_with_assignment'), # no line event for the `as x:` continuation line, so the jump never happens - # asyncio.new_event_loop() fails: socket.fileno() returns Int64, which selectors rejects - test.test_sys_settrace.JumpTestCase('test_jump_across_async_with'), + # any jump in a coroutine that awaits crashes with IndexError (net10.0 refuses jumps in coroutines) test.test_sys_settrace.JumpTestCase('test_jump_backwards_out_of_async_with_block'), test.test_sys_settrace.JumpTestCase('test_jump_forwards_out_of_async_with_block'), - test.test_sys_settrace.JumpTestCase('test_jump_out_of_async_for_block_backwards'), - test.test_sys_settrace.JumpTestCase('test_jump_out_of_async_for_block_forwards'), test.test_sys_settrace.JumpTestCase('test_jump_out_of_async_with_assignment'), test.test_sys_settrace.JumpTestCase('test_jump_out_of_async_with_block_within_finally_block'), test.test_sys_settrace.JumpTestCase('test_jump_out_of_async_with_block_within_for_block'), test.test_sys_settrace.JumpTestCase('test_jump_out_of_async_with_block_within_with_block'), test.test_sys_settrace.JumpTestCase('test_jump_over_async_for_block_before_else'), - test.test_sys_settrace.JumpTestCase('test_no_jump_backwards_into_async_for_block'), test.test_sys_settrace.JumpTestCase('test_no_jump_backwards_into_async_with_block'), test.test_sys_settrace.JumpTestCase('test_no_jump_between_async_with_blocks'), test.test_sys_settrace.JumpTestCase('test_no_jump_forwards_into_async_for_block'), test.test_sys_settrace.JumpTestCase('test_no_jump_forwards_into_async_with_block'), test.test_sys_settrace.JumpTestCase('test_no_jump_into_async_for_block_before_else'), + test.test_sys_settrace.JumpTestCase('test_jump_across_async_with'), # async with is a try/finally: "can't jump into 'finally block'" + # no async generators + test.test_sys_settrace.JumpTestCase('test_jump_out_of_async_for_block_backwards'), + test.test_sys_settrace.JumpTestCase('test_jump_out_of_async_for_block_forwards'), + test.test_sys_settrace.JumpTestCase('test_no_jump_backwards_into_async_for_block'), ] skip_tests = [] diff --git a/tests/suite/test_namebinding.py b/tests/suite/test_namebinding.py index b1ffe9d7e..401713b84 100644 --- a/tests/suite/test_namebinding.py +++ b/tests/suite/test_namebinding.py @@ -520,6 +520,15 @@ def test(): self._test_undefined(test) + def test_undefined_after_default(self): + """defaults and annotations are evaluated in the enclosing scope""" + undefined = 1 + def test(x=undefined, y: undefined = None): + x = undefined + undefined = 1 # create local binding + + self._test_undefined(test) + def test_explicit_deletion(self): """explicit deletion""" def test():