Skip to content

Preventing fallback to default tab-completion behavior works inconsistently between Register-ArgumentCompleter and the [ArgumentCompleter] attribute with script blocks #19628

Closed

Description

Prerequisites

Steps to reproduce

By default, when a script block used with Register-CommandCompleter or [ArgumentCompleter] produces no output, PowerShell falls back to default tab-completion (file and directory names).

This is usually undesired, and can be prevented by returning $null instead, but only from a script block used with Register-CommandCompleter, not also with the [ArgumentCompleter] attribute.

  • That $null works at all seems to be an accident, as it seems that it causes an exception in TabExpansion2 that is swallowed in interactive use, but effectively prevents the fallback.

    • Still, having the ability to suppress fallback to default completion is important, and it should also be available for script-block-based [ArgumentCompleter] attributes.
  • By contrast, when using the [ArgumentCompleter] attribute with a class that implements IArgumentCompleter, fallback suppression is possible, though the behavior is conceptually reversed:

    • Returning an empty enumerable effectively prevents fallback.
    • Returning $null functions as an opt-in to fallback behavior.

I think we need an officially supported - and documented - way to suppress fallback to the default behavior.

# Register an argument completer that uses $null to suppress fallback to
# default tab-completion.
Register-ArgumentCompleter -CommandName Foo1 -ParameterName Bar -ScriptBlock { $null }
function Foo1 { param($Bar) }

# Try the same with an [ArgumentCompleter] attribute.
# Not effective. Always falls back to default completion.
function Foo2 { param([ArgumentCompleter({ $null })] $Bar) }

# With an IArgumentCompleter implementation, the logic is reversed:
# Returning an *empty* [IEnumerable[CompletionResult]] suppresses the fallback.
# Returning $null opts-into falling back.
class CustomCompleter : System.Management.Automation.IArgumentCompleter {
  [System.Collections.Generic.IEnumerable[System.Management.Automation.CompletionResult]] CompleteArgument(
        [string] $CommandName,
        [string] $ParameterName,
        [string] $WordToComplete,
        [System.Management.Automation.Language.CommandAst] $CommandAst,
        [System.Collections.IDictionary] $FakeBoundParameters
  ) {
    # Return empty collection to suppress fallback.
    return [System.Collections.Generic.List[System.Management.Automation.CompletionResult]]::new()
  }
}

function Foo3 { param([ArgumentCompleter([CustomCompleter])] $Bar) }

# Perform tab-completion on all 3 functions.
(TabExpansion2 'Foo1 ').CompletionMatches.Count
(TabExpansion2 'Foo2 ').CompletionMatches.Count
(TabExpansion2 'Foo3 ').CompletionMatches.Count

Expected behavior

0
0
0

That is, all attempts to suppress the fallback behavior should succeed, irrespective of what completer implementation is chosen.

Actual behavior

MethodInvocationException:
Line |
  39 |  …      return [System.Management.Automation.CommandCompletion]::Complet …
     |                ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
     | Exception calling "CompleteInput" with "3" argument(s): "Object reference not set to an instance of an object."
0
252
0

That is:

  • The Register-ArgumentCompleter script block returning $null causes an exception in TabExpansion2, but as a result effectively returns no completions, i.e. suppresses fallback behavior.

  • By contrast, returning $null from the script block used with [ArgumentCompleter()] had no effect, and fallback occurred.

  • The IArgumentCompleter-implementing instance returning an empty enumerable effectively suppressed fallback behavior.

Error details

No response

Environment data

PowerShell 7.4.0-preview.3

Visuals

No response

