From 84369c7b55117526bd3b2e34b7d83fcab85cda53 Mon Sep 17 00:00:00 2001 From: Armaan Mcleod Date: Wed, 26 Mar 2025 22:16:58 +1100 Subject: [PATCH] Refactor and add comments to `CompletionRequiresQuotes` to clarify implementation (#25223) --- .../CommandCompletion/CompletionHelpers.cs | 30 +++++++++++++------ 1 file changed, 21 insertions(+), 9 deletions(-) diff --git a/src/System.Management.Automation/engine/CommandCompletion/CompletionHelpers.cs b/src/System.Management.Automation/engine/CommandCompletion/CompletionHelpers.cs index 77bc966d7c..bd44185b46 100644 --- a/src/System.Management.Automation/engine/CommandCompletion/CompletionHelpers.cs +++ b/src/System.Management.Automation/engine/CommandCompletion/CompletionHelpers.cs @@ -117,20 +117,32 @@ namespace System.Management.Automation return string.Empty; } + /// + /// Determines whether the specified completion string requires quotes. + /// Quoting is required if: + /// + /// There are parsing errors in the input string. + /// The parsed token count is not exactly two (the input token + EOF). + /// The first token is a string or a PowerShell keyword containing special characters. + /// + /// + /// The input string to analyze for quoting requirements. + /// true if the string requires quotes, false otherwise. internal static bool CompletionRequiresQuotes(string completion) { - // If the tokenizer sees the completion as more than two tokens, or if there is some error, then - // some form of quoting is necessary (if it's a variable, we'd need ${}, filenames would need [], etc.) - Parser.ParseInput(completion, out Token[] tokens, out ParseError[] errors); - // Expect no errors and 2 tokens (1 is for our completion, the other is eof) - // Or if the completion is a keyword, we ignore the errors - bool requireQuote = !(errors.Length == 0 && tokens.Length == 2); - if ((!requireQuote && tokens[0] is StringToken) || - (tokens.Length == 2 && (tokens[0].TokenFlags & TokenFlags.Keyword) != 0)) + bool isExpectedTokenCount = tokens.Length == 2; + + bool requireQuote = errors.Length > 0 || !isExpectedTokenCount; + + Token firstToken = tokens[0]; + bool isStringToken = firstToken is StringToken; + bool isKeywordToken = (firstToken.TokenFlags & TokenFlags.Keyword) != 0; + + if ((!requireQuote && isStringToken) || (isExpectedTokenCount && isKeywordToken)) { - requireQuote = ContainsCharsToCheck(tokens[0].Text); + requireQuote = ContainsCharsToCheck(firstToken.Text); } return requireQuote;