diff --git a/src/core/IronPython/Compiler/Ast/AstMethods.cs b/src/core/IronPython/Compiler/Ast/AstMethods.cs index ae8d877bf..0c570f4ee 100644 --- a/src/core/IronPython/Compiler/Ast/AstMethods.cs +++ b/src/core/IronPython/Compiler/Ast/AstMethods.cs @@ -76,8 +76,11 @@ internal static class AstMethods { public static readonly MethodInfo ForLoopDispose = GetMethod((Action>)PythonOps.ForLoopDispose); public static readonly MethodInfo GetClosureTupleFromContext = GetMethod((Func)PythonOps.GetClosureTupleFromContext); public static readonly MethodInfo PushFrame = GetMethod((Func>)PythonOps.PushFrame); + public static readonly MethodInfo PushFrameWithLineNumber = GetMethod((PushFrameWithLineNumberDelegate)PythonOps.PushFrame); #if DEBUG public static readonly MethodInfo PopFrame = GetMethod((Action>)PythonOps.PopFrame); +#else + public static readonly MethodInfo PopFrame = GetMethod((Action>)PythonOps.PopFrame); #endif public static readonly MethodInfo PushGeneratorFrame = GetMethod((Action)PythonOps.PushGeneratorFrame); public static readonly MethodInfo FormatString = GetMethod((Func)PythonOps.FormatString); @@ -108,5 +111,8 @@ internal static class AstMethods { private static MethodInfo GetMethod(Delegate x) { return x.Method; } + + // Func can't express a by-ref parameter + private delegate List PushFrameWithLineNumberDelegate(CodeContext context, FunctionCode function, ref int lineNo); } } diff --git a/src/core/IronPython/Compiler/Ast/Node.cs b/src/core/IronPython/Compiler/Ast/Node.cs index da0a67b33..db003b181 100644 --- a/src/core/IronPython/Compiler/Ast/Node.cs +++ b/src/core/IronPython/Compiler/Ast/Node.cs @@ -316,8 +316,12 @@ internal static MSAst.Expression RemoveDebugInfo(int prevStart, MSAst.Expression /// /// Creates a method frame for tracking purposes and enforces recursion /// - internal static MSAst.Expression AddFrame(MSAst.Expression localContext, MSAst.Expression codeObject, MSAst.Expression body) - => new FramedCodeExpression(localContext, codeObject, body, inGenerator: false); + /// + /// Whether compiled code publishes its current line through the frame. It requires to be + /// declared around the frame, which does for code that can throw. + /// + internal static MSAst.Expression AddFrame(MSAst.Expression localContext, MSAst.Expression codeObject, MSAst.Expression body, bool publishLineNumber = true) + => new FramedCodeExpression(localContext, codeObject, body, inGenerator: false, publishLineNumber); /// /// Creates a method frame for the body of a generator, which hands the frame over to its . @@ -328,7 +332,7 @@ internal static MSAst.Expression AddFrame(MSAst.Expression localContext, MSAst.E /// and removes it when the body finishes. /// internal static MSAst.Expression AddGeneratorFrame(MSAst.Expression localContext, MSAst.Expression codeObject, MSAst.Expression body) - => new FramedCodeExpression(localContext, codeObject, body, inGenerator: true); + => new FramedCodeExpression(localContext, codeObject, body, inGenerator: true, publishLineNumber: false); #if FEATURE_NET_ASYNC /// @@ -340,7 +344,7 @@ internal static MSAst.Expression AddGeneratorFrame(MSAst.Expression localContext /// The , the observer of the body's driver, moves the frame along with the body. /// internal static MSAst.Expression AddAsyncFrame(MSAst.Expression localContext, MSAst.Expression asyncFrame, MSAst.Expression codeObject, MSAst.Expression body) - => new FramedCodeExpression(localContext, codeObject, body, inGenerator: false, asyncFrame); + => new FramedCodeExpression(localContext, codeObject, body, inGenerator: false, publishLineNumber: false, asyncFrame); #endif /// @@ -359,17 +363,30 @@ private class FramedCodeVisitor : ExpressionVisitor { } } - private sealed class FramedCodeExpression : MSAst.Expression { + /// + /// Compiled code that can't suspend publishes its current line through its frame stack entry, as a pointer to + /// , which is a local of the compiled method. Interpreted code doesn't, since the + /// interpreter keeps its locals in the interpreted frame and passes a reference to a copy of the variable. + /// + private sealed class FramedCodeExpression : MSAst.Expression, IInstructionProvider { private readonly MSAst.Expression _localContext, _codeObject; - private readonly bool _inGenerator; + private readonly bool _inGenerator, _publishLineNumber; // For an async body: the AsyncBodyFrame the body hands its frame over to. private readonly MSAst.Expression? _asyncFrame; - public FramedCodeExpression(MSAst.Expression localContext, MSAst.Expression codeObject, MSAst.Expression body, bool inGenerator, MSAst.Expression? asyncFrame = null) { + // Where dynamic code isn't supported, LambdaExpression.Compile interprets the lambda, so its locals aren't on the stack. +#if NET + private static bool CanPublishLineNumber => System.Runtime.CompilerServices.RuntimeFeature.IsDynamicCodeSupported; +#else + private static bool CanPublishLineNumber => true; +#endif + + public FramedCodeExpression(MSAst.Expression localContext, MSAst.Expression codeObject, MSAst.Expression body, bool inGenerator, bool publishLineNumber, MSAst.Expression? asyncFrame = null) { _localContext = localContext; _codeObject = codeObject; _inGenerator = inGenerator; + _publishLineNumber = publishLineNumber; _asyncFrame = asyncFrame; Body = body; } @@ -378,7 +395,11 @@ public FramedCodeExpression(MSAst.Expression localContext, MSAst.Expression code public MSAst.Expression Body { get; } - public override MSAst.Expression Reduce() { + public override MSAst.Expression Reduce() => Reduce(publishLineNumber: _publishLineNumber && CanPublishLineNumber); + + void IInstructionProvider.AddInstructions(LightCompiler compiler) => compiler.Compile(Reduce(publishLineNumber: false)); + + private MSAst.Expression Reduce(bool publishLineNumber) { if (_inGenerator) { return Ast.Block( Ast.Call( @@ -414,11 +435,7 @@ public override MSAst.Expression Reduce() { AstUtils.Try( Ast.Assign( FunctionStackVariable, - Ast.Call( - AstMethods.PushFrame, - _localContext, - Ast.Assign(code, _codeObject) - ) + PushFrame(Ast.Assign(code, _codeObject), publishLineNumber) ), Body ).Finally( @@ -434,29 +451,35 @@ public override MSAst.Expression Reduce() { return AstUtils.Try( Ast.Assign( FunctionStackVariable, - Ast.Call( - AstMethods.PushFrame, - _localContext, - _codeObject - ) + PushFrame(_codeObject, publishLineNumber) ), Body ).Finally( Ast.Call( - FunctionStackVariable, - typeof(List).GetMethod(nameof(List.RemoveAt))!, - Ast.Add( - Ast.Property( - FunctionStackVariable, - "Count" - ), - Ast.Constant(-1) - ) + AstMethods.PopFrame, + FunctionStackVariable ) ); #endif } + private MSAst.Expression PushFrame(MSAst.Expression codeObject, bool publishLineNumber) { + if (publishLineNumber) { + return Ast.Call( + AstMethods.PushFrameWithLineNumber, + _localContext, + codeObject, + LineNumberExpression + ); + } + + return Ast.Call( + AstMethods.PushFrame, + _localContext, + codeObject + ); + } + public override Type Type => Body.Type; public override bool CanReduce => true; @@ -468,7 +491,7 @@ protected override MSAst.Expression VisitChildren(ExpressionVisitor visitor) { var asyncFrame = visitor.Visit(_asyncFrame); if (localContext != _localContext || _codeObject != codeObject || body != Body || asyncFrame != _asyncFrame) { - return new FramedCodeExpression(localContext, codeObject, body, _inGenerator, asyncFrame); + return new FramedCodeExpression(localContext, codeObject, body, _inGenerator, _publishLineNumber, asyncFrame); } return this; diff --git a/src/core/IronPython/Compiler/Ast/PythonAst.cs b/src/core/IronPython/Compiler/Ast/PythonAst.cs index 7c63636d7..aa58b4e4f 100644 --- a/src/core/IronPython/Compiler/Ast/PythonAst.cs +++ b/src/core/IronPython/Compiler/Ast/PythonAst.cs @@ -396,7 +396,8 @@ internal MSAst.Expression ReduceWorker() { end.Column ), AstUtils.Convert(simpleBody, typeof(object)) - ) + ), + publishLineNumber: false // there is no line number variable ); } @@ -422,7 +423,7 @@ internal MSAst.Expression ReduceWorker() { MSAst.Expression body = Ast.Block(block.ToReadOnlyCollection()); - body = AddModuleFrame(body); + body = AddModuleFrame(body, publishLineNumber: Body.CanThrow); body = WrapScopeStatements(body, Body.CanThrow); // new ComboActionRewriter().VisitNode(Transform(ag)) @@ -445,12 +446,13 @@ internal MSAst.Expression ReduceWorker() { /// /// Adds the frame of module, exec or eval code, which the code pushes and pops itself, as functions and class bodies do. /// - private MSAst.Expression AddModuleFrame(MSAst.Expression body) { + /// Whether the code has a line number variable to publish (see ). + private MSAst.Expression AddModuleFrame(MSAst.Expression body, bool publishLineNumber) { if (!PyContext.PythonOptions.Frames) { return body; } - return Ast.Block([FunctionStackVariable], AddFrame(LocalContext, FuncCodeExpr, body)); + return Ast.Block([FunctionStackVariable], AddFrame(LocalContext, FuncCodeExpr, body, publishLineNumber)); } /// diff --git a/src/core/IronPython/Modules/sys.cs b/src/core/IronPython/Modules/sys.cs index 40f542f20..212ace95a 100644 --- a/src/core/IronPython/Modules/sys.cs +++ b/src/core/IronPython/Modules/sys.cs @@ -197,7 +197,7 @@ public static string getfilesystemencodeerrors() { cur ); - stack[i] = new FunctionStack(elem.Context, elem.Code, cur); + stack[i] = elem.WithFrame(cur); } } return cur; diff --git a/src/core/IronPython/Runtime/Exceptions/TraceBack.cs b/src/core/IronPython/Runtime/Exceptions/TraceBack.cs index 80393afa0..d7684b93c 100644 --- a/src/core/IronPython/Runtime/Exceptions/TraceBack.cs +++ b/src/core/IronPython/Runtime/Exceptions/TraceBack.cs @@ -95,6 +95,7 @@ internal TraceBackFrame(CodeContext/*!*/ context, PythonDictionary globals, obje _locals = locals; _code = code; _context = context; + _lineNo = 1; } internal TraceBackFrame(CodeContext/*!*/ context, PythonDictionary globals, object locals, FunctionCode code, TraceBackFrame back) { @@ -103,6 +104,7 @@ internal TraceBackFrame(CodeContext/*!*/ context, PythonDictionary globals, obje _code = code; _context = context; _back = back; + _lineNo = 1; } internal TraceBackFrame(PythonTracebackListener traceAdapter, FunctionCode code, TraceBackFrame back, PythonDebuggingPayload debugProperties, Func> scopeCallback) { @@ -205,7 +207,7 @@ public object f_lineno { if (_traceAdapter != null) { return _lineNo; } else { - return 1; + return GetLineNumber(); } } set { @@ -217,6 +219,40 @@ public object f_lineno { } } + /// + /// Gets the current line of a frame that isn't traced. + /// + /// + /// While the code of the frame runs, compiled code publishes its line through the frame stack entry, which is read only on the + /// thread of the entry. Otherwise, the frame reports the line saved by , or 1 if no line is known. + /// + private unsafe int GetLineNumber() { + List stack = PythonOps.GetFunctionStackNoCreate(); + if (stack != null) { + for (int i = stack.Count - 1; i >= 0; i--) { + FunctionStack entry = stack[i]; + if (entry.Frame == this) { + if (entry.LineNumberPtr != null) { + return *entry.LineNumberPtr; + } + break; + } + } + } + return _lineNo; + } + + /// + /// Saves the current line that the code of this frame publishes through , the + /// of its entry, if any, so that the frame still reports it after the entry is removed + /// from the frame stack. + /// + internal unsafe void SaveLineNumber(int* lineNumberPtr) { + if (lineNumberPtr != null) { + _lineNo = *lineNumberPtr; + } + } + private void SetLineNumber(int newLineNum) { if (_traceAdapter == null || PythonTracebackListener.CurrentTraceFrame != this) { throw PythonOps.ValueError("f_lineno can only be set by a trace function on the frame of the current event, other than a 'return' event"); diff --git a/src/core/IronPython/Runtime/Operations/PythonOps.cs b/src/core/IronPython/Runtime/Operations/PythonOps.cs index 92eadb6a9..e0d29d2a8 100644 --- a/src/core/IronPython/Runtime/Operations/PythonOps.cs +++ b/src/core/IronPython/Runtime/Operations/PythonOps.cs @@ -2517,6 +2517,10 @@ private static void SetCurrentExceptionState(HandledException? state) { stack.Code, lastTraceBackFrame ); + // the entry doesn't get this frame, so the frame keeps the current line + unsafe { + tbf.SaveLineNumber(stack.LineNumberPtr); + } } lastTraceBackFrame = tbf; @@ -4520,14 +4524,57 @@ public static List PushFrame(CodeContext/*!*/ context, FunctionCo } /// - /// Removes the entry that pushed for code that can't suspend, after checking it in debug builds. + /// Pushes the frame of compiled code that can't suspend, which publishes its current line through the entry. + /// + /// + /// must be a local of the compiled method that pushes the frame, which stays at the same address until + /// the method removes the entry with . Interpreted code must not call this method: + /// the interpreter passes a reference to a copy of the variable. + /// + public static unsafe List PushFrame(CodeContext/*!*/ context, FunctionCode function, ref int lineNo) { + List stack = GetFunctionStack(); + // The variable is on the stack, so it doesn't move and needs no pin. + int* lineNumberPtr = (int*)Unsafe.AsPointer(ref lineNo); + AssertOnStack(lineNumberPtr); + stack.Add(new FunctionStack(context, function, lineNumberPtr)); + return stack; + } + + /// + /// Asserts that is on the stack, in the frame of a caller, and not in a heap object that can move. + /// + [Conditional("DEBUG"), MethodImpl(MethodImplOptions.NoInlining)] + private static unsafe void AssertOnStack(int* address) { + // The stack grows down, so the frames of the callers are just above the local of this method. + int local = 0; + Debug.Assert((byte*)address > (byte*)&local && (byte*)address - (byte*)&local < 0x100000, + "the line number of compiled code should be a local of the method that pushes the frame"); + } + + /// + /// Removes the entry that pushed for code that can't suspend. /// /// - /// Generated code calls this only in debug builds. In release builds it removes the top entry itself, without checking. + /// Generated code calls this in release builds. Debug builds call , + /// which checks the entry first. + /// + public static unsafe void PopFrame(List stack) { + int index = stack.Count - 1; + FunctionStack entry = stack[index]; + // passing the entry by value would make every call zero a stack copy of it + entry.Frame?.SaveLineNumber(entry.LineNumberPtr); + stack.RemoveAt(index); + } + + /// + /// Removes the entry that pushed for code that can't suspend, after checking it. + /// + /// + /// Generated code calls this only in debug builds. In release builds it calls . /// public static void PopFrame(CodeContext/*!*/ context, FunctionCode function, List stack) { AssertOwnFrameOnTop(context, function, stack); - stack.RemoveAt(stack.Count - 1); + PopFrame(stack); } /// @@ -4716,6 +4763,15 @@ public readonly struct FunctionStack { public readonly FunctionCode/*!*/ Code; public readonly TraceBackFrame? Frame; + /// + /// Points to the variable that holds the current line of the code, or is null if the code doesn't publish its line. + /// + /// + /// Only compiled code that can't suspend publishes its line (see ). + /// The variable is a local of the compiled method, so the pointer is valid only while the entry is on the frame stack of its thread. + /// + internal readonly unsafe int* LineNumberPtr; + internal FunctionStack(CodeContext/*!*/ context, FunctionCode/*!*/ code) { Assert.NotNull(context, code); @@ -4724,12 +4780,22 @@ internal FunctionStack(CodeContext/*!*/ context, FunctionCode/*!*/ code) { Frame = null; } - internal FunctionStack(CodeContext/*!*/ context, FunctionCode/*!*/ code, TraceBackFrame frame) { + internal unsafe FunctionStack(CodeContext/*!*/ context, FunctionCode/*!*/ code, int* lineNumberPtr) { + Assert.NotNull(context, code); + + Context = context; + Code = code; + Frame = null; + LineNumberPtr = lineNumberPtr; + } + + private unsafe FunctionStack(CodeContext/*!*/ context, FunctionCode/*!*/ code, TraceBackFrame frame, int* lineNumberPtr) { Assert.NotNull(context, code); Context = context; Code = code; Frame = frame; + LineNumberPtr = lineNumberPtr; } internal FunctionStack(TraceBackFrame frame) { @@ -4737,5 +4803,10 @@ internal FunctionStack(TraceBackFrame frame) { Code = frame.f_code; Frame = frame; } + + /// + /// Makes a copy of this entry with the given frame object, which keeps publishing the line of the code. + /// + internal unsafe FunctionStack WithFrame(TraceBackFrame frame) => new FunctionStack(Context, Code, frame, LineNumberPtr); } } diff --git a/tests/IronPython.Tests/Cases/IronPythonCasesManifest.ini b/tests/IronPython.Tests/Cases/IronPythonCasesManifest.ini index 68ac0b59a..b1463cfb2 100644 --- a/tests/IronPython.Tests/Cases/IronPythonCasesManifest.ini +++ b/tests/IronPython.Tests/Cases/IronPythonCasesManifest.ini @@ -25,6 +25,14 @@ Reason=disabled in IronLanguages/main, needs lots of work RunCondition=NOT $(IS_OSX) # TODO: figure out IsolationLevel=PROCESS # required to have quit/exit +[IronPython.test_frame_lineno] +IsolationLevel=PROCESS +Arguments=-X NoAdaptiveCompilation "$(TEST_FILE)" # the test is skipped without the option + +[IronPython.test_frame_lineno_debug] +IsolationLevel=PROCESS +Arguments=-X Debug "$(TEST_FILE)" # the test is skipped without the option + [IronPython.test_help] IsolationLevel=PROCESS # required for help to use pydoc diff --git a/tests/suite/test_frame_lineno.py b/tests/suite/test_frame_lineno.py new file mode 100644 index 000000000..b7fab0dd0 --- /dev/null +++ b/tests/suite/test_frame_lineno.py @@ -0,0 +1,100 @@ +# 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. + +""" +Test that frames report their current line. + +In IronPython, so far only compiled code does, other than generators and async code, so the test needs code compiled +up front: -X NoAdaptiveCompilation or -X Debug. test_frame_lineno_debug runs the same tests with -X Debug. +""" + +import sys +import threading +import traceback +import unittest +import warnings + +from iptest import IronPythonTestCase, is_cli, run_test + +if is_cli: + import clr + runtime = clr.GetCurrentRuntime() + no_adaptive_compilation = runtime.GetLanguageByName('python').Options.NoAdaptiveCompilation + debug_mode = runtime.Configuration.DebugMode +else: + no_adaptive_compilation = True + debug_mode = False + +def caller_line(): + return sys._getframe(1).f_lineno + +def first_line(func): + return func.__code__.co_firstlineno + +def identity(obj): + return obj + +def module_line_marker(): pass +module_line = sys._getframe().f_lineno + +@unittest.skipUnless(no_adaptive_compilation or debug_mode, 'requires -X NoAdaptiveCompilation or -X Debug') +class FrameLinenoTest(IronPythonTestCase): + def test_current_frame(self): + line = sys._getframe().f_lineno + self.assertEqual(line, first_line(self.test_current_frame) + 1) + + def test_caller_frame(self): + lines = [caller_line()] + lines.append(caller_line()) + start = first_line(self.test_caller_frame) + self.assertEqual(lines, [start + 1, start + 2]) + + def test_extract_stack(self): + line = traceback.extract_stack()[-1][1] + self.assertEqual(line, first_line(self.test_extract_stack) + 1) + + def test_warnings(self): + def warn(): + warnings.warn("message") + warnings.warn("message") + + with warnings.catch_warnings(record=True) as caught: + warnings.simplefilter("default") + warn() + # the warnings differ only by line, so they are both shown + self.assertEqual([w.lineno for w in caught], [first_line(warn) + 1, first_line(warn) + 2]) + + def test_frame_after_return(self): + # IronPython updates the line only at statements that can throw, so the last line runs a call + def get_frame(): + frame = sys._getframe() + return identity(frame) + + self.assertEqual(get_frame().f_lineno, first_line(get_frame) + 2) + + def test_frame_in_other_thread(self): + frame = sys._getframe() + lines = [] + thread = threading.Thread(target=lambda: lines.append(frame.f_lineno)) + thread.start() + thread.join() + self.assertIsInstance(lines[0], int) + self.assertEqual(frame.f_lineno, first_line(self.test_frame_in_other_thread) + 7) + + def test_class_body(self): + class C: + line = sys._getframe().f_lineno + + self.assertEqual(C.line, first_line(self.test_class_body) + 2) + + def test_module(self): + self.assertEqual(module_line, first_line(module_line_marker) + 1) + + @unittest.skipUnless(no_adaptive_compilation, 'with -X Debug, exec code starts interpreted') + def test_exec(self): + ns = {'sys': sys} + exec('x = 1\nline = sys._getframe().f_lineno', ns) + self.assertEqual(ns['line'], 2) + +run_test(__name__) diff --git a/tests/suite/test_frame_lineno_debug.py b/tests/suite/test_frame_lineno_debug.py new file mode 100644 index 000000000..857366879 --- /dev/null +++ b/tests/suite/test_frame_lineno_debug.py @@ -0,0 +1,15 @@ +# 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. + +""" +Run the tests of test_frame_lineno in debug mode, which compiles the code with debug symbols. + +The manifest runs this file with -X Debug, and test_frame_lineno itself with -X NoAdaptiveCompilation. +""" + +from iptest import run_test + +from test_frame_lineno import * + +run_test(__name__)