Skip to content

Conversation

Copy link
Contributor

Copilot AI commented Oct 23, 2025

  • Explore and understand the issue in CompletionCompleters.cs
  • Identify the root cause (RelatedAsts null reference at line 4583)
  • Implement fix to handle null RelatedAsts
  • Add Pester test to verify the fix
  • Run test to verify fix works correctly
  • Run CodeQL security scan (no issues found)
  • Move test to TabCompletion.Tests.ps1 per review feedback
  • Remove comments from test per review feedback

Summary

Fixed NullReferenceException when calling [System.Management.Automation.CompletionCompleters]::CompleteFilename("").

Root Cause

The public API CompleteFilename(string fileName) creates a CompletionContext with RelatedAsts set to null. The internal method tried to access context.RelatedAsts[^1] without checking for null, causing the exception.

Fix

Added null/empty check for context.RelatedAsts before accessing it. When null or empty, falls back to using context.ExecutionContext.SessionState.Internal.CurrentLocation.ProviderPath.

Test

Added Pester test in TabCompletion.Tests.ps1 that verifies:

  • CompleteFilename("") doesn't throw exception
  • Returns valid completion results
Original prompt

This section details on the original issue you should resolve

<issue_title>[System.Management.Automation.CompletionCompleters]::CompleteFilename("") throws NullReferenceException</issue_title>
<issue_description>### Prerequisites

Steps to reproduce

on 7.6.0-preview.5

[System.Management.Automation.CompletionCompleters]::CompleteFilename("") throws NullReferenceException

Expected behavior

should returns CompletionResult

Actual behavior

PS> [System.Management.Automation.CompletionCompleters]::CompleteFilename("")
MethodInvocationException: Exception calling "CompleteFilename" with "1" argument(s): "Object reference not set to an instance of an object."

Error details

PS> Get-Error -newest 1

