// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
using System.Buffers;
using System.Collections;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Data;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Management.Automation.Internal;
using System.Management.Automation.Language;
using System.Management.Automation.Provider;
using System.Management.Automation.Runspaces;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using Microsoft.Management.Infrastructure;
using Microsoft.Management.Infrastructure.Options;
using Microsoft.PowerShell;
using Microsoft.PowerShell.Cim;
using Microsoft.PowerShell.Commands;
using Microsoft.PowerShell.Commands.Internal.Format;
namespace System.Management.Automation
{
///
///
public static class CompletionCompleters
{
static CompletionCompleters()
{
AppDomain.CurrentDomain.AssemblyLoad += UpdateTypeCacheOnAssemblyLoad;
}
private static void UpdateTypeCacheOnAssemblyLoad(object sender, AssemblyLoadEventArgs args)
{
// Just null out the cache - we'll rebuild it the next time someone tries to complete a type.
// We could rebuild it now, but we could be loading multiple assemblies (e.g. dependent assemblies)
// and there is no sense in rebuilding anything until we're done loading all of the assemblies.
Interlocked.Exchange(ref s_typeCache, null);
}
#region Command Names
///
///
///
///
public static IEnumerable CompleteCommand(string commandName)
{
return CompleteCommand(commandName, null);
}
///
///
///
///
///
///
public static IEnumerable CompleteCommand(string commandName, string moduleName, CommandTypes commandTypes = CommandTypes.All)
{
var runspace = Runspace.DefaultRunspace;
if (runspace == null)
{
// No runspace, just return no results.
return CommandCompletion.EmptyCompletionResult;
}
var helper = new PowerShellExecutionHelper(PowerShell.Create(RunspaceMode.CurrentRunspace));
var executionContext = helper.CurrentPowerShell.Runspace.ExecutionContext;
return CompleteCommand(new CompletionContext { WordToComplete = commandName, Helper = helper, ExecutionContext = executionContext }, moduleName, commandTypes);
}
internal static List CompleteCommand(CompletionContext context)
{
return CompleteCommand(context, null);
}
private static List CompleteCommand(CompletionContext context, string moduleName, CommandTypes types = CommandTypes.All)
{
var addAmpersandIfNecessary = IsAmpersandNeeded(context, false);
string commandName = context.WordToComplete;
string quote = CompletionHelpers.HandleDoubleAndSingleQuote(ref commandName);
List commandResults = null;
if (commandName.IndexOfAny(Utils.Separators.DirectoryOrDrive) == -1)
{
// The name to complete is neither module qualified nor is it a relative/rooted file path.
Ast lastAst = null;
if (context.RelatedAsts != null && context.RelatedAsts.Count > 0)
{
lastAst = context.RelatedAsts.Last();
}
commandResults = ExecuteGetCommandCommand(useModulePrefix: false);
if (lastAst != null)
{
// We need to add the wildcard to the end so the regex is built correctly.
commandName += "*";
// Search the asts for function definitions that we might be calling
var findFunctionsVisitor = new FindFunctionsVisitor();
while (lastAst.Parent != null)
{
lastAst = lastAst.Parent;
}
lastAst.Visit(findFunctionsVisitor);
WildcardPattern commandNamePattern = WildcardPattern.Get(commandName, WildcardOptions.IgnoreCase);
foreach (var defn in findFunctionsVisitor.FunctionDefinitions)
{
if (commandNamePattern.IsMatch(defn.Name)
&& !commandResults.Any(cr => cr.CompletionText.Equals(defn.Name, StringComparison.OrdinalIgnoreCase)))
{
// Results found in the current script are prepended to show up at the top of the list.
commandResults.Insert(0, GetCommandNameCompletionResult(defn.Name, defn, addAmpersandIfNecessary, quote));
}
}
}
}
else
{
// If there is a single \, we might be looking for a module/snapin qualified command
var indexOfFirstColon = commandName.IndexOf(':');
var indexOfFirstBackslash = commandName.IndexOf('\\');
if (indexOfFirstBackslash > 0 && (indexOfFirstBackslash < indexOfFirstColon || indexOfFirstColon == -1))
{
// First try the name before the backslash as a module name.
// Use the exact module name provided by the user
moduleName = commandName.Substring(0, indexOfFirstBackslash);
commandName = commandName.Substring(indexOfFirstBackslash + 1);
commandResults = ExecuteGetCommandCommand(useModulePrefix: true);
}
}
return commandResults;
List ExecuteGetCommandCommand(bool useModulePrefix)
{
var powershell = context.Helper
.AddCommandWithPreferenceSetting("Get-Command", typeof(GetCommandCommand))
.AddParameter("All")
.AddParameter("Name", commandName + "*");
if (moduleName != null)
{
powershell.AddParameter("Module", moduleName);
}
if (!types.Equals(CommandTypes.All))
{
powershell.AddParameter("CommandType", types);
}
// Exception is ignored, the user simply does not get any completion results if the pipeline fails
Exception exceptionThrown;
var commandInfos = context.Helper.ExecuteCurrentPowerShell(out exceptionThrown);
if (commandInfos == null || commandInfos.Count == 0)
{
powershell.Commands.Clear();
powershell
.AddCommandWithPreferenceSetting("Get-Command", typeof(GetCommandCommand))
.AddParameter("All")
.AddParameter("Name", commandName)
.AddParameter("UseAbbreviationExpansion");
if (moduleName != null)
{
powershell.AddParameter("Module", moduleName);
}
if (!types.Equals(CommandTypes.All))
{
powershell.AddParameter("CommandType", types);
}
commandInfos = context.Helper.ExecuteCurrentPowerShell(out exceptionThrown);
}
List completionResults = null;
if (commandInfos != null && commandInfos.Count > 1)
{
// OrderBy is using stable sorting
var sortedCommandInfos = commandInfos.Order(new CommandNameComparer());
completionResults = MakeCommandsUnique(sortedCommandInfos, useModulePrefix, addAmpersandIfNecessary, quote);
}
else
{
completionResults = MakeCommandsUnique(commandInfos, useModulePrefix, addAmpersandIfNecessary, quote);
}
return completionResults;
}
}
private static readonly HashSet s_keywordsToExcludeFromAddingAmpersand
= new HashSet(StringComparer.OrdinalIgnoreCase) { nameof(TokenKind.InlineScript), nameof(TokenKind.Configuration) };
internal static CompletionResult GetCommandNameCompletionResult(string name, object command, bool addAmpersandIfNecessary, string quote)
{
string syntax = name, listItem = name;
var commandInfo = command as CommandInfo;
if (commandInfo != null)
{
try
{
listItem = commandInfo.Name;
// This may require parsing a script, which could fail in a number of different ways
// (syntax errors, security exceptions, etc.) If so, the name is fine for the tooltip.
syntax = commandInfo.Syntax;
}
catch (Exception)
{
}
}
syntax = string.IsNullOrEmpty(syntax) ? name : syntax;
bool needAmpersand;
if (CompletionHelpers.CompletionRequiresQuotes(name))
{
needAmpersand = quote == string.Empty && addAmpersandIfNecessary;
string quoteInUse = quote == string.Empty ? "'" : quote;
if (quoteInUse == "'")
{
name = name.Replace("'", "''");
}
else
{
name = name.Replace("`", "``");
name = name.Replace("$", "`$");
}
name = quoteInUse + name + quoteInUse;
}
else
{
needAmpersand = quote == string.Empty && addAmpersandIfNecessary &&
Tokenizer.IsKeyword(name) && !s_keywordsToExcludeFromAddingAmpersand.Contains(name);
name = quote + name + quote;
}
// It's useless to call ForEach-Object (foreach) as the first command of a pipeline. For example:
// PS C:\> fore ---> PS C:\> foreach (expected, use as the keyword)
// PS C:\> fore ---> PS C:\> & foreach (unexpected, ForEach-Object is seldom used as the first command of a pipeline)
if (needAmpersand && name != SpecialVariables.@foreach)
{
name = "& " + name;
}
return new CompletionResult(name, listItem, CompletionResultType.Command, syntax);
}
internal static List MakeCommandsUnique(IEnumerable commandInfoPsObjs, bool includeModulePrefix, bool addAmpersandIfNecessary, string quote)
{
List results = new List();
if (commandInfoPsObjs == null || !commandInfoPsObjs.Any())
{
return results;
}
var commandTable = new Dictionary(StringComparer.OrdinalIgnoreCase);
foreach (var psobj in commandInfoPsObjs)
{
object baseObj = PSObject.Base(psobj);
string name = null;
var commandInfo = baseObj as CommandInfo;
if (commandInfo != null)
{
// Skip the private commands
if (commandInfo.Visibility == SessionStateEntryVisibility.Private) { continue; }
name = commandInfo.Name;
if (includeModulePrefix && !string.IsNullOrEmpty(commandInfo.ModuleName))
{
// The command might be a prefixed commandInfo that we get by importing a module with the -Prefix parameter, for example:
// FooModule.psm1: Get-Foo
// import-module FooModule -Prefix PowerShell
// --> command 'Get-PowerShellFoo' in the global session state (prefixed commandInfo)
// command 'Get-Foo' in the module session state (un-prefixed commandInfo)
// in that case, we should not add the module name qualification because it doesn't work
if (string.IsNullOrEmpty(commandInfo.Prefix) || !ModuleCmdletBase.IsPrefixedCommand(commandInfo))
{
name = commandInfo.ModuleName + "\\" + commandInfo.Name;
}
}
}
else
{
name = baseObj as string;
if (name == null) { continue; }
}
object value;
if (!commandTable.TryGetValue(name, out value))
{
commandTable.Add(name, baseObj);
}
else
{
var list = value as List;
if (list != null)
{
list.Add(baseObj);
}
else
{
list = new List { value, baseObj };
commandTable[name] = list;
}
}
}
foreach (var keyValuePair in commandTable)
{
if (keyValuePair.Value is List commandList)
{
var modulesWithCommand = new HashSet(StringComparer.OrdinalIgnoreCase);
var importedModules = new HashSet(StringComparer.OrdinalIgnoreCase);
var commandInfoList = new List(commandList.Count);
for (int i = 0; i < commandList.Count; i++)
{
if (commandList[i] is not CommandInfo commandInfo)
{
continue;
}
commandInfoList.Add(commandInfo);
if (commandInfo.CommandType == CommandTypes.Application)
{
continue;
}
modulesWithCommand.Add(commandInfo.ModuleName);
if ((commandInfo.CommandType == CommandTypes.Cmdlet && commandInfo.CommandMetadata.CommandType is not null)
|| (commandInfo.CommandType is CommandTypes.Function or CommandTypes.Filter && commandInfo.Definition != string.Empty)
|| (commandInfo.CommandType == CommandTypes.Alias && commandInfo.Definition is not null))
{
// Checks if the command or source module has been imported.
_ = importedModules.Add(commandInfo.ModuleName);
}
}
if (commandInfoList.Count == 0)
{
continue;
}
int moduleCount = modulesWithCommand.Count;
modulesWithCommand.Clear();
int index;
if (commandInfoList[0].CommandType == CommandTypes.Application
|| importedModules.Count == 1
|| moduleCount < 2)
{
// We can use the short name for this command because there's no ambiguity about which command it resolves to.
// If the first element is an application then we know there's no conflicting commands/aliases (because of the command precedence).
// If there's just 1 module imported then the short name refers to that module (and it will be the first element in the list)
// If there's less than 2 unique modules exporting that command then we can use the short name because it can only refer to that module.
index = 1;
results.Add(GetCommandNameCompletionResult(keyValuePair.Key, commandInfoList[0], addAmpersandIfNecessary, quote));
modulesWithCommand.Add(commandInfoList[0].ModuleName);
}
else
{
index = 0;
}
for (; index < commandInfoList.Count; index++)
{
CommandInfo commandInfo = commandInfoList[index];
if (commandInfo.CommandType == CommandTypes.Application)
{
results.Add(GetCommandNameCompletionResult(commandInfo.Definition, commandInfo, addAmpersandIfNecessary, quote));
}
else if (!string.IsNullOrEmpty(commandInfo.ModuleName) && modulesWithCommand.Add(commandInfo.ModuleName))
{
var name = commandInfo.ModuleName + "\\" + commandInfo.Name;
results.Add(GetCommandNameCompletionResult(name, commandInfo, addAmpersandIfNecessary, quote));
}
}
}
else
{
// The first command might be an un-prefixed commandInfo that we get by importing a module with the -Prefix parameter,
// in that case, we should add the module name qualification because if the module is not in the module path, calling
// 'Get-Foo' directly doesn't work
string completionName = keyValuePair.Key;
if (!includeModulePrefix)
{
var commandInfo = keyValuePair.Value as CommandInfo;
if (commandInfo != null && !string.IsNullOrEmpty(commandInfo.Prefix))
{
Diagnostics.Assert(!string.IsNullOrEmpty(commandInfo.ModuleName), "the module name should exist if commandInfo.Prefix is not an empty string");
if (!ModuleCmdletBase.IsPrefixedCommand(commandInfo))
{
completionName = commandInfo.ModuleName + "\\" + completionName;
}
}
}
results.Add(GetCommandNameCompletionResult(completionName, keyValuePair.Value, addAmpersandIfNecessary, quote));
}
}
return results;
}
private sealed class FindFunctionsVisitor : AstVisitor
{
internal readonly List FunctionDefinitions = new List();
public override AstVisitAction VisitFunctionDefinition(FunctionDefinitionAst functionDefinitionAst)
{
FunctionDefinitions.Add(functionDefinitionAst);
return AstVisitAction.Continue;
}
}
#endregion Command Names
#region Module Names
internal static List CompleteModuleName(CompletionContext context, bool loadedModulesOnly, bool skipEditionCheck = false)
{
var wordToComplete = context.WordToComplete ?? string.Empty;
var result = new List();
var quote = CompletionHelpers.HandleDoubleAndSingleQuote(ref wordToComplete);
// Indicates if we should search for modules where the last part of the name matches the input text
// eg: Host finds Microsoft.PowerShell.Host
// If the user has entered a manual wildcard, or a module name that contains a "." we assume they only want results that matches the input exactly.
bool shortNameSearch = wordToComplete.Length > 0 && !WildcardPattern.ContainsWildcardCharacters(wordToComplete) && !wordToComplete.Contains('.');
if (!wordToComplete.EndsWith('*'))
{
wordToComplete += "*";
}
string[] moduleNames;
WildcardPattern shortNamePattern;
if (shortNameSearch)
{
moduleNames = new string[] { wordToComplete, "*." + wordToComplete };
shortNamePattern = new WildcardPattern(wordToComplete, WildcardOptions.IgnoreCase);
}
else
{
moduleNames = new string[] { wordToComplete };
shortNamePattern = null;
}
var powershell = context.Helper.AddCommandWithPreferenceSetting("Get-Module", typeof(GetModuleCommand)).AddParameter("Name", moduleNames);
if (!loadedModulesOnly)
{
powershell.AddParameter("ListAvailable", true);
// -SkipEditionCheck should only be set or apply to -ListAvailable
if (skipEditionCheck)
{
powershell.AddParameter("SkipEditionCheck", true);
}
}
Collection psObjects = context.Helper.ExecuteCurrentPowerShell(out _);
if (psObjects != null)
{
// When PowerShell is used interactively, completion is usually triggered by PSReadLine, with PSReadLine's SessionState
// as the engine session state. In that case, results from the module search may contain a nested module of PSReadLine,
// which should be filtered out below.
// When the completion is triggered from global session state, such as when running 'TabExpansion2' from command line,
// the module associated with engine session state will be null.
//
// Note that, it's intentional to not hard code the name 'PSReadLine' in the change, so that in case the tab completion
// is triggered from within a different module, its nested modules can also be filtered out.
HashSet nestedModulesToFilterOut = null;
PSModuleInfo currentModule = context.ExecutionContext.EngineSessionState.Module;
if (loadedModulesOnly && currentModule?.NestedModules.Count > 0)
{
nestedModulesToFilterOut = new(currentModule.NestedModules);
}
var completedModules = new HashSet(StringComparer.OrdinalIgnoreCase);
foreach (PSObject item in psObjects)
{
var moduleInfo = (PSModuleInfo)item.BaseObject;
var completionText = moduleInfo.Name;
if (!completedModules.Add(completionText))
{
continue;
}
if (shortNameSearch
&& completionText.Contains('.')
&& !shortNamePattern.IsMatch(completionText.Substring(completionText.LastIndexOf('.') + 1))
&& !shortNamePattern.IsMatch(completionText))
{
// This check is to make sure we don't return a module whose name only matches the user specified word in the middle.
// For example, when user completes with 'gmo power', we should not return 'Microsoft.PowerShell.Utility'.
continue;
}
if (nestedModulesToFilterOut is not null
&& nestedModulesToFilterOut.Contains(moduleInfo))
{
continue;
}
var toolTip = "Description: " + moduleInfo.Description + "\r\nModuleType: "
+ moduleInfo.ModuleType.ToString() + "\r\nPath: "
+ moduleInfo.Path;
completionText = CompletionHelpers.QuoteCompletionText(completionText, quote);
result.Add(new CompletionResult(completionText, listItemText: moduleInfo.Name, CompletionResultType.ParameterValue, toolTip));
}
}
return result;
}
#endregion Module Names
#region Command Parameters
private static readonly string[] s_parameterNamesOfImportDSCResource = { "Name", "ModuleName", "ModuleVersion" };
internal static List CompleteCommandParameter(CompletionContext context)
{
string partialName = null;
bool withColon = false;
CommandAst commandAst = null;
List result = new List();
// Find the parameter ast, it will be near or at the end
CommandParameterAst parameterAst = null;
DynamicKeywordStatementAst keywordAst = null;
for (int i = context.RelatedAsts.Count - 1; i >= 0; i--)
{
keywordAst ??= context.RelatedAsts[i] as DynamicKeywordStatementAst;
parameterAst = (context.RelatedAsts[i] as CommandParameterAst);
if (parameterAst != null) break;
}
if (parameterAst != null)
{
keywordAst = parameterAst.Parent as DynamicKeywordStatementAst;
}
// If parent is DynamicKeywordStatementAst - 'Import-DscResource',
// then customize the auto completion results
if (keywordAst != null && string.Equals(keywordAst.Keyword.Keyword, "Import-DscResource", StringComparison.OrdinalIgnoreCase)
&& !string.IsNullOrWhiteSpace(context.WordToComplete) && context.WordToComplete.StartsWith('-'))
{
var lastAst = context.RelatedAsts.Last();
var wordToMatch = string.Concat(context.WordToComplete.AsSpan(1), "*");
var pattern = WildcardPattern.Get(wordToMatch, WildcardOptions.IgnoreCase);
var parameterNames = keywordAst.CommandElements.Where(static ast => ast is CommandParameterAst).Select(static ast => (ast as CommandParameterAst).ParameterName);
foreach (var parameterName in s_parameterNamesOfImportDSCResource)
{
if (pattern.IsMatch(parameterName) && !parameterNames.Contains(parameterName, StringComparer.OrdinalIgnoreCase))
{
string tooltip = "[String] " + parameterName;
result.Add(new CompletionResult("-" + parameterName, parameterName, CompletionResultType.ParameterName, tooltip));
}
}
if (result.Count > 0)
{
context.ReplacementLength = context.WordToComplete.Length;
context.ReplacementIndex = lastAst.Extent.StartOffset;
}
return result;
}
bool bindPositionalParameters = true;
if (parameterAst != null)
{
// Parent must be a command
commandAst = (CommandAst)parameterAst.Parent;
partialName = parameterAst.ParameterName;
withColon = context.WordToComplete.EndsWith(':');
}
else
{
// No CommandParameterAst is found. It could be a StringConstantExpressionAst "-"
if (context.RelatedAsts[context.RelatedAsts.Count - 1] is not StringConstantExpressionAst dashAst)
return result;
if (!dashAst.Value.Trim().Equals("-", StringComparison.OrdinalIgnoreCase))
return result;
// Parent must be a command
commandAst = (CommandAst)dashAst.Parent;
partialName = string.Empty;
// If the user tries to tab complete a new parameter in front of a positional argument like: dir - C:\
// the user may want to add the parameter name so we don't want to bind positional arguments
if (commandAst is not null)
{
foreach (var element in commandAst.CommandElements)
{
if (element.Extent.StartOffset > context.TokenAtCursor.Extent.StartOffset)
{
bindPositionalParameters = element is CommandParameterAst;
break;
}
}
}
}
PseudoBindingInfo pseudoBinding = new PseudoParameterBinder()
.DoPseudoParameterBinding(commandAst, null, parameterAst, PseudoParameterBinder.BindingType.ParameterCompletion, bindPositionalParameters);
// The command cannot be found or it's not a cmdlet, not a script cmdlet, not a function.
// Try completing as if it the parameter is a command argument for native command completion.
if (pseudoBinding == null)
{
return CompleteCommandArgument(context);
}
switch (pseudoBinding.InfoType)
{
case PseudoBindingInfoType.PseudoBindingFail:
// The command is a cmdlet or script cmdlet. Binding failed
result = GetParameterCompletionResults(partialName, uint.MaxValue, pseudoBinding.UnboundParameters, withColon);
break;
case PseudoBindingInfoType.PseudoBindingSucceed:
// The command is a cmdlet or script cmdlet. Binding succeeded.
result = GetParameterCompletionResults(partialName, pseudoBinding, parameterAst, withColon);
break;
}
if (result.Count == 0)
{
result = pseudoBinding.CommandName.Equals("Set-Location", StringComparison.OrdinalIgnoreCase)
? new List(CompleteFilename(context, containerOnly: true, extension: null))
: new List(CompleteFilename(context));
}
return result;
}
///
/// Get the parameter completion results when the pseudo binding was successful.
///
///
///
///
///
///
private static List GetParameterCompletionResults(string parameterName, PseudoBindingInfo bindingInfo, CommandParameterAst parameterAst, bool withColon)
{
Diagnostics.Assert(bindingInfo.InfoType.Equals(PseudoBindingInfoType.PseudoBindingSucceed), "The pseudo binding should succeed");
List result = new List();
Assembly commandAssembly = null;
if (bindingInfo.CommandInfo is CmdletInfo cmdletInfo)
{
commandAssembly = cmdletInfo.CommandMetadata.CommandType.Assembly;
}
if (parameterName == string.Empty)
{
result = GetParameterCompletionResults(
parameterName,
bindingInfo.ValidParameterSetsFlags,
bindingInfo.UnboundParameters,
withColon,
commandAssembly);
return result;
}
if (bindingInfo.ParametersNotFound.Count > 0)
{
// The parameter name cannot be matched to any parameter
if (bindingInfo.ParametersNotFound.Any(pAst => parameterAst.GetHashCode() == pAst.GetHashCode()))
{
return result;
}
}
if (bindingInfo.AmbiguousParameters.Count > 0)
{
// The parameter name is ambiguous. It's ignored in the pseudo binding, and we should search in the UnboundParameters
if (bindingInfo.AmbiguousParameters.Any(pAst => parameterAst.GetHashCode() == pAst.GetHashCode()))
{
result = GetParameterCompletionResults(
parameterName,
bindingInfo.ValidParameterSetsFlags,
bindingInfo.UnboundParameters,
withColon,
commandAssembly);
}
return result;
}
if (bindingInfo.DuplicateParameters.Count > 0)
{
// The parameter name is resolved to a parameter that is already bound. We search it in the BoundParameters
if (bindingInfo.DuplicateParameters.Any(pAst => parameterAst.GetHashCode() == pAst.Parameter.GetHashCode()))
{
result = GetParameterCompletionResults(
parameterName,
bindingInfo.ValidParameterSetsFlags,
bindingInfo.BoundParameters.Values,
withColon,
commandAssembly);
}
return result;
}
// The parameter should be bound in the pseudo binding during the named binding
string matchedParameterName = null;
foreach (KeyValuePair entry in bindingInfo.BoundArguments)
{
switch (entry.Value.ParameterArgumentType)
{
case AstParameterArgumentType.AstPair:
{
AstPair pair = (AstPair)entry.Value;
if (pair.ParameterSpecified && pair.Parameter.GetHashCode() == parameterAst.GetHashCode())
{
matchedParameterName = entry.Key;
}
else if (pair.ArgumentIsCommandParameterAst && pair.Argument.GetHashCode() == parameterAst.GetHashCode())
{
// The parameter name cannot be resolved to a parameter
return result;
}
}
break;
case AstParameterArgumentType.Fake:
{
FakePair pair = (FakePair)entry.Value;
if (pair.ParameterSpecified && pair.Parameter.GetHashCode() == parameterAst.GetHashCode())
{
matchedParameterName = entry.Key;
}
}
break;
case AstParameterArgumentType.Switch:
{
SwitchPair pair = (SwitchPair)entry.Value;
if (pair.ParameterSpecified && pair.Parameter.GetHashCode() == parameterAst.GetHashCode())
{
matchedParameterName = entry.Key;
}
}
break;
case AstParameterArgumentType.AstArray:
case AstParameterArgumentType.PipeObject:
break;
}
if (matchedParameterName != null)
break;
}
if (matchedParameterName is null)
{
// The pseudo binder has skipped a parameter
// This will happen when completing parameters for commands with dynamic parameters.
result = GetParameterCompletionResults(
parameterName,
bindingInfo.ValidParameterSetsFlags,
bindingInfo.UnboundParameters,
withColon,
commandAssembly);
return result;
}
MergedCompiledCommandParameter param = bindingInfo.BoundParameters[matchedParameterName];
WildcardPattern pattern = WildcardPattern.Get(parameterName + "*", WildcardOptions.IgnoreCase);
string parameterType = "[" + ToStringCodeMethods.Type(param.Parameter.Type, dropNamespaces: true) + "] ";
string helpMessage = string.Empty;
if (param.Parameter.CompiledAttributes is not null)
{
foreach (Attribute attr in param.Parameter.CompiledAttributes)
{
if (attr is ParameterAttribute pattr && TryGetParameterHelpMessage(pattr, commandAssembly, out string attrHelpMessage))
{
helpMessage = $" - {attrHelpMessage}";
break;
}
}
}
string colonSuffix = withColon ? ":" : string.Empty;
if (pattern.IsMatch(matchedParameterName))
{
string completionText = $"-{matchedParameterName}{colonSuffix}";
string tooltip = $"{parameterType}{matchedParameterName}{helpMessage}";
result.Add(new CompletionResult(completionText, matchedParameterName, CompletionResultType.ParameterName, tooltip));
}
else
{
// Process alias when there is partial input
foreach (var alias in param.Parameter.Aliases)
{
if (pattern.IsMatch(alias))
{
result.Add(new CompletionResult(
$"-{alias}{colonSuffix}",
alias,
CompletionResultType.ParameterName,
$"{parameterType}{alias}{helpMessage}"));
}
}
}
return result;
}
#nullable enable
///
/// Try and get the help message text for the parameter attribute.
///
/// The attribute to check for the help message.
/// The assembly to lookup resources messages, this should be the assembly the cmdlet is defined in.
/// The help message if it was found otherwise null.
/// True if the help message was set or false if not.>
private static bool TryGetParameterHelpMessage(
ParameterAttribute attr,
Assembly? assembly,
[NotNullWhen(true)] out string? message)
{
message = null;
if (attr.HelpMessage is not null)
{
message = attr.HelpMessage;
return true;
}
if (assembly is null || attr.HelpMessageBaseName is null || attr.HelpMessageResourceId is null)
{
return false;
}
try
{
message = ResourceManagerCache.GetResourceString(assembly, attr.HelpMessageBaseName, attr.HelpMessageResourceId);
return message is not null;
}
catch (Exception)
{
return false;
}
}
#nullable disable
///
/// Get the parameter completion results by using the given valid parameter sets and available parameters.
///
///
///
///
///
/// Optional assembly used to lookup parameter help messages.
///
private static List GetParameterCompletionResults(
string parameterName,
uint validParameterSetFlags,
IEnumerable parameters,
bool withColon,
Assembly commandAssembly = null)
{
var result = new List();
var commonParamResult = new List();
var pattern = WildcardPattern.Get(parameterName + "*", WildcardOptions.IgnoreCase);
var colonSuffix = withColon ? ":" : string.Empty;
bool addCommonParameters = true;
foreach (MergedCompiledCommandParameter param in parameters)
{
bool inParameterSet = (param.Parameter.ParameterSetFlags & validParameterSetFlags) != 0 || param.Parameter.IsInAllSets;
if (!inParameterSet)
continue;
string name = param.Parameter.Name;
string type = "[" + ToStringCodeMethods.Type(param.Parameter.Type, dropNamespaces: true) + "] ";
string helpMessage = null;
bool isCommonParameter = Cmdlet.CommonParameters.Contains(name, StringComparer.OrdinalIgnoreCase);
List listInUse = isCommonParameter ? commonParamResult : result;
if (pattern.IsMatch(name))
{
// Then using functions to back dynamic keywords, we don't necessarily
// want all of the parameters to be shown to the user. Those that are marked
// DontShow will not be displayed. Also, if any of the parameters have
// don't show set, we won't show any of the common parameters either.
bool showToUser = true;
var compiledAttributes = param.Parameter.CompiledAttributes;
if (compiledAttributes != null && compiledAttributes.Count > 0)
{
foreach (var attr in compiledAttributes)
{
if (attr is ParameterAttribute pattr)
{
if (pattr.DontShow)
{
showToUser = false;
addCommonParameters = false;
break;
}
if (helpMessage is null && TryGetParameterHelpMessage(pattr, commandAssembly, out string attrHelpMessage))
{
helpMessage = $" - {attrHelpMessage}";
}
}
}
}
if (showToUser)
{
string completionText = $"-{name}{colonSuffix}";
string tooltip = $"{type}{name}{helpMessage}";
listInUse.Add(new CompletionResult(completionText, name, CompletionResultType.ParameterName,
tooltip));
}
}
else if (parameterName != string.Empty)
{
// Process alias when there is partial input
foreach (var alias in param.Parameter.Aliases)
{
if (pattern.IsMatch(alias))
{
listInUse.Add(new CompletionResult(
$"-{alias}{colonSuffix}",
alias,
CompletionResultType.ParameterName,
type + alias));
}
}
}
}
// Add the common parameters to the results if expected.
if (addCommonParameters)
{
result.AddRange(commonParamResult);
}
return result;
}
///
/// Get completion results for operators that start with
///
/// The starting text of the operator to complete.
/// A list of completion results.
public static List CompleteOperator(string wordToComplete)
{
if (wordToComplete.StartsWith('-'))
{
wordToComplete = wordToComplete.Substring(1);
}
return (from op in Tokenizer._operatorText
where op.StartsWith(wordToComplete, StringComparison.OrdinalIgnoreCase)
orderby op
select new CompletionResult("-" + op, op, CompletionResultType.ParameterName, GetOperatorDescription(op))).ToList();
}
private static string GetOperatorDescription(string op)
{
return ResourceManagerCache.GetResourceString(typeof(CompletionCompleters).Assembly,
"System.Management.Automation.resources.TabCompletionStrings",
op + "OperatorDescription");
}
#endregion Command Parameters
#region Command Arguments
internal static List CompleteCommandArgument(CompletionContext context)
{
CommandAst commandAst = null;
List result = new List();
// Find the expression ast. It should be at the end if there is one
ExpressionAst expressionAst = null;
MemberExpressionAst secondToLastMemberAst = null;
Ast lastAst = context.RelatedAsts.Last();
expressionAst = lastAst as ExpressionAst;
if (expressionAst != null)
{
if (expressionAst.Parent is CommandAst)
{
commandAst = (CommandAst)expressionAst.Parent;
if (expressionAst is ErrorExpressionAst && expressionAst.Extent.Text.EndsWith(','))
{
context.WordToComplete = string.Empty;
// BUGBUG context.CursorPosition = expressionAst.Extent.StartScriptPosition;
}
else if (commandAst.CommandElements.Count == 1 || context.WordToComplete == string.Empty)
{
expressionAst = null;
}
else if (commandAst.CommandElements.Count > 2)
{
var length = commandAst.CommandElements.Count;
var index = 1;
for (; index < length; index++)
{
if (commandAst.CommandElements[index] == expressionAst)
break;
}
CommandElementAst secondToLastAst = null;
if (index > 1)
{
secondToLastAst = commandAst.CommandElements[index - 1];
secondToLastMemberAst = secondToLastAst as MemberExpressionAst;
}
var partialPathAst = expressionAst as StringConstantExpressionAst;
if (partialPathAst != null && secondToLastAst != null &&
partialPathAst.StringConstantType == StringConstantType.BareWord &&
secondToLastAst.Extent.EndLineNumber == partialPathAst.Extent.StartLineNumber &&
secondToLastAst.Extent.EndColumnNumber == partialPathAst.Extent.StartColumnNumber &&
partialPathAst.Value.AsSpan().IndexOfAny('\\', '/') == 0)
{
var secondToLastStringConstantAst = secondToLastAst as StringConstantExpressionAst;
var secondToLastExpandableStringAst = secondToLastAst as ExpandableStringExpressionAst;
var secondToLastArrayAst = secondToLastAst as ArrayLiteralAst;
var secondToLastParamAst = secondToLastAst as CommandParameterAst;
if (secondToLastStringConstantAst != null || secondToLastExpandableStringAst != null)
{
var fullPath = ConcatenateStringPathArguments(secondToLastAst, partialPathAst.Value, context);
expressionAst = secondToLastStringConstantAst != null
? (ExpressionAst)secondToLastStringConstantAst
: (ExpressionAst)secondToLastExpandableStringAst;
context.ReplacementIndex = ((InternalScriptPosition)secondToLastAst.Extent.StartScriptPosition).Offset;
context.ReplacementLength += ((InternalScriptPosition)secondToLastAst.Extent.EndScriptPosition).Offset - context.ReplacementIndex;
context.WordToComplete = fullPath;
// context.CursorPosition = secondToLastAst.Extent.StartScriptPosition;
}
else if (secondToLastArrayAst != null)
{
// Handle cases like: dir -Path .\cd, 'a b'\new
var lastArrayElement = secondToLastArrayAst.Elements.LastOrDefault();
var fullPath = ConcatenateStringPathArguments(lastArrayElement, partialPathAst.Value, context);
if (fullPath != null)
{
expressionAst = secondToLastArrayAst;
context.ReplacementIndex = ((InternalScriptPosition)lastArrayElement.Extent.StartScriptPosition).Offset;
context.ReplacementLength += ((InternalScriptPosition)lastArrayElement.Extent.EndScriptPosition).Offset - context.ReplacementIndex;
context.WordToComplete = fullPath;
}
}
else if (secondToLastParamAst != null)
{
// Handle cases like: dir -Path: .\cd, 'a b'\new || dir -Path: 'a b'\new
var fullPath = ConcatenateStringPathArguments(secondToLastParamAst.Argument, partialPathAst.Value, context);
if (fullPath != null)
{
expressionAst = secondToLastParamAst.Argument;
context.ReplacementIndex = ((InternalScriptPosition)secondToLastParamAst.Argument.Extent.StartScriptPosition).Offset;
context.ReplacementLength += ((InternalScriptPosition)secondToLastParamAst.Argument.Extent.EndScriptPosition).Offset - context.ReplacementIndex;
context.WordToComplete = fullPath;
}
else
{
var arrayArgAst = secondToLastParamAst.Argument as ArrayLiteralAst;
if (arrayArgAst != null)
{
var lastArrayElement = arrayArgAst.Elements.LastOrDefault();
fullPath = ConcatenateStringPathArguments(lastArrayElement, partialPathAst.Value, context);
if (fullPath != null)
{
expressionAst = arrayArgAst;
context.ReplacementIndex = ((InternalScriptPosition)lastArrayElement.Extent.StartScriptPosition).Offset;
context.ReplacementLength += ((InternalScriptPosition)lastArrayElement.Extent.EndScriptPosition).Offset - context.ReplacementIndex;
context.WordToComplete = fullPath;
}
}
}
}
}
}
}
else if (expressionAst.Parent is ArrayLiteralAst && expressionAst.Parent.Parent is CommandAst)
{
commandAst = (CommandAst)expressionAst.Parent.Parent;
if (commandAst.CommandElements.Count == 1 || context.WordToComplete == string.Empty)
{
// dir -Path a.txt, b.txt
expressionAst = null;
}
else
{
// dir -Path a.txt, b.txt c
expressionAst = (ExpressionAst)expressionAst.Parent;
}
}
else if (expressionAst.Parent is ArrayLiteralAst && expressionAst.Parent.Parent is CommandParameterAst)
{
// Handle scenarios such as
// dir -Path: a.txt, || dir -Path: a.txt, b.txt
commandAst = (CommandAst)expressionAst.Parent.Parent.Parent;
if (context.WordToComplete == string.Empty)
{
// dir -Path: a.txt, b.txt
expressionAst = null;
}
else
{
// dir -Path: a.txt, b
expressionAst = (ExpressionAst)expressionAst.Parent;
}
}
else if (expressionAst.Parent is CommandParameterAst && expressionAst.Parent.Parent is CommandAst)
{
commandAst = (CommandAst)expressionAst.Parent.Parent;
if (expressionAst is ErrorExpressionAst && expressionAst.Extent.Text.EndsWith(','))
{
// dir -Path: a.txt,
context.WordToComplete = string.Empty;
// context.CursorPosition = expressionAst.Extent.StartScriptPosition;
}
else if (context.WordToComplete == string.Empty)
{
// Handle scenario like this: Set-ExecutionPolicy -Scope:CurrentUser
expressionAst = null;
}
}
}
else
{
var paramAst = lastAst as CommandParameterAst;
if (paramAst != null)
{
commandAst = paramAst.Parent as CommandAst;
}
else
{
commandAst = lastAst as CommandAst;
}
}
if (commandAst == null)
{
// We don't know if this could be expanded into anything interesting
return result;
}
PseudoBindingInfo pseudoBinding = new PseudoParameterBinder()
.DoPseudoParameterBinding(commandAst, null, null, PseudoParameterBinder.BindingType.ArgumentCompletion);
do
{
// The command cannot be found, or it's NOT a cmdlet, NOT a script cmdlet and NOT a function
if (pseudoBinding == null)
break;
bool parsedArgumentsProvidesMatch = false;
if (pseudoBinding.AllParsedArguments != null && pseudoBinding.AllParsedArguments.Count > 0)
{
ArgumentLocation argLocation;
bool treatAsExpression = false;
if (expressionAst != null)
{
treatAsExpression = true;
var dashExp = expressionAst as StringConstantExpressionAst;
if (dashExp != null && dashExp.Value.Trim().Equals("-", StringComparison.OrdinalIgnoreCase))
{
// "-" is represented as StringConstantExpressionAst. Most likely the user is typing a
// after it, so in the pseudo binder, we ignore it to avoid treating it as an argument.
// for example:
// Get-Content -Path "- --> Get-Content -Path ".\-patt.txt"
treatAsExpression = false;
}
}
if (treatAsExpression)
{
argLocation = FindTargetArgumentLocation(
pseudoBinding.AllParsedArguments, expressionAst);
}
else
{
argLocation = FindTargetArgumentLocation(
pseudoBinding.AllParsedArguments, context.TokenAtCursor ?? context.TokenBeforeCursor);
}
if (argLocation != null)
{
context.PseudoBindingInfo = pseudoBinding;
switch (pseudoBinding.InfoType)
{
case PseudoBindingInfoType.PseudoBindingSucceed:
result = GetArgumentCompletionResultsWithSuccessfulPseudoBinding(context, argLocation, commandAst);
break;
case PseudoBindingInfoType.PseudoBindingFail:
result = GetArgumentCompletionResultsWithFailedPseudoBinding(context, argLocation, commandAst);
break;
}
parsedArgumentsProvidesMatch = true;
}
}
if (!parsedArgumentsProvidesMatch)
{
int index = 0;
CommandElementAst prevElem = null;
if (expressionAst != null)
{
foreach (CommandElementAst eleAst in commandAst.CommandElements)
{
if (eleAst.GetHashCode() == expressionAst.GetHashCode())
break;
prevElem = eleAst;
index++;
}
}
else
{
var token = context.TokenAtCursor ?? context.TokenBeforeCursor;
foreach (CommandElementAst eleAst in commandAst.CommandElements)
{
if (eleAst.Extent.StartOffset > token.Extent.EndOffset)
break;
prevElem = eleAst;
index++;
}
}
// positional argument with position 0
if (index == 1)
{
CompletePositionalArgument(
pseudoBinding.CommandName,
commandAst,
context,
result,
pseudoBinding.UnboundParameters,
pseudoBinding.DefaultParameterSetFlag,
uint.MaxValue,
0);
}
else
{
if (prevElem is CommandParameterAst && ((CommandParameterAst)prevElem).Argument == null)
{
var paramName = ((CommandParameterAst)prevElem).ParameterName;
var pattern = WildcardPattern.Get(paramName + "*", WildcardOptions.IgnoreCase);
foreach (MergedCompiledCommandParameter param in pseudoBinding.UnboundParameters)
{
if (pattern.IsMatch(param.Parameter.Name))
{
ProcessParameter(pseudoBinding.CommandName, commandAst, context, result, param);
break;
}
var isAliasMatch = false;
foreach (string alias in param.Parameter.Aliases)
{
if (pattern.IsMatch(alias))
{
isAliasMatch = true;
ProcessParameter(pseudoBinding.CommandName, commandAst, context, result, param);
break;
}
}
if (isAliasMatch)
break;
}
}
}
}
} while (false);
// Indicate if the current argument completion falls into those pre-defined cases and
// has been processed already.
bool hasBeenProcessed = false;
if (result.Count > 0 && result[result.Count - 1].Equals(CompletionResult.Null))
{
result.RemoveAt(result.Count - 1);
hasBeenProcessed = true;
if (result.Count > 0)
return result;
}
// Handle some special cases such as:
// & "get-comm --> & "Get-Command"
// & "sa --> & ".\sa[v].txt"
if (expressionAst == null && !hasBeenProcessed &&
commandAst.CommandElements.Count == 1 &&
commandAst.InvocationOperator != TokenKind.Unknown &&
context.WordToComplete != string.Empty)
{
// Use literal path after Ampersand
var tryCmdletCompletion = false;
var clearLiteralPathsKey = TurnOnLiteralPathOption(context);
if (context.WordToComplete.Contains('-'))
{
tryCmdletCompletion = true;
}
try
{
var fileCompletionResults = new List(CompleteFilename(context));
if (tryCmdletCompletion)
{
// It's actually command name completion, other than argument completion
var cmdletCompletionResults = CompleteCommand(context);
if (cmdletCompletionResults != null && cmdletCompletionResults.Count > 0)
{
fileCompletionResults.AddRange(cmdletCompletionResults);
}
}
return fileCompletionResults;
}
finally
{
if (clearLiteralPathsKey)
context.Options.Remove("LiteralPaths");
}
}
if (expressionAst is StringConstantExpressionAst)
{
var pathAst = (StringConstantExpressionAst)expressionAst;
// Handle static member completion: echo [int]::
var shareMatch = Regex.Match(pathAst.Value, @"^(\[[\w\d\.]+\]::[\w\d\*]*)$");
if (shareMatch.Success)
{
int fakeReplacementIndex, fakeReplacementLength;
var input = shareMatch.Groups[1].Value;
var completionParameters = CommandCompletion.MapStringInputToParsedInput(input, input.Length);
var completionAnalysis = new CompletionAnalysis(completionParameters.Item1, completionParameters.Item2, completionParameters.Item3, context.Options);
var ret = completionAnalysis.GetResults(
context.Helper.CurrentPowerShell,
out fakeReplacementIndex,
out fakeReplacementLength);
if (ret != null && ret.Count > 0)
{
string prefix = string.Concat(TokenKind.LParen.Text(), input.AsSpan(0, fakeReplacementIndex));
foreach (CompletionResult entry in ret)
{
string completionText = prefix + entry.CompletionText;
if (entry.ResultType.Equals(CompletionResultType.Property))
completionText += TokenKind.RParen.Text();
result.Add(new CompletionResult(completionText, entry.ListItemText, entry.ResultType,
entry.ToolTip));
}
return result;
}
}
// Handle member completion with wildcard: echo $a.*
if (pathAst.Value.Contains('*') && secondToLastMemberAst != null &&
secondToLastMemberAst.Extent.EndLineNumber == pathAst.Extent.StartLineNumber &&
secondToLastMemberAst.Extent.EndColumnNumber == pathAst.Extent.StartColumnNumber)
{
var memberName = pathAst.Value.EndsWith('*')
? pathAst.Value
: pathAst.Value + "*";
var targetExpr = secondToLastMemberAst.Expression;
if (IsSplattedVariable(targetExpr))
{
// It's splatted variable, and the member completion is not useful
return result;
}
var memberAst = secondToLastMemberAst.Member as StringConstantExpressionAst;
if (memberAst != null)
{
memberName = memberAst.Value + memberName;
}
CompleteMemberHelper(false, memberName, targetExpr, context, result);
if (result.Count > 0)
{
context.ReplacementIndex =
((InternalScriptPosition)secondToLastMemberAst.Expression.Extent.EndScriptPosition).Offset + 1;
if (memberAst != null)
context.ReplacementLength += memberAst.Value.Length;
return result;
}
}
// Treat it as the file name completion
// Handle this scenario: & 'c:\a b'\
string fileName = pathAst.Value;
if (commandAst.InvocationOperator != TokenKind.Unknown && fileName.AsSpan().IndexOfAny('\\', '/') == 0 &&
commandAst.CommandElements.Count == 2 && commandAst.CommandElements[0] is StringConstantExpressionAst &&
commandAst.CommandElements[0].Extent.EndLineNumber == expressionAst.Extent.StartLineNumber &&
commandAst.CommandElements[0].Extent.EndColumnNumber == expressionAst.Extent.StartColumnNumber)
{
if (pseudoBinding != null)
{
// CommandElements[0] is resolved to a command
return result;
}
else
{
var constantAst = (StringConstantExpressionAst)commandAst.CommandElements[0];
fileName = constantAst.Value + fileName;
context.ReplacementIndex = ((InternalScriptPosition)constantAst.Extent.StartScriptPosition).Offset;
context.ReplacementLength += ((InternalScriptPosition)constantAst.Extent.EndScriptPosition).Offset - context.ReplacementIndex;
context.WordToComplete = fileName;
// commandAst.InvocationOperator != TokenKind.Unknown, so we should use literal path
var clearLiteralPathKey = TurnOnLiteralPathOption(context);
try
{
return new List(CompleteFilename(context));
}
finally
{
if (clearLiteralPathKey)
context.Options.Remove("LiteralPaths");
}
}
}
}
// The default argument completion: file path completion, command name completion('WordToComplete' is not empty and contains a dash).
// If the current argument completion has been process already, we don't go through the default argument completion anymore.
if (!hasBeenProcessed)
{
var commandName = commandAst.GetCommandName();
var customCompleter = GetCustomArgumentCompleter(
"NativeArgumentCompleters",
new[] { commandName, Path.GetFileName(commandName), Path.GetFileNameWithoutExtension(commandName) },
context);
if (customCompleter != null)
{
if (InvokeScriptArgumentCompleter(
customCompleter,
new object[] { context.WordToComplete, commandAst, context.CursorPosition.Offset },
result))
{
return result;
}
}
var clearLiteralPathKey = false;
if (pseudoBinding == null)
{
// the command could be a native command such as notepad.exe, we use literal path in this case
clearLiteralPathKey = TurnOnLiteralPathOption(context);
}
try
{
result = new List(CompleteFilename(context));
}
finally
{
if (clearLiteralPathKey)
context.Options.Remove("LiteralPaths");
}
// The word to complete contains a dash and it's not the first character. We try command names in this case.
if (context.WordToComplete.IndexOf('-') > 0)
{
var commandResults = CompleteCommand(context);
if (commandResults != null)
result.AddRange(commandResults);
}
}
return result;
}
internal static string ConcatenateStringPathArguments(CommandElementAst stringAst, string partialPath, CompletionContext completionContext)
{
var constantPathAst = stringAst as StringConstantExpressionAst;
if (constantPathAst != null)
{
string quote = string.Empty;
switch (constantPathAst.StringConstantType)
{
case StringConstantType.SingleQuoted:
quote = "'";
break;
case StringConstantType.DoubleQuoted:
quote = "\"";
break;
default:
break;
}
return quote + constantPathAst.Value + partialPath + quote;
}
else
{
var expandablePathAst = stringAst as ExpandableStringExpressionAst;
string fullPath = null;
if (expandablePathAst != null &&
IsPathSafelyExpandable(expandableStringAst: expandablePathAst,
extraText: partialPath,
executionContext: completionContext.ExecutionContext,
expandedString: out fullPath))
{
return fullPath;
}
}
return null;
}
///
/// Get the argument completion results when the pseudo binding was not successful.
///
private static List GetArgumentCompletionResultsWithFailedPseudoBinding(
CompletionContext context,
ArgumentLocation argLocation,
CommandAst commandAst)
{
List result = new List();
PseudoBindingInfo bindingInfo = context.PseudoBindingInfo;
if (argLocation.IsPositional)
{
CompletePositionalArgument(
bindingInfo.CommandName,
commandAst,
context,
result,
bindingInfo.UnboundParameters,
bindingInfo.DefaultParameterSetFlag,
uint.MaxValue,
argLocation.Position);
}
else
{
string paramName = argLocation.Argument.ParameterName;
WildcardPattern pattern = WildcardPattern.Get(paramName + "*", WildcardOptions.IgnoreCase);
foreach (MergedCompiledCommandParameter param in bindingInfo.UnboundParameters)
{
if (pattern.IsMatch(param.Parameter.Name))
{
ProcessParameter(bindingInfo.CommandName, commandAst, context, result, param);
break;
}
bool isAliasMatch = false;
foreach (string alias in param.Parameter.Aliases)
{
if (pattern.IsMatch(alias))
{
isAliasMatch = true;
ProcessParameter(bindingInfo.CommandName, commandAst, context, result, param);
break;
}
}
if (isAliasMatch)
break;
}
}
return result;
}
///
/// Get the argument completion results when the pseudo binding was successful.
///
private static List GetArgumentCompletionResultsWithSuccessfulPseudoBinding(
CompletionContext context,
ArgumentLocation argLocation,
CommandAst commandAst)
{
PseudoBindingInfo bindingInfo = context.PseudoBindingInfo;
Diagnostics.Assert(bindingInfo.InfoType.Equals(PseudoBindingInfoType.PseudoBindingSucceed), "Caller needs to make sure the pseudo binding was successful");
List result = new List();
if (argLocation.IsPositional && argLocation.Argument == null)
{
AstPair lastPositionalArg;
AstParameterArgumentPair targetPositionalArg =
FindTargetPositionalArgument(
bindingInfo.AllParsedArguments,
argLocation.Position,
out lastPositionalArg);
if (targetPositionalArg != null)
argLocation.Argument = targetPositionalArg;
else
{
if (lastPositionalArg != null)
{
bool lastPositionalGetBound = false;
Collection parameterNames = new Collection();
foreach (KeyValuePair entry in bindingInfo.BoundArguments)
{
// positional argument
if (!entry.Value.ParameterSpecified)
{
var arg = (AstPair)entry.Value;
if (arg.Argument.GetHashCode() == lastPositionalArg.Argument.GetHashCode())
{
lastPositionalGetBound = true;
break;
}
}
else if (entry.Value.ParameterArgumentType.Equals(AstParameterArgumentType.AstArray))
{
// check if the positional argument would be bound to a "ValueFromRemainingArgument" parameter
var arg = (AstArrayPair)entry.Value;
if (arg.Argument.Any(exp => exp.GetHashCode() == lastPositionalArg.Argument.GetHashCode()))
{
parameterNames.Add(entry.Key);
}
}
}
if (parameterNames.Count > 0)
{
// parameter should be in BoundParameters
foreach (string param in parameterNames)
{
MergedCompiledCommandParameter parameter = bindingInfo.BoundParameters[param];
ProcessParameter(bindingInfo.CommandName, commandAst, context, result, parameter, bindingInfo.BoundArguments);
}
return result;
}
else if (!lastPositionalGetBound)
{
// last positional argument was not bound, then positional argument 'tab' wants to
// expand will not get bound either
return result;
}
}
CompletePositionalArgument(
bindingInfo.CommandName,
commandAst,
context,
result,
bindingInfo.UnboundParameters,
bindingInfo.DefaultParameterSetFlag,
bindingInfo.ValidParameterSetsFlags,
argLocation.Position,
bindingInfo.BoundArguments);
return result;
}
}
if (argLocation.Argument != null)
{
Collection parameterNames = new Collection();
foreach (KeyValuePair entry in bindingInfo.BoundArguments)
{
if (entry.Value.ParameterArgumentType.Equals(AstParameterArgumentType.PipeObject))
continue;
if (entry.Value.ParameterArgumentType.Equals(AstParameterArgumentType.AstArray) && !argLocation.Argument.ParameterSpecified)
{
var arrayArg = (AstArrayPair)entry.Value;
var target = (AstPair)argLocation.Argument;
if (arrayArg.Argument.Any(exp => exp.GetHashCode() == target.Argument.GetHashCode()))
{
parameterNames.Add(entry.Key);
}
}
else if (entry.Value.GetHashCode() == argLocation.Argument.GetHashCode())
{
parameterNames.Add(entry.Key);
}
}
if (parameterNames.Count > 0)
{
// those parameters should be in BoundParameters
foreach (string param in parameterNames)
{
MergedCompiledCommandParameter parameter = bindingInfo.BoundParameters[param];
ProcessParameter(bindingInfo.CommandName, commandAst, context, result, parameter, bindingInfo.BoundArguments);
}
}
}
return result;
}
///
/// Get the positional argument completion results based on the position it's in the command line.
///
private static void CompletePositionalArgument(
string commandName,
CommandAst commandAst,
CompletionContext context,
List result,
IEnumerable parameters,
uint defaultParameterSetFlag,
uint validParameterSetFlags,
int position,
Dictionary boundArguments = null)
{
bool isProcessedAsPositional = false;
bool isDefaultParameterSetValid = defaultParameterSetFlag != 0 &&
(defaultParameterSetFlag & validParameterSetFlags) != 0;
MergedCompiledCommandParameter positionalParam = null;
MergedCompiledCommandParameter bestMatchParam = null;
ParameterSetSpecificMetadata bestMatchSet = null;
// Finds the parameter with the position closest to the specified position
foreach (MergedCompiledCommandParameter param in parameters)
{
bool isInParameterSet = (param.Parameter.ParameterSetFlags & validParameterSetFlags) != 0 || param.Parameter.IsInAllSets;
if (!isInParameterSet)
{
continue;
}
var parameterSetDataCollection = param.Parameter.GetMatchingParameterSetData(validParameterSetFlags);
foreach (ParameterSetSpecificMetadata parameterSetData in parameterSetDataCollection)
{
// in the first pass, we skip the remaining argument ones
if (parameterSetData.ValueFromRemainingArguments)
{
continue;
}
// Check the position
int positionInParameterSet = parameterSetData.Position;
if (positionInParameterSet < position)
{
// The parameter is not positional (position == int.MinValue), or its position is lower than what we want.
continue;
}
if (bestMatchSet is null
|| bestMatchSet.Position > positionInParameterSet
|| (isDefaultParameterSetValid && positionInParameterSet == bestMatchSet.Position && defaultParameterSetFlag == parameterSetData.ParameterSetFlag))
{
bestMatchParam = param;
bestMatchSet = parameterSetData;
if (positionInParameterSet == position)
{
break;
}
}
}
}
if (bestMatchParam is not null)
{
if (isDefaultParameterSetValid)
{
if (bestMatchSet.ParameterSetFlag == defaultParameterSetFlag)
{
ProcessParameter(commandName, commandAst, context, result, bestMatchParam, boundArguments);
isProcessedAsPositional = result.Count > 0;
}
else
{
positionalParam ??= bestMatchParam;
}
}
else
{
isProcessedAsPositional = true;
ProcessParameter(commandName, commandAst, context, result, bestMatchParam, boundArguments);
}
}
if (!isProcessedAsPositional && positionalParam != null)
{
isProcessedAsPositional = true;
ProcessParameter(commandName, commandAst, context, result, positionalParam, boundArguments);
}
if (!isProcessedAsPositional)
{
foreach (MergedCompiledCommandParameter param in parameters)
{
bool isInParameterSet = (param.Parameter.ParameterSetFlags & validParameterSetFlags) != 0 || param.Parameter.IsInAllSets;
if (!isInParameterSet)
continue;
var parameterSetDataCollection = param.Parameter.GetMatchingParameterSetData(validParameterSetFlags);
foreach (ParameterSetSpecificMetadata parameterSetData in parameterSetDataCollection)
{
// in the second pass, we check the remaining argument ones
if (parameterSetData.ValueFromRemainingArguments)
{
ProcessParameter(commandName, commandAst, context, result, param, boundArguments);
break;
}
}
}
}
}
///
/// Process a parameter to get the argument completion results.
///
///
/// If the argument completion falls into these pre-defined cases:
/// 1. The matching parameter is declared with ValidateSetAttribute
/// 2. The matching parameter is of type Enum
/// 3. The matching parameter is of type SwitchParameter
/// 4. Falls into the native command argument completion
/// a null instance of CompletionResult is added to the end of the
/// "result" list, to indicate that this particular argument completion
/// has been processed already. If the "result" list is still empty, we
/// will not go through the default argument completion steps anymore.
///
private static void ProcessParameter(
string commandName,
CommandAst commandAst,
CompletionContext context,
List result,
MergedCompiledCommandParameter parameter,
Dictionary boundArguments = null)
{
CompletionResult fullMatch = null;
Type parameterType = GetEffectiveParameterType(parameter.Parameter.Type);
if (parameterType.IsArray)
{
parameterType = parameterType.GetElementType();
}
foreach (ValidateArgumentsAttribute att in parameter.Parameter.ValidationAttributes)
{
if (att is ValidateSetAttribute setAtt)
{
RemoveLastNullCompletionResult(result);
string wordToComplete = context.WordToComplete ?? string.Empty;
string quote = CompletionHelpers.HandleDoubleAndSingleQuote(ref wordToComplete);
var pattern = WildcardPattern.Get(wordToComplete + "*", WildcardOptions.IgnoreCase);
var setList = new List();
foreach (string value in setAtt.ValidValues)
{
if (value == string.Empty)
{
continue;
}
if (wordToComplete.Equals(value, StringComparison.OrdinalIgnoreCase))
{
string completionText = quote == string.Empty ? value : quote + value + quote;
fullMatch = new CompletionResult(completionText, value, CompletionResultType.ParameterValue, value);
continue;
}
if (pattern.IsMatch(value))
{
setList.Add(value);
}
}
if (fullMatch != null)
{
result.Add(fullMatch);
}
setList.Sort();
foreach (string entry in setList)
{
string realEntry = entry;
string completionText = entry;
completionText = CompletionHelpers.QuoteCompletionText(completionText, quote);
result.Add(new CompletionResult(completionText, entry, CompletionResultType.ParameterValue, entry));
}
result.Add(CompletionResult.Null);
return;
}
}
if (parameterType.IsEnum)
{
RemoveLastNullCompletionResult(result);
IEnumerable enumValues = LanguagePrimitives.EnumSingleTypeConverter.GetEnumValues(parameterType);
// Exclude values not accepted by ValidateRange-attributes
foreach (ValidateArgumentsAttribute att in parameter.Parameter.ValidationAttributes)
{
if (att is ValidateRangeAttribute rangeAtt)
{
enumValues = rangeAtt.GetValidatedElements(enumValues);
}
}
string wordToComplete = context.WordToComplete ?? string.Empty;
string quote = CompletionHelpers.HandleDoubleAndSingleQuote(ref wordToComplete);
var pattern = WildcardPattern.Get(wordToComplete + "*", WildcardOptions.IgnoreCase);
var enumList = new List();
foreach (Enum value in enumValues)
{
string name = value.ToString();
if (wordToComplete.Equals(name, StringComparison.OrdinalIgnoreCase))
{
string completionText = quote == string.Empty ? name : quote + name + quote;
fullMatch = new CompletionResult(completionText, name, CompletionResultType.ParameterValue, name);
continue;
}
if (pattern.IsMatch(name))
{
enumList.Add(name);
}
}
if (fullMatch != null)
{
result.Add(fullMatch);
}
enumList.Sort();
result.AddRange(from entry in enumList
let completionText = quote == string.Empty ? entry : quote + entry + quote
select new CompletionResult(completionText, entry, CompletionResultType.ParameterValue, entry));
result.Add(CompletionResult.Null);
return;
}
if (parameterType.Equals(typeof(SwitchParameter)))
{
RemoveLastNullCompletionResult(result);
if (context.WordToComplete == string.Empty || context.WordToComplete.Equals("$", StringComparison.Ordinal))
{
result.Add(new CompletionResult("$true", "$true", CompletionResultType.ParameterValue, "$true"));
result.Add(new CompletionResult("$false", "$false", CompletionResultType.ParameterValue, "$false"));
}
result.Add(CompletionResult.Null);
return;
}
NativeCommandArgumentCompletion(commandName, parameter.Parameter, result, commandAst, context, boundArguments);
}
private static IEnumerable NativeCommandArgumentCompletion_InferTypesOfArgument(
Dictionary boundArguments,
CommandAst commandAst,
CompletionContext context,
string parameterName)
{
if (boundArguments == null)
{
yield break;
}
AstParameterArgumentPair astParameterArgumentPair;
if (!boundArguments.TryGetValue(parameterName, out astParameterArgumentPair))
{
yield break;
}
Ast argumentAst = null;
switch (astParameterArgumentPair.ParameterArgumentType)
{
case AstParameterArgumentType.AstPair:
{
AstPair astPair = (AstPair)astParameterArgumentPair;
argumentAst = astPair.Argument;
}
break;
case AstParameterArgumentType.PipeObject:
{
var pipelineAst = commandAst.Parent as PipelineAst;
if (pipelineAst != null)
{
int i;
for (i = 0; i < pipelineAst.PipelineElements.Count; i++)
{
if (pipelineAst.PipelineElements[i] == commandAst)
break;
}
if (i != 0)
{
argumentAst = pipelineAst.PipelineElements[i - 1];
}
}
}
break;
default:
break;
}
if (argumentAst == null)
{
yield break;
}
ExpressionAst argumentExpressionAst = argumentAst as ExpressionAst;
if (argumentExpressionAst == null)
{
CommandExpressionAst argumentCommandExpressionAst = argumentAst as CommandExpressionAst;
if (argumentCommandExpressionAst != null)
{
argumentExpressionAst = argumentCommandExpressionAst.Expression;
}
}
object argumentValue;
if (argumentExpressionAst != null && SafeExprEvaluator.TrySafeEval(argumentExpressionAst, context.ExecutionContext, out argumentValue))
{
if (argumentValue != null)
{
IEnumerable enumerable = LanguagePrimitives.GetEnumerable(argumentValue) ??
new object[] { argumentValue };
foreach (var element in enumerable)
{
if (element == null)
{
continue;
}
PSObject pso = PSObject.AsPSObject(element);
if ((pso.TypeNames.Count > 0) && (!(pso.TypeNames[0].Equals(pso.BaseObject.GetType().FullName, StringComparison.OrdinalIgnoreCase))))
{
yield return new PSTypeName(pso.TypeNames[0]);
}
if (pso.BaseObject is not PSCustomObject)
{
yield return new PSTypeName(pso.BaseObject.GetType());
}
}
yield break;
}
}
foreach (PSTypeName typeName in AstTypeInference.InferTypeOf(argumentAst, context.TypeInferenceContext, TypeInferenceRuntimePermissions.AllowSafeEval))
{
yield return typeName;
}
}
internal static IList NativeCommandArgumentCompletion_ExtractSecondaryArgument(
Dictionary boundArguments,
string parameterName)
{
List result = new List();
if (boundArguments == null)
{
return result;
}
AstParameterArgumentPair argumentValue;
if (!boundArguments.TryGetValue(parameterName, out argumentValue))
{
return result;
}
switch (argumentValue.ParameterArgumentType)
{
case AstParameterArgumentType.AstPair:
{
var value = (AstPair)argumentValue;
if (value.Argument is StringConstantExpressionAst)
{
var argument = (StringConstantExpressionAst)value.Argument;
result.Add(argument.Value);
}
else if (value.Argument is ArrayLiteralAst)
{
var argument = (ArrayLiteralAst)value.Argument;
foreach (ExpressionAst entry in argument.Elements)
{
var entryAsString = entry as StringConstantExpressionAst;
if (entryAsString != null)
{
result.Add(entryAsString.Value);
}
else
{
result.Clear();
break;
}
}
}
break;
}
case AstParameterArgumentType.AstArray:
{
var value = (AstArrayPair)argumentValue;
var argument = value.Argument;
foreach (ExpressionAst entry in argument)
{
var entryAsString = entry as StringConstantExpressionAst;
if (entryAsString != null)
{
result.Add(entryAsString.Value);
}
else
{
result.Clear();
break;
}
}
break;
}
default:
break;
}
return result;
}
private static void NativeCommandArgumentCompletion(
string commandName,
CompiledCommandParameter parameter,
List result,
CommandAst commandAst,
CompletionContext context,
Dictionary boundArguments = null)
{
string parameterName = parameter.Name;
// Fall back to the commandAst command name if a command name is not found. This can be caused by a script block or AST with the matching function definition being passed to CompleteInput
// This allows for editors and other tools using CompleteInput with Script/AST definitions to get values from RegisteredArgumentCompleters to better match the console experience.
// See issue https://github.com/PowerShell/PowerShell/issues/10567
string actualCommandName = string.IsNullOrEmpty(commandName)
? commandAst.GetCommandName()
: commandName;
if (string.IsNullOrEmpty(actualCommandName))
{
return;
}
string parameterFullName = $"{actualCommandName}:{parameterName}";
ScriptBlock customCompleter = GetCustomArgumentCompleter(
"CustomArgumentCompleters",
new[] { parameterFullName, parameterName },
context);
if (customCompleter != null)
{
if (InvokeScriptArgumentCompleter(
customCompleter,
commandName, parameterName, context.WordToComplete, commandAst, context,
result))
{
return;
}
}
var argumentCompleterAttribute = parameter.CompiledAttributes.OfType().FirstOrDefault();
if (argumentCompleterAttribute != null)
{
try
{
var completer = argumentCompleterAttribute.CreateArgumentCompleter();
if (completer != null)
{
var customResults = completer.CompleteArgument(commandName, parameterName,
context.WordToComplete, commandAst, GetBoundArgumentsAsHashtable(context));
if (customResults != null)
{
result.AddRange(customResults);
result.Add(CompletionResult.Null);
return;
}
}
else
{
if (InvokeScriptArgumentCompleter(
argumentCompleterAttribute.ScriptBlock,
commandName, parameterName, context.WordToComplete, commandAst, context,
result))
{
return;
}
}
}
catch (Exception)
{
}
}
var argumentCompletionsAttribute = parameter.CompiledAttributes.OfType().FirstOrDefault();
if (argumentCompletionsAttribute != null)
{
var customResults = argumentCompletionsAttribute.CompleteArgument(commandName, parameterName,
context.WordToComplete, commandAst, GetBoundArgumentsAsHashtable(context));
if (customResults != null)
{
result.AddRange(customResults);
result.Add(CompletionResult.Null);
return;
}
}
switch (commandName)
{
case "Get-Command":
{
if (parameterName.Equals("Module", StringComparison.OrdinalIgnoreCase))
{
NativeCompletionGetCommand(context, /* moduleName: */ null, parameterName, result);
break;
}
if (parameterName.Equals("ExcludeModule", StringComparison.OrdinalIgnoreCase))
{
NativeCompletionGetCommand(context, moduleName: null, parameterName, result);
break;
}
if (parameterName.Equals("Name", StringComparison.OrdinalIgnoreCase))
{
var moduleNames = NativeCommandArgumentCompletion_ExtractSecondaryArgument(boundArguments, "Module");
if (moduleNames.Count > 0)
{
foreach (string module in moduleNames)
{
NativeCompletionGetCommand(context, module, parameterName, result);
}
}
else
{
NativeCompletionGetCommand(context, /* moduleName: */ null, parameterName, result);
}
break;
}
if (parameterName.Equals("ParameterType", StringComparison.OrdinalIgnoreCase))
{
NativeCompletionTypeName(context, result);
break;
}
break;
}
case "Show-Command":
{
NativeCompletionGetHelpCommand(context, parameterName, /* isHelpRelated: */ false, result);
break;
}
case "help":
case "Get-Help":
{
NativeCompletionGetHelpCommand(context, parameterName, /* isHelpRelated: */ true, result);
break;
}
case "Save-Help":
{
if (parameterName.Equals("Module", StringComparison.OrdinalIgnoreCase))
{
CompleteModule(context, result);
}
break;
}
case "Update-Help":
{
if (parameterName.Equals("Module", StringComparison.OrdinalIgnoreCase))
{
CompleteModule(context, result);
}
break;
}
case "Invoke-Expression":
{
if (parameterName.Equals("Command", StringComparison.OrdinalIgnoreCase))
{
var commandResults = CompleteCommand(context);
if (commandResults != null)
result.AddRange(commandResults);
}
break;
}
case "Clear-EventLog":
case "Get-EventLog":
case "Limit-EventLog":
case "Remove-EventLog":
case "Write-EventLog":
{
NativeCompletionEventLogCommands(context, parameterName, result);
break;
}
case "Get-Job":
case "Receive-Job":
case "Remove-Job":
case "Stop-Job":
case "Wait-Job":
case "Suspend-Job":
case "Resume-Job":
{
NativeCompletionJobCommands(context, parameterName, result);
break;
}
case "Disable-ScheduledJob":
case "Enable-ScheduledJob":
case "Get-ScheduledJob":
case "Unregister-ScheduledJob":
{
NativeCompletionScheduledJobCommands(context, parameterName, result);
break;
}
case "Get-Module":
{
bool loadedModulesOnly = boundArguments == null || !boundArguments.ContainsKey("ListAvailable");
bool skipEditionCheck = !loadedModulesOnly && boundArguments.ContainsKey("SkipEditionCheck");
NativeCompletionModuleCommands(context, parameterName, result, loadedModulesOnly, skipEditionCheck: skipEditionCheck);
break;
}
case "Remove-Module":
{
NativeCompletionModuleCommands(context, parameterName, result, loadedModulesOnly: true);
break;
}
case "Import-Module":
{
bool skipEditionCheck = boundArguments != null && boundArguments.ContainsKey("SkipEditionCheck");
NativeCompletionModuleCommands(context, parameterName, result, isImportModule: true, skipEditionCheck: skipEditionCheck);
break;
}
case "Debug-Process":
case "Get-Process":
case "Stop-Process":
case "Wait-Process":
case "Enter-PSHostProcess":
{
NativeCompletionProcessCommands(context, parameterName, result);
break;
}
case "Get-PSDrive":
case "Remove-PSDrive":
{
if (parameterName.Equals("PSProvider", StringComparison.OrdinalIgnoreCase))
{
NativeCompletionProviderCommands(context, parameterName, result);
}
else if (parameterName.Equals("Name", StringComparison.OrdinalIgnoreCase))
{
var psProviders = NativeCommandArgumentCompletion_ExtractSecondaryArgument(boundArguments, "PSProvider");
if (psProviders.Count > 0)
{
foreach (string psProvider in psProviders)
{
NativeCompletionDriveCommands(context, psProvider, parameterName, result);
}
}
else
{
NativeCompletionDriveCommands(context, /* psProvider: */ null, parameterName, result);
}
}
break;
}
case "New-PSDrive":
{
NativeCompletionProviderCommands(context, parameterName, result);
break;
}
case "Get-PSProvider":
{
NativeCompletionProviderCommands(context, parameterName, result);
break;
}
case "Get-Service":
case "Start-Service":
case "Restart-Service":
case "Resume-Service":
case "Set-Service":
case "Stop-Service":
case "Suspend-Service":
{
NativeCompletionServiceCommands(context, parameterName, result);
break;
}
case "Clear-Variable":
case "Get-Variable":
case "Remove-Variable":
case "Set-Variable":
{
NativeCompletionVariableCommands(context, parameterName, result);
break;
}
case "Get-Alias":
{
NativeCompletionAliasCommands(context, parameterName, result);
break;
}
case "Get-TraceSource":
case "Set-TraceSource":
case "Trace-Command":
{
NativeCompletionTraceSourceCommands(context, parameterName, result);
break;
}
case "Push-Location":
case "Set-Location":
{
NativeCompletionSetLocationCommand(context, parameterName, result);
break;
}
case "Move-Item":
case "Copy-Item":
{
NativeCompletionCopyMoveItemCommand(context, parameterName, result);
break;
}
case "New-Item":
{
NativeCompletionNewItemCommand(context, parameterName, result);
break;
}
case "ForEach-Object":
{
if (parameterName.Equals("MemberName", StringComparison.OrdinalIgnoreCase))
{
NativeCompletionMemberName(context, result, commandAst, boundArguments?[parameterName], propertiesOnly: false);
}
break;
}
case "Group-Object":
case "Measure-Object":
case "Sort-Object":
case "Where-Object":
{
if (parameterName.Equals("Property", StringComparison.OrdinalIgnoreCase))
{
NativeCompletionMemberName(context, result, commandAst, boundArguments?[parameterName]);
}
else if (parameterName.Equals("Value", StringComparison.OrdinalIgnoreCase)
&& boundArguments?["Property"] is AstPair pair && pair.Argument is StringConstantExpressionAst stringAst)
{
NativeCompletionMemberValue(context, result, commandAst, stringAst.Value);
}
break;
}
case "Format-Custom":
case "Format-List":
case "Format-Table":
case "Format-Wide":
{
if (parameterName.Equals("Property", StringComparison.OrdinalIgnoreCase)
|| parameterName.Equals("ExcludeProperty", StringComparison.OrdinalIgnoreCase))
{
NativeCompletionMemberName(context, result, commandAst, boundArguments?[parameterName]);
}
else if (parameterName.Equals("View", StringComparison.OrdinalIgnoreCase))
{
NativeCompletionFormatViewName(context, boundArguments, result, commandAst, commandName);
}
break;
}
case "Select-Object":
{
if (parameterName.Equals("Property", StringComparison.OrdinalIgnoreCase)
|| parameterName.Equals("ExcludeProperty", StringComparison.OrdinalIgnoreCase)
|| parameterName.Equals("ExpandProperty", StringComparison.OrdinalIgnoreCase))
{
NativeCompletionMemberName(context, result, commandAst, boundArguments?[parameterName]);
}
break;
}
case "New-Object":
{
if (parameterName.Equals("TypeName", StringComparison.OrdinalIgnoreCase))
{
NativeCompletionTypeName(context, result);
}
break;
}
case "Get-CimClass":
case "Get-CimInstance":
case "Get-CimAssociatedInstance":
case "Invoke-CimMethod":
case "New-CimInstance":
case "Register-CimIndicationEvent":
case "Set-CimInstance":
{
// Avoids completion for parameters that expect a hashtable.
if (parameterName.Equals("Arguments", StringComparison.OrdinalIgnoreCase)
|| (parameterName.Equals("Property", StringComparison.OrdinalIgnoreCase) && !commandName.Equals("Get-CimInstance")))
{
break;
}
HashSet excludedValues = null;
if (parameterName.Equals("Property", StringComparison.OrdinalIgnoreCase) && boundArguments["Property"] is AstPair pair)
{
excludedValues = GetParameterValues(pair, context.CursorPosition.Offset);
}
NativeCompletionCimCommands(parameterName, boundArguments, result, commandAst, context, excludedValues, commandName);
break;
}
default:
{
NativeCompletionPathArgument(context, parameterName, result);
break;
}
}
}
private static Hashtable GetBoundArgumentsAsHashtable(CompletionContext context)
{
var result = new Hashtable(StringComparer.OrdinalIgnoreCase);
if (context.PseudoBindingInfo != null)
{
var boundArguments = context.PseudoBindingInfo.BoundArguments;
if (boundArguments != null)
{
foreach (var boundArgument in boundArguments)
{
var astPair = boundArgument.Value as AstPair;
if (astPair != null)
{
var parameterAst = astPair.Argument as CommandParameterAst;
var exprAst = parameterAst != null
? parameterAst.Argument
: astPair.Argument as ExpressionAst;
object value;
if (exprAst != null && SafeExprEvaluator.TrySafeEval(exprAst, context.ExecutionContext, out value))
{
result[boundArgument.Key] = value;
}
continue;
}
var switchPair = boundArgument.Value as SwitchPair;
if (switchPair != null)
{
result[boundArgument.Key] = switchPair.Argument;
continue;
}
// Ignored:
// AstArrayPair - only used for ValueFromRemainingArguments, not that useful for tab completion
// FakePair - missing argument, not that useful
// PipeObjectPair - no actual argument, makes for a poor api
}
}
}
return result;
}
private static ScriptBlock GetCustomArgumentCompleter(
string optionKey,
IEnumerable keys,
CompletionContext context)
{
ScriptBlock scriptBlock;
var options = context.Options;
if (options != null)
{
var customCompleters = options[optionKey] as Hashtable;
if (customCompleters != null)
{
foreach (var key in keys)
{
if (customCompleters.ContainsKey(key))
{
scriptBlock = customCompleters[key] as ScriptBlock;
if (scriptBlock != null)
return scriptBlock;
}
}
}
}
bool isNative = optionKey.Equals("NativeArgumentCompleters", StringComparison.OrdinalIgnoreCase);
var registeredCompleters = isNative ? context.NativeArgumentCompleters : context.CustomArgumentCompleters;
if (registeredCompleters != null)
{
foreach (var key in keys)
{
if (registeredCompleters.TryGetValue(key, out scriptBlock))
{
return scriptBlock;
}
}
// For a native command, if a fallback completer is registered, then return it.
// For example, the 'Microsoft.PowerShell.UnixTabCompletion' module.
if (isNative && registeredCompleters.TryGetValue(RegisterArgumentCompleterCommand.FallbackCompleterKey, out scriptBlock))
{
return scriptBlock;
}
}
return null;
}
private static bool InvokeScriptArgumentCompleter(
ScriptBlock scriptBlock,
string commandName,
string parameterName,
string wordToComplete,
CommandAst commandAst,
CompletionContext context,
List resultList)
{
bool result = InvokeScriptArgumentCompleter(
scriptBlock,
new object[] { commandName, parameterName, wordToComplete, commandAst, GetBoundArgumentsAsHashtable(context) },
resultList);
if (result)
{
resultList.Add(CompletionResult.Null);
}
return result;
}
private static bool InvokeScriptArgumentCompleter(
ScriptBlock scriptBlock,
object[] argumentsToCompleter,
List result)
{
Collection customResults = null;
try
{
customResults = scriptBlock.Invoke(argumentsToCompleter);
}
catch (Exception)
{
}
if (customResults == null || customResults.Count == 0)
{
return false;
}
foreach (var customResult in customResults)
{
var resultAsCompletion = customResult.BaseObject as CompletionResult;
if (resultAsCompletion != null)
{
result.Add(resultAsCompletion);
continue;
}
var resultAsString = customResult.ToString();
result.Add(new CompletionResult(resultAsString));
}
return true;
}
// All the methods for native command argument completion will add a null instance of the type CompletionResult to the end of the
// "result" list, to indicate that this particular argument completion has fallen into one of the native command argument completion methods,
// and has been processed already. So if the "result" list is still empty afterward, we will not go through the default argument completion anymore.
#region Native Command Argument Completion
private static void RemoveLastNullCompletionResult(List result)
{
if (result.Count > 0 && result[result.Count - 1].Equals(CompletionResult.Null))
{
result.RemoveAt(result.Count - 1);
}
}
private static void NativeCompletionCimCommands(
string parameter,
Dictionary boundArguments,
List result,
CommandAst commandAst,
CompletionContext context,
HashSet excludedValues,
string commandName)
{
if (boundArguments != null)
{
AstParameterArgumentPair astParameterArgumentPair;
if ((boundArguments.TryGetValue("ComputerName", out astParameterArgumentPair)
|| boundArguments.TryGetValue("CimSession", out astParameterArgumentPair))
&& astParameterArgumentPair != null)
{
switch (astParameterArgumentPair.ParameterArgumentType)
{
case AstParameterArgumentType.PipeObject:
case AstParameterArgumentType.Fake:
break;
default:
return; // we won't tab-complete remote class names
}
}
}
RemoveLastNullCompletionResult(result);
if (parameter.Equals("Namespace", StringComparison.OrdinalIgnoreCase))
{
NativeCompletionCimNamespace(result, context);
result.Add(CompletionResult.Null);
return;
}
string pseudoboundCimNamespace = NativeCommandArgumentCompletion_ExtractSecondaryArgument(boundArguments, "Namespace").FirstOrDefault();
if (parameter.Equals("ClassName", StringComparison.OrdinalIgnoreCase))
{
NativeCompletionCimClassName(pseudoboundCimNamespace, result, context);
result.Add(CompletionResult.Null);
return;
}
bool gotInstance = false;
IEnumerable cimClassTypeNames = null;
string pseudoboundClassName = NativeCommandArgumentCompletion_ExtractSecondaryArgument(boundArguments, "ClassName").FirstOrDefault();
if (pseudoboundClassName != null)
{
gotInstance = false;
var tmp = new List();
tmp.Add(new PSTypeName(typeof(CimInstance).FullName + "#" + (pseudoboundCimNamespace ?? "root/cimv2") + "/" + pseudoboundClassName));
cimClassTypeNames = tmp;
}
else if (boundArguments != null && boundArguments.ContainsKey("InputObject"))
{
gotInstance = true;
cimClassTypeNames = NativeCommandArgumentCompletion_InferTypesOfArgument(boundArguments, commandAst, context, "InputObject");
}
if (cimClassTypeNames != null)
{
foreach (PSTypeName typeName in cimClassTypeNames)
{
if (TypeInferenceContext.ParseCimCommandsTypeName(typeName, out pseudoboundCimNamespace, out pseudoboundClassName))
{
if (parameter.Equals("ResultClassName", StringComparison.OrdinalIgnoreCase))
{
NativeCompletionCimAssociationResultClassName(pseudoboundCimNamespace, pseudoboundClassName, result, context);
}
else if (parameter.Equals("MethodName", StringComparison.OrdinalIgnoreCase))
{
NativeCompletionCimMethodName(pseudoboundCimNamespace, pseudoboundClassName, !gotInstance, result, context);
}
else if (parameter.Equals("Arguments", StringComparison.OrdinalIgnoreCase))
{
string pseudoboundMethodName = NativeCommandArgumentCompletion_ExtractSecondaryArgument(boundArguments, "MethodName").FirstOrDefault();
NativeCompletionCimMethodArgumentName(pseudoboundCimNamespace, pseudoboundClassName, pseudoboundMethodName, excludedValues, result, context);
}
else if (parameter.Equals("Property", StringComparison.OrdinalIgnoreCase))
{
bool includeReadOnly = !commandName.Equals("Set-CimInstance", StringComparison.OrdinalIgnoreCase);
NativeCompletionCimPropertyName(pseudoboundCimNamespace, pseudoboundClassName, includeReadOnly, excludedValues, result, context);
}
}
}
result.Add(CompletionResult.Null);
}
}
private static readonly ConcurrentDictionary> s_cimNamespaceAndClassNameToAssociationResultClassNames =
new ConcurrentDictionary>(StringComparer.OrdinalIgnoreCase);
private static IEnumerable NativeCompletionCimAssociationResultClassName_GetResultClassNames(
string cimNamespaceOfSource,
string cimClassNameOfSource)
{
StringBuilder safeClassName = new StringBuilder();
foreach (char c in cimClassNameOfSource)
{
if (char.IsLetterOrDigit(c) || c == '_')
{
safeClassName.Append(c);
}
}
List resultClassNames = new List();
using (var cimSession = CimSession.Create(null))
{
CimClass cimClass = cimSession.GetClass(cimNamespaceOfSource ?? "root/cimv2", cimClassNameOfSource);
while (cimClass != null)
{
string query = string.Format(
CultureInfo.InvariantCulture,
"associators of {{{0}}} WHERE SchemaOnly",
cimClass.CimSystemProperties.ClassName);
resultClassNames.AddRange(
cimSession.QueryInstances(cimNamespaceOfSource ?? "root/cimv2", "WQL", query)
.Select(static associationInstance => associationInstance.CimSystemProperties.ClassName));
cimClass = cimClass.CimSuperClass;
}
}
resultClassNames.Sort(StringComparer.OrdinalIgnoreCase);
return resultClassNames.Distinct(StringComparer.OrdinalIgnoreCase).ToList();
}
private static void NativeCompletionCimAssociationResultClassName(
string pseudoboundNamespace,
string pseudoboundClassName,
List result,
CompletionContext context)
{
if (string.IsNullOrWhiteSpace(pseudoboundClassName))
{
return;
}
IEnumerable resultClassNames = s_cimNamespaceAndClassNameToAssociationResultClassNames.GetOrAdd(
(pseudoboundNamespace ?? "root/cimv2") + ":" + pseudoboundClassName,
_ => NativeCompletionCimAssociationResultClassName_GetResultClassNames(pseudoboundNamespace, pseudoboundClassName));
WildcardPattern resultClassNamePattern = WildcardPattern.Get(context.WordToComplete + "*", WildcardOptions.IgnoreCase | WildcardOptions.CultureInvariant);
result.AddRange(resultClassNames
.Where(resultClassNamePattern.IsMatch)
.Select(x => new CompletionResult(x, x, CompletionResultType.Type, string.Create(CultureInfo.InvariantCulture, $"{pseudoboundClassName} -> {x}"))));
}
private static void NativeCompletionCimMethodName(
string pseudoboundNamespace,
string pseudoboundClassName,
bool staticMethod,
List result,
CompletionContext context)
{
if (string.IsNullOrWhiteSpace(pseudoboundClassName))
{
return;
}
CimClass cimClass;
using (var cimSession = CimSession.Create(null))
{
cimClass = cimSession.GetClass(pseudoboundNamespace ?? "root/cimv2", pseudoboundClassName);
}
WildcardPattern methodNamePattern = WildcardPattern.Get(context.WordToComplete + "*", WildcardOptions.CultureInvariant | WildcardOptions.IgnoreCase);
List localResults = new List();
foreach (CimMethodDeclaration methodDeclaration in cimClass.CimClassMethods)
{
string methodName = methodDeclaration.Name;
if (!methodNamePattern.IsMatch(methodName))
{
continue;
}
bool currentMethodIsStatic = methodDeclaration.Qualifiers.Any(static q => q.Name.Equals("Static", StringComparison.OrdinalIgnoreCase));
if ((currentMethodIsStatic && !staticMethod) || (!currentMethodIsStatic && staticMethod))
{
continue;
}
StringBuilder tooltipText = new StringBuilder();
tooltipText.Append(methodName);
tooltipText.Append('(');
bool gotFirstParameter = false;
foreach (var methodParameter in methodDeclaration.Parameters)
{
bool outParameter = methodParameter.Qualifiers.Any(static q => q.Name.Equals("Out", StringComparison.OrdinalIgnoreCase));
if (!gotFirstParameter)
{
gotFirstParameter = true;
}
else
{
tooltipText.Append(", ");
}
if (outParameter)
{
tooltipText.Append("[out] ");
}
tooltipText.Append(CimInstanceAdapter.CimTypeToTypeNameDisplayString(methodParameter.CimType));
tooltipText.Append(' ');
tooltipText.Append(methodParameter.Name);
if (outParameter)
{
continue;
}
}
tooltipText.Append(')');
localResults.Add(new CompletionResult(methodName, methodName, CompletionResultType.Method, tooltipText.ToString()));
}
result.AddRange(localResults.OrderBy(static x => x.ListItemText, StringComparer.OrdinalIgnoreCase));
}
private static void NativeCompletionCimMethodArgumentName(
string pseudoboundNamespace,
string pseudoboundClassName,
string pseudoboundMethodName,
HashSet excludedParameters,
List result,
CompletionContext context)
{
if (string.IsNullOrWhiteSpace(pseudoboundClassName) || string.IsNullOrWhiteSpace(pseudoboundMethodName))
{
return;
}
CimClass cimClass;
using (var cimSession = CimSession.Create(null))
{
using var options = new CimOperationOptions();
options.Flags |= CimOperationFlags.LocalizedQualifiers;
cimClass = cimSession.GetClass(pseudoboundNamespace ?? "root/cimv2", pseudoboundClassName, options);
}
var methodParameters = cimClass.CimClassMethods[pseudoboundMethodName]?.Parameters;
if (methodParameters is null)
{
return;
}
foreach (var parameter in methodParameters)
{
if ((string.IsNullOrEmpty(context.WordToComplete) || parameter.Name.StartsWith(context.WordToComplete, StringComparison.OrdinalIgnoreCase))
&& (excludedParameters is null || !excludedParameters.Contains(parameter.Name))
&& parameter.Qualifiers["In"]?.Value is true)
{
string parameterDescription = parameter.Qualifiers["Description"]?.Value as string ?? string.Empty;
string toolTip = $"[{CimInstanceAdapter.CimTypeToTypeNameDisplayString(parameter.CimType)}] {parameterDescription}";
result.Add(new CompletionResult(parameter.Name, parameter.Name, CompletionResultType.Property, toolTip));
}
}
}
private static void NativeCompletionCimPropertyName(
string pseudoboundNamespace,
string pseudoboundClassName,
bool includeReadOnly,
HashSet excludedProperties,
List result,
CompletionContext context)
{
if (string.IsNullOrWhiteSpace(pseudoboundClassName))
{
return;
}
CimClass cimClass;
using (var cimSession = CimSession.Create(null))
{
using var options = new CimOperationOptions();
options.Flags |= CimOperationFlags.LocalizedQualifiers;
cimClass = cimSession.GetClass(pseudoboundNamespace ?? "root/cimv2", pseudoboundClassName, options);
}
foreach (var property in cimClass.CimClassProperties)
{
bool isReadOnly = (property.Flags & CimFlags.ReadOnly) != 0;
if ((!isReadOnly || (isReadOnly && includeReadOnly))
&& (string.IsNullOrEmpty(context.WordToComplete) || property.Name.StartsWith(context.WordToComplete, StringComparison.OrdinalIgnoreCase))
&& (excludedProperties is null || !excludedProperties.Contains(property.Name)))
{
string propertyDescription = property.Qualifiers["Description"]?.Value as string ?? string.Empty;
string accessString = isReadOnly ? "{ get; }" : "{ get; set; }";
string toolTip = $"[{CimInstanceAdapter.CimTypeToTypeNameDisplayString(property.CimType)}] {accessString} {propertyDescription}";
result.Add(new CompletionResult(property.Name, property.Name, CompletionResultType.Property, toolTip));
}
}
}
private static readonly ConcurrentDictionary> s_cimNamespaceToClassNames =
new ConcurrentDictionary>(StringComparer.OrdinalIgnoreCase);
private static IEnumerable NativeCompletionCimClassName_GetClassNames(string targetNamespace)
{
List result = new List();
using (CimSession cimSession = CimSession.Create(null))
{
using (var operationOptions = new CimOperationOptions { ClassNamesOnly = true })
foreach (CimClass cimClass in cimSession.EnumerateClasses(targetNamespace, null, operationOptions))
using (cimClass)
{
string className = cimClass.CimSystemProperties.ClassName;
result.Add(className);
}
}
return result;
}
private static void NativeCompletionCimClassName(
string pseudoBoundNamespace,
List result,
CompletionContext context)
{
string targetNamespace = pseudoBoundNamespace ?? "root/cimv2";
List regularClasses = new List();
List systemClasses = new List();
IEnumerable allClasses = s_cimNamespaceToClassNames.GetOrAdd(
targetNamespace,
NativeCompletionCimClassName_GetClassNames);
WildcardPattern classNamePattern = WildcardPattern.Get(context.WordToComplete + "*", WildcardOptions.CultureInvariant | WildcardOptions.IgnoreCase);
foreach (string className in allClasses)
{
if (context.Helper.CancelTabCompletion)
{
break;
}
if (!classNamePattern.IsMatch(className))
{
continue;
}
if (className.Length > 0 && className[0] == '_')
{
systemClasses.Add(className);
}
else
{
regularClasses.Add(className);
}
}
regularClasses.Sort(StringComparer.OrdinalIgnoreCase);
systemClasses.Sort(StringComparer.OrdinalIgnoreCase);
result.AddRange(
regularClasses.Concat(systemClasses)
.Select(className => new CompletionResult(className, className, CompletionResultType.Type, targetNamespace + ":" + className)));
}
private static void NativeCompletionCimNamespace(
List result,
CompletionContext context)
{
string containerNamespace = "root";
string prefixOfChildNamespace = string.Empty;
if (!string.IsNullOrEmpty(context.WordToComplete))
{
int lastSlashOrBackslash = context.WordToComplete.AsSpan().LastIndexOfAny('\\', '/');
if (lastSlashOrBackslash != (-1))
{
containerNamespace = context.WordToComplete.Substring(0, lastSlashOrBackslash);
prefixOfChildNamespace = context.WordToComplete.Substring(lastSlashOrBackslash + 1);
}
}
List namespaceResults = new List();
WildcardPattern childNamespacePattern = WildcardPattern.Get(prefixOfChildNamespace + "*", WildcardOptions.IgnoreCase | WildcardOptions.CultureInvariant);
using (CimSession cimSession = CimSession.Create(null))
{
foreach (CimInstance namespaceInstance in cimSession.EnumerateInstances(containerNamespace, "__Namespace"))
using (namespaceInstance)
{
if (context.Helper.CancelTabCompletion)
{
break;
}
CimProperty namespaceNameProperty = namespaceInstance.CimInstanceProperties["Name"];
if (namespaceNameProperty == null)
{
continue;
}
if (namespaceNameProperty.Value is not string childNamespace)
{
continue;
}
if (!childNamespacePattern.IsMatch(childNamespace))
{
continue;
}
namespaceResults.Add(new CompletionResult(
containerNamespace + "/" + childNamespace,
childNamespace,
CompletionResultType.Namespace,
containerNamespace + "/" + childNamespace));
}
}
result.AddRange(namespaceResults.OrderBy(static x => x.ListItemText, StringComparer.OrdinalIgnoreCase));
}
private static void NativeCompletionGetCommand(CompletionContext context, string moduleName, string paramName, List result)
{
if (!string.IsNullOrEmpty(paramName) && paramName.Equals("Name", StringComparison.OrdinalIgnoreCase))
{
RemoveLastNullCompletionResult(result);
// Available commands
var commandResults = CompleteCommand(context, moduleName);
if (commandResults != null)
result.AddRange(commandResults);
// Consider files only if the -Module parameter is not present
if (moduleName == null)
{
// ps1 files and directories. We only complete the files with .ps1 extension for Get-Command, because the -Syntax
// may only works on files with .ps1 extension
var ps1Extension = new HashSet(StringComparer.OrdinalIgnoreCase) { StringLiterals.PowerShellScriptFileExtension };
var moduleFilesResults = new List(CompleteFilename(context, /* containerOnly: */ false, ps1Extension));
if (moduleFilesResults.Count > 0)
result.AddRange(moduleFilesResults);
}
result.Add(CompletionResult.Null);
}
else if (!string.IsNullOrEmpty(paramName)
&& (paramName.Equals("Module", StringComparison.OrdinalIgnoreCase)
|| paramName.Equals("ExcludeModule", StringComparison.OrdinalIgnoreCase)))
{
CompleteModule(context, result);
}
}
private static void CompleteModule(CompletionContext context, List result)
{
RemoveLastNullCompletionResult(result);
var modules = new HashSet(StringComparer.OrdinalIgnoreCase);
var moduleResults = CompleteModuleName(context, loadedModulesOnly: true);
if (moduleResults != null)
{
foreach (CompletionResult moduleResult in moduleResults)
{
if (!modules.Contains(moduleResult.ToolTip))
{
modules.Add(moduleResult.ToolTip);
result.Add(moduleResult);
}
}
}
moduleResults = CompleteModuleName(context, loadedModulesOnly: false);
if (moduleResults != null)
{
foreach (CompletionResult moduleResult in moduleResults)
{
if (!modules.Contains(moduleResult.ToolTip))
{
modules.Add(moduleResult.ToolTip);
result.Add(moduleResult);
}
}
}
result.Add(CompletionResult.Null);
}
private static void NativeCompletionGetHelpCommand(CompletionContext context, string paramName, bool isHelpRelated, List result)
{
if (!string.IsNullOrEmpty(paramName) && paramName.Equals("Name", StringComparison.OrdinalIgnoreCase))
{
RemoveLastNullCompletionResult(result);
// Available commands
const CommandTypes commandTypes = CommandTypes.Cmdlet | CommandTypes.Function | CommandTypes.Alias | CommandTypes.ExternalScript | CommandTypes.Configuration;
var commandResults = CompleteCommand(context, /* moduleName: */ null, commandTypes);
if (commandResults != null)
result.AddRange(commandResults);
// ps1 files and directories
var ps1Extension = new HashSet(StringComparer.OrdinalIgnoreCase) { StringLiterals.PowerShellScriptFileExtension };
var fileResults = new List(CompleteFilename(context, /* containerOnly: */ false, ps1Extension));
if (fileResults.Count > 0)
result.AddRange(fileResults);
if (isHelpRelated)
{
// Available topics
var helpTopicResults = CompleteHelpTopics(context);
if (helpTopicResults != null)
result.AddRange(helpTopicResults);
}
result.Add(CompletionResult.Null);
}
}
private static void NativeCompletionEventLogCommands(CompletionContext context, string paramName, List result)
{
if (!string.IsNullOrEmpty(paramName) && paramName.Equals("LogName", StringComparison.OrdinalIgnoreCase))
{
RemoveLastNullCompletionResult(result);
var logName = context.WordToComplete ?? string.Empty;
var quote = CompletionHelpers.HandleDoubleAndSingleQuote(ref logName);
if (!logName.EndsWith('*'))
{
logName += "*";
}
var pattern = WildcardPattern.Get(logName, WildcardOptions.IgnoreCase);
var powerShellExecutionHelper = context.Helper;
var powershell = powerShellExecutionHelper.AddCommandWithPreferenceSetting("Microsoft.PowerShell.Management\\Get-EventLog").AddParameter("LogName", "*");
Exception exceptionThrown;
var psObjects = powerShellExecutionHelper.ExecuteCurrentPowerShell(out exceptionThrown);
if (psObjects != null)
{
foreach (dynamic eventLog in psObjects)
{
var completionText = eventLog.Log.ToString();
var listItemText = completionText;
completionText = CompletionHelpers.QuoteCompletionText(completionText, quote);
if (pattern.IsMatch(listItemText))
{
result.Add(new CompletionResult(completionText, listItemText, CompletionResultType.ParameterValue, listItemText));
}
}
}
result.Add(CompletionResult.Null);
}
}
private static void NativeCompletionJobCommands(CompletionContext context, string paramName, List result)
{
if (string.IsNullOrEmpty(paramName))
return;
var wordToComplete = context.WordToComplete ?? string.Empty;
var quote = CompletionHelpers.HandleDoubleAndSingleQuote(ref wordToComplete);
if (!wordToComplete.EndsWith('*'))
{
wordToComplete += "*";
}
var pattern = WildcardPattern.Get(wordToComplete, WildcardOptions.IgnoreCase);
var paramIsName = paramName.Equals("Name", StringComparison.OrdinalIgnoreCase);
var (parameterName, value) = paramIsName ? ("Name", wordToComplete) : ("IncludeChildJob", (object)true);
var powerShellExecutionHelper = context.Helper;
powerShellExecutionHelper.AddCommandWithPreferenceSetting("Get-Job", typeof(GetJobCommand)).AddParameter(parameterName, value);
Exception exceptionThrown;
var psObjects = powerShellExecutionHelper.ExecuteCurrentPowerShell(out exceptionThrown);
if (psObjects == null)
return;
if (paramName.Equals("Id", StringComparison.OrdinalIgnoreCase))
{
RemoveLastNullCompletionResult(result);
foreach (dynamic psJob in psObjects)
{
var completionText = psJob.Id.ToString();
if (pattern.IsMatch(completionText))
{
var listItemText = completionText;
completionText = quote + completionText + quote;
result.Add(new CompletionResult(completionText, listItemText, CompletionResultType.ParameterValue, listItemText));
}
}
result.Add(CompletionResult.Null);
}
else if (paramName.Equals("InstanceId", StringComparison.OrdinalIgnoreCase))
{
RemoveLastNullCompletionResult(result);
foreach (dynamic psJob in psObjects)
{
var completionText = psJob.InstanceId.ToString();
if (pattern.IsMatch(completionText))
{
var listItemText = completionText;
completionText = quote + completionText + quote;
result.Add(new CompletionResult(completionText, listItemText, CompletionResultType.ParameterValue, listItemText));
}
}
result.Add(CompletionResult.Null);
}
else if (paramIsName)
{
RemoveLastNullCompletionResult(result);
foreach (dynamic psJob in psObjects)
{
var completionText = psJob.Name;
var listItemText = completionText;
completionText = CompletionHelpers.QuoteCompletionText(completionText, quote);
result.Add(new CompletionResult(completionText, listItemText, CompletionResultType.ParameterValue, listItemText));
}
result.Add(CompletionResult.Null);
}
}
private static void NativeCompletionScheduledJobCommands(CompletionContext context, string paramName, List result)
{
if (string.IsNullOrEmpty(paramName))
return;
var wordToComplete = context.WordToComplete ?? string.Empty;
var quote = CompletionHelpers.HandleDoubleAndSingleQuote(ref wordToComplete);
if (!wordToComplete.EndsWith('*'))
{
wordToComplete += "*";
}
var pattern = WildcardPattern.Get(wordToComplete, WildcardOptions.IgnoreCase);
var powerShellExecutionHelper = context.Helper;
if (paramName.Equals("Name", StringComparison.OrdinalIgnoreCase))
{
powerShellExecutionHelper.AddCommandWithPreferenceSetting("PSScheduledJob\\Get-ScheduledJob").AddParameter("Name", wordToComplete);
}
else
{
powerShellExecutionHelper.AddCommandWithPreferenceSetting("PSScheduledJob\\Get-ScheduledJob");
}
Exception exceptionThrown;
var psObjects = powerShellExecutionHelper.ExecuteCurrentPowerShell(out exceptionThrown);
if (psObjects == null)
return;
if (paramName.Equals("Id", StringComparison.OrdinalIgnoreCase))
{
RemoveLastNullCompletionResult(result);
foreach (dynamic psJob in psObjects)
{
var completionText = psJob.Id.ToString();
if (pattern.IsMatch(completionText))
{
var listItemText = completionText;
completionText = quote + completionText + quote;
result.Add(new CompletionResult(completionText, listItemText, CompletionResultType.ParameterValue, listItemText));
}
}
result.Add(CompletionResult.Null);
}
else if (paramName.Equals("Name", StringComparison.OrdinalIgnoreCase))
{
RemoveLastNullCompletionResult(result);
foreach (dynamic psJob in psObjects)
{
var completionText = psJob.Name;
var listItemText = completionText;
completionText = CompletionHelpers.QuoteCompletionText(completionText, quote);
result.Add(new CompletionResult(completionText, listItemText, CompletionResultType.ParameterValue, listItemText));
}
result.Add(CompletionResult.Null);
}
}
private static void NativeCompletionModuleCommands(
CompletionContext context,
string paramName,
List result,
bool loadedModulesOnly = false,
bool isImportModule = false,
bool skipEditionCheck = false)
{
if (string.IsNullOrEmpty(paramName))
{
return;
}
if (paramName.Equals("Name", StringComparison.OrdinalIgnoreCase))
{
RemoveLastNullCompletionResult(result);
if (isImportModule)
{
var moduleExtensions = new HashSet(StringComparer.OrdinalIgnoreCase)
{ StringLiterals.PowerShellScriptFileExtension,
StringLiterals.PowerShellModuleFileExtension,
StringLiterals.PowerShellDataFileExtension,
StringLiterals.PowerShellNgenAssemblyExtension,
StringLiterals.PowerShellILAssemblyExtension,
StringLiterals.PowerShellILExecutableExtension,
StringLiterals.PowerShellCmdletizationFileExtension
};
var moduleFilesResults = new List(CompleteFilename(context, containerOnly: false, moduleExtensions));
if (moduleFilesResults.Count > 0)
result.AddRange(moduleFilesResults);
var assemblyOrModuleName = context.WordToComplete;
if (assemblyOrModuleName.IndexOfAny(Utils.Separators.DirectoryOrDrive) != -1)
{
// The partial input is a path, then we don't iterate modules under $ENV:PSModulePath
return;
}
}
var moduleResults = CompleteModuleName(context, loadedModulesOnly, skipEditionCheck);
if (moduleResults != null && moduleResults.Count > 0)
result.AddRange(moduleResults);
result.Add(CompletionResult.Null);
}
else if (paramName.Equals("Assembly", StringComparison.OrdinalIgnoreCase))
{
RemoveLastNullCompletionResult(result);
var moduleExtensions = new HashSet(StringComparer.OrdinalIgnoreCase) { ".dll" };
var moduleFilesResults = new List(CompleteFilename(context, /* containerOnly: */ false, moduleExtensions));
if (moduleFilesResults.Count > 0)
result.AddRange(moduleFilesResults);
result.Add(CompletionResult.Null);
}
}
private static void NativeCompletionProcessCommands(CompletionContext context, string paramName, List result)
{
if (string.IsNullOrEmpty(paramName))
return;
var wordToComplete = context.WordToComplete ?? string.Empty;
var quote = CompletionHelpers.HandleDoubleAndSingleQuote(ref wordToComplete);
if (!wordToComplete.EndsWith('*'))
{
wordToComplete += "*";
}
var powerShellExecutionHelper = context.Helper;
if (paramName.Equals("Id", StringComparison.OrdinalIgnoreCase))
{
powerShellExecutionHelper.AddCommandWithPreferenceSetting("Microsoft.PowerShell.Management\\Get-Process");
}
else
{
powerShellExecutionHelper.AddCommandWithPreferenceSetting("Microsoft.PowerShell.Management\\Get-Process").AddParameter("Name", wordToComplete);
}
Exception exceptionThrown;
var psObjects = powerShellExecutionHelper.ExecuteCurrentPowerShell(out exceptionThrown);
if (psObjects == null)
return;
if (paramName.Equals("Id", StringComparison.OrdinalIgnoreCase))
{
RemoveLastNullCompletionResult(result);
var pattern = WildcardPattern.Get(wordToComplete, WildcardOptions.IgnoreCase);
foreach (dynamic process in psObjects)
{
var processId = process.Id.ToString();
if (pattern.IsMatch(processId))
{
var processName = process.Name;
var idAndName = $"{processId} - {processName}";
processId = quote + processId + quote;
result.Add(new CompletionResult(processId, idAndName, CompletionResultType.ParameterValue, idAndName));
}
}
result.Add(CompletionResult.Null);
}
else if (paramName.Equals("Name", StringComparison.OrdinalIgnoreCase))
{
RemoveLastNullCompletionResult(result);
var uniqueSet = new HashSet(StringComparer.OrdinalIgnoreCase);
foreach (dynamic process in psObjects)
{
var completionText = process.Name;
var listItemText = completionText;
if (uniqueSet.Contains(completionText))
continue;
uniqueSet.Add(completionText);
completionText = CompletionHelpers.QuoteCompletionText(completionText, quote);
// on macOS, system processes names will be empty if PowerShell isn't run as `sudo`
if (string.IsNullOrEmpty(listItemText))
{
continue;
}
result.Add(new CompletionResult(completionText, listItemText, CompletionResultType.ParameterValue, listItemText));
}
result.Add(CompletionResult.Null);
}
}
private static void NativeCompletionProviderCommands(CompletionContext context, string paramName, List result)
{
if (string.IsNullOrEmpty(paramName) || !paramName.Equals("PSProvider", StringComparison.OrdinalIgnoreCase))
{
return;
}
RemoveLastNullCompletionResult(result);
var providerName = context.WordToComplete ?? string.Empty;
var quote = CompletionHelpers.HandleDoubleAndSingleQuote(ref providerName);
if (!providerName.EndsWith('*'))
{
providerName += "*";
}
var powerShellExecutionHelper = context.Helper;
powerShellExecutionHelper.AddCommandWithPreferenceSetting("Microsoft.PowerShell.Management\\Get-PSProvider").AddParameter("PSProvider", providerName);
var psObjects = powerShellExecutionHelper.ExecuteCurrentPowerShell(out _);
if (psObjects == null)
return;
foreach (dynamic providerInfo in psObjects)
{
var completionText = providerInfo.Name;
var listItemText = completionText;
completionText = CompletionHelpers.QuoteCompletionText(completionText, quote);
result.Add(new CompletionResult(completionText, listItemText, CompletionResultType.ParameterValue, listItemText));
}
result.Add(CompletionResult.Null);
}
private static void NativeCompletionDriveCommands(CompletionContext context, string psProvider, string paramName, List result)
{
if (string.IsNullOrEmpty(paramName) || !paramName.Equals("Name", StringComparison.OrdinalIgnoreCase))
return;
RemoveLastNullCompletionResult(result);
var wordToComplete = context.WordToComplete ?? string.Empty;
var quote = CompletionHelpers.HandleDoubleAndSingleQuote(ref wordToComplete);
if (!wordToComplete.EndsWith('*'))
{
wordToComplete += "*";
}
var powerShellExecutionHelper = context.Helper;
var powershell = powerShellExecutionHelper
.AddCommandWithPreferenceSetting("Microsoft.PowerShell.Management\\Get-PSDrive")
.AddParameter("Name", wordToComplete);
if (psProvider != null)
powershell.AddParameter("PSProvider", psProvider);
var psObjects = powerShellExecutionHelper.ExecuteCurrentPowerShell(out _);
if (psObjects != null)
{
foreach (dynamic driveInfo in psObjects)
{
var completionText = driveInfo.Name;
var listItemText = completionText;
completionText = CompletionHelpers.QuoteCompletionText(completionText, quote);
result.Add(new CompletionResult(completionText, listItemText, CompletionResultType.ParameterValue, listItemText));
}
}
result.Add(CompletionResult.Null);
}
private static void NativeCompletionServiceCommands(CompletionContext context, string paramName, List result)
{
if (string.IsNullOrEmpty(paramName))
return;
var wordToComplete = context.WordToComplete ?? string.Empty;
var quote = CompletionHelpers.HandleDoubleAndSingleQuote(ref wordToComplete);
if (!wordToComplete.EndsWith('*'))
{
wordToComplete += "*";
}
Exception exceptionThrown;
var powerShellExecutionHelper = context.Helper;
if (paramName.Equals("DisplayName", StringComparison.OrdinalIgnoreCase))
{
RemoveLastNullCompletionResult(result);
powerShellExecutionHelper
.AddCommandWithPreferenceSetting("Microsoft.PowerShell.Management\\Get-Service")
.AddParameter("DisplayName", wordToComplete)
.AddCommandWithPreferenceSetting("Microsoft.PowerShell.Utility\\Sort-Object")
.AddParameter("Property", "DisplayName");
var psObjects = powerShellExecutionHelper.ExecuteCurrentPowerShell(out exceptionThrown);
if (psObjects != null)
{
foreach (dynamic serviceInfo in psObjects)
{
var completionText = serviceInfo.DisplayName;
var listItemText = completionText;
completionText = CompletionHelpers.QuoteCompletionText(completionText, quote);
result.Add(new CompletionResult(completionText, listItemText, CompletionResultType.ParameterValue, listItemText));
}
}
result.Add(CompletionResult.Null);
}
else if (paramName.Equals("Name", StringComparison.OrdinalIgnoreCase))
{
RemoveLastNullCompletionResult(result);
powerShellExecutionHelper.AddCommandWithPreferenceSetting("Microsoft.PowerShell.Management\\Get-Service").AddParameter("Name", wordToComplete);
var psObjects = powerShellExecutionHelper.ExecuteCurrentPowerShell(out exceptionThrown);
if (psObjects != null)
{
foreach (dynamic serviceInfo in psObjects)
{
var completionText = serviceInfo.Name;
var listItemText = completionText;
completionText = CompletionHelpers.QuoteCompletionText(completionText, quote);
result.Add(new CompletionResult(completionText, listItemText, CompletionResultType.ParameterValue, listItemText));
}
}
result.Add(CompletionResult.Null);
}
}
private static void NativeCompletionVariableCommands(CompletionContext context, string paramName, List result)
{
if (string.IsNullOrEmpty(paramName) || !paramName.Equals("Name", StringComparison.OrdinalIgnoreCase))
{
return;
}
RemoveLastNullCompletionResult(result);
var variableName = context.WordToComplete ?? string.Empty;
var quote = CompletionHelpers.HandleDoubleAndSingleQuote(ref variableName);
if (!variableName.EndsWith('*'))
{
variableName += "*";
}
var powerShellExecutionHelper = context.Helper;
var powershell = powerShellExecutionHelper.AddCommandWithPreferenceSetting("Microsoft.PowerShell.Utility\\Get-Variable").AddParameter("Name", variableName);
var psObjects = powerShellExecutionHelper.ExecuteCurrentPowerShell(out _);
if (psObjects == null)
return;
foreach (dynamic variable in psObjects)
{
var effectiveQuote = quote;
var completionText = variable.Name;
var listItemText = completionText;
// Handle special characters ? and * in variable names
if (completionText.IndexOfAny(Utils.Separators.StarOrQuestion) != -1)
{
effectiveQuote = "'";
completionText = completionText.Replace("?", "`?");
completionText = completionText.Replace("*", "`*");
}
if (!completionText.Equals("$", StringComparison.Ordinal) && CompletionHelpers.CompletionRequiresQuotes(completionText))
{
var quoteInUse = effectiveQuote == string.Empty ? "'" : effectiveQuote;
if (quoteInUse == "'")
completionText = completionText.Replace("'", "''");
completionText = quoteInUse + completionText + quoteInUse;
}
else
{
completionText = effectiveQuote + completionText + effectiveQuote;
}
result.Add(new CompletionResult(completionText, listItemText, CompletionResultType.ParameterValue, listItemText));
}
result.Add(CompletionResult.Null);
}
private static void NativeCompletionAliasCommands(CompletionContext context, string paramName, List result)
{
if (string.IsNullOrEmpty(paramName) ||
(!paramName.Equals("Definition", StringComparison.OrdinalIgnoreCase) &&
!paramName.Equals("Name", StringComparison.OrdinalIgnoreCase)))
{
return;
}
RemoveLastNullCompletionResult(result);
var powerShellExecutionHelper = context.Helper;
if (paramName.Equals("Name", StringComparison.OrdinalIgnoreCase))
{
var commandName = context.WordToComplete ?? string.Empty;
var quote = CompletionHelpers.HandleDoubleAndSingleQuote(ref commandName);
if (!commandName.EndsWith('*'))
{
commandName += "*";
}
Exception exceptionThrown;
var powershell = powerShellExecutionHelper.AddCommandWithPreferenceSetting("Microsoft.PowerShell.Utility\\Get-Alias").AddParameter("Name", commandName);
var psObjects = powerShellExecutionHelper.ExecuteCurrentPowerShell(out exceptionThrown);
if (psObjects != null)
{
foreach (dynamic aliasInfo in psObjects)
{
var completionText = aliasInfo.Name;
var listItemText = completionText;
completionText = CompletionHelpers.QuoteCompletionText(completionText, quote);
result.Add(new CompletionResult(completionText, listItemText, CompletionResultType.ParameterValue, listItemText));
}
}
}
else
{
// Complete for the parameter Definition
// Available commands
const CommandTypes commandTypes = CommandTypes.Cmdlet | CommandTypes.Function | CommandTypes.ExternalScript | CommandTypes.Configuration;
var commandResults = CompleteCommand(context, /* moduleName: */ null, commandTypes);
if (commandResults != null && commandResults.Count > 0)
result.AddRange(commandResults);
// The parameter Definition takes a file
var fileResults = new List(CompleteFilename(context));
if (fileResults.Count > 0)
result.AddRange(fileResults);
}
result.Add(CompletionResult.Null);
}
private static void NativeCompletionTraceSourceCommands(CompletionContext context, string paramName, List result)
{
if (string.IsNullOrEmpty(paramName) || !paramName.Equals("Name", StringComparison.OrdinalIgnoreCase))
{
return;
}
RemoveLastNullCompletionResult(result);
var traceSourceName = context.WordToComplete ?? string.Empty;
var quote = CompletionHelpers.HandleDoubleAndSingleQuote(ref traceSourceName);
if (!traceSourceName.EndsWith('*'))
{
traceSourceName += "*";
}
var powerShellExecutionHelper = context.Helper;
var powershell = powerShellExecutionHelper.AddCommandWithPreferenceSetting("Microsoft.PowerShell.Utility\\Get-TraceSource").AddParameter("Name", traceSourceName);
Exception exceptionThrown;
var psObjects = powerShellExecutionHelper.ExecuteCurrentPowerShell(out exceptionThrown);
if (psObjects == null)
return;
foreach (dynamic trace in psObjects)
{
var completionText = trace.Name;
var listItemText = completionText;
completionText = CompletionHelpers.QuoteCompletionText(completionText, quote);
result.Add(new CompletionResult(completionText, listItemText, CompletionResultType.ParameterValue, listItemText));
}
result.Add(CompletionResult.Null);
}
private static void NativeCompletionSetLocationCommand(CompletionContext context, string paramName, List result)
{
if (string.IsNullOrEmpty(paramName) ||
(!paramName.Equals("Path", StringComparison.OrdinalIgnoreCase) &&
!paramName.Equals("LiteralPath", StringComparison.OrdinalIgnoreCase)))
{
return;
}
RemoveLastNullCompletionResult(result);
context.WordToComplete ??= string.Empty;
var clearLiteralPath = false;
if (paramName.Equals("LiteralPath", StringComparison.OrdinalIgnoreCase))
{
clearLiteralPath = TurnOnLiteralPathOption(context);
}
try
{
var fileNameResults = CompleteFilename(context, containerOnly: true, extension: null);
if (fileNameResults != null)
result.AddRange(fileNameResults);
}
finally
{
if (clearLiteralPath)
context.Options.Remove("LiteralPaths");
}
result.Add(CompletionResult.Null);
}
///
/// Provides completion results for NewItemCommand.
///
/// Completion context.
/// Name of the parameter whose value needs completion.
/// List of completion suggestions.
private static void NativeCompletionNewItemCommand(CompletionContext context, string paramName, List result)
{
if (string.IsNullOrEmpty(paramName))
{
return;
}
var executionContext = context.ExecutionContext;
var boundArgs = GetBoundArgumentsAsHashtable(context);
var providedPath = boundArgs["Path"] as string ?? executionContext.SessionState.Path.CurrentLocation.Path;
ProviderInfo provider;
executionContext.LocationGlobber.GetProviderPath(providedPath, out provider);
var isFileSystem = provider != null &&
provider.Name.Equals(FileSystemProvider.ProviderName, StringComparison.OrdinalIgnoreCase);
// AutoComplete only if filesystem provider.
if (isFileSystem)
{
if (paramName.Equals("ItemType", StringComparison.OrdinalIgnoreCase))
{
if (!string.IsNullOrEmpty(context.WordToComplete))
{
WildcardPattern patternEvaluator = WildcardPattern.Get(context.WordToComplete + "*", WildcardOptions.IgnoreCase);
if (patternEvaluator.IsMatch("file"))
{
result.Add(new CompletionResult("File"));
}
else if (patternEvaluator.IsMatch("directory"))
{
result.Add(new CompletionResult("Directory"));
}
else if (patternEvaluator.IsMatch("symboliclink"))
{
result.Add(new CompletionResult("SymbolicLink"));
}
else if (patternEvaluator.IsMatch("junction"))
{
result.Add(new CompletionResult("Junction"));
}
else if (patternEvaluator.IsMatch("hardlink"))
{
result.Add(new CompletionResult("HardLink"));
}
}
else
{
result.Add(new CompletionResult("File"));
result.Add(new CompletionResult("Directory"));
result.Add(new CompletionResult("SymbolicLink"));
result.Add(new CompletionResult("Junction"));
result.Add(new CompletionResult("HardLink"));
}
result.Add(CompletionResult.Null);
}
}
}
private static void NativeCompletionCopyMoveItemCommand(CompletionContext context, string paramName, List result)
{
if (string.IsNullOrEmpty(paramName))
{
return;
}
if (paramName.Equals("LiteralPath", StringComparison.OrdinalIgnoreCase) || paramName.Equals("Path", StringComparison.OrdinalIgnoreCase))
{
NativeCompletionPathArgument(context, paramName, result);
}
else if (paramName.Equals("Destination", StringComparison.OrdinalIgnoreCase))
{
// The parameter Destination for Move-Item and Copy-Item takes literal path
RemoveLastNullCompletionResult(result);
context.WordToComplete ??= string.Empty;
var clearLiteralPath = TurnOnLiteralPathOption(context);
try
{
var fileNameResults = CompleteFilename(context);
if (fileNameResults != null)
result.AddRange(fileNameResults);
}
finally
{
if (clearLiteralPath)
context.Options.Remove("LiteralPaths");
}
result.Add(CompletionResult.Null);
}
}
private static void NativeCompletionPathArgument(CompletionContext context, string paramName, List result)
{
if (string.IsNullOrEmpty(paramName) ||
(!paramName.Equals("LiteralPath", StringComparison.OrdinalIgnoreCase) &&
(!paramName.Equals("Path", StringComparison.OrdinalIgnoreCase)) &&
(!paramName.Equals("FilePath", StringComparison.OrdinalIgnoreCase))))
{
return;
}
RemoveLastNullCompletionResult(result);
context.WordToComplete ??= string.Empty;
var clearLiteralPath = false;
if (paramName.Equals("LiteralPath", StringComparison.OrdinalIgnoreCase))
{
clearLiteralPath = TurnOnLiteralPathOption(context);
}
try
{
var fileNameResults = CompleteFilename(context);
if (fileNameResults != null)
result.AddRange(fileNameResults);
}
finally
{
if (clearLiteralPath)
context.Options.Remove("LiteralPaths");
}
result.Add(CompletionResult.Null);
}
private static IEnumerable GetInferenceTypes(CompletionContext context, CommandAst commandAst)
{
// Command is something like where-object/foreach-object/format-list/etc. where there is a parameter that is a property name
// and we want member names based on the input object, which is either the parameter InputObject, or comes from the pipeline.
if (commandAst.Parent is not PipelineAst pipelineAst)
{
return null;
}
int i;
for (i = 0; i < pipelineAst.PipelineElements.Count; i++)
{
if (pipelineAst.PipelineElements[i] == commandAst)
{
break;
}
}
IEnumerable prevType = null;
if (i == 0)
{
// based on a type of the argument which is binded to 'InputObject' parameter.
AstParameterArgumentPair pair;
if (!context.PseudoBindingInfo.BoundArguments.TryGetValue("InputObject", out pair)
|| !pair.ArgumentSpecified)
{
return null;
}
var astPair = pair as AstPair;
if (astPair == null || astPair.Argument == null)
{
return null;
}
prevType = AstTypeInference.InferTypeOf(astPair.Argument, context.TypeInferenceContext, TypeInferenceRuntimePermissions.AllowSafeEval);
}
else
{
// based on OutputTypeAttribute() of the first cmdlet in pipeline.
prevType = AstTypeInference.InferTypeOf(pipelineAst.PipelineElements[i - 1], context.TypeInferenceContext, TypeInferenceRuntimePermissions.AllowSafeEval);
}
return prevType;
}
private static void NativeCompletionMemberName(CompletionContext context, List result, CommandAst commandAst, AstParameterArgumentPair parameterInfo, bool propertiesOnly = true)
{
IEnumerable prevType = TypeInferenceVisitor.GetInferredEnumeratedTypes(GetInferenceTypes(context, commandAst));
if (prevType is not null)
{
HashSet excludedMembers = null;
if (parameterInfo is AstPair pair)
{
excludedMembers = GetParameterValues(pair, context.CursorPosition.Offset);
}
Func filter = propertiesOnly ? IsPropertyMember : null;
CompleteMemberByInferredType(context.TypeInferenceContext, prevType, result, context.WordToComplete + "*", filter, isStatic: false, excludedMembers, addMethodParenthesis: false);
}
result.Add(CompletionResult.Null);
}
private static void NativeCompletionMemberValue(CompletionContext context, List result, CommandAst commandAst, string propertyName)
{
string wordToComplete = context.WordToComplete.Trim('"', '\'');
IEnumerable prevTypes = GetInferenceTypes(context, commandAst);
if (prevTypes is not null)
{
foreach (var type in prevTypes)
{
if (type.Type is null)
{
continue;
}
PropertyInfo property = type.Type.GetProperty(propertyName, BindingFlags.IgnoreCase | BindingFlags.Public | BindingFlags.Instance);
if (property is not null && property.PropertyType.IsEnum)
{
foreach (var value in property.PropertyType.GetEnumNames())
{
if (value.StartsWith(wordToComplete, StringComparison.OrdinalIgnoreCase))
{
result.Add(new CompletionResult(value, value, CompletionResultType.ParameterValue, value));
}
}
break;
}
}
}
result.Add(CompletionResult.Null);
}
///
/// Returns all string values bound to a parameter except the one the cursor is currently at.
///
private static HashSetGetParameterValues(AstPair parameter, int cursorOffset)
{
var result = new HashSet(StringComparer.OrdinalIgnoreCase);
var parameterValues = parameter.Argument.FindAll(ast => !(cursorOffset >= ast.Extent.StartOffset && cursorOffset <= ast.Extent.EndOffset) && ast is StringConstantExpressionAst, searchNestedScriptBlocks: false);
foreach (Ast ast in parameterValues)
{
result.Add(ast.Extent.Text);
}
return result;
}
private static void NativeCompletionFormatViewName(
CompletionContext context,
Dictionary boundArguments,
List result,
CommandAst commandAst,
string commandName)
{
IEnumerable prevType = NativeCommandArgumentCompletion_InferTypesOfArgument(boundArguments, commandAst, context, "InputObject");
if (prevType is not null)
{
string[] inferTypeNames = prevType.Select(t => t.Name).ToArray();
CompleteFormatViewByInferredType(context, inferTypeNames, result, commandName);
}
result.Add(CompletionResult.Null);
}
private static void NativeCompletionTypeName(CompletionContext context, List result)
{
var wordToComplete = context.WordToComplete;
var isQuoted = wordToComplete.Length > 0 && (wordToComplete[0].IsSingleQuote() || wordToComplete[0].IsDoubleQuote());
string prefix = string.Empty;
string suffix = string.Empty;
if (isQuoted)
{
prefix = suffix = wordToComplete.Substring(0, 1);
var endQuoted = (wordToComplete.Length > 1) && wordToComplete[wordToComplete.Length - 1] == wordToComplete[0];
wordToComplete = wordToComplete.Substring(1, wordToComplete.Length - (endQuoted ? 2 : 1));
}
if (wordToComplete.Contains('['))
{
var cursor = (InternalScriptPosition)context.CursorPosition;
cursor = cursor.CloneWithNewOffset(cursor.Offset - context.TokenAtCursor.Extent.StartOffset - (isQuoted ? 1 : 0));
var fullTypeName = Parser.ScanType(wordToComplete, ignoreErrors: true);
var typeNameToComplete = CompletionAnalysis.FindTypeNameToComplete(fullTypeName, cursor);
if (typeNameToComplete == null)
return;
var openBrackets = 0;
var closeBrackets = 0;
foreach (char c in wordToComplete)
{
if (c == '[') openBrackets += 1;
else if (c == ']') closeBrackets += 1;
}
wordToComplete = typeNameToComplete.FullName;
var typeNameText = fullTypeName.Extent.Text;
if (!isQuoted)
{
// We need to add quotes - the square bracket messes up parsing the argument
prefix = suffix = "'";
}
if (closeBrackets < openBrackets)
{
suffix = suffix.Insert(0, new string(']', (openBrackets - closeBrackets)));
}
if (isQuoted && closeBrackets == openBrackets)
{
// Already quoted, and has matching []. We can give a better Intellisense experience
// if we only replace the minimum.
context.ReplacementIndex = typeNameToComplete.Extent.StartOffset + context.TokenAtCursor.Extent.StartOffset + 1;
context.ReplacementLength = wordToComplete.Length;
prefix = suffix = string.Empty;
}
else
{
prefix += typeNameText.Substring(0, typeNameToComplete.Extent.StartOffset);
suffix = suffix.Insert(0, typeNameText.Substring(typeNameToComplete.Extent.EndOffset));
}
}
context.WordToComplete = wordToComplete;
var typeResults = CompleteType(context, prefix, suffix);
if (typeResults != null)
{
result.AddRange(typeResults);
}
result.Add(CompletionResult.Null);
}
#endregion Native Command Argument Completion
///
/// Find the positional argument at the specific position from the parsed argument list.
///
///
///
///
///
/// If the command line after the [tab] will not be truncated, the return value could be non-null: Get-Cmdlet [tab] abc
/// If the command line after the [tab] is truncated, the return value will always be null
///
private static AstPair FindTargetPositionalArgument(Collection parsedArguments, int position, out AstPair lastPositionalArgument)
{
int index = 0;
lastPositionalArgument = null;
foreach (AstParameterArgumentPair pair in parsedArguments)
{
if (!pair.ParameterSpecified && index == position)
return (AstPair)pair;
else if (!pair.ParameterSpecified)
{
index++;
lastPositionalArgument = (AstPair)pair;
}
}
// Cannot find an existing positional argument at 'position'
return null;
}
///
/// Find the location where 'tab' is typed based on the line and column.
///
private static ArgumentLocation FindTargetArgumentLocation(Collection parsedArguments, Token token)
{
int position = 0;
AstParameterArgumentPair prevArg = null;
foreach (AstParameterArgumentPair pair in parsedArguments)
{
switch (pair.ParameterArgumentType)
{
case AstParameterArgumentType.AstPair:
{
var arg = (AstPair)pair;
if (arg.ParameterSpecified)
{
// Named argument
if (arg.Parameter.Extent.StartOffset > token.Extent.StartOffset)
{
// case: Get-Cmdlet -Param abc
return GenerateArgumentLocation(prevArg, position);
}
if ((token.Kind == TokenKind.Parameter && token.Extent.StartOffset == arg.Parameter.Extent.StartOffset)
|| (token.Extent.StartOffset > arg.Argument.Extent.StartOffset && token.Extent.EndOffset < arg.Argument.Extent.EndOffset))
{
// case 1: Get-Cmdlet -Param abc
// case 2: dir -Path .\abc.txt, -File
return new ArgumentLocation() { Argument = arg, IsPositional = false, Position = -1 };
}
}
else
{
// Positional argument
if (arg.Argument.Extent.StartOffset > token.Extent.StartOffset)
{
// case: Get-Cmdlet abc
return GenerateArgumentLocation(prevArg, position);
}
position++;
}
prevArg = arg;
}
break;
case AstParameterArgumentType.Fake:
case AstParameterArgumentType.Switch:
{
if (pair.Parameter.Extent.StartOffset > token.Extent.StartOffset)
{
return GenerateArgumentLocation(prevArg, position);
}
prevArg = pair;
}
break;
case AstParameterArgumentType.AstArray:
case AstParameterArgumentType.PipeObject:
Diagnostics.Assert(false, "parsed arguments should not contain AstArray and PipeObject");
break;
}
}
// The 'tab' should be typed after the last argument
return GenerateArgumentLocation(prevArg, position);
}
///
///
/// The argument that is right before the 'tab' location.
/// The number of positional arguments before the 'tab' location.
///
private static ArgumentLocation GenerateArgumentLocation(AstParameterArgumentPair prev, int position)
{
// Tab is typed before the first argument
if (prev == null)
{
return new ArgumentLocation() { Argument = null, IsPositional = true, Position = 0 };
}
switch (prev.ParameterArgumentType)
{
case AstParameterArgumentType.AstPair:
case AstParameterArgumentType.Switch:
if (!prev.ParameterSpecified)
return new ArgumentLocation() { Argument = null, IsPositional = true, Position = position };
return prev.Parameter.Extent.Text.EndsWith(':')
? new ArgumentLocation() { Argument = prev, IsPositional = false, Position = -1 }
: new ArgumentLocation() { Argument = null, IsPositional = true, Position = position };
case AstParameterArgumentType.Fake:
return new ArgumentLocation() { Argument = prev, IsPositional = false, Position = -1 };
default:
Diagnostics.Assert(false, "parsed arguments should not contain AstArray and PipeObject");
return null;
}
}
///
/// Find the location where 'tab' is typed based on the expressionAst.
///
///
///
///
private static ArgumentLocation FindTargetArgumentLocation(Collection parsedArguments, ExpressionAst expAst)
{
Diagnostics.Assert(expAst != null, "Caller needs to make sure expAst is not null");
int position = 0;
foreach (AstParameterArgumentPair pair in parsedArguments)
{
switch (pair.ParameterArgumentType)
{
case AstParameterArgumentType.AstPair:
{
AstPair arg = (AstPair)pair;
if (arg.ArgumentIsCommandParameterAst)
continue;
if (arg.ParameterContainsArgument && arg.Argument == expAst)
{
return new ArgumentLocation() { IsPositional = false, Position = -1, Argument = arg };
}
if (arg.Argument.GetHashCode() == expAst.GetHashCode())
{
return arg.ParameterSpecified ?
new ArgumentLocation() { IsPositional = false, Position = -1, Argument = arg } :
new ArgumentLocation() { IsPositional = true, Position = position, Argument = arg };
}
if (!arg.ParameterSpecified)
position++;
}
break;
case AstParameterArgumentType.Fake:
case AstParameterArgumentType.Switch:
// FakePair and SwitchPair contains no ExpressionAst
break;
case AstParameterArgumentType.AstArray:
case AstParameterArgumentType.PipeObject:
Diagnostics.Assert(false, "parsed arguments should not contain AstArray and PipeObject arguments");
break;
}
}
// We should be able to find the ExpAst from the parsed argument list, if all parameters was specified correctly.
// We may try to complete something incorrect
// ls -Recurse -QQQ qwe<+tab>
return null;
}
private sealed class ArgumentLocation
{
internal bool IsPositional { get; set; }
internal int Position { get; set; }
internal AstParameterArgumentPair Argument { get; set; }
}
#endregion Command Arguments
#region Filenames
///
///
///
///
[SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly")]
public static IEnumerable CompleteFilename(string fileName)
{
var runspace = Runspace.DefaultRunspace;
if (runspace == null)
{
// No runspace, just return no results.
return CommandCompletion.EmptyCompletionResult;
}
var helper = new PowerShellExecutionHelper(PowerShell.Create(RunspaceMode.CurrentRunspace));
var executionContext = helper.CurrentPowerShell.Runspace.ExecutionContext;
return CompleteFilename(new CompletionContext { WordToComplete = fileName, Helper = helper, ExecutionContext = executionContext });
}
internal static IEnumerable CompleteFilename(CompletionContext context)
{
return CompleteFilename(context, containerOnly: false, extension: null);
}
[SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly")]
internal static IEnumerable CompleteFilename(CompletionContext context, bool containerOnly, HashSet extension)
{
var wordToComplete = context.WordToComplete;
var quote = CompletionHelpers.HandleDoubleAndSingleQuote(ref wordToComplete);
// Matches file shares with and without the provider name and with either slash direction.
// Avoids matching Windows device paths like \\.\CDROM0 and \\?\Volume{b8f3fc1c-5cd6-4553-91e2-d6814c4cd375}\
var shareMatch = s_shareMatch.Match(wordToComplete);
if (shareMatch.Success)
{
// Only match share names, no filenames.
var provider = shareMatch.Groups[1].Value;
var server = shareMatch.Groups[2].Value;
var sharePattern = WildcardPattern.Get(shareMatch.Groups[3].Value + "*", WildcardOptions.IgnoreCase);
var ignoreHidden = context.GetOption("IgnoreHiddenShares", @default: false);
var shares = GetFileShares(server, ignoreHidden);
if (shares.Count == 0)
{
return CommandCompletion.EmptyCompletionResult;
}
var shareResults = new List(shares.Count);
foreach (var share in shares)
{
if (sharePattern.IsMatch(share))
{
string sharePath = $"\\\\{server}\\{share}";
string completionText;
if (quote == string.Empty)
{
completionText = share.Contains(' ')
? $"'{provider}{sharePath}'"
: $"{provider}{sharePath}";
}
else
{
completionText = $"{quote}{provider}{sharePath}{quote}";
}
shareResults.Add(new CompletionResult(completionText, share, CompletionResultType.ProviderContainer, sharePath));
}
}
return shareResults;
}
string filter;
string basePath;
int providerSeparatorIndex = -1;
bool defaultRelativePath = false;
bool inputUsedHomeChar = false;
if (string.IsNullOrEmpty(wordToComplete))
{
filter = "*";
basePath = ".";
defaultRelativePath = true;
}
else
{
providerSeparatorIndex = wordToComplete.IndexOf("::", StringComparison.Ordinal);
int pathStartOffset = providerSeparatorIndex == -1 ? 0 : providerSeparatorIndex + 2;
inputUsedHomeChar = pathStartOffset + 2 <= wordToComplete.Length
&& wordToComplete[pathStartOffset] is '~'
&& wordToComplete[pathStartOffset + 1] is '/' or '\\';
// This simple analysis is quick but doesn't handle scenarios where a separator character is not actually a separator
// For example "\" or ":" in *nix filenames. This is only a problem if it appears to be the last separator though.
int lastSeparatorIndex = wordToComplete.LastIndexOfAny(Utils.Separators.DirectoryOrDrive);
if (lastSeparatorIndex == -1)
{
// Input is a simple word with no path separators like: "Program Files"
filter = $"{wordToComplete}*";
basePath = ".";
defaultRelativePath = true;
}
else
{
if (lastSeparatorIndex + 1 == wordToComplete.Length)
{
// Input ends with a separator like: "./", "filesystem::" or "C:"
filter = "*";
basePath = wordToComplete;
}
else
{
// Input contains a separator, but doesn't end with one like: "C:\Program Fil" or "Registry::HKEY_LOC"
filter = $"{wordToComplete.Substring(lastSeparatorIndex + 1)}*";
basePath = wordToComplete.Substring(0, lastSeparatorIndex + 1);
}
if (!inputUsedHomeChar && basePath[0] is not '/' and not '\\')
{
defaultRelativePath = !context.ExecutionContext.LocationGlobber.IsAbsolutePath(wordToComplete, out _);
}
}
}
StringConstantType stringType;
switch (quote)
{
case "":
stringType = StringConstantType.BareWord;
break;
case "\"":
stringType = StringConstantType.DoubleQuoted;
break;
default:
stringType = StringConstantType.SingleQuoted;
break;
}
var useLiteralPath = context.GetOption("LiteralPaths", @default: false);
if (useLiteralPath)
{
basePath = EscapePath(basePath, stringType, useLiteralPath, out _);
}
PowerShell currentPS = context.Helper
.AddCommandWithPreferenceSetting("Microsoft.PowerShell.Management\\Resolve-Path")
.AddParameter("Path", basePath);
string relativeBasePath;
var useRelativePath = context.GetOption("RelativePaths", @default: defaultRelativePath);
if (useRelativePath)
{
if (providerSeparatorIndex != -1)
{
// User must have requested relative paths but that's not valid with provider paths.
return CommandCompletion.EmptyCompletionResult;
}
var lastAst = context.RelatedAsts?[^1];
if (lastAst?.Parent is UsingStatementAst usingStatement
&& usingStatement.UsingStatementKind is UsingStatementKind.Module or UsingStatementKind.Assembly
&& lastAst.Extent.File is not null)
{
relativeBasePath = Directory.GetParent(lastAst.Extent.File).FullName;
_ = currentPS.AddParameter("RelativeBasePath", relativeBasePath);
}
else
{
relativeBasePath = context.ExecutionContext.SessionState.Internal.CurrentLocation.ProviderPath;
}
}
else
{
relativeBasePath = string.Empty;
}
var resolvedPaths = context.Helper.ExecuteCurrentPowerShell(out _);
if (resolvedPaths is null || resolvedPaths.Count == 0)
{
return CommandCompletion.EmptyCompletionResult;
}
var resolvedProvider = ((PathInfo)resolvedPaths[0].BaseObject).Provider;
string providerPrefix;
if (providerSeparatorIndex == -1)
{
providerPrefix = string.Empty;
}
else if (providerSeparatorIndex == resolvedProvider.Name.Length)
{
providerPrefix = $"{resolvedProvider.Name}::";
}
else
{
providerPrefix = $"{resolvedProvider.ModuleName}\\{resolvedProvider.Name}::";
}
List results;
switch (resolvedProvider.Name)
{
case FileSystemProvider.ProviderName:
results = GetFileSystemProviderResults(
context,
resolvedProvider,
resolvedPaths,
filter,
extension,
containerOnly,
useRelativePath,
useLiteralPath,
inputUsedHomeChar,
providerPrefix,
stringType,
relativeBasePath);
break;
default:
results = GetDefaultProviderResults(
context,
resolvedProvider,
resolvedPaths,
filter,
containerOnly,
useRelativePath,
useLiteralPath,
inputUsedHomeChar,
providerPrefix,
stringType);
break;
}
return results.OrderBy(x => x.ToolTip);
}
///
/// Helper method for generating path completion results for the file system provider.
///
///
///
///
///
///
///
///
///
///
///
///
///
///
private static List GetFileSystemProviderResults(
CompletionContext context,
ProviderInfo provider,
Collection resolvedPaths,
string filterText,
HashSet includedExtensions,
bool containersOnly,
bool relativePaths,
bool literalPaths,
bool inputUsedHome,
string providerPrefix,
StringConstantType stringType,
string relativeBasePath)
{
#if DEBUG
Diagnostics.Assert(provider.Name.Equals(FileSystemProvider.ProviderName), "Provider should be filesystem provider.");
#endif
var enumerationOptions = _enumerationOptions;
var results = new List();
string homePath = inputUsedHome && !string.IsNullOrEmpty(provider.Home) ? provider.Home : null;
WildcardPattern wildcardFilter;
if (WildcardPattern.ContainsRangeWildcard(filterText))
{
wildcardFilter = WildcardPattern.Get(filterText, WildcardOptions.IgnoreCase);
filterText = "*";
}
else
{
wildcardFilter = null;
}
foreach (var item in resolvedPaths)
{
var pathInfo = (PathInfo)item.BaseObject;
var dirInfo = new DirectoryInfo(pathInfo.ProviderPath);
bool baseQuotesNeeded = false;
string basePath;
if (!relativePaths)
{
if (pathInfo.Drive is null)
{
basePath = dirInfo.FullName;
}
else
{
int stringStartIndex = pathInfo.Drive.Root.EndsWith(provider.ItemSeparator) && pathInfo.Drive.Root.Length > 1
? pathInfo.Drive.Root.Length - 1
: pathInfo.Drive.Root.Length;
basePath = pathInfo.Drive.VolumeSeparatedByColon
? string.Concat(pathInfo.Drive.Name, ":", dirInfo.FullName.AsSpan(stringStartIndex))
: string.Concat(pathInfo.Drive.Name, dirInfo.FullName.AsSpan(stringStartIndex));
}
basePath = basePath.EndsWith(provider.ItemSeparator)
? providerPrefix + basePath
: providerPrefix + basePath + provider.ItemSeparator;
basePath = RebuildPathWithVars(basePath, homePath, stringType, literalPaths, out baseQuotesNeeded);
}
else
{
basePath = null;
}
IEnumerable fileSystemObjects = containersOnly
? dirInfo.EnumerateDirectories(filterText, enumerationOptions)
: dirInfo.EnumerateFileSystemInfos(filterText, enumerationOptions);
foreach (var entry in fileSystemObjects)
{
bool isContainer = entry.Attributes.HasFlag(FileAttributes.Directory);
if (!isContainer && includedExtensions is not null && !includedExtensions.Contains(entry.Extension))
{
continue;
}
var entryName = entry.Name;
if (wildcardFilter is not null && !wildcardFilter.IsMatch(entryName))
{
continue;
}
if (basePath is null)
{
basePath = context.ExecutionContext.EngineSessionState.NormalizeRelativePath(
entry.FullName,
relativeBasePath);
if (!basePath.StartsWith($"..{provider.ItemSeparator}", StringComparison.Ordinal))
{
basePath = $".{provider.ItemSeparator}{basePath}";
}
basePath = basePath.Remove(basePath.Length - entry.Name.Length);
basePath = RebuildPathWithVars(basePath, homePath, stringType, literalPaths, out baseQuotesNeeded);
}
var resultType = isContainer
? CompletionResultType.ProviderContainer
: CompletionResultType.ProviderItem;
bool leafQuotesNeeded;
var completionText = NewPathCompletionText(
basePath,
EscapePath(entryName, stringType, literalPaths, out leafQuotesNeeded),
stringType,
containsNestedExpressions: false,
forceQuotes: baseQuotesNeeded || leafQuotesNeeded,
addAmpersand: false);
results.Add(new CompletionResult(completionText, entryName, resultType, entry.FullName));
}
}
return results;
}
///
/// Helper method for generating path completion results standard providers that don't need any special treatment.
///
///
///
///
///
///
///
///
///
///
///
///
private static List GetDefaultProviderResults(
CompletionContext context,
ProviderInfo provider,
Collection resolvedPaths,
string filterText,
bool containersOnly,
bool relativePaths,
bool literalPaths,
bool inputUsedHome,
string providerPrefix,
StringConstantType stringType)
{
string homePath = inputUsedHome && !string.IsNullOrEmpty(provider.Home)
? provider.Home
: null;
var pattern = WildcardPattern.Get(filterText, WildcardOptions.IgnoreCase);
var results = new List();
foreach (var item in resolvedPaths)
{
var pathInfo = (PathInfo)item.BaseObject;
string baseTooltip = pathInfo.ProviderPath.Equals(string.Empty, StringComparison.Ordinal)
? pathInfo.Path
: pathInfo.ProviderPath;
if (baseTooltip[^1] is not '\\' and not '/' and not ':')
{
baseTooltip += provider.ItemSeparator;
}
_ = context.Helper.CurrentPowerShell
.AddCommandWithPreferenceSetting("Microsoft.PowerShell.Management\\Get-ChildItem")
.AddParameter("LiteralPath", pathInfo.Path);
bool hadErrors;
var childItemOutput = context.Helper.ExecuteCurrentPowerShell(out _, out hadErrors);
if (childItemOutput.Count == 1 &&
(pathInfo.Provider.FullName + "::" + pathInfo.ProviderPath).EqualsOrdinalIgnoreCase(childItemOutput[0].Properties["PSPath"].Value as string))
{
// Get-ChildItem returned the item itself instead of the children so there must be no child items to complete.
continue;
}
var childrenInfoTable = new Dictionary(childItemOutput.Count);
var childNameList = new List(childItemOutput.Count);
if (hadErrors)
{
// Get-ChildItem failed to get some items (Access denied or something)
// Save relevant info and try again to get just the names.
foreach (dynamic child in childItemOutput)
{
childrenInfoTable.Add(GetChildNameFromPsObject(child, provider.ItemSeparator), child.PSIsContainer);
}
_ = context.Helper.CurrentPowerShell
.AddCommandWithPreferenceSetting("Microsoft.PowerShell.Management\\Get-ChildItem")
.AddParameter("LiteralPath", pathInfo.Path)
.AddParameter("Name");
childItemOutput = context.Helper.ExecuteCurrentPowerShell(out _);
foreach (var child in childItemOutput)
{
var childName = (string)child.BaseObject;
childNameList.Add(childName);
}
}
else
{
foreach (dynamic child in childItemOutput)
{
var childName = GetChildNameFromPsObject(child, provider.ItemSeparator);
childrenInfoTable.Add(childName, child.PSIsContainer);
childNameList.Add(childName);
}
}
if (childNameList.Count == 0)
{
continue;
}
string basePath = providerPrefix.Length > 0
? string.Concat(providerPrefix, pathInfo.Path.AsSpan(providerPrefix.Length))
: pathInfo.Path;
if (basePath[^1] is not '\\' and not '/' and not ':')
{
basePath += provider.ItemSeparator;
}
if (relativePaths)
{
basePath = context.ExecutionContext.EngineSessionState.NormalizeRelativePath(
basePath + childNameList[0], context.ExecutionContext.SessionState.Internal.CurrentLocation.ProviderPath);
if (!basePath.StartsWith($"..{provider.ItemSeparator}", StringComparison.Ordinal))
{
basePath = $".{provider.ItemSeparator}{basePath}";
}
basePath = basePath.Remove(basePath.Length - childNameList[0].Length);
}
bool baseQuotesNeeded;
basePath = RebuildPathWithVars(basePath, homePath, stringType, literalPaths, out baseQuotesNeeded);
foreach (var childName in childNameList)
{
if (!pattern.IsMatch(childName))
{
continue;
}
CompletionResultType resultType;
if (childrenInfoTable.TryGetValue(childName, out bool isContainer))
{
if (containersOnly && !isContainer)
{
continue;
}
resultType = isContainer
? CompletionResultType.ProviderContainer
: CompletionResultType.ProviderItem;
}
else
{
resultType = CompletionResultType.Text;
}
bool leafQuotesNeeded;
var completionText = NewPathCompletionText(
basePath,
EscapePath(childName, stringType, literalPaths, out leafQuotesNeeded),
stringType,
containsNestedExpressions: false,
forceQuotes: baseQuotesNeeded || leafQuotesNeeded,
addAmpersand: false);
results.Add(new CompletionResult(completionText, childName, resultType, baseTooltip + childName));
}
}
return results;
}
private static string GetChildNameFromPsObject(dynamic psObject, char separator)
{
if (((PSObject)psObject).BaseObject is string result)
{
// The "Get-ChildItem" call for this provider returned a string that we assume is the child name.
// This is what the SCCM provider returns.
return result;
}
string childName = psObject.PSChildName;
if (childName is not null)
{
return childName;
}
// Some providers (Like the variable provider) don't include a PSChildName property
// so we get the child name from the path instead.
childName = psObject.PSPath ?? string.Empty;
int ProviderSeparatorIndex = childName.IndexOf("::", StringComparison.Ordinal);
childName = childName.Substring(ProviderSeparatorIndex + 2);
int indexOfName = childName.LastIndexOf(separator);
if (indexOfName == -1 || indexOfName + 1 == childName.Length)
{
return childName;
}
return childName.Substring(indexOfName + 1);
}
///
/// Takes a path and rebuilds it with the specified variable replacements.
/// Also escapes special characters as needed.
///
private static string RebuildPathWithVars(
string path,
string homePath,
StringConstantType stringType,
bool literalPath,
out bool quotesAreNeeded)
{
var sb = new StringBuilder(path.Length);
int homeIndex = string.IsNullOrEmpty(homePath)
? -1
: path.IndexOf(homePath, StringComparison.OrdinalIgnoreCase);
quotesAreNeeded = false;
bool useSingleQuoteEscapeRules = stringType is StringConstantType.SingleQuoted or StringConstantType.BareWord;
for (int i = 0; i < path.Length; i++)
{
// on Windows, we need to preserve the expanded home path as native commands don't understand it
#if UNIX
if (i == homeIndex)
{
_ = sb.Append('~');
i += homePath.Length - 1;
continue;
}
#endif
EscapeCharIfNeeded(sb, path, i, stringType, literalPath, useSingleQuoteEscapeRules, ref quotesAreNeeded);
_ = sb.Append(path[i]);
}
return sb.ToString();
}
private static string EscapePath(string path, StringConstantType stringType, bool literalPath, out bool quotesAreNeeded)
{
var sb = new StringBuilder(path.Length);
bool useSingleQuoteEscapeRules = stringType is StringConstantType.SingleQuoted or StringConstantType.BareWord;
quotesAreNeeded = false;
for (int i = 0; i < path.Length; i++)
{
EscapeCharIfNeeded(sb, path, i, stringType, literalPath, useSingleQuoteEscapeRules, ref quotesAreNeeded);
_ = sb.Append(path[i]);
}
return sb.ToString();
}
private static void EscapeCharIfNeeded(
StringBuilder sb,
string path,
int index,
StringConstantType stringType,
bool literalPath,
bool useSingleQuoteEscapeRules,
ref bool quotesAreNeeded)
{
switch (path[index])
{
case '#':
case '-':
case '@':
if (index == 0 && stringType == StringConstantType.BareWord)
{
// Chars that would start a new token when used as the first char in a bareword argument.
quotesAreNeeded = true;
}
break;
case ' ':
case ',':
case ';':
case '(':
case ')':
case '{':
case '}':
case '|':
case '&':
if (stringType == StringConstantType.BareWord)
{
// Chars that would start a new token when used anywhere in a bareword argument.
quotesAreNeeded = true;
}
break;
case '[':
case ']':
if (!literalPath)
{
// Wildcard characters that need to be escaped.
int backtickCount;
if (useSingleQuoteEscapeRules)
{
backtickCount = 1;
}
else
{
backtickCount = sb[^1] == '`' ? 4 : 2;
}
_ = sb.Append('`', backtickCount);
quotesAreNeeded = true;
}
break;
case '`':
// Literal backtick needs to be escaped to not be treated as an escape character
if (useSingleQuoteEscapeRules)
{
if (!literalPath)
{
_ = sb.Append('`');
}
}
else
{
int backtickCount = !literalPath && sb[^1] == '`' ? 3 : 1;
_ = sb.Append('`', backtickCount);
}
if (stringType is StringConstantType.BareWord or StringConstantType.DoubleQuoted)
{
quotesAreNeeded = true;
}
break;
case '$':
// $ needs to be escaped so following chars are not parsed as a variable/subexpression
if (!useSingleQuoteEscapeRules)
{
_ = sb.Append('`');
}
if (stringType is StringConstantType.BareWord or StringConstantType.DoubleQuoted)
{
quotesAreNeeded = true;
}
break;
default:
if (useSingleQuoteEscapeRules)
{
// Bareword or singlequoted input string.
if (path[index].IsSingleQuote())
{
// SingleQuotes are escaped with more single quotes. quotesAreNeeded is set so bareword strings can quoted.
_ = sb.Append('\'');
quotesAreNeeded = true;
}
else if (!quotesAreNeeded && stringType == StringConstantType.BareWord && path[index].IsDoubleQuote())
{
// Bareword string with double quote inside. Make sure to quote it so we don't need to escape it.
quotesAreNeeded = true;
}
}
else if (path[index].IsDoubleQuote())
{
// Double quoted or bareword with variables input string. Need to escape double quotes.
_ = sb.Append('`');
quotesAreNeeded = true;
}
break;
}
}
private static string NewPathCompletionText(string parent, string leaf, StringConstantType stringType, bool containsNestedExpressions, bool forceQuotes, bool addAmpersand)
{
string result;
if (stringType == StringConstantType.SingleQuoted)
{
result = addAmpersand ? $"& '{parent}{leaf}'" : $"'{parent}{leaf}'";
}
else if (stringType == StringConstantType.DoubleQuoted)
{
result = addAmpersand ? $"& \"{parent}{leaf}\"" : $"\"{parent}{leaf}\"";
}
else
{
if (forceQuotes)
{
if (containsNestedExpressions)
{
result = addAmpersand ? $"& \"{parent}{leaf}\"" : $"\"{parent}{leaf}\"";
}
else
{
result = addAmpersand ? $"& '{parent}{leaf}'" : $"'{parent}{leaf}'";
}
}
else
{
result = string.Concat(parent, leaf);
}
}
return result;
}
private static readonly Regex s_shareMatch = new(
@"(^Microsoft\.PowerShell\.Core\\FileSystem::|^FileSystem::|^)(?:\\\\|//)(?![.|?])([^\\/]+)(?:\\|/)([^\\/]*)$",
RegexOptions.IgnoreCase | RegexOptions.Compiled);
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
private struct SHARE_INFO_1
{
public string netname;
public int type;
public string remark;
}
private static readonly System.IO.EnumerationOptions _enumerationOptions = new System.IO.EnumerationOptions
{
MatchCasing = MatchCasing.CaseInsensitive,
AttributesToSkip = 0 // Default is to skip Hidden and System files, so we clear this to retain existing behavior
};
internal static List GetFileShares(string machine, bool ignoreHidden)
{
#if UNIX
return new List();
#else
nint shBuf = nint.Zero;
uint numEntries = 0;
uint totalEntries;
uint resumeHandle = 0;
try
{
int result = Interop.Windows.NetShareEnum(
machine,
level: 1,
out shBuf,
Interop.Windows.MAX_PREFERRED_LENGTH,
out numEntries,
out totalEntries,
ref resumeHandle);
var shares = new List();
if (result == Interop.Windows.ERROR_SUCCESS || result == Interop.Windows.ERROR_MORE_DATA)
{
for (int i = 0; i < numEntries; ++i)
{
nint curInfoPtr = shBuf + (Marshal.SizeOf() * i);
SHARE_INFO_1 shareInfo = Marshal.PtrToStructure(curInfoPtr);
if ((shareInfo.type & Interop.Windows.STYPE_MASK) != Interop.Windows.STYPE_DISKTREE)
{
continue;
}
if (ignoreHidden && shareInfo.netname.EndsWith('$'))
{
continue;
}
shares.Add(shareInfo.netname);
}
}
return shares;
}
finally
{
if (shBuf != nint.Zero)
{
Interop.Windows.NetApiBufferFree(shBuf);
}
}
#endif
}
private static bool CheckFileExtension(string path, HashSet extension)
{
if (extension == null || extension.Count == 0)
return true;
var ext = System.IO.Path.GetExtension(path);
return ext == null || extension.Contains(ext);
}
#endregion Filenames
#region Variable
///
///
///
///
public static IEnumerable CompleteVariable(string variableName)
{
var runspace = Runspace.DefaultRunspace;
if (runspace == null)
{
// No runspace, just return no results.
return CommandCompletion.EmptyCompletionResult;
}
var helper = new PowerShellExecutionHelper(PowerShell.Create(RunspaceMode.CurrentRunspace));
var executionContext = helper.CurrentPowerShell.Runspace.ExecutionContext;
return CompleteVariable(new CompletionContext { WordToComplete = variableName, Helper = helper, ExecutionContext = executionContext });
}
private static readonly string[] s_variableScopes = new string[] { "Global:", "Local:", "Script:", "Private:", "Using:" };
private static readonly SearchValues s_charactersRequiringQuotes = SearchValues.Create("-`&@'\"#{}()$,;|<> .\\/ \t^");
private static bool ContainsCharactersRequiringQuotes(ReadOnlySpan text)
=> text.ContainsAny(s_charactersRequiringQuotes);
internal static List CompleteVariable(CompletionContext context)
{
HashSet hashedResults = new(StringComparer.OrdinalIgnoreCase);
List results = new();
List tempResults = new();
var wordToComplete = context.WordToComplete;
string scopePrefix = string.Empty;
var colon = wordToComplete.IndexOf(':');
if (colon >= 0)
{
scopePrefix = wordToComplete.Remove(colon + 1);
wordToComplete = wordToComplete.Substring(colon + 1);
}
var lastAst = context.RelatedAsts?[^1];
var variableAst = lastAst as VariableExpressionAst;
if (lastAst is PropertyMemberAst ||
(lastAst is not null && lastAst.Parent is ParameterAst parameter && parameter.DefaultValue != lastAst))
{
// User is adding a new parameter or a class member, variable tab completion is not useful.
return results;
}
var prefix = variableAst != null && variableAst.Splatted ? "@" : "$";
bool tokenAtCursorUsedBraces = context.TokenAtCursor is not null && context.TokenAtCursor.Text.StartsWith("${");
// Look for variables in the input (e.g. parameters, etc.) before checking session state - these
// variables might not exist in session state yet.
var wildcardPattern = WildcardPattern.Get(wordToComplete + "*", WildcardOptions.IgnoreCase);
if (lastAst is not null)
{
Ast parent = lastAst.Parent;
var findVariablesVisitor = new FindVariablesVisitor
{
CompletionVariableAst = lastAst,
StopSearchOffset = lastAst.Extent.StartOffset,
Context = context.TypeInferenceContext
};
while (parent != null)
{
if (parent is IParameterMetadataProvider)
{
findVariablesVisitor.Top = parent;
parent.Visit(findVariablesVisitor);
}
parent = parent.Parent;
}
foreach (string varName in findVariablesVisitor.FoundVariables)
{
if (!wildcardPattern.IsMatch(varName))
{
continue;
}
VariableInfo varInfo = findVariablesVisitor.VariableInfoTable[varName];
PSTypeName varType = varInfo.LastDeclaredConstraint ?? varInfo.LastAssignedType;
string toolTip;
if (varType is null)
{
toolTip = varName;
}
else
{
toolTip = varType.Type is not null
? StringUtil.Format("[{0}]${1}", ToStringCodeMethods.Type(varType.Type, dropNamespaces: true), varName)
: varType.Name;
}
var completionText = !tokenAtCursorUsedBraces && !ContainsCharactersRequiringQuotes(varName)
? prefix + scopePrefix + varName
: prefix + "{" + scopePrefix + varName + "}";
AddUniqueVariable(hashedResults, results, completionText, varName, toolTip);
}
}
if (colon == -1)
{
var allVariables = context.ExecutionContext.SessionState.Internal.GetVariableTable();
foreach (var key in allVariables.Keys)
{
if (wildcardPattern.IsMatch(key))
{
var variable = allVariables[key];
var name = variable.Name;
var value = variable.Value;
var toolTip = value is null
? key
: StringUtil.Format("[{0}]${1}", ToStringCodeMethods.Type(value.GetType(), dropNamespaces: true), key);
if (!string.IsNullOrEmpty(variable.Description))
{
toolTip += $" - {variable.Description}";
}
var completionText = !tokenAtCursorUsedBraces && !ContainsCharactersRequiringQuotes(name)
? prefix + name
: prefix + "{" + name + "}";
AddUniqueVariable(hashedResults, tempResults, completionText, key, toolTip);
}
}
if (tempResults.Count > 0)
{
results.AddRange(tempResults.OrderBy(item => item.ListItemText, StringComparer.OrdinalIgnoreCase));
tempResults.Clear();
}
}
else
{
string pattern;
if (s_variableScopes.Contains(scopePrefix, StringComparer.OrdinalIgnoreCase))
{
pattern = string.Concat("variable:", wordToComplete, "*");
}
else
{
pattern = scopePrefix + wordToComplete + "*";
}
var powerShellExecutionHelper = context.Helper;
powerShellExecutionHelper
.AddCommandWithPreferenceSetting("Microsoft.PowerShell.Management\\Get-Item").AddParameter("Path", pattern)
.AddCommandWithPreferenceSetting("Microsoft.PowerShell.Utility\\Sort-Object").AddParameter("Property", "Name");
var psobjs = powerShellExecutionHelper.ExecuteCurrentPowerShell(out _);
if (psobjs is not null)
{
foreach (dynamic psobj in psobjs)
{
var name = psobj.Name as string;
if (!string.IsNullOrEmpty(name))
{
var tooltip = name;
var variable = PSObject.Base(psobj) as PSVariable;
if (variable != null)
{
var value = variable.Value;
if (value != null)
{
tooltip = StringUtil.Format("[{0}]${1}",
ToStringCodeMethods.Type(value.GetType(),
dropNamespaces: true), name);
}
if (!string.IsNullOrEmpty(variable.Description))
{
tooltip += $" - {variable.Description}";
}
}
var completedName = !tokenAtCursorUsedBraces && !ContainsCharactersRequiringQuotes(name)
? prefix + scopePrefix + name
: prefix + "{" + scopePrefix + name + "}";
AddUniqueVariable(hashedResults, results, completedName, name, tooltip);
}
}
}
}
if (colon == -1 && "env".StartsWith(wordToComplete, StringComparison.OrdinalIgnoreCase))
{
var envVars = Environment.GetEnvironmentVariables();
foreach (var key in envVars.Keys)
{
var name = "env:" + key;
var completedName = !tokenAtCursorUsedBraces && !ContainsCharactersRequiringQuotes(name)
? prefix + name
: prefix + "{" + name + "}";
AddUniqueVariable(hashedResults, tempResults, completedName, name, "[string]" + name);
}
results.AddRange(tempResults.OrderBy(item => item.ListItemText, StringComparer.OrdinalIgnoreCase));
tempResults.Clear();
}
if (colon == -1)
{
// Return variables already in session state first, because we can sometimes give better information,
// like the variables type.
foreach (var specialVariable in s_specialVariablesCache.Value)
{
if (wildcardPattern.IsMatch(specialVariable))
{
var completedName = !tokenAtCursorUsedBraces && !ContainsCharactersRequiringQuotes(specialVariable)
? prefix + specialVariable
: prefix + "{" + specialVariable + "}";
AddUniqueVariable(hashedResults, results, completedName, specialVariable, specialVariable);
}
}
var allDrives = context.ExecutionContext.SessionState.Drive.GetAll();
foreach (var drive in allDrives)
{
if (drive.Name.Length < 2
|| !wildcardPattern.IsMatch(drive.Name)
|| !drive.Provider.ImplementingType.IsAssignableTo(typeof(IContentCmdletProvider)))
{
continue;
}
var completedName = !tokenAtCursorUsedBraces && !ContainsCharactersRequiringQuotes(drive.Name)
? prefix + drive.Name + ":"
: prefix + "{" + drive.Name + ":}";
var tooltip = string.IsNullOrEmpty(drive.Description)
? drive.Name
: drive.Description;
AddUniqueVariable(hashedResults, tempResults, completedName, drive.Name, tooltip);
}
if (tempResults.Count > 0)
{
results.AddRange(tempResults.OrderBy(item => item.ListItemText, StringComparer.OrdinalIgnoreCase));
}
foreach (var scope in s_variableScopes)
{
if (wildcardPattern.IsMatch(scope))
{
var completedName = !tokenAtCursorUsedBraces && !ContainsCharactersRequiringQuotes(scope)
? prefix + scope
: prefix + "{" + scope + "}";
AddUniqueVariable(hashedResults, results, completedName, scope, scope);
}
}
}
return results;
}
private static void AddUniqueVariable(HashSet hashedResults, List results, string completionText, string listItemText, string tooltip)
{
if (hashedResults.Add(completionText))
{
results.Add(new CompletionResult(completionText, listItemText, CompletionResultType.Variable, tooltip));
}
}
internal static readonly HashSet s_varModificationCommands = new(StringComparer.OrdinalIgnoreCase)
{
"New-Variable",
"nv",
"Set-Variable",
"set",
"sv"
};
internal static readonly string[] s_varModificationParameters = new string[]
{
"Name",
"Value"
};
internal static readonly string[] s_outVarParameters = new string[]
{
"ErrorVariable",
"ev",
"WarningVariable",
"wv",
"InformationVariable",
"iv",
"OutVariable",
"ov",
};
internal static readonly string[] s_pipelineVariableParameters = new string[]
{
"PipelineVariable",
"pv"
};
internal static readonly HashSet s_localScopeCommandNames = new(StringComparer.OrdinalIgnoreCase)
{
"Microsoft.PowerShell.Core\\ForEach-Object",
"ForEach-Object",
"foreach",
"%",
"Microsoft.PowerShell.Core\\Where-Object",
"Where-Object",
"where",
"?",
"BeforeAll",
"BeforeEach"
};
private sealed class VariableInfo
{
internal PSTypeName LastDeclaredConstraint;
internal PSTypeName LastAssignedType;
}
private sealed class FindVariablesVisitor : AstVisitor2
{
internal Ast Top;
internal Ast CompletionVariableAst;
internal readonly List FoundVariables = new();
internal readonly Dictionary VariableInfoTable = new(StringComparer.OrdinalIgnoreCase);
internal int StopSearchOffset;
internal TypeInferenceContext Context;
private static PSTypeName GetInferredVarTypeFromAst(Ast ast)
{
PSTypeName type;
switch (ast)
{
case ConstantExpressionAst constant:
type = new PSTypeName(constant.StaticType);
break;
case ExpandableStringExpressionAst:
type = new PSTypeName(typeof(string));
break;
case ConvertExpressionAst convertExpression:
type = new PSTypeName(convertExpression.Type.TypeName);
break;
case HashtableAst:
type = new PSTypeName(typeof(Hashtable));
break;
case ArrayExpressionAst:
case ArrayLiteralAst:
type = new PSTypeName(typeof(object[]));
break;
case ScriptBlockExpressionAst:
type = new PSTypeName(typeof(ScriptBlock));
break;
default:
type = null;
break;
}
return type;
}
private void SaveVariableInfo(string variableName, PSTypeName variableType, bool isConstraint)
{
if (VariableInfoTable.TryGetValue(variableName, out VariableInfo varInfo))
{
if (isConstraint)
{
varInfo.LastDeclaredConstraint = variableType;
}
else
{
varInfo.LastAssignedType = variableType;
}
}
else
{
varInfo = isConstraint
? new VariableInfo() { LastDeclaredConstraint = variableType }
: new VariableInfo() { LastAssignedType = variableType };
VariableInfoTable.Add(variableName, varInfo);
FoundVariables.Add(variableName);
}
}
public override AstVisitAction DefaultVisit(Ast ast)
{
if (ast.Extent.StartOffset > StopSearchOffset)
{
// When visiting do while/until statements, the condition will be visited before the statement block.
// The condition itself may not be interesting if it's after the cursor, but the statement block could be.
return ast is PipelineBaseAst && ast.Parent is DoUntilStatementAst or DoWhileStatementAst
? AstVisitAction.SkipChildren
: AstVisitAction.StopVisit;
}
return AstVisitAction.Continue;
}
public override AstVisitAction VisitAssignmentStatement(AssignmentStatementAst assignmentStatementAst)
{
if (assignmentStatementAst.Extent.StartOffset > StopSearchOffset)
{
return assignmentStatementAst.Parent is DoUntilStatementAst or DoWhileStatementAst ?
AstVisitAction.SkipChildren
: AstVisitAction.StopVisit;
}
ProcessAssignmentLeftSide(assignmentStatementAst.Left, assignmentStatementAst.Right);
return AstVisitAction.Continue;
}
private void ProcessAssignmentLeftSide(ExpressionAst left, StatementAst right)
{
if (left is AttributedExpressionAst attributedExpression)
{
var firstConvertExpression = attributedExpression as ConvertExpressionAst;
ExpressionAst child = attributedExpression.Child;
while (child is AttributedExpressionAst attributeChild)
{
if (firstConvertExpression is null && attributeChild is ConvertExpressionAst convertExpression)
{
// Multiple type constraint can be set on a variable like this: [int] [string] $Var1 = 1
// But it's the left most type constraint that determines the final type.
firstConvertExpression = convertExpression;
}
child = attributeChild.Child;
}
if (child is VariableExpressionAst variableExpression)
{
if (variableExpression == CompletionVariableAst || s_specialVariablesCache.Value.Contains(variableExpression.VariablePath.UserPath))
{
return;
}
if (firstConvertExpression is not null)
{
SaveVariableInfo(variableExpression.VariablePath.UnqualifiedPath, new PSTypeName(firstConvertExpression.Type.TypeName), isConstraint: true);
}
else
{
PSTypeName lastAssignedType = right is CommandExpressionAst commandExpression
? GetInferredVarTypeFromAst(commandExpression.Expression)
: null;
SaveVariableInfo(variableExpression.VariablePath.UnqualifiedPath, lastAssignedType, isConstraint: false);
}
}
}
else if (left is VariableExpressionAst variableExpression)
{
if (variableExpression == CompletionVariableAst || s_specialVariablesCache.Value.Contains(variableExpression.VariablePath.UserPath))
{
return;
}
PSTypeName lastAssignedType;
if (right is CommandExpressionAst commandExpression)
{
lastAssignedType = GetInferredVarTypeFromAst(commandExpression.Expression);
}
else
{
lastAssignedType = null;
}
SaveVariableInfo(variableExpression.VariablePath.UnqualifiedPath, lastAssignedType, isConstraint: false);
}
else if (left is ArrayLiteralAst array)
{
foreach (ExpressionAst expression in array.Elements)
{
ProcessAssignmentLeftSide(expression, right);
}
}
else if (left is ParenExpressionAst parenExpression)
{
ExpressionAst pureExpression = parenExpression.Pipeline.GetPureExpression();
if (pureExpression is not null)
{
ProcessAssignmentLeftSide(pureExpression, right);
}
}
}
public override AstVisitAction VisitCommand(CommandAst commandAst)
{
if (commandAst.Extent.StartOffset > StopSearchOffset)
{
return AstVisitAction.StopVisit;
}
var commandName = commandAst.GetCommandName();
if (commandName is not null && s_varModificationCommands.Contains(commandName))
{
StaticBindingResult bindingResult = StaticParameterBinder.BindCommand(commandAst, resolve: false, s_varModificationParameters);
if (bindingResult is not null
&& bindingResult.BoundParameters.TryGetValue("Name", out ParameterBindingResult variableName))
{
var nameValue = variableName.ConstantValue as string;
if (nameValue is not null)
{
PSTypeName variableType;
if (bindingResult.BoundParameters.TryGetValue("Value", out ParameterBindingResult variableValue))
{
variableType = GetInferredVarTypeFromAst(variableValue.Value);
}
else
{
variableType = null;
}
SaveVariableInfo(nameValue, variableType, isConstraint: false);
}
}
}
var bindResult = StaticParameterBinder.BindCommand(commandAst, resolve: false);
if (bindResult is not null)
{
foreach (var parameterName in s_outVarParameters)
{
if (bindResult.BoundParameters.TryGetValue(parameterName, out ParameterBindingResult outVarBind))
{
var varName = outVarBind.ConstantValue as string;
if (varName is not null)
{
SaveVariableInfo(varName, new PSTypeName(typeof(ArrayList)), isConstraint: false);
}
}
}
if (commandAst.Parent is PipelineAst pipeline && pipeline.Extent.EndOffset > CompletionVariableAst.Extent.StartOffset)
{
foreach (var parameterName in s_pipelineVariableParameters)
{
if (bindResult.BoundParameters.TryGetValue(parameterName, out ParameterBindingResult pipeVarBind))
{
var varName = pipeVarBind.ConstantValue as string;
if (varName is not null)
{
var inferredTypes = AstTypeInference.InferTypeOf(commandAst, Context, TypeInferenceRuntimePermissions.AllowSafeEval);
PSTypeName varType = inferredTypes.Count == 0
? null
: inferredTypes[0];
SaveVariableInfo(varName, varType, isConstraint: false);
}
}
}
}
}
foreach (RedirectionAst redirection in commandAst.Redirections)
{
if (redirection is FileRedirectionAst fileRedirection
&& fileRedirection.Location is StringConstantExpressionAst redirectTarget
&& redirectTarget.Value.StartsWith("variable:", StringComparison.OrdinalIgnoreCase)
&& redirectTarget.Value.Length > "variable:".Length)
{
string varName = redirectTarget.Value.Substring("variable:".Length);
PSTypeName varType;
switch (fileRedirection.FromStream)
{
case RedirectionStream.Error:
varType = new PSTypeName(typeof(ErrorRecord));
break;
case RedirectionStream.Warning:
varType = new PSTypeName(typeof(WarningRecord));
break;
case RedirectionStream.Verbose:
varType = new PSTypeName(typeof(VerboseRecord));
break;
case RedirectionStream.Debug:
varType = new PSTypeName(typeof(DebugRecord));
break;
case RedirectionStream.Information:
varType = new PSTypeName(typeof(InformationRecord));
break;
default:
varType = null;
break;
}
SaveVariableInfo(varName, varType, isConstraint: false);
}
}
return AstVisitAction.Continue;
}
public override AstVisitAction VisitParameter(ParameterAst parameterAst)
{
if (parameterAst.Extent.StartOffset > StopSearchOffset)
{
return AstVisitAction.StopVisit;
}
VariableExpressionAst variableExpression = parameterAst.Name;
if (variableExpression == CompletionVariableAst)
{
return AstVisitAction.Continue;
}
SaveVariableInfo(variableExpression.VariablePath.UnqualifiedPath, new PSTypeName(parameterAst.StaticType), isConstraint: true);
return AstVisitAction.Continue;
}
public override AstVisitAction VisitForEachStatement(ForEachStatementAst forEachStatementAst)
{
if (forEachStatementAst.Extent.StartOffset > StopSearchOffset || forEachStatementAst.Variable == CompletionVariableAst)
{
return AstVisitAction.StopVisit;
}
SaveVariableInfo(forEachStatementAst.Variable.VariablePath.UnqualifiedPath, variableType: null, isConstraint: false);
return AstVisitAction.Continue;
}
public override AstVisitAction VisitAttribute(AttributeAst attributeAst)
{
// Attributes can't assign values to variables so they aren't interesting.
return AstVisitAction.SkipChildren;
}
public override AstVisitAction VisitFunctionDefinition(FunctionDefinitionAst functionDefinitionAst)
{
return functionDefinitionAst != Top ? AstVisitAction.SkipChildren : AstVisitAction.Continue;
}
public override AstVisitAction VisitScriptBlockExpression(ScriptBlockExpressionAst scriptBlockExpressionAst)
{
if (scriptBlockExpressionAst == Top)
{
return AstVisitAction.Continue;
}
Ast parent = scriptBlockExpressionAst.Parent;
// This loop checks if the scriptblock is used as a command, or an argument for a command, eg: ForEach-Object -Process {$Var1 = "Hello"}, {Var2 = $true}
while (true)
{
if (parent is CommandAst cmdAst)
{
string cmdName = cmdAst.GetCommandName();
return s_localScopeCommandNames.Contains(cmdName)
|| (cmdAst.CommandElements[0] is ScriptBlockExpressionAst && cmdAst.InvocationOperator == TokenKind.Dot)
? AstVisitAction.Continue
: AstVisitAction.SkipChildren;
}
if (parent is not CommandExpressionAst and not PipelineAst and not StatementBlockAst and not ArrayExpressionAst and not ArrayLiteralAst)
{
return AstVisitAction.SkipChildren;
}
parent = parent.Parent;
}
}
public override AstVisitAction VisitDataStatement(DataStatementAst dataStatementAst)
{
if (dataStatementAst.Extent.StartOffset >= StopSearchOffset)
{
return AstVisitAction.StopVisit;
}
if (dataStatementAst.Variable is not null)
{
SaveVariableInfo(dataStatementAst.Variable, variableType: null, isConstraint: false);
}
return AstVisitAction.SkipChildren;
}
}
private static readonly Lazy> s_specialVariablesCache = new(BuildSpecialVariablesCache);
private static SortedSet BuildSpecialVariablesCache()
{
var result = new SortedSet(StringComparer.OrdinalIgnoreCase);
foreach (var member in typeof(SpecialVariables).GetFields(BindingFlags.NonPublic | BindingFlags.Static))
{
if (member.FieldType.Equals(typeof(string)))
{
result.Add((string)member.GetValue(null));
}
}
return result;
}
internal static PSTypeName GetLastDeclaredTypeConstraint(VariableExpressionAst variableAst, TypeInferenceContext typeInferenceContext)
{
Ast parent = variableAst.Parent;
var findVariablesVisitor = new FindVariablesVisitor()
{
CompletionVariableAst = variableAst,
StopSearchOffset = variableAst.Extent.StartOffset,
Context = typeInferenceContext
};
while (parent != null)
{
if (parent is IParameterMetadataProvider)
{
findVariablesVisitor.Top = parent;
parent.Visit(findVariablesVisitor);
}
if (findVariablesVisitor.VariableInfoTable.TryGetValue(variableAst.VariablePath.UserPath, out VariableInfo varInfo)
&& varInfo.LastDeclaredConstraint is not null)
{
return varInfo.LastDeclaredConstraint;
}
parent = parent.Parent;
}
return null;
}
#endregion Variables
#region Comments
internal static List CompleteComment(CompletionContext context, ref int replacementIndex, ref int replacementLength)
{
if (context.WordToComplete.StartsWith("<#", StringComparison.Ordinal))
{
return CompleteCommentHelp(context, ref replacementIndex, ref replacementLength);
}
// Complete #requires statements
if (context.WordToComplete.StartsWith("#requires ", StringComparison.OrdinalIgnoreCase))
{
return CompleteRequires(context, ref replacementIndex, ref replacementLength);
}
var results = new List();
// Complete the history entries
Match matchResult = Regex.Match(context.WordToComplete, @"^#([\w\-]*)$");
if (!matchResult.Success)
{
return results;
}
string wordToComplete = matchResult.Groups[1].Value;
Collection psobjs;
int entryId;
if (Regex.IsMatch(wordToComplete, @"^[0-9]+$") && LanguagePrimitives.TryConvertTo(wordToComplete, out entryId))
{
context.Helper.AddCommandWithPreferenceSetting("Get-History", typeof(GetHistoryCommand)).AddParameter("Id", entryId);
psobjs = context.Helper.ExecuteCurrentPowerShell(out _);
if (psobjs != null && psobjs.Count == 1)
{
var historyInfo = PSObject.Base(psobjs[0]) as HistoryInfo;
if (historyInfo != null)
{
var commandLine = historyInfo.CommandLine;
if (!string.IsNullOrEmpty(commandLine))
{
// var tooltip = "Id: " + historyInfo.Id + "\n" +
// "ExecutionStatus: " + historyInfo.ExecutionStatus + "\n" +
// "StartExecutionTime: " + historyInfo.StartExecutionTime + "\n" +
// "EndExecutionTime: " + historyInfo.EndExecutionTime + "\n";
// Use the commandLine as the Tooltip in case the commandLine is multiple lines of scripts
results.Add(new CompletionResult(commandLine, commandLine, CompletionResultType.History, commandLine));
}
}
}
return results;
}
wordToComplete = "*" + wordToComplete + "*";
context.Helper.AddCommandWithPreferenceSetting("Get-History", typeof(GetHistoryCommand));
psobjs = context.Helper.ExecuteCurrentPowerShell(out _);
var pattern = WildcardPattern.Get(wordToComplete, WildcardOptions.IgnoreCase);
if (psobjs != null)
{
for (int index = psobjs.Count - 1; index >= 0; index--)
{
var psobj = psobjs[index];
if (PSObject.Base(psobj) is not HistoryInfo historyInfo) continue;
var commandLine = historyInfo.CommandLine;
if (!string.IsNullOrEmpty(commandLine) && pattern.IsMatch(commandLine))
{
// var tooltip = "Id: " + historyInfo.Id + "\n" +
// "ExecutionStatus: " + historyInfo.ExecutionStatus + "\n" +
// "StartExecutionTime: " + historyInfo.StartExecutionTime + "\n" +
// "EndExecutionTime: " + historyInfo.EndExecutionTime + "\n";
// Use the commandLine as the Tooltip in case the commandLine is multiple lines of scripts
results.Add(new CompletionResult(commandLine, commandLine, CompletionResultType.History, commandLine));
}
}
}
return results;
}
private static List CompleteRequires(CompletionContext context, ref int replacementIndex, ref int replacementLength)
{
var results = new List();
int cursorIndex = context.CursorPosition.ColumnNumber - 1;
string lineToCursor = context.CursorPosition.Line.Substring(0, cursorIndex);
// RunAsAdministrator must be the last parameter in a Requires statement so no completion if the cursor is after the parameter.
if (lineToCursor.Contains(" -RunAsAdministrator", StringComparison.OrdinalIgnoreCase))
{
return results;
}
// Regex to find parameter like " -Parameter1" or " -"
MatchCollection hashtableKeyMatches = Regex.Matches(lineToCursor, @"\s+-([A-Za-z]+|$)");
if (hashtableKeyMatches.Count == 0)
{
return results;
}
Group currentParameterMatch = hashtableKeyMatches[^1].Groups[1];
// Complete the parameter if the cursor is at a parameter
if (currentParameterMatch.Index + currentParameterMatch.Length == cursorIndex)
{
string currentParameterPrefix = currentParameterMatch.Value;
replacementIndex = context.CursorPosition.Offset - currentParameterPrefix.Length;
replacementLength = currentParameterPrefix.Length;
// Produce completions for all parameters that begin with the prefix we've found,
// but which haven't already been specified in the line we need to complete
foreach (string parameter in s_requiresParameters)
{
if (parameter.StartsWith(currentParameterPrefix, StringComparison.OrdinalIgnoreCase)
&& !context.CursorPosition.Line.Contains($" -{parameter}", StringComparison.OrdinalIgnoreCase))
{
string toolTip = GetRequiresParametersToolTip(parameter);
results.Add(new CompletionResult(parameter, parameter, CompletionResultType.ParameterName, toolTip));
}
}
return results;
}
// Regex to find parameter values (any text that appears after various delimiters)
hashtableKeyMatches = Regex.Matches(lineToCursor, @"(\s+|,|;|{|\""|'|=)(\w+|$)");
string currentValue;
if (hashtableKeyMatches.Count == 0)
{
currentValue = string.Empty;
}
else
{
currentValue = hashtableKeyMatches[^1].Groups[2].Value;
}
replacementIndex = context.CursorPosition.Offset - currentValue.Length;
replacementLength = currentValue.Length;
// Complete PSEdition parameter values
if (currentParameterMatch.Value.Equals("PSEdition", StringComparison.OrdinalIgnoreCase))
{
foreach (string psEditionEntry in s_requiresPSEditions)
{
if (psEditionEntry.StartsWith(currentValue, StringComparison.OrdinalIgnoreCase))
{
string toolTip = GetRequiresPsEditionsToolTip(psEditionEntry);
results.Add(new CompletionResult(psEditionEntry, psEditionEntry, CompletionResultType.ParameterValue, toolTip));
}
}
return results;
}
// Complete Modules module specification values
if (currentParameterMatch.Value.Equals("Modules", StringComparison.OrdinalIgnoreCase))
{
int hashtableStart = lineToCursor.LastIndexOf("@{");
int hashtableEnd = lineToCursor.LastIndexOf('}');
bool insideHashtable = hashtableStart != -1 && (hashtableEnd == -1 || hashtableEnd < hashtableStart);
// If not inside a hashtable, try to complete a module simple name
if (!insideHashtable)
{
context.WordToComplete = currentValue;
return CompleteModuleName(context, true);
}
string hashtableString = lineToCursor.Substring(hashtableStart);
// Regex to find hashtable keys with or without quotes
hashtableKeyMatches = Regex.Matches(hashtableString, @"(@{|;)\s*(?:'|\""|\w*)\w*");
// Build the list of keys we might want to complete, based on what's already been provided
var moduleSpecKeysToComplete = new HashSet(s_requiresModuleSpecKeys);
bool sawModuleNameLast = false;
foreach (Match existingHashtableKeyMatch in hashtableKeyMatches)
{
string existingHashtableKey = existingHashtableKeyMatch.Value.TrimStart(s_hashtableKeyPrefixes);
if (string.IsNullOrEmpty(existingHashtableKey))
{
continue;
}
// Remove the existing key we just saw
moduleSpecKeysToComplete.Remove(existingHashtableKey);
// We need to remember later if we saw "ModuleName" as the last hashtable key, for completions
if (sawModuleNameLast = existingHashtableKey.Equals("ModuleName", StringComparison.OrdinalIgnoreCase))
{
continue;
}
// "RequiredVersion" is mutually exclusive with "ModuleVersion" and "MaximumVersion"
if (existingHashtableKey.Equals("ModuleVersion", StringComparison.OrdinalIgnoreCase)
|| existingHashtableKey.Equals("MaximumVersion", StringComparison.OrdinalIgnoreCase))
{
moduleSpecKeysToComplete.Remove("RequiredVersion");
continue;
}
if (existingHashtableKey.Equals("RequiredVersion", StringComparison.OrdinalIgnoreCase))
{
moduleSpecKeysToComplete.Remove("ModuleVersion");
moduleSpecKeysToComplete.Remove("MaximumVersion");
continue;
}
}
Group lastHashtableKeyPrefixGroup = hashtableKeyMatches[^1].Groups[0];
// If we're not completing a key for the hashtable, try to complete module names, but nothing else
bool completingHashtableKey = lastHashtableKeyPrefixGroup.Index + lastHashtableKeyPrefixGroup.Length == hashtableString.Length;
if (!completingHashtableKey)
{
if (sawModuleNameLast)
{
context.WordToComplete = currentValue;
return CompleteModuleName(context, true);
}
return results;
}
// Now try to complete hashtable keys
foreach (string moduleSpecKey in moduleSpecKeysToComplete)
{
if (moduleSpecKey.StartsWith(currentValue, StringComparison.OrdinalIgnoreCase))
{
string toolTip = GetRequiresModuleSpecKeysToolTip(moduleSpecKey);
results.Add(new CompletionResult(moduleSpecKey, moduleSpecKey, CompletionResultType.ParameterValue, toolTip));
}
}
}
return results;
}
private static readonly string[] s_requiresParameters = new string[]
{
"Modules",
"PSEdition",
"RunAsAdministrator",
"Version"
};
private static string GetRequiresParametersToolTip(string name) => name switch
{
"Modules" => TabCompletionStrings.RequiresModulesParameterDescription,
"PSEdition" => TabCompletionStrings.RequiresPSEditionParameterDescription,
"RunAsAdministrator" => TabCompletionStrings.RequiresRunAsAdministratorParameterDescription,
"Version" => TabCompletionStrings.RequiresVersionParameterDescription,
_ => string.Empty
};
private static readonly string[] s_requiresPSEditions = new string[]
{
"Core",
"Desktop"
};
private static string GetRequiresPsEditionsToolTip(string name) => name switch
{
"Core" => TabCompletionStrings.RequiresPsEditionCoreDescription,
"Desktop" => TabCompletionStrings.RequiresPsEditionDesktopDescription,
_ => string.Empty
};
private static readonly string[] s_requiresModuleSpecKeys = new string[]
{
"GUID",
"MaximumVersion",
"ModuleName",
"ModuleVersion",
"RequiredVersion"
};
private static string GetRequiresModuleSpecKeysToolTip(string name) => name switch
{
"GUID" => TabCompletionStrings.RequiresModuleSpecGUIDDescription,
"MaximumVersion" => TabCompletionStrings.RequiresModuleSpecMaximumVersionDescription,
"ModuleName" => TabCompletionStrings.RequiresModuleSpecModuleNameDescription,
"ModuleVersion" => TabCompletionStrings.RequiresModuleSpecModuleVersionDescription,
"RequiredVersion" => TabCompletionStrings.RequiresModuleSpecRequiredVersionDescription,
_ => string.Empty
};
private static readonly char[] s_hashtableKeyPrefixes = new[]
{
'@',
'{',
';',
'"',
'\'',
' ',
};
private static List CompleteCommentHelp(CompletionContext context, ref int replacementIndex, ref int replacementLength)
{
// Finds comment keywords like ".DESCRIPTION"
MatchCollection usedKeywords = Regex.Matches(context.TokenAtCursor.Text, @"(?<=^\s*\.)\w*", RegexOptions.Multiline);
if (usedKeywords.Count == 0)
{
return null;
}
// Last keyword at or before the cursor
Match lineKeyword = null;
for (int i = usedKeywords.Count - 1; i >= 0; i--)
{
Match keyword = usedKeywords[i];
if (context.CursorPosition.Offset >= keyword.Index + context.TokenAtCursor.Extent.StartOffset)
{
lineKeyword = keyword;
break;
}
}
if (lineKeyword is null)
{
return null;
}
// Cursor is within or at the start/end of the keyword
if (context.CursorPosition.Offset <= lineKeyword.Index + lineKeyword.Length + context.TokenAtCursor.Extent.StartOffset)
{
replacementIndex = context.TokenAtCursor.Extent.StartOffset + lineKeyword.Index;
replacementLength = lineKeyword.Value.Length;
var validKeywords = new HashSet(s_commentHelpKeywords, StringComparer.OrdinalIgnoreCase);
foreach (Match keyword in usedKeywords)
{
if (keyword == lineKeyword || s_commentHelpAllowedDuplicateKeywords.Contains(keyword.Value))
{
continue;
}
validKeywords.Remove(keyword.Value);
}
var result = new List();
foreach (string keyword in validKeywords)
{
if (keyword.StartsWith(lineKeyword.Value, StringComparison.OrdinalIgnoreCase))
{
string toolTip = GetCommentHelpKeywordsToolTip(keyword);
result.Add(new CompletionResult(keyword, keyword, CompletionResultType.Keyword, toolTip));
}
}
return result.Count > 0 ? result : null;
}
// Finds the argument for the keyword (any characters following the keyword, ignoring leading/trailing whitespace). For example "C:\New folder"
Match keywordArgument = Regex.Match(context.CursorPosition.Line, @"(?<=^\s*\.\w+\s+)\S.*(?<=\S)");
int lineStartIndex = lineKeyword.Index - context.CursorPosition.Line.IndexOf(lineKeyword.Value) + context.TokenAtCursor.Extent.StartOffset;
int argumentIndex = keywordArgument.Success ? keywordArgument.Index : context.CursorPosition.ColumnNumber - 1;
replacementIndex = lineStartIndex + argumentIndex;
replacementLength = keywordArgument.Value.Length;
if (lineKeyword.Value.Equals("PARAMETER", StringComparison.OrdinalIgnoreCase))
{
return CompleteCommentParameterValue(context, keywordArgument.Value);
}
if (lineKeyword.Value.Equals("FORWARDHELPTARGETNAME", StringComparison.OrdinalIgnoreCase))
{
var result = new List(CompleteCommand(keywordArgument.Value, "*", CommandTypes.All));
return result.Count > 0 ? result : null;
}
if (lineKeyword.Value.Equals("FORWARDHELPCATEGORY", StringComparison.OrdinalIgnoreCase))
{
var result = new List();
foreach (string category in s_commentHelpForwardCategories)
{
if (category.StartsWith(keywordArgument.Value, StringComparison.OrdinalIgnoreCase))
{
result.Add(new CompletionResult(category));
}
}
return result.Count > 0 ? result : null;
}
if (lineKeyword.Value.Equals("REMOTEHELPRUNSPACE", StringComparison.OrdinalIgnoreCase))
{
var result = new List();
foreach (CompletionResult variable in CompleteVariable(keywordArgument.Value))
{
// ListItemText is used because it excludes the "$" as expected by REMOTEHELPRUNSPACE.
result.Add(new CompletionResult(variable.ListItemText, variable.ListItemText, variable.ResultType, variable.ToolTip));
}
return result.Count > 0 ? result : null;
}
if (lineKeyword.Value.Equals("EXTERNALHELP", StringComparison.OrdinalIgnoreCase))
{
context.WordToComplete = keywordArgument.Value;
var result = new List(CompleteFilename(context, containerOnly: false, (new HashSet() { ".xml" })));
return result.Count > 0 ? result : null;
}
return null;
}
private static readonly string[] s_commentHelpKeywords = new string[]
{
"COMPONENT",
"DESCRIPTION",
"EXAMPLE",
"EXTERNALHELP",
"FORWARDHELPCATEGORY",
"FORWARDHELPTARGETNAME",
"FUNCTIONALITY",
"INPUTS",
"LINK",
"NOTES",
"OUTPUTS",
"PARAMETER",
"REMOTEHELPRUNSPACE",
"ROLE",
"SYNOPSIS"
};
private static string GetCommentHelpKeywordsToolTip(string name) => name switch
{
"COMPONENT" => TabCompletionStrings.CommentHelpCOMPONENTKeywordDescription,
"DESCRIPTION" => TabCompletionStrings.CommentHelpDESCRIPTIONKeywordDescription,
"EXAMPLE" => TabCompletionStrings.CommentHelpEXAMPLEKeywordDescription,
"EXTERNALHELP" => TabCompletionStrings.CommentHelpEXTERNALHELPKeywordDescription,
"FORWARDHELPCATEGORY" => TabCompletionStrings.CommentHelpFORWARDHELPCATEGORYKeywordDescription,
"FORWARDHELPTARGETNAME" => TabCompletionStrings.CommentHelpFORWARDHELPTARGETNAMEKeywordDescription,
"FUNCTIONALITY" => TabCompletionStrings.CommentHelpFUNCTIONALITYKeywordDescription,
"INPUTS" => TabCompletionStrings.CommentHelpINPUTSKeywordDescription,
"LINK" => TabCompletionStrings.CommentHelpLINKKeywordDescription,
"NOTES" => TabCompletionStrings.CommentHelpNOTESKeywordDescription,
"OUTPUTS" => TabCompletionStrings.CommentHelpOUTPUTSKeywordDescription,
"PARAMETER" => TabCompletionStrings.CommentHelpPARAMETERKeywordDescription,
"REMOTEHELPRUNSPACE" => TabCompletionStrings.CommentHelpREMOTEHELPRUNSPACEKeywordDescription,
"ROLE" => TabCompletionStrings.CommentHelpROLEKeywordDescription,
"SYNOPSIS" => TabCompletionStrings.CommentHelpSYNOPSISKeywordDescription,
_ => string.Empty
};
private static readonly HashSet s_commentHelpAllowedDuplicateKeywords = new(StringComparer.OrdinalIgnoreCase)
{
"EXAMPLE",
"LINK",
"PARAMETER"
};
private static readonly string[] s_commentHelpForwardCategories = new string[]
{
"Alias",
"All",
"Cmdlet",
"ExternalScript",
"FAQ",
"Filter",
"Function",
"General",
"Glossary",
"HelpFile",
"Provider",
"ScriptCommand"
};
private static FunctionDefinitionAst GetCommentHelpFunctionTarget(CompletionContext context)
{
if (context.TokenAtCursor.Kind != TokenKind.Comment)
{
return null;
}
Ast lastAst = context.RelatedAsts[^1];
Ast firstAstAfterComment = lastAst.Find(ast => ast.Extent.StartOffset >= context.TokenAtCursor.Extent.EndOffset && ast is not NamedBlockAst, searchNestedScriptBlocks: false);
// Comment-based help can apply to a following function definition if it starts within 2 lines
int commentEndLine = context.TokenAtCursor.Extent.EndLineNumber + 2;
if (lastAst is NamedBlockAst)
{
// Helpblock before function inside advanced function
if (firstAstAfterComment is not null
&& firstAstAfterComment.Extent.StartLineNumber <= commentEndLine
&& firstAstAfterComment is FunctionDefinitionAst outerHelpFunctionDefAst)
{
return outerHelpFunctionDefAst;
}
// Helpblock inside function
if (lastAst.Parent.Parent is FunctionDefinitionAst innerHelpFunctionDefAst)
{
return innerHelpFunctionDefAst;
}
}
if (lastAst is ScriptBlockAst)
{
// Helpblock before function
if (firstAstAfterComment is not null
&& firstAstAfterComment.Extent.StartLineNumber <= commentEndLine
&& firstAstAfterComment is FunctionDefinitionAst statement)
{
return statement;
}
// Advanced function with help inside
if (lastAst.Parent is FunctionDefinitionAst advFuncDefAst)
{
return advFuncDefAst;
}
}
return null;
}
private static List CompleteCommentParameterValue(CompletionContext context, string wordToComplete)
{
FunctionDefinitionAst foundFunction = GetCommentHelpFunctionTarget(context);
ReadOnlyCollection foundParameters = null;
if (foundFunction is not null)
{
foundParameters = foundFunction.Parameters ?? foundFunction.Body.ParamBlock?.Parameters;
}
else if (context.RelatedAsts[^1] is ScriptBlockAst scriptAst)
{
// The helpblock is for a script file
foundParameters = scriptAst.ParamBlock?.Parameters;
}
if (foundParameters is null || foundParameters.Count == 0)
{
return null;
}
var parametersToShow = new HashSet(StringComparer.OrdinalIgnoreCase);
foreach (ParameterAst parameter in foundParameters)
{
if (parameter.Name.VariablePath.UserPath.StartsWith(wordToComplete, StringComparison.OrdinalIgnoreCase))
{
parametersToShow.Add(parameter.Name.VariablePath.UserPath);
}
}
MatchCollection usedParameters = Regex.Matches(context.TokenAtCursor.Text, @"(?<=^\s*\.parameter\s+)\w.*(?<=\S)", RegexOptions.Multiline | RegexOptions.IgnoreCase);
foreach (Match parameter in usedParameters)
{
if (wordToComplete.Equals(parameter.Value, StringComparison.OrdinalIgnoreCase))
{
continue;
}
parametersToShow.Remove(parameter.Value);
}
var result = new List();
foreach (string parameter in parametersToShow)
{
result.Add(new CompletionResult(parameter));
}
return result.Count > 0 ? result : null;
}
#endregion Comments
#region Members
// List of extension methods
private static readonly List> s_extensionMethods =
new List>
{
new Tuple("Where", "Where({ expression } [, mode [, numberToReturn]])"),
new Tuple("ForEach", "ForEach(expression [, arguments...])"),
new Tuple("PSWhere", "PSWhere({ expression } [, mode [, numberToReturn]])"),
new Tuple("PSForEach", "PSForEach(expression [, arguments...])"),
};
// List of DSC collection-value variables
private static readonly HashSet s_dscCollectionVariables =
new HashSet(StringComparer.OrdinalIgnoreCase) { "SelectedNodes", "AllNodes" };
internal static List