-
Notifications
You must be signed in to change notification settings - Fork 7.1k
/
CompletionCompleters.cs
7186 lines (6209 loc) · 316 KB
/
CompletionCompleters.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
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.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;
namespace System.Management.Automation
{
/// <summary>
/// </summary>
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
/// <summary>
/// </summary>
/// <param name="commandName"></param>
/// <returns></returns>
public static IEnumerable<CompletionResult> CompleteCommand(string commandName)
{
return CompleteCommand(commandName, null);
}
/// <summary>
/// </summary>
/// <param name="commandName"></param>
/// <param name="moduleName"></param>
/// <param name="commandTypes"></param>
/// <returns></returns>
[SuppressMessage("Microsoft.Design", "CA1026:DefaultParametersShouldNotBeUsed")]
public static IEnumerable<CompletionResult> 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<CompletionResult> CompleteCommand(CompletionContext context)
{
return CompleteCommand(context, null);
}
private static List<CompletionResult> CompleteCommand(CompletionContext context, string moduleName, CommandTypes types = CommandTypes.All)
{
var addAmpersandIfNecessary = IsAmpersandNeeded(context, false);
string commandName = context.WordToComplete;
string quote = HandleDoubleAndSingleQuote(ref commandName);
List<CompletionResult> 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<CompletionResult> 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<CompletionResult> completionResults = null;
if (commandInfos != null && commandInfos.Count > 1)
{
// OrderBy is using stable sorting
var sortedCommandInfos = commandInfos.OrderBy(a => a, new CommandNameComparer());
completionResults = MakeCommandsUnique(sortedCommandInfos, useModulePrefix, addAmpersandIfNecessary, quote);
}
else
{
completionResults = MakeCommandsUnique(commandInfos, useModulePrefix, addAmpersandIfNecessary, quote);
}
return completionResults;
}
}
private static readonly HashSet<string> s_keywordsToExcludeFromAddingAmpersand
= new HashSet<string>(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 (CompletionRequiresQuotes(name, false))
{
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<tab> ---> PS C:\> foreach (expected, use as the keyword)
// PS C:\> fore<tab> ---> 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<CompletionResult> MakeCommandsUnique(IEnumerable<PSObject> commandInfoPsObjs, bool includeModulePrefix, bool addAmpersandIfNecessary, string quote)
{
List<CompletionResult> results = new List<CompletionResult>();
if (commandInfoPsObjs == null || !commandInfoPsObjs.Any())
{
return results;
}
var commandTable = new Dictionary<string, object>(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<object>;
if (list != null)
{
list.Add(baseObj);
}
else
{
list = new List<object> { value, baseObj };
commandTable[name] = list;
}
}
}
List<CompletionResult> endResults = null;
foreach (var keyValuePair in commandTable)
{
var commandList = keyValuePair.Value as List<object>;
if (commandList != null)
{
if (endResults == null)
{
endResults = new List<CompletionResult>();
}
// 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 = commandList[0] 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, commandList[0], addAmpersandIfNecessary, quote));
// For the other commands that are hidden, we need to disambiguate,
// but put these at the end as it's less likely any of the hidden
// commands are desired. If we can't add anything to disambiguate,
// then we'll skip adding a completion result.
for (int index = 1; index < commandList.Count; index++)
{
var commandInfo = commandList[index] as CommandInfo;
Diagnostics.Assert(commandInfo != null, "Elements should always be CommandInfo");
if (commandInfo.CommandType == CommandTypes.Application)
{
endResults.Add(GetCommandNameCompletionResult(commandInfo.Definition, commandInfo, addAmpersandIfNecessary, quote));
}
else if (!string.IsNullOrEmpty(commandInfo.ModuleName))
{
var name = commandInfo.ModuleName + "\\" + commandInfo.Name;
endResults.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));
}
}
if (endResults != null && endResults.Count > 0)
{
results.AddRange(endResults);
}
return results;
}
private class FindFunctionsVisitor : AstVisitor
{
internal readonly List<FunctionDefinitionAst> FunctionDefinitions = new List<FunctionDefinitionAst>();
public override AstVisitAction VisitFunctionDefinition(FunctionDefinitionAst functionDefinitionAst)
{
FunctionDefinitions.Add(functionDefinitionAst);
return AstVisitAction.Continue;
}
}
#endregion Command Names
#region Module Names
internal static List<CompletionResult> CompleteModuleName(CompletionContext context, bool loadedModulesOnly, bool skipEditionCheck = false)
{
var moduleName = context.WordToComplete ?? string.Empty;
var result = new List<CompletionResult>();
var quote = HandleDoubleAndSingleQuote(ref moduleName);
if (!moduleName.EndsWith('*'))
{
moduleName += "*";
}
var powershell = context.Helper.AddCommandWithPreferenceSetting("Get-Module", typeof(GetModuleCommand)).AddParameter("Name", moduleName);
if (!loadedModulesOnly)
{
powershell.AddParameter("ListAvailable", true);
// -SkipEditionCheck should only be set or apply to -ListAvailable
if (skipEditionCheck)
{
powershell.AddParameter("SkipEditionCheck", true);
}
}
Exception exceptionThrown;
var psObjects = context.Helper.ExecuteCurrentPowerShell(out exceptionThrown);
if (psObjects != null)
{
foreach (dynamic moduleInfo in psObjects)
{
var completionText = moduleInfo.Name.ToString();
var listItemText = completionText;
var toolTip = "Description: " + moduleInfo.Description.ToString() + "\r\nModuleType: "
+ moduleInfo.ModuleType.ToString() + "\r\nPath: "
+ moduleInfo.Path.ToString();
if (CompletionRequiresQuotes(completionText, false))
{
var quoteInUse = quote == string.Empty ? "'" : quote;
if (quoteInUse == "'")
completionText = completionText.Replace("'", "''");
completionText = quoteInUse + completionText + quoteInUse;
}
else
{
completionText = quote + completionText + quote;
}
result.Add(new CompletionResult(completionText, listItemText, CompletionResultType.ParameterValue, toolTip));
}
}
return result;
}
#endregion Module Names
#region Command Parameters
private static string[] s_parameterNamesOfImportDSCResource = { "Name", "ModuleName", "ModuleVersion" };
internal static List<CompletionResult> CompleteCommandParameter(CompletionContext context)
{
string partialName = null;
bool withColon = false;
CommandAst commandAst = null;
List<CompletionResult> result = new List<CompletionResult>();
// 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--)
{
if (keywordAst == null)
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 = context.WordToComplete.Substring(1) + "*";
var pattern = WildcardPattern.Get(wordToMatch, WildcardOptions.IgnoreCase);
var parameterNames = keywordAst.CommandElements.Where(ast => ast is CommandParameterAst).Select(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;
}
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 "-"
var dashAst = (context.RelatedAsts[context.RelatedAsts.Count - 1] as StringConstantExpressionAst);
if (dashAst == null)
return result;
if (!dashAst.Value.Trim().Equals("-", StringComparison.OrdinalIgnoreCase))
return result;
// Parent must be a command
commandAst = (CommandAst)dashAst.Parent;
partialName = string.Empty;
}
PseudoBindingInfo pseudoBinding = new PseudoParameterBinder()
.DoPseudoParameterBinding(commandAst, null, parameterAst, PseudoParameterBinder.BindingType.ParameterCompletion);
// 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<CompletionResult>(CompleteFilename(context, containerOnly: true, extension: null))
: new List<CompletionResult>(CompleteFilename(context));
}
return result;
}
/// <summary>
/// Get the parameter completion results when the pseudo binding was successful.
/// </summary>
/// <param name="parameterName"></param>
/// <param name="bindingInfo"></param>
/// <param name="parameterAst"></param>
/// <param name="withColon"></param>
/// <returns></returns>
private static List<CompletionResult> GetParameterCompletionResults(string parameterName, PseudoBindingInfo bindingInfo, CommandParameterAst parameterAst, bool withColon)
{
Diagnostics.Assert(bindingInfo.InfoType.Equals(PseudoBindingInfoType.PseudoBindingSucceed), "The pseudo binding should succeed");
List<CompletionResult> result = new List<CompletionResult>();
if (parameterName == string.Empty)
{
result = GetParameterCompletionResults(
parameterName,
bindingInfo.ValidParameterSetsFlags,
bindingInfo.UnboundParameters,
withColon);
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);
}
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);
}
return result;
}
// The parameter should be bound in the pseudo binding during the named binding
string matchedParameterName = null;
foreach (KeyValuePair<string, AstParameterArgumentPair> 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;
}
Diagnostics.Assert(matchedParameterName != null, "we should find matchedParameterName from the BoundArguments");
MergedCompiledCommandParameter param = bindingInfo.BoundParameters[matchedParameterName];
WildcardPattern pattern = WildcardPattern.Get(parameterName + "*", WildcardOptions.IgnoreCase);
string parameterType = "[" + ToStringCodeMethods.Type(param.Parameter.Type, dropNamespaces: true) + "] ";
string colonSuffix = withColon ? ":" : string.Empty;
if (pattern.IsMatch(matchedParameterName))
{
string completionText = "-" + matchedParameterName + colonSuffix;
string tooltip = parameterType + matchedParameterName;
result.Add(new CompletionResult(completionText, matchedParameterName, CompletionResultType.ParameterName, tooltip));
}
// Process alias when there is partial input
result.AddRange(from alias in param.Parameter.Aliases
where pattern.IsMatch(alias)
select
new CompletionResult("-" + alias + colonSuffix, alias, CompletionResultType.ParameterName,
parameterType + alias));
return result;
}
/// <summary>
/// Get the parameter completion results by using the given valid parameter sets and available parameters.
/// </summary>
/// <param name="parameterName"></param>
/// <param name="validParameterSetFlags"></param>
/// <param name="parameters"></param>
/// <param name="withColon"></param>
/// <returns></returns>
private static List<CompletionResult> GetParameterCompletionResults(
string parameterName,
uint validParameterSetFlags,
IEnumerable<MergedCompiledCommandParameter> parameters,
bool withColon)
{
var result = new List<CompletionResult>();
var commonParamResult = new List<CompletionResult>();
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) + "] ";
bool isCommonParameter = Cmdlet.CommonParameters.Contains(name, StringComparer.OrdinalIgnoreCase);
List<CompletionResult> 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)
{
var pattr = attr as ParameterAttribute;
if (pattr != null && pattr.DontShow)
{
showToUser = false;
addCommonParameters = false;
break;
}
}
}
if (showToUser)
{
string completionText = "-" + name + colonSuffix;
string tooltip = type + name;
listInUse.Add(new CompletionResult(completionText, name, CompletionResultType.ParameterName,
tooltip));
}
}
if (parameterName != string.Empty)
{
// Process alias when there is partial input
listInUse.AddRange(from alias in param.Parameter.Aliases
where pattern.IsMatch(alias)
select
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;
}
/// <summary>
/// Get completion results for operators that start with <paramref name="wordToComplete"/>
/// </summary>
/// <param name="wordToComplete">The starting text of the operator to complete.</param>
/// <returns>A list of completion results.</returns>
public static List<CompletionResult> 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<CompletionResult> CompleteCommandArgument(CompletionContext context)
{
CommandAst commandAst = null;
List<CompletionResult> result = new List<CompletionResult>();
// 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.IndexOfAny(Utils.Separators.Directory) == 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<tab>
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<tab> || dir -Path: 'a b'\new<tab>
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 <tab>
expressionAst = null;
}
else
{
// dir -Path a.txt, b.txt c<tab>
expressionAst = (ExpressionAst)expressionAst.Parent;
}
}
else if (expressionAst.Parent is ArrayLiteralAst && expressionAst.Parent.Parent is CommandParameterAst)
{
// Handle scenarios such as
// dir -Path: a.txt, <tab> || dir -Path: a.txt, b.txt <tab>
commandAst = (CommandAst)expressionAst.Parent.Parent.Parent;
if (context.WordToComplete == string.Empty)
{
// dir -Path: a.txt, b.txt <tab>
expressionAst = null;
}
else
{
// dir -Path: a.txt, b<tab>
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,<tab>
context.WordToComplete = string.Empty;
// context.CursorPosition = expressionAst.Extent.StartScriptPosition;
}
else if (context.WordToComplete == string.Empty)
{
// Handle scenario like this: Set-ExecutionPolicy -Scope:CurrentUser <tab>
expressionAst = null;
}
}
}
else
{
var paramAst = lastAst as CommandParameterAst;
if (paramAst != null)
{
commandAst = paramAst.Parent as CommandAst;