Exception             :
    Type           : System.Management.Automation.MethodInvocationException
    ErrorRecord    :
        Exception             :
            Type    : System.Management.Automation.ParentContainsErrorRecordException
            Message : Exception calling "CompleteFilename" with "1" argument(s): "Object reference not set to an instance of an object."
            HResult : -2146233087
        CategoryInfo          : NotSpecified: (:) [], ParentContainsErrorRecordException
        FullyQualifiedErrorId : NullReferenceException
        InvocationInfo        :
            ScriptLineNumber : 1
            OffsetInLine     : 1
            HistoryId        : 1
            Line             : [System.Management.Automation.CompletionCompleters]::CompleteFilename("")
            Statement        : [System.Management.Automation.CompletionCompleters]::CompleteFilename("")
            PositionMessage  : At line:1 char:1
                               + [System.Management.Automation.CompletionCompleters]::CompleteFilename …
                               + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
            CommandOrigin    : Internal
        ScriptStackTrace      : at <ScriptBlock>, <No file>: line 1
    TargetSite     :
        Name          : ConvertToMethodInvocationException
        DeclaringType : [System.Management.Automation.ExceptionHandlingOps]
        MemberType    : Method
        Module        : System.Management.Automation.dll
    Message        : Exception calling "CompleteFilename" with "1" argument(s): "Object reference not set to an instance of an object."
    Data           :
        System.Management.Automation.Interpreter.InterpretedFrameInfo, System.Management.Automation, Version=7.6.0.5, Culture=neutral, PublicKeyToken=31bf3856ad364e35 : <ScriptBlock>

    InnerException :
        Type       : System.NullReferenceException
        TargetSite :
            Name          : CompleteFilename
            DeclaringType : [System.Management.Automation.CompletionCompleters]
            MemberType    : Method
            Module        : System.Management.Automation.dll
        Message    : Object reference not set to an instance of an object.
        Source     : System.Management.Automation
        HResult    : -2147467261
        StackTrace :
   at System.Management.Automation.CompletionCompleters.CompleteFilename(CompletionContext context, Boolean containerOnly, HashSet`1 extension)
   at CallSite.Target(Closure, CallSite, Type, String)
    Source         : System.Management.Automation
    HResult        : -2146233087
    StackTrace     :
   at System.Management.Automation.ExceptionHandlingOps.ConvertToMethodInvocationException(Exception exception, Type typeToThrow, String methodName, Int32 numArgs, MemberInfo memberInfo)
   at CallSite.Target(Closure, CallSite, Type, String)
   at System.Dynamic.UpdateDelegates.UpdateAndExecute2[T0,T1,TRet](CallSite site, T0 arg0, T1 arg1)
   at System.Management.Automation.Interpreter.DynamicInstruction`3.Run(InterpretedFrame frame)
   at System.Management.Automation.Interpreter.EnterTryCatchFinallyInstruction.Run(InterpretedFrame frame)
CategoryInfo          : NotSpecified: (:) [], MethodInvocationException
FullyQualifiedErrorId : NullReferenceException
InvocationInfo        :
    ScriptLineNumber : 1
    OffsetInLine     : 1
    HistoryId        : 1
    Line             : [System.Management.Automation.CompletionCompleters]::CompleteFilename("")
    Statement        : [System.Management.Automation.CompletionCompleters]::CompleteFilename("")
    PositionMessage  : At line:1 char:1
                       + [System.Management.Automation.CompletionCompleters]::CompleteFilename …
                       + ~...

</details>

Fixes PowerShell/PowerShell#26277

<!-- START COPILOT CODING AGENT TIPS -->
---

💡 You can make Copilot smarter by setting up custom instructions, customizing its development environment and configuring Model Context Protocol (MCP) servers. Learn more [Copilot coding agent tips](https://gh.io/copilot-coding-agent-tips) in the docs.

@iSazonov iSazonov added the CL-General Indicates that a PR should be marked as a general cmdlet change in the Change Log label Oct 23, 2025
Co-authored-by: iSazonov <22290914+iSazonov@users.noreply.github.com>
Copilot AI changed the title [WIP] Fix NullReferenceException in CompleteFilename method Fix NullReferenceException in CompleteFilename when called with empty string Oct 23, 2025
Copilot AI requested a review from iSazonov October 23, 2025 06:02
@iSazonov
Copy link
Collaborator

@copilot Please move new test to TabCompletion.Tests.ps1 file.

…ts.ps1

Co-authored-by: iSazonov <22290914+iSazonov@users.noreply.github.com>
Copy link
Contributor Author

Copilot AI commented Oct 23, 2025

@copilot Please move new test to TabCompletion.Tests.ps1 file.

Moved the test to TabCompletion.Tests.ps1 as requested in commit 459c0f3.

@iSazonov
Copy link
Collaborator

@copilot Please remove your comments from the new test.

Co-authored-by: iSazonov <22290914+iSazonov@users.noreply.github.com>
Copy link
Contributor Author

Copilot AI commented Oct 23, 2025

@copilot Please remove your comments from the new test.

Removed comments from the test in commit 534098c.

@iSazonov iSazonov marked this pull request as ready for review October 23, 2025 06:56
Copilot AI review requested due to automatic review settings October 23, 2025 06:56
Copy link
Contributor

Copilot AI left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull Request Overview

This PR fixes a NullReferenceException thrown when calling CompleteFilename("") with an empty string by adding a null check for context.RelatedAsts before accessing it.

Key Changes:

  • Added null/empty check for context.RelatedAsts before array indexing
  • Added fallback to use current provider path when RelatedAsts is null/empty
  • Added Pester test to verify the fix works correctly

Reviewed Changes

Copilot reviewed 2 out of 2 changed files in this pull request and generated no comments.

File Description
src/System.Management.Automation/engine/CommandCompletion/CompletionCompleters.cs Added null check for context.RelatedAsts and fallback logic to use current provider path
test/powershell/Host/TabCompletion/TabCompletion.Tests.ps1 Added test case to verify CompleteFilename("") doesn't throw exception
Comments suppressed due to low confidence (1)

src/System.Management.Automation/engine/CommandCompletion/CompletionCompleters.cs:1

  • The else block at line 4598 is paired with the if statement at line 4583, but based on the overall control flow structure, this creates an incorrect nesting. The else block (lines 4599-4602) should be associated with the if statement at line 4583, but there's already a closing brace at line 4598 that closes that if block. This means the else at line 4598 cannot be paired with the if at line 4583. The correct structure should have the else block (4599-4602) immediately follow the closing brace at 4598 without the 'else' keyword on line 4598, or the braces need to be restructured to properly nest the conditional logic.
// Copyright (c) Microsoft Corporation.

Tip: Customize your code reviews with copilot-instructions.md. Create the file or learn how to get started.

@daxian-dbw
Copy link
Member

Suppressed by #26291

@daxian-dbw daxian-dbw closed this Oct 23, 2025
@microsoft-github-policy-service
Copy link
Contributor

microsoft-github-policy-service bot commented Oct 23, 2025

📣 Hey @@Copilot, how did we do? We would love to hear your feedback with the link below! 🗣️

🔗 https://aka.ms/PSRepoFeedback

@iSazonov iSazonov deleted the copilot/fix-nullreferenceexception-filename branch October 24, 2025 03:07
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

CL-General Indicates that a PR should be marked as a general cmdlet change in the Change Log

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants