-
Notifications
You must be signed in to change notification settings - Fork 7.1k
/
TypeInferenceVisitor.cs
2662 lines (2320 loc) · 104 KB
/
TypeInferenceVisitor.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.Generic;
using System.Globalization;
using System.Linq;
using System.Management.Automation.Language;
using System.Management.Automation.Runspaces;
using System.Reflection;
using System.Text;
using System.Text.RegularExpressions;
using Microsoft.PowerShell.Commands;
using CimClass = Microsoft.Management.Infrastructure.CimClass;
using CimInstance = Microsoft.Management.Infrastructure.CimInstance;
namespace System.Management.Automation
{
/// <summary>
/// Enum describing permissions to use runtime evaluation during type inference.
/// </summary>
public enum TypeInferenceRuntimePermissions
{
/// <summary>
/// No runtime use is allowed.
/// </summary>
None = 0,
/// <summary>
/// Use of SafeExprEvaluator visitor is allowed.
/// </summary>
AllowSafeEval = 1,
}
/// <summary>
/// Static class containing methods to work with type inference of abstract syntax trees.
/// </summary>
internal static class AstTypeInference
{
/// <summary>
/// Infers the type that the result of executing a statement would have without using runtime safe eval.
/// </summary>
/// <param name="ast">The ast to infer the type from.</param>
/// <returns>List of inferred typenames.</returns>
public static IList<PSTypeName> InferTypeOf(Ast ast)
{
return InferTypeOf(ast, TypeInferenceRuntimePermissions.None);
}
/// <summary>
/// Infers the type that the result of executing a statement would have.
/// </summary>
/// <param name="ast">The ast to infer the type from.</param>
/// <param name="evalPermissions">The runtime usage permissions allowed during type inference.</param>
/// <returns>List of inferred typenames.</returns>
public static IList<PSTypeName> InferTypeOf(Ast ast, TypeInferenceRuntimePermissions evalPermissions)
{
return InferTypeOf(ast, PowerShell.Create(RunspaceMode.CurrentRunspace), evalPermissions);
}
/// <summary>
/// Infers the type that the result of executing a statement would have without using runtime safe eval.
/// </summary>
/// <param name="ast">The ast to infer the type from.</param>
/// <param name="powerShell">The instance of powershell to use for expression evaluation needed for type inference.</param>
/// <returns>List of inferred typenames.</returns>
public static IList<PSTypeName> InferTypeOf(Ast ast, PowerShell powerShell)
{
return InferTypeOf(ast, powerShell, TypeInferenceRuntimePermissions.None);
}
/// <summary>
/// Infers the type that the result of executing a statement would have.
/// </summary>
/// <param name="ast">The ast to infer the type from.</param>
/// <param name="powerShell">The instance of powershell to user for expression evaluation needed for type inference.</param>
/// <param name="evalPersmissions">The runtime usage permissions allowed during type inference.</param>
/// <returns>List of inferred typenames.</returns>
public static IList<PSTypeName> InferTypeOf(Ast ast, PowerShell powerShell, TypeInferenceRuntimePermissions evalPersmissions)
{
var context = new TypeInferenceContext(powerShell);
return InferTypeOf(ast, context, evalPersmissions);
}
/// <summary>
/// Infers the type that the result of executing a statement would have.
/// </summary>
/// <param name="ast">The ast to infer the type from.</param>
/// <param name="context">The current type inference context.</param>
/// <param name="evalPersmissions">The runtime usage permissions allowed during type inference.</param>
/// <returns>List of inferred typenames.</returns>
internal static IList<PSTypeName> InferTypeOf(
Ast ast,
TypeInferenceContext context,
TypeInferenceRuntimePermissions evalPersmissions = TypeInferenceRuntimePermissions.None)
{
var originalRuntimePermissions = context.RuntimePermissions;
try
{
context.RuntimePermissions = evalPersmissions;
return context.InferType(ast, new TypeInferenceVisitor(context)).Distinct(new PSTypeNameComparer()).ToList();
}
finally
{
context.RuntimePermissions = originalRuntimePermissions;
}
}
}
internal class PSTypeNameComparer : IEqualityComparer<PSTypeName>
{
public bool Equals(PSTypeName x, PSTypeName y)
{
return x.Name.Equals(y.Name);
}
public int GetHashCode(PSTypeName obj)
{
return obj.Name.GetHashCode();
}
}
internal class TypeInferenceContext
{
public static readonly PSTypeName[] EmptyPSTypeNameArray = Array.Empty<PSTypeName>();
private readonly PowerShell _powerShell;
public TypeInferenceContext() : this(PowerShell.Create(RunspaceMode.CurrentRunspace))
{
}
/// <summary>
/// Initializes a new instance of the <see cref="TypeInferenceContext"/> class.
/// The powerShell instance passed need to have a non null Runspace.
/// </summary>
/// <param name="powerShell">The instance of powershell to use for expression evaluation needed for type inference.</param>
public TypeInferenceContext(PowerShell powerShell)
{
Diagnostics.Assert(powerShell.Runspace != null, "Callers are required to ensure we have a runspace");
_powerShell = powerShell;
Helper = new PowerShellExecutionHelper(powerShell);
}
// used to infer types in script properties attached to an object,
// to be able to determine the type of $this in the scripts properties
public PSTypeName CurrentThisType { get; set; }
public TypeDefinitionAst CurrentTypeDefinitionAst { get; set; }
public TypeInferenceRuntimePermissions RuntimePermissions { get; set; }
internal PowerShellExecutionHelper Helper { get; }
internal ExecutionContext ExecutionContext => _powerShell.Runspace.ExecutionContext;
public bool TryGetRepresentativeTypeNameFromExpressionSafeEval(ExpressionAst expression, out PSTypeName typeName)
{
typeName = null;
if (RuntimePermissions != TypeInferenceRuntimePermissions.AllowSafeEval)
{
return false;
}
return expression != null &&
SafeExprEvaluator.TrySafeEval(expression, ExecutionContext, out var value) &&
TryGetRepresentativeTypeNameFromValue(value, out typeName);
}
internal IList<object> GetMembersByInferredType(PSTypeName typename, bool isStatic, Func<object, bool> filter)
{
List<object> results = new List<object>();
Func<object, bool> filterToCall = filter;
if (typename is PSSyntheticTypeName synthetic)
{
foreach (var mem in synthetic.Members)
{
results.Add(new PSInferredProperty(mem.Name, mem.PSTypeName));
}
}
if (typename.Type != null)
{
AddMembersByInferredTypesClrType(typename, isStatic, filter, filterToCall, results);
}
else if (typename.TypeDefinitionAst != null)
{
AddMembersByInferredTypeDefinitionAst(typename, isStatic, filter, filterToCall, results);
}
else
{
// Look in the type table first.
if (!isStatic)
{
var consolidatedString = new ConsolidatedString(new[] { typename.Name });
results.AddRange(ExecutionContext.TypeTable.GetMembers<PSMemberInfo>(consolidatedString));
}
AddMembersByInferredTypeCimType(typename, results, filterToCall);
}
return results;
}
internal void AddMembersByInferredTypesClrType(PSTypeName typename, bool isStatic, Func<object, bool> filter, Func<object, bool> filterToCall, List<object> results)
{
if (CurrentTypeDefinitionAst == null || CurrentTypeDefinitionAst.Type != typename.Type)
{
if (filterToCall == null)
{
filterToCall = o => !IsMemberHidden(o);
}
else
{
filterToCall = o => !IsMemberHidden(o) && filter(o);
}
}
IEnumerable<Type> elementTypes;
if (typename.Type.IsArray)
{
elementTypes = new[] { typename.Type.GetElementType() };
}
else
{
var elementList = new List<Type>();
foreach (var t in typename.Type.GetInterfaces())
{
if (t.IsGenericType && t.GetGenericTypeDefinition() == typeof(IEnumerable<>))
{
elementList.Add(t);
}
}
elementTypes = elementList;
}
foreach (var type in elementTypes.Prepend(typename.Type))
{
// Look in the type table first.
if (!isStatic)
{
var consolidatedString = DotNetAdapter.GetInternedTypeNameHierarchy(type);
results.AddRange(ExecutionContext.TypeTable.GetMembers<PSMemberInfo>(consolidatedString));
}
var members = isStatic
? PSObject.DotNetStaticAdapter.BaseGetMembers<PSMemberInfo>(type)
: PSObject.DotNetInstanceAdapter.GetPropertiesAndMethods(type, false);
if (filterToCall != null)
{
foreach (var member in members)
{
if (filterToCall(member))
{
results.Add(member);
}
}
}
else
{
results.AddRange(members);
}
}
}
internal void AddMembersByInferredTypeDefinitionAst(
PSTypeName typename,
bool isStatic,
Func<object, bool> filter,
Func<object, bool> filterToCall,
List<object> results)
{
if (CurrentTypeDefinitionAst != typename.TypeDefinitionAst)
{
if (filterToCall == null)
{
filterToCall = o => !IsMemberHidden(o);
}
else
{
filterToCall = o => !IsMemberHidden(o) && filter(o);
}
}
bool foundConstructor = false;
foreach (var member in typename.TypeDefinitionAst.Members)
{
bool add;
if (member is PropertyMemberAst propertyMember)
{
add = propertyMember.IsStatic == isStatic;
}
else
{
var functionMember = (FunctionMemberAst)member;
add = (functionMember.IsConstructor && isStatic) || (!functionMember.IsConstructor && functionMember.IsStatic == isStatic);
foundConstructor |= functionMember.IsConstructor;
}
if (filterToCall != null && add)
{
add = filterToCall(member);
}
if (add)
{
results.Add(member);
}
}
// iterate through bases/interfaces
foreach (var baseType in typename.TypeDefinitionAst.BaseTypes)
{
if (!(baseType.TypeName is TypeName baseTypeName))
{
continue;
}
var baseTypeDefinitionAst = baseTypeName._typeDefinitionAst;
if (baseTypeDefinitionAst is null)
{
var baseReflectionType = baseTypeName.GetReflectionType();
if (baseReflectionType is not null)
{
results.AddRange(GetMembersByInferredType(new PSTypeName(baseReflectionType), isStatic, filterToCall));
}
}
else
{
results.AddRange(GetMembersByInferredType(new PSTypeName(baseTypeDefinitionAst), isStatic, filterToCall));
}
}
// Add stuff from our base class System.Object.
if (isStatic)
{
// Don't add base class constructors
if (filter == null)
{
filterToCall = o => !IsConstructor(o);
}
else
{
filterToCall = o => !IsConstructor(o) && filter(o);
}
if (!foundConstructor)
{
results.Add(
new CompilerGeneratedMemberFunctionAst(
PositionUtilities.EmptyExtent,
typename.TypeDefinitionAst,
SpecialMemberFunctionType.DefaultConstructor));
}
}
else
{
// Reset the filter because the recursive call will add IsHidden back if necessary.
filterToCall = filter;
}
PSTypeName baseMembersType;
if (typename.TypeDefinitionAst.IsEnum)
{
if (!isStatic)
{
results.Add(new PSInferredProperty("value__", new PSTypeName(typeof(int))));
}
baseMembersType = new PSTypeName(typeof(Enum));
}
else
{
baseMembersType = new PSTypeName(typeof(object));
}
results.AddRange(GetMembersByInferredType(baseMembersType, isStatic, filterToCall));
}
internal void AddMembersByInferredTypeCimType(PSTypeName typename, List<object> results, Func<object, bool> filterToCall)
{
if (ParseCimCommandsTypeName(typename, out var cimNamespace, out var className))
{
var powerShellExecutionHelper = Helper;
powerShellExecutionHelper.AddCommandWithPreferenceSetting("CimCmdlets\\Get-CimClass")
.AddParameter("Namespace", cimNamespace)
.AddParameter("Class", className);
var classes = powerShellExecutionHelper.ExecuteCurrentPowerShell(out _);
var cimClasses = new List<CimClass>();
foreach (var c in classes)
{
if (PSObject.Base(c) is CimClass cc)
{
cimClasses.Add(cc);
}
}
foreach (var cimClass in cimClasses)
{
if (filterToCall == null)
{
results.AddRange(cimClass.CimClassProperties);
}
else
{
foreach (var prop in cimClass.CimClassProperties)
{
if (filterToCall(prop))
{
results.Add(prop);
}
}
}
}
}
}
internal IEnumerable<PSTypeName> InferType(Ast ast, TypeInferenceVisitor visitor)
{
var res = ast.Accept(visitor);
Diagnostics.Assert(res != null, "Fix visit methods to not return null");
return (IEnumerable<PSTypeName>)res;
}
private static bool TryGetRepresentativeTypeNameFromValue(object value, out PSTypeName type)
{
type = null;
if (value != null)
{
if (value is IList list
&& list.Count > 0)
{
value = list[0];
}
value = PSObject.Base(value);
if (value != null)
{
var typeObject = value.GetType();
if (typeObject.FullName.Equals("System.Management.Automation.PSObject", StringComparison.Ordinal))
{
var psobjectPropertyList = new List<PSMemberNameAndType>();
foreach (var property in ((PSObject)value).Properties)
{
if (property.IsHidden)
{
continue;
}
var propertyTypeName = new PSTypeName(property.TypeNameOfValue);
psobjectPropertyList.Add(new PSMemberNameAndType(property.Name, propertyTypeName, property.Value));
}
type = PSSyntheticTypeName.Create(typeObject, psobjectPropertyList);
}
else
{
type = new PSTypeName(typeObject);
}
return true;
}
}
return false;
}
internal static bool ParseCimCommandsTypeName(PSTypeName typename, out string cimNamespace, out string className)
{
cimNamespace = null;
className = null;
if (typename == null)
{
return false;
}
if (typename.Type != null)
{
return false;
}
var match = Regex.Match(typename.Name, "(?<NetTypeName>.*)#(?<CimNamespace>.*)[/\\\\](?<CimClassName>.*)");
if (!match.Success)
{
return false;
}
if (!match.Groups["NetTypeName"].Value.EqualsOrdinalIgnoreCase(typeof(CimInstance).FullName))
{
return false;
}
cimNamespace = match.Groups["CimNamespace"].Value;
className = match.Groups["CimClassName"].Value;
return true;
}
private static bool IsMemberHidden(object member)
{
switch (member)
{
case PSMemberInfo psMemberInfo:
return psMemberInfo.IsHidden;
case MemberInfo memberInfo:
return memberInfo.GetCustomAttributes(typeof(HiddenAttribute), false).Length != 0;
case PropertyMemberAst propertyMember:
return propertyMember.IsHidden;
case FunctionMemberAst functionMember:
return functionMember.IsHidden;
}
return false;
}
private static bool IsConstructor(object member)
{
var psMethod = member as PSMethod;
var methodCacheEntry = psMethod?.adapterData as DotNetAdapter.MethodCacheEntry;
return methodCacheEntry != null && methodCacheEntry.methodInformationStructures[0].method.IsConstructor;
}
}
internal class TypeInferenceVisitor : ICustomAstVisitor2
{
private readonly TypeInferenceContext _context;
private static readonly PSTypeName StringPSTypeName = new PSTypeName(typeof(string));
public TypeInferenceVisitor(TypeInferenceContext context)
{
_context = context;
}
private IEnumerable<PSTypeName> InferTypes(Ast ast)
{
return _context.InferType(ast, this);
}
object ICustomAstVisitor.VisitTypeExpression(TypeExpressionAst typeExpressionAst)
{
return new[] { new PSTypeName(typeExpressionAst.StaticType) };
}
object ICustomAstVisitor.VisitMemberExpression(MemberExpressionAst memberExpressionAst)
{
return InferTypesFrom(memberExpressionAst);
}
object ICustomAstVisitor.VisitInvokeMemberExpression(InvokeMemberExpressionAst invokeMemberExpressionAst)
{
return InferTypesFrom(invokeMemberExpressionAst);
}
object ICustomAstVisitor.VisitArrayExpression(ArrayExpressionAst arrayExpressionAst)
{
if (arrayExpressionAst.SubExpression.Statements.Count == 0)
{
return new[] { new PSTypeName(typeof(object[])) };
}
return new[] { GetArrayType(InferTypes(arrayExpressionAst.SubExpression)) };
}
object ICustomAstVisitor.VisitArrayLiteral(ArrayLiteralAst arrayLiteralAst)
{
var inferredElementTypes = new List<PSTypeName>();
foreach (ExpressionAst expression in arrayLiteralAst.Elements)
{
inferredElementTypes.AddRange(InferTypes(expression));
}
return new[] { GetArrayType(inferredElementTypes) };
}
object ICustomAstVisitor.VisitHashtable(HashtableAst hashtableAst)
{
if (hashtableAst.KeyValuePairs.Count > 0)
{
var properties = new List<PSMemberNameAndType>();
void AddInferredTypes(Ast ast, string keyName)
{
bool foundAnyTypes = false;
foreach (PSTypeName item in InferTypes(ast))
{
foundAnyTypes = true;
properties.Add(new PSMemberNameAndType(keyName, item));
}
if (!foundAnyTypes)
{
properties.Add(new PSMemberNameAndType(keyName, new PSTypeName("System.Object")));
}
}
foreach (var kv in hashtableAst.KeyValuePairs)
{
string name = null;
if (kv.Item1 is StringConstantExpressionAst stringConstantExpressionAst)
{
name = stringConstantExpressionAst.Value;
}
else if (kv.Item1 is ConstantExpressionAst constantExpressionAst)
{
name = constantExpressionAst.Value.ToString();
}
else if (SafeExprEvaluator.TrySafeEval(kv.Item1, _context.ExecutionContext, out object nameValue))
{
name = nameValue.ToString();
}
if (name is not null)
{
if (kv.Item2 is PipelineAst pipelineAst && pipelineAst.GetPureExpression() is ExpressionAst expression)
{
object value;
if (expression is ConstantExpressionAst constant)
{
value = constant.Value;
}
else
{
_ = SafeExprEvaluator.TrySafeEval(expression, _context.ExecutionContext, out value);
}
if (value is null)
{
AddInferredTypes(expression, name);
continue;
}
PSTypeName valueType = new(value.GetType());
properties.Add(new PSMemberNameAndType(name, valueType, value));
}
else
{
AddInferredTypes(kv.Item2, name);
}
}
}
return new[] { PSSyntheticTypeName.Create(typeof(Hashtable), properties) };
}
return new[] { new PSTypeName(typeof(Hashtable)) };
}
object ICustomAstVisitor.VisitScriptBlockExpression(ScriptBlockExpressionAst scriptBlockExpressionAst)
{
return new[] { new PSTypeName(typeof(ScriptBlock)) };
}
object ICustomAstVisitor.VisitParenExpression(ParenExpressionAst parenExpressionAst)
{
return parenExpressionAst.Pipeline.Accept(this);
}
object ICustomAstVisitor.VisitExpandableStringExpression(ExpandableStringExpressionAst expandableStringExpressionAst)
{
return new[] { StringPSTypeName };
}
object ICustomAstVisitor.VisitIndexExpression(IndexExpressionAst indexExpressionAst)
{
return InferTypeFrom(indexExpressionAst);
}
object ICustomAstVisitor.VisitAttributedExpression(AttributedExpressionAst attributedExpressionAst)
{
return attributedExpressionAst.Child.Accept(this);
}
object ICustomAstVisitor.VisitBlockStatement(BlockStatementAst blockStatementAst)
{
return blockStatementAst.Body.Accept(this);
}
object ICustomAstVisitor.VisitUsingExpression(UsingExpressionAst usingExpressionAst)
{
return usingExpressionAst.SubExpression.Accept(this);
}
object ICustomAstVisitor.VisitVariableExpression(VariableExpressionAst ast)
{
var inferredTypes = new List<PSTypeName>();
InferTypeFrom(ast, inferredTypes);
return inferredTypes;
}
object ICustomAstVisitor.VisitMergingRedirection(MergingRedirectionAst mergingRedirectionAst)
{
return TypeInferenceContext.EmptyPSTypeNameArray;
}
object ICustomAstVisitor.VisitBinaryExpression(BinaryExpressionAst binaryExpressionAst)
{
// TODO: Handle other kinds of expressions on the right side.
if (binaryExpressionAst.Operator == TokenKind.As && binaryExpressionAst.Right is TypeExpressionAst typeExpression)
{
var type = typeExpression.TypeName.GetReflectionType();
var psTypeName = type != null ? new PSTypeName(type) : new PSTypeName(typeExpression.TypeName.FullName);
return new[] { psTypeName };
}
return InferTypes(binaryExpressionAst.Left);
}
object ICustomAstVisitor.VisitUnaryExpression(UnaryExpressionAst unaryExpressionAst)
{
var tokenKind = unaryExpressionAst.TokenKind;
return (tokenKind == TokenKind.Not || tokenKind == TokenKind.Exclaim)
? BinaryExpressionAst.BoolTypeNameArray
: unaryExpressionAst.Child.Accept(this);
}
object ICustomAstVisitor.VisitConvertExpression(ConvertExpressionAst convertExpressionAst)
{
// The reflection type of PSCustomObject is PSObject, so this covers both the
// [PSObject] @{ Key = "Value" } and the [PSCustomObject] @{ Key = "Value" } case.
var type = convertExpressionAst.Type.TypeName.GetReflectionType();
if (type is null && convertExpressionAst.Type.TypeName is TypeName unavailableType && unavailableType._typeDefinitionAst is not null)
{
return new[] { new PSTypeName(unavailableType._typeDefinitionAst) };
}
if (type == typeof(PSObject) && convertExpressionAst.Child is HashtableAst hashtableAst)
{
if (InferTypes(hashtableAst).FirstOrDefault() is PSSyntheticTypeName syntheticTypeName)
{
return new[] { PSSyntheticTypeName.Create(type, syntheticTypeName.Members) };
}
}
var psTypeName = type != null ? new PSTypeName(type) : new PSTypeName(convertExpressionAst.Type.TypeName.FullName);
return new[] { psTypeName };
}
object ICustomAstVisitor.VisitConstantExpression(ConstantExpressionAst constantExpressionAst)
{
var value = constantExpressionAst.Value;
return value != null ? new[] { new PSTypeName(value.GetType()) } : TypeInferenceContext.EmptyPSTypeNameArray;
}
object ICustomAstVisitor.VisitStringConstantExpression(StringConstantExpressionAst stringConstantExpressionAst)
{
return new[] { StringPSTypeName };
}
object ICustomAstVisitor.VisitSubExpression(SubExpressionAst subExpressionAst)
{
return subExpressionAst.SubExpression.Accept(this);
}
object ICustomAstVisitor.VisitErrorStatement(ErrorStatementAst errorStatementAst)
{
var inferredTypes = new List<PSTypeName>();
if (errorStatementAst.Conditions is not null)
{
foreach (var ast in errorStatementAst.Conditions)
{
inferredTypes.AddRange(InferTypes(ast));
}
}
if (errorStatementAst.Bodies is not null)
{
foreach (var ast in errorStatementAst.Bodies)
{
inferredTypes.AddRange(InferTypes(ast));
}
}
if (errorStatementAst.NestedAst is not null)
{
foreach (var ast in errorStatementAst.NestedAst)
{
inferredTypes.AddRange(InferTypes(ast));
}
}
return inferredTypes;
}
object ICustomAstVisitor.VisitErrorExpression(ErrorExpressionAst errorExpressionAst)
{
var inferredTypes = new List<PSTypeName>();
foreach (var ast in errorExpressionAst.NestedAst)
{
inferredTypes.AddRange(InferTypes(ast));
}
return inferredTypes;
}
object ICustomAstVisitor.VisitScriptBlock(ScriptBlockAst scriptBlockAst)
{
var res = new List<PSTypeName>(10);
var beginBlock = scriptBlockAst.BeginBlock;
var processBlock = scriptBlockAst.ProcessBlock;
var endBlock = scriptBlockAst.EndBlock;
// The following is used when we don't find OutputType, which is checked elsewhere.
if (beginBlock != null)
{
res.AddRange(InferTypes(beginBlock));
}
if (processBlock != null)
{
res.AddRange(InferTypes(processBlock));
}
if (endBlock != null)
{
res.AddRange(InferTypes(endBlock));
}
return res;
}
object ICustomAstVisitor.VisitParamBlock(ParamBlockAst paramBlockAst)
{
return TypeInferenceContext.EmptyPSTypeNameArray;
}
object ICustomAstVisitor.VisitNamedBlock(NamedBlockAst namedBlockAst)
{
var inferredTypes = new List<PSTypeName>();
for (var index = 0; index < namedBlockAst.Statements.Count; index++)
{
var ast = namedBlockAst.Statements[index];
inferredTypes.AddRange(InferTypes(ast));
}
return inferredTypes;
}
object ICustomAstVisitor.VisitTypeConstraint(TypeConstraintAst typeConstraintAst)
{
return TypeInferenceContext.EmptyPSTypeNameArray;
}
object ICustomAstVisitor.VisitAttribute(AttributeAst attributeAst)
{
return TypeInferenceContext.EmptyPSTypeNameArray;
}
object ICustomAstVisitor.VisitNamedAttributeArgument(NamedAttributeArgumentAst namedAttributeArgumentAst)
{
return TypeInferenceContext.EmptyPSTypeNameArray;
}
object ICustomAstVisitor.VisitParameter(ParameterAst parameterAst)
{
var res = new List<PSTypeName>();
var attributes = parameterAst.Attributes;
bool typeConstraintAdded = false;
foreach (var attrib in attributes)
{
switch (attrib)
{
case TypeConstraintAst typeConstraint:
if (!typeConstraintAdded)
{
res.Add(new PSTypeName(typeConstraint.TypeName));
typeConstraintAdded = true;
}
break;
case AttributeAst attributeAst:
PSTypeNameAttribute attribute = null;
try
{
attribute = attributeAst.GetAttribute() as PSTypeNameAttribute;
}
catch (RuntimeException)
{
}
if (attribute != null)
{
res.Add(new PSTypeName(attribute.PSTypeName));
}
break;
}
}
return res;
}
object ICustomAstVisitor.VisitFunctionDefinition(FunctionDefinitionAst functionDefinitionAst)
{
return TypeInferenceContext.EmptyPSTypeNameArray;
}
object ICustomAstVisitor.VisitStatementBlock(StatementBlockAst statementBlockAst)
{
var inferredTypes = new List<PSTypeName>();
foreach (var ast in statementBlockAst.Statements)
{
inferredTypes.AddRange(InferTypes(ast));
}
return inferredTypes;
}
object ICustomAstVisitor.VisitIfStatement(IfStatementAst ifStmtAst)
{
var res = new List<PSTypeName>();
foreach (var clause in ifStmtAst.Clauses)
{
res.AddRange(InferTypes(clause.Item2));
}
var elseClause = ifStmtAst.ElseClause;
if (elseClause != null)
{
res.AddRange(InferTypes(elseClause));
}
return res;
}
object ICustomAstVisitor.VisitTrap(TrapStatementAst trapStatementAst)
{
return trapStatementAst.Body.Accept(this);
}
object ICustomAstVisitor.VisitSwitchStatement(SwitchStatementAst switchStatementAst)
{
var res = new List<PSTypeName>(8);
var clauses = switchStatementAst.Clauses;
var defaultStatement = switchStatementAst.Default;
foreach (var clause in clauses)
{
res.AddRange(InferTypes(clause.Item2));
}
if (defaultStatement != null)
{
res.AddRange(InferTypes(defaultStatement));
}
return res;
}
object ICustomAstVisitor.VisitDataStatement(DataStatementAst dataStatementAst)
{
return dataStatementAst.Body.Accept(this);
}
object ICustomAstVisitor.VisitForEachStatement(ForEachStatementAst forEachStatementAst)
{
return forEachStatementAst.Body.Accept(this);
}
object ICustomAstVisitor.VisitDoWhileStatement(DoWhileStatementAst doWhileStatementAst)
{
return doWhileStatementAst.Body.Accept(this);
}
object ICustomAstVisitor.VisitForStatement(ForStatementAst forStatementAst)
{
return forStatementAst.Body.Accept(this);
}
object ICustomAstVisitor.VisitWhileStatement(WhileStatementAst whileStatementAst)
{
return whileStatementAst.Body.Accept(this);
}
object ICustomAstVisitor.VisitCatchClause(CatchClauseAst catchClauseAst)
{
return catchClauseAst.Body.Accept(this);
}
object ICustomAstVisitor.VisitTryStatement(TryStatementAst tryStatementAst)
{
var res = new List<PSTypeName>(5);
res.AddRange(InferTypes(tryStatementAst.Body));
foreach (var catchClauseAst in tryStatementAst.CatchClauses)
{
res.AddRange(InferTypes(catchClauseAst));
}
if (tryStatementAst.Finally != null)
{
res.AddRange(InferTypes(tryStatementAst.Finally));
}
return res;