-
-
Notifications
You must be signed in to change notification settings - Fork 8
/
PipeScript.types.ps1xml
7186 lines (6476 loc) · 250 KB
/
PipeScript.types.ps1xml
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
<!-- Generated with EZOut 2.0.4: Install-Module EZOut or https://github.com/StartAutomating/EZOut -->
<Types>
<Type>
<Name>System.Management.Automation.AliasInfo</Name>
<Members>
<AliasProperty>
<Name>Namespace</Name>
<ReferencedMemberName>CommandNamespace</ReferencedMemberName>
</AliasProperty>
</Members>
</Type>
<Type>
<Name>System.Management.Automation.ApplicationInfo</Name>
<Members>
<AliasProperty>
<Name>Namespace</Name>
<ReferencedMemberName>CommandNamespace</ReferencedMemberName>
</AliasProperty>
<ScriptProperty>
<Name>Root</Name>
<GetScriptBlock>
if ($this.'.Root') {
return $this.'.Root'
}
$nextRoot = $this.Source | Split-Path
:findingRoot do {
$lastRoot = $nextRoot
$lastRootName = $lastRoot | Split-Path -Leaf
if ($lastRootName -as [Version]) {
$lastRootName = $lastRoot | Split-Path | Split-Path -Leaf
}
foreach ($fileNameThatIndicatesRoot in 'LICENSE', 'LICENSE.txt',
"$LastRootName.psd1", "$LastRootName.psm1", ".git") {
$lookingForPath = Join-Path $lastRoot $fileNameThatIndicatesRoot
if (Test-Path $lookingForPath) {
break findingRoot
}
}
$nextRoot = $nextRoot | Split-Path
} while ($nextRoot)
$this | Add-Member NoteProperty '.Root' "$lastRoot" -Force
$this.'.Root'
</GetScriptBlock>
<SetScriptBlock>
$this | Add-Member NoteProperty ".Root" $args -Force
</SetScriptBlock>
</ScriptProperty>
</Members>
</Type>
<Type>
<Name>System.Management.Automation.Language.Ast</Name>
<Members>
<ScriptMethod>
<Name>ConvertFromAST</Name>
<Script>
param()
return $this
</Script>
</ScriptMethod>
<ScriptMethod>
<Name>FirstElements</Name>
<Script>
<#
.SYNOPSIS
Gets the First N elements in an AST
.DESCRIPTION
Gets the First N elements within an AST, excluding this element.
#>
param(
# The number of elements to get. By default, one.
[int]
$NumberOfElements = 1
)
$foundElementCount = 0
foreach ($foundElement in $this.FindAll({$true}, $true)) {
if (-not $foundElementCount) {
$foundElementCount++
continue
}
# We want to skip named blocks in this case, as we're really after the first "real" element.
if ($foundElement -is [Management.Automation.Language.NamedBlockAst]) {
continue
}
if ($foundElementCount -le $NumberOfElements) {
$foundElementCount++
$foundElement
} else {
break
}
}
</Script>
</ScriptMethod>
<ScriptMethod>
<Name>GetLineage</Name>
<Script>
<#
.SYNOPSIS
Gets AST Lineage
.DESCRIPTION
Gets the Lineage of an Abstract Syntax Tree element.
The Lineage is all of the Abstract Syntax Tree's parents.
#>
$thisParent = $this.Parent
while ($thisParent) {
$thisParent
$thisParent = $thisParent.Parent
}
</Script>
</ScriptMethod>
<ScriptMethod>
<Name>IsEquivalentTo</Name>
<Script>
<#
.SYNOPSIS
Attempts to Determine Ast Equivalence
.DESCRIPTION
Attempts to Determine if `$this` Ast element is the same as some `$Other` object.
If `$Other is a `[string]`, it will be converted into a `[ScriptBlock]`
If `$Other is a `[ScriptBlock]`, it will become the `[ScriptBlock]`s AST
If the types differ, `$other is not equivalent to `$this.
If the content is the same with all whitespace removed, it will be considered equivalent.
.NOTES
Due to the detection mechanism, IsEquivalentTo will consider strings with whitespace changes equivalent.
#>
param(
# The other item.
$Other
)
if (-not $other) { return $false }
if ($other -is [string]) {
$other = [ScriptBlock]::Create($other).Ast
}
if ($other -is [scriptblock]) {
$other = $Other.Ast
}
if ($other -isnot [Management.Automation.Language.Ast]) {
return $false
}
if ($other.GetType() -ne $this.GetType()) { return $false }
# We're going to start off very easy, and slightly incorrect:
($this -replace '[\s\r\n]') -eq ($other -replace '[\s\r\n]')
# (There are many cases where, say, variable renames would be innocuous, but that's a rabbit hole of variable detection. The same is true of commands.)
# However, in 98% of cases, two scriptblocks without whitespace that are the same are equivalent. The exception to the rule: whitespace within strings.
</Script>
</ScriptMethod>
<ScriptMethod>
<Name>Transpile</Name>
<Script>
[ScriptBlock]::Create(
"$this"
) | .>PipeScript
</Script>
</ScriptMethod>
<ScriptProperty>
<Name>ByType</Name>
<GetScriptBlock>
<#
.SYNOPSIS
Gets PowerShell AST Nodes by type
.DESCRIPTION
Gets a dictionary of all nodes in a PowerShell AST beneath this point, grouped by type.
.EXAMPLE
{"hello world"}.Ast.ByType
#>
if (-not $this.'.ByType') {
$ByType = [Collections.Generic.Dictionary[Type,Collections.Generic.List[PSObject]]]::new()
foreach ($node in $this.FindAll({$true}, $true)) {
$nodeType = $node.GetType()
if (-not $ByType[$nodeType]) {
$ByType[$nodeType] = [Collections.Generic.List[PSObject]]::new()
}
$ByType[$nodeType].Add($node)
}
Add-Member -InputObject $this -MemberType NoteProperty -Name '.ByType' -Value $ByType -Force
}
$this.'.ByType'
</GetScriptBlock>
</ScriptProperty>
<ScriptProperty>
<Name>Commands</Name>
<GetScriptBlock>
<#
.SYNOPSIS
Gets all Commands within an AST
.DESCRIPTION
Gets all Command references within a PowerShell Abstract Syntax Tree
.EXAMPLE
{Get-Process}.Ast.Commands
#>
,@(foreach ($node in $this.ByType[[Management.Automation.Language.CommandAST]]) {
$node
})
</GetScriptBlock>
</ScriptProperty>
<ScriptProperty>
<Name>Defines</Name>
<GetScriptBlock>
<#
.SYNOPSIS
Gets all Definitions within an AST
.DESCRIPTION
Gets all Function and Type Definitions and Parameters within a PowerShell Abstract Syntax Tree
.EXAMPLE
{function foo() { "foo"} class bar { $bar = "none"} }.Ast.Defines
#>
, @(
foreach ($node in $this.ByType[@(
[Management.Automation.Language.FunctionDefinitionAst]
[Management.Automation.Language.TypeDefinitionAst]
[Management.Automation.Language.ParameterAst]
)]) {
$node
}
)
</GetScriptBlock>
</ScriptProperty>
<ScriptProperty>
<Name>First</Name>
<GetScriptBlock>
<#
.SYNOPSIS
Gets the first nested AST
.DESCRIPTION
Gets the first nested element of this AST
.EXAMPLE
{
do { } while ($false)
}.First
#>
param()
$this.FirstElements(1)
</GetScriptBlock>
</ScriptProperty>
<ScriptProperty>
<Name>IsEmpty</Name>
<GetScriptBlock>
<#
.SYNOPSIS
Determines if a PowerShell AST is empty
.DESCRIPTION
Determines if a PowerShell Abstract Syntax Tree is empty.
It will be considered empty if is a ScriptBlockExpression with no parameters or statements in any blocks.
#>
param()
$ast = $this
if ($ast.Body) {
$ast = $ast.Body
}
if ($ast -isnot [Management.Automation.Language.ScriptBlockExpressionAST]) {
return $false
}
foreach ($property in $ast.psobject.Properties) {
if ($property.Name -notmatch 'Block$') { continue }
if ($property.Value.Statements.Count) { return $false }
if ($property.Value.Parameters.Count) { return $false }
}
return $true
</GetScriptBlock>
</ScriptProperty>
<ScriptProperty>
<Name>Tokens</Name>
<GetScriptBlock>
$text = $this.Extent.ToString()
$previousToken = $null
$tokenCount = 0
@(foreach ($token in [Management.Automation.PSParser]::Tokenize($text, [ref]$null)) {
Add-Member NoteProperty Text $text -Force -InputObject $token
Add-Member NoteProperty PreviousToken $previousToken -Force -InputObject $token
if ($token.Type -in 'Variable', 'String') {
$realContent = $text.Substring($token.Start, $token.Length)
Add-Member NoteProperty Content $realContent -Force -InputObject $token
}
$previousToken = $token
$tokenCount++
$token
})
</GetScriptBlock>
</ScriptProperty>
<ScriptProperty>
<Name>Transpilers</Name>
<GetScriptBlock>
$scriptText = $this.Extent.ToString()
# If the ScriptBlock had attributes, we'll add them to a special list of things that will be transpiled first.
# Find all AST elements within the script block.
$astList = @($this.FindAll({$true}, $false))
# At various points within transpilation, we will be skipping processing until a known end pointer. For now, set this to null.
$skipUntil = 0
# Keep track of the offset from a starting position as well, for the same reason.
$myOffset = 0
# Walk over each item in the abstract syntax tree.
:NextAstItem foreach ($item in $astList) {
# If skipUntil was set,
if ($skipUntil) {
# find the space between now and the last known offset.
try {
$newOffset = $scriptText.IndexOf($item.Extent.Text, $myOffset)
if ($newOffset -eq -1) { continue }
$myOffset = $newOffset
} catch {
$ex =$_
$null = $null
}
if ($myOffset -lt $skipUntil) { # If this is before our skipUntil point
continue # ignore this AST element.
}
$skipUntil = $null # If we have reached our skipUntil point, let's stop skipping.
}
# otherwise, find if any pipescripts match this AST
$foundTranspilers = Get-Transpiler -CouldPipe $item -ValidateInput $item
if ($foundTranspilers) {
foreach ($transpiler in $foundTranspilers) {
[PSCustomObject][Ordered]@{
PSTypeName = 'PipeScript.Transpiler.Location'
Transpiler =
if ($Transpiler.ExtensionInputObject.ResolvedCommand) {
@($Transpiler.ExtensionInputObject.ResolvedCommand) -ne $null
} else {
$Transpiler.ExtensionCommand
}
AST = $item
}
}
$start = $scriptText.IndexOf($item.Extent.Text, $myOffset) # determine the end of this AST element
$end = $start + $item.Extent.Text.Length
$skipUntil = $end # set SkipUntil
}
}
</GetScriptBlock>
</ScriptProperty>
<ScriptProperty>
<Name>Types</Name>
<GetScriptBlock>
<#
.SYNOPSIS
Gets all Types within an AST
.DESCRIPTION
Gets all Types referenced within a PowerShell Abstract Syntax Tree
.EXAMPLE
{[int];[psobject];[xml]}.Ast.Types
#>
,@(foreach ($node in $this.ByType[[Management.Automation.Language.TypeExpressionAst]]) {
$node
})
</GetScriptBlock>
</ScriptProperty>
<ScriptProperty>
<Name>Unique</Name>
<GetScriptBlock>
<#
.SYNOPSIS
Gets unique AST elements
.DESCRIPTION
Gets unique AST elements. Uniqueness is defined by being literally the same text.
#>
$uniqueElements = [Ordered]@{}
foreach ($foundElement in @($this.FindAll({$true},$true))) {
if ($uniqueElements["$foundElement"]) {
continue
}
$uniqueElements["$foundElement"] = $foundElement
}
@($uniqueElements.Values)
</GetScriptBlock>
</ScriptProperty>
<ScriptProperty>
<Name>Variables</Name>
<GetScriptBlock>
<#
.SYNOPSIS
Gets all Variables within an AST
.DESCRIPTION
Gets all Variable references within a PowerShell Abstract Syntax Tree
.EXAMPLE
{$x, $y, $z}.Ast.Variables
#>
, @(foreach ($node in $this.ByType[[Management.Automation.Language.VariableExpressionAst]]) {
$node
})
</GetScriptBlock>
</ScriptProperty>
</Members>
</Type>
<Type>
<Name>System.Management.Automation.Language.AttributeAst</Name>
<Members>
<AliasProperty>
<Name>Args</Name>
<ReferencedMemberName>ArgumentList</ReferencedMemberName>
</AliasProperty>
<AliasProperty>
<Name>Arguments</Name>
<ReferencedMemberName>ArgumentList</ReferencedMemberName>
</AliasProperty>
<AliasProperty>
<Name>Parameters</Name>
<ReferencedMemberName>Parameter</ReferencedMemberName>
</AliasProperty>
<ScriptProperty>
<Name>ArgumentList</Name>
<GetScriptBlock>
$Parameter = [Ordered]@{}
$ArgumentList = @()
# Collect all of the arguments of the attribute, in the order they were specified.
$argsInOrder = @(
@($this.PositionalArguments) + @($this.NamedArguments) |
Sort-Object { $_.Extent.StartOffset}
)
# Now we need to map each of those arguments into either named or positional arguments.
foreach ($attributeArg in $argsInOrder) {
# Named arguments are fairly straightforward:
if ($attributeArg -is [Management.Automation.Language.NamedAttributeArgumentAst]) {
$argName = $attributeArg.ArgumentName
$argAst = $attributeArg.Argument
$parameter[$argName] =
if ($argName -eq $argAst) { # If the argument is the name,
$true # treat it as a [switch] parameter.
}
# If the argument value was an ScriptBlockExpression
else {
$argAst
}
} else {
# If we are a positional parameter, for the moment:
if ($parameter.Count) {
# add it to the last named parameter.
$parameter[@($parameter.Keys)[-1]] =
@() + $parameter[@($parameter.Keys)[-1]] + $argAst
} else {
# Or add it to the list of string arguments.
$ArgumentList +=
$attributeArg.ConvertFromAst()
}
}
}
return $ArgumentList
</GetScriptBlock>
</ScriptProperty>
<ScriptProperty>
<Name>Parameter</Name>
<GetScriptBlock>
<#
.SYNOPSIS
Gets the parameters of an attribute
.DESCRIPTION
Gets the named parameters of an attribute.
.EXAMPLE
{
[AnAttribute(Parameter='Value')]$null
}.Ast.EndBlock.Statements[0].PipelineElements[0].Expression.Attribute.Parameters
#>
$Parameter = [Ordered]@{}
# Collect all of the arguments of the attribute, in the order they were specified.
$argsInOrder = @(
@($this.PositionalArguments) + @($this.NamedArguments) |
Sort-Object { $_.Extent.StartOffset}
)
# Now we need to map each of those arguments into either named or positional arguments.
foreach ($attributeArg in $argsInOrder) {
# Named arguments are fairly straightforward:
if ($attributeArg -is [Management.Automation.Language.NamedAttributeArgumentAst]) {
$argName = $attributeArg.ArgumentName
$argAst = $attributeArg.Argument
$parameter[$argName] =
if ($argName -eq $argAst) { # If the argument is the name,
$true # treat it as a [switch] parameter.
}
# If the argument value was an ScriptBlockExpression
else {
$argAst.ConvertFromAst()
}
} else {
# If we are a positional parameter, for the moment:
if ($parameter.Count) {
# add it to the last named parameter.
$parameter[@($parameter.Keys)[-1]] =
@() + $parameter[@($parameter.Keys)[-1]] + $attributeArg.ConvertFromAst()
}
}
}
return $Parameter
</GetScriptBlock>
</ScriptProperty>
<ScriptProperty>
<Name>ResolvedCommand</Name>
<GetScriptBlock>
<#
.SYNOPSIS
Resolves an Attribute to a CommandInfo
.DESCRIPTION
Resolves an Attribute to one or more CommandInfo.
.EXAMPLE
{
[InvokePipeScript()]$null
}.Ast.EndBlock.Statements[0].PipelineElements[0].Expression.Attribute.ResolvedCommand
.EXAMPLE
{
[Microsoft.PowerShell.Core.GetCommand()]$null
}.Ast.EndBlock.Statements[0].PipelineElements[0].Expression.Attribute.ResolvedCommand
.EXAMPLE
{
[Get_Command()]$null
}.Ast.EndBlock.Statements[0].PipelineElements[0].Expression.Attribute.ResolvedCommand
.EXAMPLE
{
[GetCommand()]$null
}.Ast.EndBlock.Statements[0].PipelineElements[0].Expression.Attribute.ResolvedCommand
.EXAMPLE
{
[cmd()]$null
}.EndBlock.Statements[0].PipelineElements[0].Expression.Attribute.ResolvedCommand
#>
# Get the name of the transpiler.
$transpilerStepName =
if ($this.TypeName.IsGeneric) {
$this.TypeName.TypeName.Name
} else {
$this.TypeName.Name
}
$decamelCase = [Regex]::new('(?<=[a-z])(?=[A-Z])')
@(
# If a Transpiler exists by that name, it will be returned first.
Get-Transpiler -TranspilerName $transpilerStepName
# Then, any periods in the attribute name will be converted to slashes,
$fullCommandName = $transpilerStepName -replace '\.','\' -replace
'_','-' # and any underscores to dashes.
# Then, the first CamelCased code will have a - injected in between the CamelCase.
$fullCommandName = $decamelCase.Replace($fullCommandName, '-', 1)
# Now we will try to find the command.
$ExecutionContext.SessionState.InvokeCommand.GetCommand($fullCommandName, 'All')
)
</GetScriptBlock>
</ScriptProperty>
</Members>
</Type>
<Type>
<Name>AutomaticVariable.Command</Name>
<Members>
<ScriptProperty>
<Name>VariableName</Name>
<GetScriptBlock>
<#
.SYNOPSIS
Gets the automatic variable name
.DESCRIPTION
Gets the name of an automatic variable that is defined in an Automatic?Variable* command.
#>
$this -replace '(?>Magic|Automatic)\p{P}Variable\p{P}' -replace
'^(?>PowerShell|PipeScript)' -replace
'^\p{P}' -replace '\p{P}$'
</GetScriptBlock>
</ScriptProperty>
</Members>
</Type>
<Type>
<Name>BuildScript.Command</Name>
<Members>
<ScriptProperty>
<Name>Template</Name>
<GetScriptBlock>
$potentialTemplatePaths =
@(
$this.Source -replace '\.ps1$', '.ps.ps1'
$this.Source -replace '\.ps1$', '.ps1.ps1'
)
foreach ($potentialTemplatePath in $potentialTemplatePaths ) {
if (Test-Path $potentialTemplatePath) {
return (Get-PipeScript -PipeScriptPath $potentialTemplatePath)
}
}
</GetScriptBlock>
</ScriptProperty>
</Members>
</Type>
<Type>
<Name>System.Management.Automation.Language.CommandAst</Name>
<Members>
<AliasProperty>
<Name>Args</Name>
<ReferencedMemberName>ArgumentList</ReferencedMemberName>
</AliasProperty>
<AliasProperty>
<Name>Arguments</Name>
<ReferencedMemberName>ArgumentList</ReferencedMemberName>
</AliasProperty>
<AliasProperty>
<Name>Parameters</Name>
<ReferencedMemberName>Parameter</ReferencedMemberName>
</AliasProperty>
<ScriptMethod>
<Name>AsSentence</Name>
<Script>
<#
.SYNOPSIS
Maps Natural Language Syntax to PowerShell Parameters
.DESCRIPTION
Maps a statement in natural language syntax to a set of PowerShell parameters.
All parameters will be collected.
For the purposes of natural language processing ValueFromPipeline will be ignored.
The order the parameters is declared takes precedence over Position attributes.
.NOTES
Each potential command can be thought of as a simple sentence with (mostly) natural syntax
command <parametername> ...<parameterargument> (etc)
either more natural or PowerShell syntax should be allowed, for example:
~~~PowerShell
all functions can Quack {
"quack"
}
~~~
would map to the command all and the parameters -Function and -Can (with the arguments Quack and {"quack"})
Assuming -Functions was a `[switch]` or an alias to a `[switch]`, it will match that `[switch]` and only that switch.
If -Functions was not a `[switch]`, it will match values from that point.
If the parameter type is not a list or PSObject, only the next parameter will be matched.
If the parameter type *is* a list or an PSObject,
or ValueFromRemainingArguments is present and no named parameters were found,
then all remaining arguments will be matched until the next named parameter is found.
_Aliasing is important_ when working with a given parameter.
The alias, _not_ the parameter name, will be what is mapped in .Parameters.
#>
param()
# Because we want to have flexible open-ended arguments here, we do not hard-code any arguments:
# we parse them.
# We're trying to determine:
# Was it right to left?
$IsRightToLeft = $false
# Are there specific commands it might be?
$SpecificCommands = @()
# If so, what are their names?
$specificCommandNames = @()
# We want to start after the first element by default
$startingElementIndex = 1
for ($argIndex =0 ; $argIndex -lt $args.Count; $argIndex++) {
$arg = $args[$argIndex]
# If the argument was an int and greater than one
if ($arg -is [int] -and $arg -gt 1) {
$startingElementIndex = $arg # start parsing that many words in (#479).
continue
}
$commandInfos = $arg -as [Management.Automation.CommandInfo[]]
if ($commandInfos) {
foreach ($cmdInfo in $commandInfos) {
$SpecificCommands += $cmdInfo
$specificCommandNames += $cmdInfo.Name
}
continue
}
if ($arg -match '^[-/]{0,2}(?:Is)?RightToLeft$') {
# If -RightToLeft was passed
$IsRightToLeft = $true
continue
}
$argCommands = @(
$foundTranspiler = Get-Transpiler -TranspilerName $arg
if ($foundTranspiler) {
foreach ($transpiler in $foundTranspiler) {
if ($transpiler.Validate($arg)) {
$transpiler
}
}
} else {
$ExecutionContext.SessionState.InvokeCommand.GetCommands($arg, 'All', $true)
}
)
if ($argCommands) {
$SpecificCommands += $argCommands
continue
}
}
$mappedParameters = [Ordered]@{}
$sentence = [Ordered]@{
PSTypeName='PipeScript.Sentence'
Command = $null
}
$commandAst = $this
$commandElements = @($commandAst.CommandElements)
# If we are going right to left, reverse the command elements
if ($IsRightToLeft) {
[Array]::Reverse($commandElements)
}
$commandElements = # Walk thru each command element
@(foreach ($element in $commandElements) {
# If the element is an array literal, expand it
if ($element -is [Management.Automation.Language.ArrayLiteralAst]) {
$element.Elements
} else {
# otherwise, include it as is.
$element
}
})
# Now we have all of the words in a sentence.
# We can still determine if an item in a list was in a list by inspecting it's parent.
$sentences = @()
if ($SpecificCommands) {
$potentialCommands = $SpecificCommands
$potentialCommandNames = @($SpecificCommands | Select-Object -ExpandProperty Name)
} else {
# The first command element should be the name of the command.
$firstCommandElement = $commandElements[0]
$commandName = ''
$potentialCommandNames = @()
$potentialCommands =
@(
if ($firstCommandElement.Value -and $firstCommandElement.StringConstantType -eq 'BareWord') {
$commandName = $firstCommandElement.Value
$foundTranspiler = Get-Transpiler -TranspilerName $commandName
if ($foundTranspiler) {
foreach ($transpiler in $foundTranspiler) {
if ($transpiler.Validate($commandAst)) {
$potentialCommandNames += $commandName
$transpiler
}
}
} else {
foreach ($foundCmd in $ExecutionContext.SessionState.InvokeCommand.GetCommands($commandName, 'All', $true)) {
$foundCmd
$potentialCommandNames += $commandName
}
}
})
if (-not $potentialCommands) {
[PSCustomObject][Ordered]@{
PSTypeName = 'PipeScript.Sentence'
Keyword = ''
Command = $null
Arguments = $commandElements[0..$commandElements.Length]
}
}
}
$mappedParameters = [Ordered]@{}
if (-not $Script:SentenceWordCache) {
$Script:SentenceWordCache = @{}
}
$potentialCommandIndex = -1
:nextPotentialCommand foreach ($potentialCommand in $potentialCommands) {
$potentialCommandIndex++
$commandName = $potentialCommandName = $potentialCommandNames[$potentialCommandIndex]
# To save time, generate a map of all potential bareword aliases for this command.
$potentialCommandBarewordMap = [Ordered]@{}
foreach ($parameterInfo in $potentialCommand.Parameters.Values) {
$potentialCommandBarewordMap[$parameterInfo.Name] = $parameterInfo
if ($parameterInfo.Aliases) {
foreach ($aliasName in $parameterInfo.Aliases) {
$potentialCommandBarewordMap[$aliasName] = $parameterInfo
}
}
}
# Cache the potential parameters
$potentialParameters = $potentialCommand.Parameters
# Assume the current parameter is empty,
$currentParameter = ''
# the current parameter metadata is null,
$currentParameterMetadata = $null
# there is no current clause,
$currentClause = @()
# and there are no unbound parameters.
$unboundParameters = @()
$clauses = @()
# Walk over each command element in a for loop (we may adjust the index when we match)
for ($commandElementIndex = $startingElementIndex ;$commandElementIndex -lt $commandElements.Count; $commandElementIndex++) {
$commandElement = $CommandElements[$commandElementIndex]
# by default, we assume we haven't found a parameter.
$parameterFound = $false
$barewordSequenece =
@(for ($cei = $commandElementIndex; $cei -lt $commandElements.Count; $cei++) {
if (
$commandElements[$cei] -isnot [Management.Automation.Language.StringConstantExpressionAst] -or
$commandElements[$cei].StringConstantType -ne 'Bareword'
) { break }
$commandElements[$cei].Value
})
# That assumption is quickly challenged if the AST type was CommandParameter
if ($commandElement -is [Management.Automation.Language.CommandParameterAst]) {
# If there were already clauses, finalize them before we start this clause
if ($currentClause) {
$clauses += [PSCustomObject][Ordered]@{
PSTypeName = 'PipeScript.Sentence.Clause'
Name = if ($currentParameter) { $currentParameter} else { '' }
ParameterName = if ($currentParameterMetadata) { $currentParameterMetadata.Name } else { '' }
Words = $currentClause
}
}
$commandParameter = $commandElement
# In that case, we know the name they want to use for the parameter
$currentParameter = $commandParameter.ParameterName
$currentClause = @($currentParameter)
$currentClauseValues = @()
# We need to get the parameter metadata as well.
$currentParameterMetadata =
# If it was the real name of a parameter, this is easy
if ($potentialCommand.Parameters[$currentParameter]) {
$potentialCommand.Parameters[$currentParameter]
$parameterFound = $true
}
else {
# Otherwise, we need to search each parameter for aliases.
foreach ($cmdParam in $potentialCommand.Parameters.Values) {
if ($cmdParam.Aliases -contains $currentParameter) {
$parameterFound = $true
$cmdParam
break
}
}
}
# If the parameter had an argument
if ($commandParameter.Argument) {
# Use that argument
if ($mappedParameters[$currentParameter]) {
$mappedParameters[$currentParameter] = @($mappedParameters[$currentParameter]) + @(
$commandParameter.Argument
)
} else {
$mappedParameters[$currentParameter] = $commandParameter.Argument
}
# and move onto the next element.
$clauses += [PSCustomObject][Ordered]@{
PSTypeName = 'PipeScript.Sentence.Clause'
Name = if ($currentParameter) { $currentParameter} else { '' }
ParameterName = if ($currentParameterMetadata) { $currentParameterMetadata.Name } else { '' }
Words = $currentClause
ParameterValues = @($commandParameter.Argument)
}
$currentParameter = ''
$currentParameterMetadata = $null
$currentClause = @()
$currentClauseValues = @()
continue
}
# Since we have found a parameter, we advance the index.
$commandElementIndex++
}
# If the command element was a bareword, it could also be the name of a parameter
elseif ($barewordSequenece) {
# We need to know the name of the parameter as it was written.
# However, we also want to allow --parameters and /parameters,
$potentialParameterName = $barewordSequenece[0]
# therefore, we will compare against the potential name without leading dashes or slashes.
$parameterFound = $false
:MappedBareword for (
$barewordSequenceIndex = $barewordSequenece.Length - 1;
$barewordSequenceIndex -ge 0;
$barewordSequenceIndex--
) {
$combinedBareword = $barewordSequenece[0..$barewordSequenceIndex] -replace '^[-/]{0,}' -join ' '
if (-not $potentialCommandBarewordMap[$combinedBareword]) {
continue
}
# If we are already in a clause
if ($currentClause) {
# output the existing clause
$clauses += [PSCustomObject][Ordered]@{
PSTypeName = 'PipeScript.Sentence.Clause'
Name = if ($currentParameter) { $currentParameter} else { '' }
ParameterName = if ($currentParameterMetadata) { $currentParameterMetadata.Name } else { '' }
Words = $currentClause
ParameterValues = $currentClauseValues
}
}
# keep track of of it and advance the index.
$currentParameter = $combinedBareword
$currentParameterMetadata = $potentialCommandBarewordMap[$combinedBareword]
$currentClause = @($commandElements[$commandElementIndex..($commandElementIndex + $barewordSequenceIndex)])
$currentClauseValues = @()
$commandElementIndex = $commandElementIndex +$barewordSequenceIndex + 1
$parameterFound = $true
break MappedBareword
}
if (-not $parameterFound) {
foreach ($potentialParameter in $potentialCommand.Parameters.Values) {
# If we did not, check the parameter for .ValueFromRemainingArguments
foreach ($attr in $potentialParameter.Attributes) {
if ($attr.ValueFromRemainingArguments) {
$valueFromRemainingArgumentsParameter = $potentialParameter
break
}
}
}
}
}
# If we have our current parameter, but it is a switch,