diff --git a/CHANGELOG.md b/CHANGELOG.md index f94a43aca..0640253e9 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,12 @@ # PowerShell Editor Services Release History +## v4.1.0 +### Wednesday, December 04, 2024 + +See more details at the GitHub Release for [v4.1.0](https://github.com/PowerShell/PowerShellEditorServices/releases/tag/v4.1.0). + +Debugger optimizations and incremental build support! + ## v4.0.0 ### Monday, November 18, 2024 diff --git a/PowerShellEditorServices.Common.props b/PowerShellEditorServices.Common.props index 1bc5e8f5c..010fe2a8c 100644 --- a/PowerShellEditorServices.Common.props +++ b/PowerShellEditorServices.Common.props @@ -1,6 +1,6 @@ - 4.0.0 + 4.1.0 Microsoft © Microsoft Corporation. diff --git a/PowerShellEditorServices.build.ps1 b/PowerShellEditorServices.build.ps1 index 5002127b2..ec2f4e1fa 100644 --- a/PowerShellEditorServices.build.ps1 +++ b/PowerShellEditorServices.build.ps1 @@ -125,18 +125,20 @@ task RestorePsesModules -If (-not (Test-Path "module/PSReadLine") -or -not (Test } Task Build FindDotNet, CreateBuildInfo, RestorePsesModules, { - Write-Build DarkGreen "Building PowerShellEditorServices" + Write-Build DarkGreen 'Building PowerShellEditorServices' Invoke-BuildExec { & dotnet publish $script:dotnetBuildArgs ./src/PowerShellEditorServices/PowerShellEditorServices.csproj -f $script:NetFramework.Standard } Invoke-BuildExec { & dotnet publish $script:dotnetBuildArgs ./src/PowerShellEditorServices.Hosting/PowerShellEditorServices.Hosting.csproj -f $script:NetFramework.PS74 } if (-not $script:IsNix) { Invoke-BuildExec { & dotnet publish $script:dotnetBuildArgs ./src/PowerShellEditorServices.Hosting/PowerShellEditorServices.Hosting.csproj -f $script:NetFramework.PS51 } } +} -If { + $Null -eq $script:ChangesDetected -or $true -eq $script:ChangesDetected } Task AssembleModule -After Build { - Write-Build DarkGreen "Assembling PowerShellEditorServices module" - $psesOutputPath = "./module/PowerShellEditorServices" + Write-Build DarkGreen 'Assembling PowerShellEditorServices module' + $psesOutputPath = './module/PowerShellEditorServices' $psesBinOutputPath = "$psesOutputPath/bin" $psesDepsPath = "$psesBinOutputPath/Common" $psesCoreHostPath = "$psesBinOutputPath/Core" @@ -147,8 +149,8 @@ Task AssembleModule -After Build { } # Copy documents to module root - foreach ($document in @("LICENSE", "NOTICE.txt", "README.md", "SECURITY.md")) { - Copy-Item -Force -Path $document -Destination "./module" + foreach ($document in @('LICENSE', 'NOTICE.txt', 'README.md', 'SECURITY.md')) { + Copy-Item -Force -Path $document -Destination './module' } # Assemble PSES module @@ -186,13 +188,13 @@ Task AssembleModule -After Build { } Task BuildCmdletHelp -After AssembleModule { - Write-Build DarkGreen "Building cmdlet help" + Write-Build DarkGreen 'Building cmdlet help' New-ExternalHelp -Path ./module/docs -OutputPath ./module/PowerShellEditorServices/Commands/en-US -Force } Task SetupHelpForTests { - Write-Build DarkMagenta "Updating help (for tests)" - Update-Help -Module Microsoft.PowerShell.Management,Microsoft.PowerShell.Utility -Force -Scope CurrentUser -UICulture en-US + Write-Build DarkMagenta 'Updating help (for tests)' + Update-Help -Module Microsoft.PowerShell.Management, Microsoft.PowerShell.Utility -Force -Scope CurrentUser -UICulture en-US } Task TestPS74 Build, SetupHelpForTests, { @@ -210,7 +212,7 @@ Task TestPS51 -If (-not $script:IsNix) Build, SetupHelpForTests, { # TODO: See https://github.com/PowerShell/vscode-powershell/issues/3886 # Inheriting the module path for powershell.exe breaks things! $originalModulePath = $env:PSModulePath - $env:PSModulePath = "" + $env:PSModulePath = '' Invoke-BuildExec { & dotnet $script:dotnetTestArgs $script:NetFramework.PS51 } } finally { $env:PSModulePath = $originalModulePath @@ -221,7 +223,7 @@ Task TestPS51 -If (-not $script:IsNix) Build, SetupHelpForTests, { # should just be the latest supported framework. Task TestE2EPwsh Build, SetupHelpForTests, { Set-Location ./test/PowerShellEditorServices.Test.E2E/ - $env:PWSH_EXE_NAME = "pwsh" + $env:PWSH_EXE_NAME = 'pwsh' Invoke-BuildExec { & dotnet $script:dotnetTestArgs $script:NetFramework.PS74 } } @@ -240,12 +242,12 @@ Task TestE2EDaily -If (Test-Path $PwshDaily) Build, SetupHelpForTests, { Task TestE2EPowerShell -If (-not $script:IsNix) Build, SetupHelpForTests, { Set-Location ./test/PowerShellEditorServices.Test.E2E/ - $env:PWSH_EXE_NAME = "powershell" + $env:PWSH_EXE_NAME = 'powershell' try { # TODO: See https://github.com/PowerShell/vscode-powershell/issues/3886 # Inheriting the module path for powershell.exe breaks things! $originalModulePath = $env:PSModulePath - $env:PSModulePath = "" + $env:PSModulePath = '' Invoke-BuildExec { & dotnet $script:dotnetTestArgs $script:NetFramework.PS74 } } finally { $env:PSModulePath = $originalModulePath @@ -254,45 +256,62 @@ Task TestE2EPowerShell -If (-not $script:IsNix) Build, SetupHelpForTests, { Task TestE2EPwshCLM -If (-not $script:IsNix) Build, SetupHelpForTests, { Set-Location ./test/PowerShellEditorServices.Test.E2E/ - $env:PWSH_EXE_NAME = "pwsh" + $env:PWSH_EXE_NAME = 'pwsh' - if (-not [Security.Principal.WindowsIdentity]::GetCurrent().Owner.IsWellKnown("BuiltInAdministratorsSid")) { - Write-Build DarkRed "Skipping Constrained Language Mode tests as they must be ran in an elevated process" + if (-not [Security.Principal.WindowsIdentity]::GetCurrent().Owner.IsWellKnown('BuiltInAdministratorsSid')) { + Write-Build DarkRed 'Skipping Constrained Language Mode tests as they must be ran in an elevated process' return } try { - Write-Build DarkGreen "Running end-to-end tests in Constrained Language Mode" - [System.Environment]::SetEnvironmentVariable("__PSLockdownPolicy", "0x80000007", [System.EnvironmentVariableTarget]::Machine) + Write-Build DarkGreen 'Running end-to-end tests in Constrained Language Mode' + [System.Environment]::SetEnvironmentVariable('__PSLockdownPolicy', '0x80000007', [System.EnvironmentVariableTarget]::Machine) Invoke-BuildExec { & dotnet $script:dotnetTestArgs $script:NetFramework.PS74 } } finally { - [System.Environment]::SetEnvironmentVariable("__PSLockdownPolicy", $null, [System.EnvironmentVariableTarget]::Machine) + [System.Environment]::SetEnvironmentVariable('__PSLockdownPolicy', $null, [System.EnvironmentVariableTarget]::Machine) } } Task TestE2EPowerShellCLM -If (-not $script:IsNix) Build, SetupHelpForTests, { Set-Location ./test/PowerShellEditorServices.Test.E2E/ - $env:PWSH_EXE_NAME = "powershell" + $env:PWSH_EXE_NAME = 'powershell' - if (-not [Security.Principal.WindowsIdentity]::GetCurrent().Owner.IsWellKnown("BuiltInAdministratorsSid")) { - Write-Build DarkRed "Skipping Constrained Language Mode tests as they must be ran in an elevated process" + if (-not [Security.Principal.WindowsIdentity]::GetCurrent().Owner.IsWellKnown('BuiltInAdministratorsSid')) { + Write-Build DarkRed 'Skipping Constrained Language Mode tests as they must be ran in an elevated process' return } try { - Write-Build DarkGreen "Running end-to-end tests in Constrained Language Mode" - [System.Environment]::SetEnvironmentVariable("__PSLockdownPolicy", "0x80000007", [System.EnvironmentVariableTarget]::Machine) + Write-Build DarkGreen 'Running end-to-end tests in Constrained Language Mode' + [System.Environment]::SetEnvironmentVariable('__PSLockdownPolicy', '0x80000007', [System.EnvironmentVariableTarget]::Machine) # TODO: See https://github.com/PowerShell/vscode-powershell/issues/3886 # Inheriting the module path for powershell.exe breaks things! $originalModulePath = $env:PSModulePath - $env:PSModulePath = "" + $env:PSModulePath = '' Invoke-BuildExec { & dotnet $script:dotnetTestArgs $script:NetFramework.PS74 } } finally { - [System.Environment]::SetEnvironmentVariable("__PSLockdownPolicy", $null, [System.EnvironmentVariableTarget]::Machine) + [System.Environment]::SetEnvironmentVariable('__PSLockdownPolicy', $null, [System.EnvironmentVariableTarget]::Machine) $env:PSModulePath = $originalModulePath } } +Task BuildIfChanged.Init -Before BuildIfChanged { + [bool]$script:ChangesDetected = $false +} + +Task BuildIfChanged -Inputs { + $slash = [IO.Path]::DirectorySeparatorChar + Get-ChildItem ./src -Filter '*.cs' -Recurse + | Where-Object FullName -NotLike ('*' + $slash + 'obj' + $slash + '*') + | Where-Object FullName -NotLike ('*' + $slash + 'bin' + $slash + '*') +} -Outputs { + './src/PowerShellEditorServices/bin/Debug/netstandard2.0/Microsoft.PowerShell.EditorServices.dll' + './src/PowerShellEditorServices.Hosting/bin/Debug/net8.0/Microsoft.PowerShell.EditorServices.Hosting.dll' +} -Jobs { + Write-Build DarkMagenta 'Changes detected, rebuilding' + $script:ChangesDetected = $true +}, Build + Task Test TestPS74, TestE2EPwsh, TestPS51, TestE2EPowerShell Task TestFull Test, TestE2EDaily, TestE2EPwshCLM, TestE2EPowerShellCLM diff --git a/README.md b/README.md index 46c126336..48341ab68 100644 --- a/README.md +++ b/README.md @@ -153,7 +153,7 @@ Please note that we only consider the following as stable APIs that can be relie The types of PowerShell Editor Services can change at any moment and should not be linked against in a production environment. -## Development +## Development Environment > [!TIP] > The easiest way to manually test changes you've made in PowerShellEditorServices is to follow the [vscode-powershell development doc](https://github.com/PowerShell/vscode-powershell/blob/main/docs/development.md). @@ -175,31 +175,31 @@ Install-Module InvokeBuild -Scope CurrentUser Install-Module platyPS -Scope CurrentUser ``` -### 4. Delete `NuGet.Config` +### 4. Adjust `nuget.config` if necessary -Our NuGet configuration points to a private feed necessary for secure builds, -and it must be committed to the repo as it is. -The easiest way to build without access to that private feed is to delete the file: +Our NuGet configuration uses a secure feed with allow-listed third party dependency packages. If your contribution requires any changes to the included NuGet packages, you must disable this secure feed. + +First, run this command to prevent accidentally commiting changes to this file ```powershell -Remove-Item NuGet.Config +git update-index --skip-worktree nuget.config ``` -Please be careful not to commit this change in a PR. +Then, either delete the file or remove the `packagesources` section to use nuget.org again. Your PR _will_ fail automated build checks and you _must_ inform us at the top of your PR so the appropriate packages can be added if approved. -Now you're ready to build the code. -You can do so in one of two ways: +## Build PowerShell Editor Services +Now you're ready to build the code. You can do so in one of two ways: -### Building the code from PowerShell +### PowerShell ```powershell -PS C:\path\to\PowerShellEditorServices> Invoke-Build Build +PS C:\src\PowerShellEditorServices> Invoke-Build ``` -### Building the code from Visual Studio Code +### Visual Studio Code Open the PowerShellEditorServices folder that you cloned locally and press Ctrl+Shift+B -(or Cmd+Shift+B on macOS). +(or Cmd+Shift+B on macOS) which will run the default build task. ## Code of Conduct diff --git a/module/PowerShellEditorServices/PowerShellEditorServices.psd1 b/module/PowerShellEditorServices/PowerShellEditorServices.psd1 index f93cdb035..c71dc1dfe 100644 --- a/module/PowerShellEditorServices/PowerShellEditorServices.psd1 +++ b/module/PowerShellEditorServices/PowerShellEditorServices.psd1 @@ -19,7 +19,7 @@ RootModule = if ($PSEdition -eq 'Core') } # Version number of this module. -ModuleVersion = '4.0.0' +ModuleVersion = '4.1.0' # ID used to uniquely identify this module GUID = '9ca15887-53a2-479a-9cda-48d26bcb6c47' diff --git a/src/PowerShellEditorServices/Server/PsesDebugServer.cs b/src/PowerShellEditorServices/Server/PsesDebugServer.cs index 31f6a988f..6fbecce9c 100644 --- a/src/PowerShellEditorServices/Server/PsesDebugServer.cs +++ b/src/PowerShellEditorServices/Server/PsesDebugServer.cs @@ -117,6 +117,7 @@ public async Task StartAsync() response.SupportsHitConditionalBreakpoints = true; response.SupportsLogPoints = true; response.SupportsSetVariable = true; + response.SupportsDelayedStackTraceLoading = true; return Task.CompletedTask; }); diff --git a/src/PowerShellEditorServices/Services/DebugAdapter/DebugService.cs b/src/PowerShellEditorServices/Services/DebugAdapter/DebugService.cs index 667a26bdd..195d0508b 100644 --- a/src/PowerShellEditorServices/Services/DebugAdapter/DebugService.cs +++ b/src/PowerShellEditorServices/Services/DebugAdapter/DebugService.cs @@ -6,8 +6,6 @@ using System.Collections.Generic; using System.Linq; using System.Management.Automation; -using System.Management.Automation.Language; -using System.Reflection; using System.Threading; using System.Threading.Tasks; using Microsoft.Extensions.Logging; @@ -50,7 +48,6 @@ internal class DebugService private VariableContainerDetails scriptScopeVariables; private VariableContainerDetails localScopeVariables; private StackFrameDetails[] stackFrameDetails; - private readonly PropertyInfo invocationTypeScriptPositionProperty; private readonly SemaphoreSlim debugInfoHandle = AsyncUtils.CreateSimpleLockingSemaphore(); #endregion @@ -75,6 +72,11 @@ internal class DebugService /// public DebuggerStoppedEventArgs CurrentDebuggerStoppedEventArgs { get; private set; } + /// + /// Returns a task that completes when script frames and variables have completed population + /// + public Task StackFramesAndVariablesFetched { get; private set; } + /// /// Tracks whether we are running Debug-Runspace in an out-of-process runspace. /// @@ -111,12 +113,6 @@ public DebugService( _debugContext.DebuggerResuming += OnDebuggerResuming; _debugContext.BreakpointUpdated += OnBreakpointUpdated; _remoteFileManager = remoteFileManager; - - invocationTypeScriptPositionProperty = - typeof(InvocationInfo) - .GetProperty( - "ScriptPosition", - BindingFlags.NonPublic | BindingFlags.Instance); } #endregion @@ -981,8 +977,8 @@ await _executionService.ExecutePSCommandAsync( } } - // Get call stack and variables. - await FetchStackFramesAndVariablesAsync(noScriptName ? localScriptPath : null).ConfigureAwait(false); + // Begin call stack and variables fetch. We don't need to block here. + StackFramesAndVariablesFetched = FetchStackFramesAndVariablesAsync(noScriptName ? localScriptPath : null); // If this is a remote connection and the debugger stopped at a line // in a script file, get the file contents @@ -996,53 +992,6 @@ await _remoteFileManager.FetchRemoteFileAsync( _psesHost.CurrentRunspace).ConfigureAwait(false); } - if (stackFrameDetails.Length > 0) - { - // Augment the top stack frame with details from the stop event - if (invocationTypeScriptPositionProperty.GetValue(e.InvocationInfo) is IScriptExtent scriptExtent) - { - StackFrameDetails targetFrame = stackFrameDetails[0]; - - // Certain context changes (like stepping into the default value expression - // of a parameter) do not create a call stack frame. In order to represent - // this context change we create a fake call stack frame. - if (!string.IsNullOrEmpty(scriptExtent.File) - && !PathUtils.IsPathEqual(scriptExtent.File, targetFrame.ScriptPath)) - { - await debugInfoHandle.WaitAsync().ConfigureAwait(false); - try - { - targetFrame = new StackFrameDetails - { - ScriptPath = scriptExtent.File, - // Just use the last frame's variables since we don't have a - // good way to get real values. - AutoVariables = targetFrame.AutoVariables, - CommandVariables = targetFrame.CommandVariables, - // Ideally we'd get a real value here but since there's no real - // call stack frame for this, we'd need to replicate a lot of - // engine code. - FunctionName = "", - }; - - StackFrameDetails[] newFrames = new StackFrameDetails[stackFrameDetails.Length + 1]; - newFrames[0] = targetFrame; - stackFrameDetails.CopyTo(newFrames, 1); - stackFrameDetails = newFrames; - } - finally - { - debugInfoHandle.Release(); - } - } - - targetFrame.StartLineNumber = scriptExtent.StartLineNumber; - targetFrame.EndLineNumber = scriptExtent.EndLineNumber; - targetFrame.StartColumnNumber = scriptExtent.StartColumnNumber; - targetFrame.EndColumnNumber = scriptExtent.EndColumnNumber; - } - } - CurrentDebuggerStoppedEventArgs = new DebuggerStoppedEventArgs( e, diff --git a/src/PowerShellEditorServices/Services/DebugAdapter/Handlers/ScopesHandler.cs b/src/PowerShellEditorServices/Services/DebugAdapter/Handlers/ScopesHandler.cs index 04adf185e..daa3d8e60 100644 --- a/src/PowerShellEditorServices/Services/DebugAdapter/Handlers/ScopesHandler.cs +++ b/src/PowerShellEditorServices/Services/DebugAdapter/Handlers/ScopesHandler.cs @@ -18,16 +18,27 @@ internal class ScopesHandler : IScopesHandler public ScopesHandler(DebugService debugService) => _debugService = debugService; + /// + /// Retrieves the variable scopes (containers) for the currently selected stack frame. Variables details are fetched via a separate request. + /// public Task Handle(ScopesArguments request, CancellationToken cancellationToken) { - VariableScope[] variableScopes = - _debugService.GetVariableScopes( - (int)request.FrameId); + // HACK: The StackTraceHandler injects an artificial label frame as the first frame as a performance optimization, so when scopes are requested by the client, we need to adjust the frame index accordingly to match the underlying PowerShell frame, so when the client clicks on the label (or hit the default breakpoint), they get variables populated from the top of the PowerShell stackframe. If the client dives deeper, we need to reflect that as well (though 90% of debug users don't actually investigate this) + // VSCode Frame 0 (Label) -> PowerShell StackFrame 0 (for convenience) + // VSCode Frame 1 (First Real PS Frame) -> Also PowerShell StackFrame 0 + // VSCode Frame 2 -> PowerShell StackFrame 1 + // VSCode Frame 3 -> PowerShell StackFrame 2 + // etc. + int powershellFrameId = request.FrameId == 0 ? 0 : (int)request.FrameId - 1; + + VariableScope[] variableScopes = _debugService.GetVariableScopes(powershellFrameId); return Task.FromResult(new ScopesResponse { - Scopes = new Container(variableScopes - .Select(LspDebugUtils.CreateScope)) + Scopes = new Container( + variableScopes + .Select(LspDebugUtils.CreateScope) + ) }); } } diff --git a/src/PowerShellEditorServices/Services/DebugAdapter/Handlers/StackTraceHandler.cs b/src/PowerShellEditorServices/Services/DebugAdapter/Handlers/StackTraceHandler.cs index f53e094e7..84d23a8b6 100644 --- a/src/PowerShellEditorServices/Services/DebugAdapter/Handlers/StackTraceHandler.cs +++ b/src/PowerShellEditorServices/Services/DebugAdapter/Handlers/StackTraceHandler.cs @@ -1,64 +1,133 @@ // Copyright (c) Microsoft Corporation. // Licensed under the MIT License. +#nullable enable using System; using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; +using System.Management.Automation; using Microsoft.PowerShell.EditorServices.Services; -using Microsoft.PowerShell.EditorServices.Services.DebugAdapter; -using Microsoft.PowerShell.EditorServices.Utility; using OmniSharp.Extensions.DebugAdapter.Protocol.Models; using OmniSharp.Extensions.DebugAdapter.Protocol.Requests; +using Microsoft.PowerShell.EditorServices.Services.DebugAdapter; +using System.Linq; +using OmniSharp.Extensions.JsonRpc; + +namespace Microsoft.PowerShell.EditorServices.Handlers; -namespace Microsoft.PowerShell.EditorServices.Handlers +internal class StackTraceHandler(DebugService debugService) : IStackTraceHandler { - internal class StackTraceHandler : IStackTraceHandler + /// + /// Because we don't know the size of the stacktrace beforehand, we will tell the client that there are more frames available, this is effectively a paging size, as the client should request this many frames after the first one. + /// + private const int INITIAL_PAGE_SIZE = 20; + + public async Task Handle(StackTraceArguments request, CancellationToken cancellationToken) { - private readonly DebugService _debugService; + if (!debugService.IsDebuggerStopped) + { + throw new RpcErrorException(0, null!, "Stacktrace was requested while we are not stopped at a breakpoint. This is a violation of the DAP protocol, and is probably a bug."); + } - public StackTraceHandler(DebugService debugService) => _debugService = debugService; + // Adapting to int to let us use LINQ, realistically if you have a stacktrace larger than this that the client is requesting, you have bigger problems... + int skip = Convert.ToInt32(request.StartFrame ?? 0); + int take = Convert.ToInt32(request.Levels ?? 0); - public async Task Handle(StackTraceArguments request, CancellationToken cancellationToken) - { - StackFrameDetails[] stackFrameDetails = await _debugService.GetStackFramesAsync(cancellationToken).ConfigureAwait(false); + // We generate a label for the breakpoint and can return that immediately if the client is supporting DelayedStackTraceLoading. + InvocationInfo invocationInfo = debugService.CurrentDebuggerStoppedEventArgs?.OriginalEvent?.InvocationInfo + ?? throw new RpcErrorException(0, null!, "InvocationInfo was not available on CurrentDebuggerStoppedEvent args. This is a bug and you should report it."); - // Handle a rare race condition where the adapter requests stack frames before they've - // begun building. - if (stackFrameDetails is null) - { - return new StackTraceResponse - { - StackFrames = Array.Empty(), - TotalFrames = 0 - }; - } - - List newStackFrames = new(); - - long startFrameIndex = request.StartFrame ?? 0; - long maxFrameCount = stackFrameDetails.Length; - - // If the number of requested levels == 0 (or null), that means get all stack frames - // after the specified startFrame index. Otherwise get all the stack frames. - long requestedFrameCount = request.Levels ?? 0; - if (requestedFrameCount > 0) - { - maxFrameCount = Math.Min(maxFrameCount, startFrameIndex + requestedFrameCount); - } + StackFrame breakpointLabel = CreateBreakpointLabel(invocationInfo); - for (long i = startFrameIndex; i < maxFrameCount; i++) + if (skip == 0 && take == 1) // This indicates the client is doing an initial fetch, so we want to return quickly to unblock the UI and wait on the remaining stack frames for the subsequent requests. + { + return new StackTraceResponse() { - // Create the new StackFrame object with an ID that can - // be referenced back to the current list of stack frames - newStackFrames.Add(LspDebugUtils.CreateStackFrame(stackFrameDetails[i], id: i)); - } + StackFrames = new StackFrame[] { breakpointLabel }, + TotalFrames = INITIAL_PAGE_SIZE //Indicate to the client that there are more frames available + }; + } + + // Wait until the stack frames and variables have been fetched. + await debugService.StackFramesAndVariablesFetched.ConfigureAwait(false); + + StackFrameDetails[] stackFrameDetails = await debugService.GetStackFramesAsync(cancellationToken) + .ConfigureAwait(false); + // Handle a rare race condition where the adapter requests stack frames before they've + // begun building. + if (stackFrameDetails is null) + { return new StackTraceResponse { - StackFrames = newStackFrames, - TotalFrames = newStackFrames.Count + StackFrames = Array.Empty(), + TotalFrames = 0 + }; + } + + List newStackFrames = new(); + if (skip == 0) + { + newStackFrames.Add(breakpointLabel); + } + + newStackFrames.AddRange( + stackFrameDetails + .Skip(skip != 0 ? skip - 1 : skip) + .Take(take != 0 ? take - 1 : take) + .Select((frame, index) => CreateStackFrame(frame, index + 1)) + ); + + return new StackTraceResponse + { + StackFrames = newStackFrames, + TotalFrames = newStackFrames.Count + }; + } + + public static StackFrame CreateStackFrame(StackFrameDetails stackFrame, long id) + { + SourcePresentationHint sourcePresentationHint = + stackFrame.IsExternalCode ? SourcePresentationHint.Deemphasize : SourcePresentationHint.Normal; + + // When debugging an interactive session, the ScriptPath is which is not a valid source file. + // We need to make sure the user can't open the file associated with this stack frame. + // It will generate a VSCode error in this case. + Source? source = null; + if (!stackFrame.ScriptPath.Contains("")) + { + source = new Source + { + Path = stackFrame.ScriptPath, + PresentationHint = sourcePresentationHint }; } + + return new StackFrame + { + Id = id, + Name = (source is not null) ? stackFrame.FunctionName : "Interactive Session", + Line = (source is not null) ? stackFrame.StartLineNumber : 0, + EndLine = stackFrame.EndLineNumber, + Column = (source is not null) ? stackFrame.StartColumnNumber : 0, + EndColumn = stackFrame.EndColumnNumber, + Source = source + }; } + + public static StackFrame CreateBreakpointLabel(InvocationInfo invocationInfo, int id = 0) => new() + { + Name = "", + Id = id, + Source = new() + { + Path = invocationInfo.ScriptName + }, + Line = invocationInfo.ScriptLineNumber, + Column = invocationInfo.OffsetInLine, + PresentationHint = StackFramePresentationHint.Label + }; + } + diff --git a/src/PowerShellEditorServices/Utility/LspDebugUtils.cs b/src/PowerShellEditorServices/Utility/LspDebugUtils.cs index 115689586..36677743c 100644 --- a/src/PowerShellEditorServices/Utility/LspDebugUtils.cs +++ b/src/PowerShellEditorServices/Utility/LspDebugUtils.cs @@ -56,38 +56,6 @@ public static Breakpoint CreateBreakpoint( }; } - public static StackFrame CreateStackFrame( - StackFrameDetails stackFrame, - long id) - { - SourcePresentationHint sourcePresentationHint = - stackFrame.IsExternalCode ? SourcePresentationHint.Deemphasize : SourcePresentationHint.Normal; - - // When debugging an interactive session, the ScriptPath is which is not a valid source file. - // We need to make sure the user can't open the file associated with this stack frame. - // It will generate a VSCode error in this case. - Source source = null; - if (!stackFrame.ScriptPath.Contains("<")) - { - source = new Source - { - Path = stackFrame.ScriptPath, - PresentationHint = sourcePresentationHint - }; - } - - return new StackFrame - { - Id = id, - Name = (source != null) ? stackFrame.FunctionName : "Interactive Session", - Line = (source != null) ? stackFrame.StartLineNumber : 0, - EndLine = stackFrame.EndLineNumber, - Column = (source != null) ? stackFrame.StartColumnNumber : 0, - EndColumn = stackFrame.EndColumnNumber, - Source = source - }; - } - public static Scope CreateScope(VariableScope scope) { return new Scope diff --git a/test/PowerShellEditorServices.Test.E2E/DebugAdapterProtocolMessageTests.cs b/test/PowerShellEditorServices.Test.E2E/DebugAdapterProtocolMessageTests.cs index a3c68eadb..bb794516f 100644 --- a/test/PowerShellEditorServices.Test.E2E/DebugAdapterProtocolMessageTests.cs +++ b/test/PowerShellEditorServices.Test.E2E/DebugAdapterProtocolMessageTests.cs @@ -2,22 +2,31 @@ // Licensed under the MIT License. using System; +using System.Diagnostics; using System.IO; using System.Linq; using System.Runtime.InteropServices; using System.Text; using System.Threading; using System.Threading.Tasks; -using Microsoft.Extensions.Logging; -using Microsoft.Extensions.Logging.Debug; using OmniSharp.Extensions.DebugAdapter.Client; +using DapStackFrame = OmniSharp.Extensions.DebugAdapter.Protocol.Models.StackFrame; +using OmniSharp.Extensions.DebugAdapter.Protocol.Events; using OmniSharp.Extensions.DebugAdapter.Protocol.Models; using OmniSharp.Extensions.DebugAdapter.Protocol.Requests; +using OmniSharp.Extensions.JsonRpc.Server; using Xunit; using Xunit.Abstractions; +using Microsoft.Extensions.Logging.Abstractions; namespace PowerShellEditorServices.Test.E2E { + public class XunitOutputTraceListener(ITestOutputHelper output) : TraceListener + { + public override void Write(string message) => output.WriteLine(message); + public override void WriteLine(string message) => output.WriteLine(message); + } + [Trait("Category", "DAP")] public class DebugAdapterProtocolMessageTests : IAsyncLifetime, IDisposable { @@ -28,16 +37,26 @@ public class DebugAdapterProtocolMessageTests : IAsyncLifetime, IDisposable private DebugAdapterClient PsesDebugAdapterClient; private PsesStdioProcess _psesProcess; + /// + /// Completes when the debug adapter is started. + /// public TaskCompletionSource Started { get; } = new TaskCompletionSource(); - + /// + /// Completes when the first breakpoint is reached. + /// + public TaskCompletionSource Stopped { get; } = new TaskCompletionSource(); + + /// + /// Constructor. The ITestOutputHelper is injected by xUnit and used to write diagnostic logs. + /// + /// public DebugAdapterProtocolMessageTests(ITestOutputHelper output) => _output = output; public async Task InitializeAsync() { - LoggerFactory debugLoggerFactory = new(); - debugLoggerFactory.AddProvider(new DebugLoggerProvider()); + // NOTE: To see debug logger output, add this line to your test - _psesProcess = new PsesStdioProcess(debugLoggerFactory, true); + _psesProcess = new PsesStdioProcess(new NullLoggerFactory(), true); await _psesProcess.Start(); TaskCompletionSource initialized = new(); @@ -53,11 +72,6 @@ public async Task InitializeAsync() options .WithInput(_psesProcess.OutputStream) .WithOutput(_psesProcess.InputStream) - .ConfigureLogging(builder => - builder - .AddDebug() - .SetMinimumLevel(LogLevel.Trace) - ) // The OnStarted delegate gets run when we receive the _Initialized_ event from the server: // https://microsoft.github.io/debug-adapter-protocol/specification#Events_Initialized .OnStarted((_, _) => @@ -65,6 +79,13 @@ public async Task InitializeAsync() Started.SetResult(true); return Task.CompletedTask; }) + // We use this to create a task we can await to test debugging after a breakpoint has been received. + .OnNotification(null, (stoppedEvent, _) => + { + Console.WriteLine("StoppedEvent received"); + Stopped.SetResult(stoppedEvent); + return Task.CompletedTask; + }) // The OnInitialized delegate gets run when we first receive the _Initialize_ response: // https://microsoft.github.io/debug-adapter-protocol/specification#Requests_Initialize .OnInitialized((_, _, _, _) => @@ -263,6 +284,83 @@ public async Task CanSetBreakpointsAsync() (i) => Assert.Equal("after breakpoint", i)); } + [SkippableFact] + public async Task FailsIfStacktraceRequestedWhenNotPaused() + { + Skip.If(PsesStdioProcess.RunningInConstrainedLanguageMode, + "Breakpoints can't be set in Constrained Language Mode."); + string filePath = NewTestFile(GenerateScriptFromLoggingStatements( + "labelTestBreakpoint" + )); + // Set a breakpoint + await PsesDebugAdapterClient.SetBreakpoints( + new SetBreakpointsArguments + { + Source = new Source { Name = Path.GetFileName(filePath), Path = filePath }, + Breakpoints = new SourceBreakpoint[] { new SourceBreakpoint { Line = 1 } }, + SourceModified = false, + } + ); + + // Signal to start the script + await PsesDebugAdapterClient.RequestConfigurationDone(new ConfigurationDoneArguments()); + await PsesDebugAdapterClient.LaunchScript(filePath, Started); + + + // Get the stacktrace for the breakpoint + await Assert.ThrowsAsync(() => PsesDebugAdapterClient.RequestStackTrace( + new StackTraceArguments { } + )); + } + + [SkippableFact] + public async Task SendsInitialLabelBreakpointForPerformanceReasons() + { + Skip.If(PsesStdioProcess.RunningInConstrainedLanguageMode, + "Breakpoints can't be set in Constrained Language Mode."); + string filePath = NewTestFile(GenerateScriptFromLoggingStatements( + "before breakpoint", + "at breakpoint", + "after breakpoint" + )); + + //TODO: This is technically wrong per the spec, configDone should be completed BEFORE launching, but this is how the vscode client does it today and we really need to fix that. + await PsesDebugAdapterClient.LaunchScript(filePath, Started); + + // {"command":"setBreakpoints","arguments":{"source":{"name":"dfsdfg.ps1","path":"/Users/tyleonha/Code/PowerShell/Misc/foo/dfsdfg.ps1"},"lines":[2],"breakpoints":[{"line":2}],"sourceModified":false},"type":"request","seq":3} + SetBreakpointsResponse setBreakpointsResponse = await PsesDebugAdapterClient.SetBreakpoints(new SetBreakpointsArguments + { + Source = new Source { Name = Path.GetFileName(filePath), Path = filePath }, + Breakpoints = new SourceBreakpoint[] { new SourceBreakpoint { Line = 2 } }, + SourceModified = false, + }); + + Breakpoint breakpoint = setBreakpointsResponse.Breakpoints.First(); + Assert.True(breakpoint.Verified); + Assert.Equal(filePath, breakpoint.Source.Path, ignoreCase: s_isWindows); + Assert.Equal(2, breakpoint.Line); + + ConfigurationDoneResponse configDoneResponse = await PsesDebugAdapterClient.RequestConfigurationDone(new ConfigurationDoneArguments()); + + // FIXME: I think there is a race condition here. If you remove this, the following line Stack Trace fails because the breakpoint hasn't been hit yet. I think the whole getLog process just works long enough for ConfigurationDone to complete and for the breakpoint to be hit. + + // I've tried to do this properly by waiting for a StoppedEvent, but that doesn't seem to work, I'm probably just not wiring it up right in the handler. + Assert.NotNull(configDoneResponse); + Assert.Collection(await GetLog(), + (i) => Assert.Equal("before breakpoint", i)); + File.Delete(s_testOutputPath); + + // Get the stacktrace for the breakpoint + StackTraceResponse stackTraceResponse = await PsesDebugAdapterClient.RequestStackTrace( + new StackTraceArguments { ThreadId = 1 } + ); + DapStackFrame firstFrame = stackTraceResponse.StackFrames.First(); + Assert.Equal( + firstFrame.PresentationHint, + StackFramePresentationHint.Label + ); + } + // This is a regression test for a bug where user code causes a new synchronization context // to be created, breaking the extension. It's most evident when debugging PowerShell // scripts that use System.Windows.Forms. It required fixing both Editor Services and