Activity

  1. added
    Needs-Triage
    on May 8, 2023
  2. jhoneill commented on May 9, 2023

    @jhoneill

    I think we need an officially supported - and documented - way to suppress fallback to the default behavior.

    This is the heart of it. An empty array worked for both in the limited test I tried, so it could be as simple as adding a note to documentation that an empty array means "no completions available". I think the difference is only in how null is handled and if that works as an unsupported accident in one place, that might be considered tolerable.

    It has always grated with me that if there is an error (e.g. can't get values from the server) it falls back to completing files. I do have a custom file completer which is used for my custom version of CD and is bound to copy, move, remove, start, get-content , but the number of completers I have worked on since I first met tab expansion++ in V3 must be well over 100 and none of the others benefits if a file is inserted. So I would get rid of the fallback completely - I'm sure there is a reason for having it but I've never encountered it.

  3. mklement0 commented on May 9, 2023

    @mklement0
    ContributorAuthor

    An empty array worked for both in the limited test I tried

    Unfortunately, , @() doesn't seem to work in the ArgumentCompleter case (with a script block) either: (@() alone would be the same as producing no output). (With Register-ArgumentCompleter it does work, but also triggers an error in TabExpansion2, just like $null).

    # -> nonzero value, implying that completion matches were still offered.
    function Foo2 { param([ArgumentCompleter({ , @() })] $Bar) }; (TabExpansion2 'Foo2 ').CompletionMatches.Count
    

    I have yet to find a workaround - even throwing doesn't help.


    So I would get rid of the fallback completely
    I'm sure there is a reason for having it but I've never encountered it.

    Indeed. (As an aside: the default behavior - even in the absence of custom completers - is currently often useless - see #14147)

    The only potential justification I can think of is to enable fallback chaining, so that multiple custom completers can yield to others if they find no completions (in effect, you can only specify multiple completers by having both a Register-ArgumentCompleter and a [ArgumentCompleter()] completer)

    In the realm of argument completions, this seems unlikely however, and even if there were value in that, the default behavior should be not to fall back.

    E.g., you may want to override an [ArgumentCompleter()] attribute that a command comes with with a Register-ArgumentCompleter completer, meaning no fallback. (A parameter-specific Register-ArgumentCompleter completer is invoked first; an all-parameters one last)

    In short:

    • Unless it's deemed to be too breaking a change, I agree that we should unconditionally disable fallback altogether - both between custom completers and to the default completions.
  4. jhoneill commented on May 9, 2023

    @jhoneill

    Hmmm. I tested with the code in this gist
    https://gist.github.com/jhoneill/f327b7913735db4ab6f1adaaa7bcf67d#file-vtformat-ps1-L29

    And just commented out lines 40 and 41 to return an empty array from a class and that seemed to work.

    There is a difference in how the class and script block work. The class always returns [IEnumerable[CompletionResult]] the word to complete doesn't tab-expand to something it's empty. (Sloppy language on my part saying 'Empty array' @() might not work - unpopulated [IEnumerable[CompletionResult]] does)
    The script block outputs individual completion results one by one. I think if it returns nothing at all or null or a empty array they are all treated the same i.e. completing without results is treated as an answer. But when I told the class to return null or to throw an error, tab expansion fell back to using files.

    Gist
    GitHub Gist: instantly share code, notes, and snippets.
  5. mklement0 commented on May 9, 2023

    @mklement0
    ContributorAuthor

    Yes, I was only talking about suppressing fallback from a script-block-based [ArgumentCompleter()] implementation.

    (
    That it does work from an IArgumentCompleter-based implementation - with reversed logic - is already part of the initial post.)

    The initial post also implies that Register-ArgumentCompleter and [ArgumentCompleter()] treat a $null output from a script block differently: with the former it in effect suppresses fallback (though suspiciously surfaced as a .NET exception when using TabExpansion2), with the latter it doesn't.
    )

  6. mklement0 commented on May 9, 2023

    @mklement0
    ContributorAuthor

    A pragmatic summary re available workarounds is:

    If you currently want to suppress fallback to the default completions, use either:

    • Register-ArgumentCompleter and emit $null from the script block if no completions are found.

    • An IArgumentCompleter-based (rather than a script-block-based) [ArgumentCompleter()] attribute, and return an empty IEnumerable<CompletionResult> (e.g. [System.Collections.Generic.List[System.Management.Automation.CompletionResult]]::new() from a PowerShell class implementation)

    The latter workaround - available only if you have the option to modify the command - is preferable, because it doesn't rely on undocumented behavior.

  7. microsoft-github-policy-service commented on Nov 15, 2023

    @microsoft-github-policy-service
    Contributor

    This issue has not had any activity in 6 months, if this is a bug please try to reproduce on the latest version of PowerShell and reopen a new issue and reference this issue if this is still a blocker for you.

  8. microsoft-github-policy-service commented on Nov 15, 2023

    @microsoft-github-policy-service
    Contributor

    This issue has not had any activity in 6 months, if this is a bug please try to reproduce on the latest version of PowerShell and reopen a new issue and reference this issue if this is still a blocker for you.

  9. added
    Resolution-No Activity
    on Nov 15, 2023
  10. microsoft-github-policy-service commented on Nov 15, 2023

    @microsoft-github-policy-service
    Contributor

    This issue has not had any activity in 6 months, if this is a bug please try to reproduce on the latest version of PowerShell and reopen a new issue and reference this issue if this is still a blocker for you.

  11. microsoft-github-policy-service commented on Nov 22, 2023

    @microsoft-github-policy-service
    Contributor

    This issue has been marked as "No Activity" as there has been no activity for 6 months. It has been closed for housekeeping purposes.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    Needs-TriageResolution-No Activity

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions