Team Ai
Datasetpublic

MegaBites-AI/Windows-powershell

sourceHugging Facemitupdated 6mo agoView on Hugging Face
0likes372downloads
Compiler.cs7080 linesDownload Raw Back to parser
1// Copyright (c) Microsoft Corporation.2// Licensed under the MIT License.3 4using System.Collections;5using System.Collections.Generic;6using System.Collections.ObjectModel;7using System.Collections.Specialized;8using System.Diagnostics;9using System.Dynamic;10using System.Globalization;11using System.IO;12using System.Linq;13using System.Linq.Expressions;14using System.Management.Automation.Internal;15using System.Management.Automation.Interpreter;16using System.Management.Automation.Runspaces;17using System.Reflection;18using System.Runtime.CompilerServices;19using System.Text.RegularExpressions;20 21using Microsoft.PowerShell.Commands;22 23namespace System.Management.Automation.Language24{25    using KeyValuePair = Tuple<ExpressionAst, StatementAst>;26    using IfClause = Tuple<PipelineBaseAst, StatementBlockAst>;27 28    internal static class CachedReflectionInfo29    {30        // ReSharper disable InconsistentNaming31        internal const BindingFlags InstanceFlags = BindingFlags.Instance | BindingFlags.NonPublic;32        internal const BindingFlags StaticFlags = BindingFlags.Static | BindingFlags.NonPublic;33        internal const BindingFlags StaticPublicFlags = BindingFlags.Static | BindingFlags.Public;34        internal const BindingFlags InstancePublicFlags = BindingFlags.Instance | BindingFlags.Public;35 36        internal static readonly ConstructorInfo ObjectList_ctor =37            typeof(List<object>).GetConstructor(Type.EmptyTypes);38 39        internal static readonly MethodInfo ObjectList_ToArray =40            typeof(List<object>).GetMethod(nameof(List<object>.ToArray), Type.EmptyTypes);41 42        internal static readonly MethodInfo ArrayOps_AddObject =43            typeof(ArrayOps).GetMethod(nameof(ArrayOps.AddObjectArray), StaticFlags);44 45        internal static readonly MethodInfo ArrayOps_GetMDArrayValue =46            typeof(ArrayOps).GetMethod(nameof(ArrayOps.GetMDArrayValue), StaticFlags);47 48        internal static readonly MethodInfo ArrayOps_GetMDArrayValueOrSlice =49            typeof(ArrayOps).GetMethod(nameof(ArrayOps.GetMDArrayValueOrSlice), StaticFlags);50 51        internal static readonly MethodInfo ArrayOps_GetNonIndexable =52            typeof(ArrayOps).GetMethod(nameof(ArrayOps.GetNonIndexable), StaticFlags);53 54        internal static readonly MethodInfo ArrayOps_IndexStringMessage =55            typeof(ArrayOps).GetMethod(nameof(ArrayOps.IndexStringMessage), StaticFlags);56 57        internal static readonly MethodInfo ArrayOps_Multiply =58            typeof(ArrayOps).GetMethod(nameof(ArrayOps.Multiply), StaticFlags);59 60        internal static readonly MethodInfo ArrayOps_SetMDArrayValue =61            typeof(ArrayOps).GetMethod(nameof(ArrayOps.SetMDArrayValue), StaticFlags);62 63        internal static readonly MethodInfo ArrayOps_SlicingIndex =64            typeof(ArrayOps).GetMethod(nameof(ArrayOps.SlicingIndex), StaticFlags);65 66        internal static readonly ConstructorInfo BreakException_ctor =67            typeof(BreakException).GetConstructor(InstanceFlags, null, CallingConventions.Standard, new Type[] { typeof(string) }, null);68 69        internal static readonly MethodInfo CharOps_CompareIeq =70            typeof(CharOps).GetMethod(nameof(CharOps.CompareIeq), StaticFlags);71 72        internal static readonly MethodInfo CharOps_CompareIne =73            typeof(CharOps).GetMethod(nameof(CharOps.CompareIne), StaticFlags);74 75        internal static readonly MethodInfo CharOps_CompareStringIeq =76            typeof(CharOps).GetMethod(nameof(CharOps.CompareStringIeq), StaticFlags);77 78        internal static readonly MethodInfo CharOps_CompareStringIne =79            typeof(CharOps).GetMethod(nameof(CharOps.CompareStringIne), StaticFlags);80 81        internal static readonly MethodInfo CommandParameterInternal_CreateArgument =82            typeof(CommandParameterInternal).GetMethod(nameof(CommandParameterInternal.CreateArgument), StaticFlags);83 84        internal static readonly MethodInfo CommandParameterInternal_CreateParameter =85            typeof(CommandParameterInternal).GetMethod(nameof(CommandParameterInternal.CreateParameter), StaticFlags);86 87        internal static readonly MethodInfo CommandParameterInternal_CreateParameterWithArgument =88            typeof(CommandParameterInternal).GetMethod(nameof(CommandParameterInternal.CreateParameterWithArgument), StaticFlags);89 90        internal static readonly MethodInfo CommandRedirection_UnbindForExpression =91            typeof(CommandRedirection).GetMethod(nameof(CommandRedirection.UnbindForExpression), InstanceFlags);92 93        internal static readonly ConstructorInfo ContinueException_ctor =94            typeof(ContinueException).GetConstructor(InstanceFlags, null, CallingConventions.Standard, new Type[] { typeof(string) }, null);95 96        internal static readonly MethodInfo Convert_ChangeType =97            typeof(Convert).GetMethod(nameof(Convert.ChangeType), new Type[] { typeof(object), typeof(Type) });98 99        internal static readonly MethodInfo Debugger_EnterScriptFunction =100            typeof(ScriptDebugger).GetMethod(nameof(ScriptDebugger.EnterScriptFunction), InstanceFlags);101 102        internal static readonly MethodInfo Debugger_ExitScriptFunction =103            typeof(ScriptDebugger).GetMethod(nameof(ScriptDebugger.ExitScriptFunction), InstanceFlags);104 105        internal static readonly MethodInfo Debugger_OnSequencePointHit =106            typeof(ScriptDebugger).GetMethod(nameof(ScriptDebugger.OnSequencePointHit), InstanceFlags);107 108        internal static readonly MethodInfo EnumerableOps_AddEnumerable =109            typeof(EnumerableOps).GetMethod(nameof(EnumerableOps.AddEnumerable), StaticFlags);110 111        internal static readonly MethodInfo EnumerableOps_AddObject =112            typeof(EnumerableOps).GetMethod(nameof(EnumerableOps.AddObject), StaticFlags);113 114        internal static readonly MethodInfo EnumerableOps_Compare =115            typeof(EnumerableOps).GetMethod(nameof(EnumerableOps.Compare), StaticFlags);116 117        internal static readonly MethodInfo EnumerableOps_GetEnumerator =118            typeof(EnumerableOps).GetMethod(nameof(EnumerableOps.GetEnumerator), StaticFlags);119 120        internal static readonly MethodInfo EnumerableOps_GetCOMEnumerator =121            typeof(EnumerableOps).GetMethod(nameof(EnumerableOps.GetCOMEnumerator), StaticFlags);122 123        internal static readonly MethodInfo EnumerableOps_GetGenericEnumerator =124            typeof(EnumerableOps).GetMethod(nameof(EnumerableOps.GetGenericEnumerator), StaticFlags);125 126        internal static readonly MethodInfo EnumerableOps_GetSlice =127            typeof(EnumerableOps).GetMethod(nameof(EnumerableOps.GetSlice), StaticFlags);128 129        internal static readonly MethodInfo EnumerableOps_MethodInvoker =130            typeof(EnumerableOps).GetMethod(nameof(EnumerableOps.MethodInvoker), StaticFlags);131 132        internal static readonly MethodInfo EnumerableOps_Where =133            typeof(EnumerableOps).GetMethod(nameof(EnumerableOps.Where), StaticFlags);134 135        internal static readonly MethodInfo EnumerableOps_ForEach =136            typeof(EnumerableOps).GetMethod(nameof(EnumerableOps.ForEach), StaticFlags);137 138        internal static readonly MethodInfo EnumerableOps_Multiply =139            typeof(EnumerableOps).GetMethod(nameof(EnumerableOps.Multiply), StaticFlags);140 141        internal static readonly MethodInfo EnumerableOps_PropertyGetter =142            typeof(EnumerableOps).GetMethod(nameof(EnumerableOps.PropertyGetter), StaticFlags);143 144        internal static readonly MethodInfo EnumerableOps_SlicingIndex =145            typeof(EnumerableOps).GetMethod(nameof(EnumerableOps.SlicingIndex), StaticFlags);146 147        internal static readonly MethodInfo EnumerableOps_ToArray =148            typeof(EnumerableOps).GetMethod(nameof(EnumerableOps.ToArray), StaticFlags);149 150        internal static readonly MethodInfo EnumerableOps_WriteEnumerableToPipe =151            typeof(EnumerableOps).GetMethod(nameof(EnumerableOps.WriteEnumerableToPipe), StaticFlags);152 153        internal static readonly ConstructorInfo ErrorRecord__ctor =154            typeof(ErrorRecord).GetConstructor(155                InstanceFlags | BindingFlags.Public,156                null,157                CallingConventions.Standard,158                new Type[] { typeof(ErrorRecord), typeof(RuntimeException) },159                null);160 161        internal static readonly PropertyInfo Exception_Message =162            typeof(Exception).GetProperty(nameof(Exception.Message));163 164        internal static readonly MethodInfo ExceptionHandlingOps_CheckActionPreference =165            typeof(ExceptionHandlingOps).GetMethod(nameof(ExceptionHandlingOps.CheckActionPreference), StaticFlags);166 167        internal static readonly MethodInfo ExceptionHandlingOps_ConvertToArgumentConversionException =168            typeof(ExceptionHandlingOps).GetMethod(nameof(ExceptionHandlingOps.ConvertToArgumentConversionException), StaticFlags);169 170        internal static readonly MethodInfo ExceptionHandlingOps_ConvertToException =171            typeof(ExceptionHandlingOps).GetMethod(nameof(ExceptionHandlingOps.ConvertToException), StaticFlags);172 173        internal static readonly MethodInfo ExceptionHandlingOps_ConvertToMethodInvocationException =174            typeof(ExceptionHandlingOps).GetMethod(nameof(ExceptionHandlingOps.ConvertToMethodInvocationException), StaticFlags);175 176        internal static readonly MethodInfo ExceptionHandlingOps_FindMatchingHandler =177            typeof(ExceptionHandlingOps).GetMethod(nameof(ExceptionHandlingOps.FindMatchingHandler), StaticFlags);178 179        internal static readonly MethodInfo ExceptionHandlingOps_RestoreStoppingPipeline =180            typeof(ExceptionHandlingOps).GetMethod(nameof(ExceptionHandlingOps.RestoreStoppingPipeline), StaticFlags);181 182        internal static readonly MethodInfo ExceptionHandlingOps_SuspendStoppingPipeline =183            typeof(ExceptionHandlingOps).GetMethod(nameof(ExceptionHandlingOps.SuspendStoppingPipeline), StaticFlags);184 185        internal static readonly PropertyInfo ExecutionContext_CurrentExceptionBeingHandled =186            typeof(ExecutionContext).GetProperty(nameof(ExecutionContext.CurrentExceptionBeingHandled), InstanceFlags);187 188        internal static readonly FieldInfo ExecutionContext_Debugger =189            typeof(ExecutionContext).GetField(nameof(ExecutionContext._debugger), InstanceFlags);190 191        internal static readonly FieldInfo ExecutionContext_DebuggingMode =192            typeof(ExecutionContext).GetField(nameof(ExecutionContext._debuggingMode), InstanceFlags);193 194        internal static readonly PropertyInfo ExecutionContext_ExceptionHandlerInEnclosingStatementBlock =195            typeof(ExecutionContext).GetProperty(nameof(ExecutionContext.PropagateExceptionsToEnclosingStatementBlock), InstanceFlags);196 197        internal static readonly MethodInfo ExecutionContext_IsStrictVersion =198            typeof(ExecutionContext).GetMethod(nameof(ExecutionContext.IsStrictVersion), StaticFlags);199 200        internal static readonly PropertyInfo ExecutionContext_QuestionMarkVariableValue =201            typeof(ExecutionContext).GetProperty(nameof(ExecutionContext.QuestionMarkVariableValue), InstanceFlags);202 203        internal static readonly PropertyInfo ExecutionContext_LanguageMode =204            typeof(ExecutionContext).GetProperty(nameof(ExecutionContext.LanguageMode), InstanceFlags);205 206        internal static readonly PropertyInfo ExecutionContext_EngineIntrinsics =207            typeof(ExecutionContext).GetProperty(nameof(ExecutionContext.EngineIntrinsics), InstanceFlags);208 209        internal static readonly MethodInfo FileRedirection_BindForExpression =210            typeof(FileRedirection).GetMethod(nameof(FileRedirection.BindForExpression), InstanceFlags);211 212        internal static readonly MethodInfo FileRedirection_CallDoCompleteForExpression =213            typeof(FileRedirection).GetMethod(nameof(FileRedirection.CallDoCompleteForExpression), InstanceFlags);214 215        internal static readonly ConstructorInfo FileRedirection_ctor =216            typeof(FileRedirection).GetConstructor(217                InstanceFlags,218                null,219                CallingConventions.Standard,220                new Type[] { typeof(RedirectionStream), typeof(bool), typeof(string) },221                null);222 223        internal static readonly MethodInfo FileRedirection_Dispose =224            typeof(FileRedirection).GetMethod(nameof(FileRedirection.Dispose));225 226        internal static readonly FieldInfo FunctionContext__currentSequencePointIndex =227            typeof(FunctionContext).GetField(nameof(FunctionContext._currentSequencePointIndex), InstanceFlags);228 229        internal static readonly FieldInfo FunctionContext__executionContext =230            typeof(FunctionContext).GetField(nameof(FunctionContext._executionContext), InstanceFlags);231 232        internal static readonly FieldInfo FunctionContext__functionName =233            typeof(FunctionContext).GetField(nameof(FunctionContext._functionName), InstanceFlags);234 235        internal static readonly FieldInfo FunctionContext__localsTuple =236            typeof(FunctionContext).GetField(nameof(FunctionContext._localsTuple), InstanceFlags);237 238        internal static readonly FieldInfo FunctionContext__outputPipe =239            typeof(FunctionContext).GetField(nameof(FunctionContext._outputPipe), InstanceFlags);240 241        internal static readonly MethodInfo FunctionContext_PopTrapHandlers =242            typeof(FunctionContext).GetMethod(nameof(FunctionContext.PopTrapHandlers), InstanceFlags);243 244        internal static readonly MethodInfo FunctionContext_PushTrapHandlers =245            typeof(FunctionContext).GetMethod(nameof(FunctionContext.PushTrapHandlers), InstanceFlags);246 247        internal static readonly MethodInfo FunctionOps_DefineFunction =248            typeof(FunctionOps).GetMethod(nameof(FunctionOps.DefineFunction), StaticFlags);249 250        internal static readonly ConstructorInfo Hashtable_ctor =251            typeof(Hashtable).GetConstructor(252                BindingFlags.Instance | BindingFlags.Public,253                null,254                CallingConventions.Standard,255                new Type[] { typeof(int), typeof(IEqualityComparer) },256                null);257 258        internal static readonly MethodInfo ByRefOps_GetByRefPropertyValue =259            typeof(ByRefOps).GetMethod(nameof(ByRefOps.GetByRefPropertyValue), StaticFlags);260 261        internal static readonly MethodInfo HashtableOps_Add =262            typeof(HashtableOps).GetMethod(nameof(HashtableOps.Add), StaticFlags);263 264        internal static readonly MethodInfo HashtableOps_AddKeyValuePair =265            typeof(HashtableOps).GetMethod(nameof(HashtableOps.AddKeyValuePair), StaticFlags);266 267        internal static readonly PropertyInfo ICollection_Count =268            typeof(ICollection).GetProperty(nameof(ICollection.Count));269 270        internal static readonly MethodInfo IComparable_CompareTo =271            typeof(IComparable).GetMethod(nameof(IComparable.CompareTo));272 273        internal static readonly MethodInfo IDisposable_Dispose =274            typeof(IDisposable).GetMethod(nameof(IDisposable.Dispose));275 276        internal static readonly MethodInfo IEnumerable_GetEnumerator =277            typeof(IEnumerable).GetMethod(nameof(IEnumerable.GetEnumerator));278 279        internal static readonly PropertyInfo IEnumerator_Current =280            typeof(IEnumerator).GetProperty(nameof(IEnumerator.Current));281 282        internal static readonly MethodInfo IEnumerator_MoveNext =283            typeof(IEnumerator).GetMethod(nameof(IEnumerator.MoveNext));284 285        internal static readonly MethodInfo IList_get_Item =286            typeof(IList).GetMethod("get_Item");287 288        internal static readonly MethodInfo InterpreterError_NewInterpreterException =289            typeof(InterpreterError).GetMethod(nameof(InterpreterError.NewInterpreterException), StaticFlags);290 291        internal static readonly MethodInfo InterpreterError_NewInterpreterExceptionWithInnerException =292            typeof(InterpreterError).GetMethod(nameof(InterpreterError.NewInterpreterExceptionWithInnerException), StaticFlags);293 294        internal static readonly MethodInfo LanguagePrimitives_GetInvalidCastMessages =295            typeof(LanguagePrimitives).GetMethod(nameof(LanguagePrimitives.GetInvalidCastMessages), StaticFlags);296 297        internal static readonly MethodInfo LanguagePrimitives_IsNull =298            typeof(LanguagePrimitives).GetMethod(nameof(LanguagePrimitives.IsNull), StaticFlags);299 300        internal static readonly MethodInfo LanguagePrimitives_ThrowInvalidCastException =301            typeof(LanguagePrimitives).GetMethod(nameof(LanguagePrimitives.ThrowInvalidCastException), StaticFlags);302 303        internal static readonly MethodInfo LocalPipeline_GetExecutionContextFromTLS =304            typeof(LocalPipeline).GetMethod(nameof(LocalPipeline.GetExecutionContextFromTLS), StaticFlags);305 306        internal static readonly MethodInfo LoopFlowException_MatchLabel =307            typeof(LoopFlowException).GetMethod(nameof(LoopFlowException.MatchLabel), InstanceFlags);308 309        internal static readonly MethodInfo MergingRedirection_BindForExpression =310            typeof(MergingRedirection).GetMethod(nameof(MergingRedirection.BindForExpression), InstanceFlags);311 312        internal static readonly ConstructorInfo MethodException_ctor =313            typeof(MethodException).GetConstructor(314                InstanceFlags,315                null,316                new Type[] { typeof(string), typeof(Exception), typeof(string), typeof(object[]) },317                null);318 319        internal static readonly MethodInfo MutableTuple_IsValueSet =320            typeof(MutableTuple).GetMethod(nameof(MutableTuple.IsValueSet), InstanceFlags);321 322        internal static readonly MethodInfo Object_Equals =323            typeof(object).GetMethod(nameof(object.Equals), new Type[] { typeof(object) });324 325        internal static readonly ConstructorInfo OrderedDictionary_ctor =326            typeof(OrderedDictionary).GetConstructor(327                BindingFlags.Instance | BindingFlags.Public,328                null,329                CallingConventions.Standard,330                new Type[] { typeof(int), typeof(IEqualityComparer) },331                null);332 333        internal static readonly MethodInfo Parser_ScanNumber =334            typeof(Parser).GetMethod(nameof(Parser.ScanNumber), StaticFlags);335 336        internal static readonly MethodInfo ParserOps_ContainsOperatorCompiled =337            typeof(ParserOps).GetMethod(nameof(ParserOps.ContainsOperatorCompiled), StaticFlags);338 339        internal static readonly MethodInfo ParserOps_ImplicitOp =340            typeof(ParserOps).GetMethod(nameof(ParserOps.ImplicitOp), StaticFlags);341 342        internal static readonly MethodInfo ParserOps_JoinOperator =343            typeof(ParserOps).GetMethod(nameof(ParserOps.JoinOperator), StaticFlags);344 345        internal static readonly MethodInfo ParserOps_LikeOperator =346            typeof(ParserOps).GetMethod(nameof(ParserOps.LikeOperator), StaticFlags);347 348        internal static readonly MethodInfo ParserOps_MatchOperator =349            typeof(ParserOps).GetMethod(nameof(ParserOps.MatchOperator), StaticFlags);350 351        internal static readonly MethodInfo ParserOps_RangeOperator =352            typeof(ParserOps).GetMethod(nameof(ParserOps.RangeOperator), StaticFlags);353 354        internal static readonly MethodInfo ParserOps_GetRangeEnumerator =355            typeof(ParserOps).GetMethod(nameof(ParserOps.GetRangeEnumerator), StaticFlags);356 357        internal static readonly MethodInfo ParserOps_ReplaceOperator =358            typeof(ParserOps).GetMethod(nameof(ParserOps.ReplaceOperator), StaticFlags);359 360        internal static readonly MethodInfo ParserOps_SplitOperator =361            typeof(ParserOps).GetMethod(nameof(ParserOps.SplitOperator), StaticFlags);362 363        internal static readonly MethodInfo ParserOps_UnaryJoinOperator =364            typeof(ParserOps).GetMethod(nameof(ParserOps.UnaryJoinOperator), StaticFlags);365 366        internal static readonly MethodInfo ParserOps_UnarySplitOperator =367            typeof(ParserOps).GetMethod(nameof(ParserOps.UnarySplitOperator), StaticFlags);368 369        internal static readonly ConstructorInfo Pipe_ctor =370            typeof(Pipe).GetConstructor(InstanceFlags, null, CallingConventions.Standard, new Type[] { typeof(List<object>) }, null);371 372        internal static readonly MethodInfo Pipe_Add =373            typeof(Pipe).GetMethod(nameof(Pipe.Add), InstanceFlags);374 375        internal static readonly MethodInfo Pipe_SetVariableListForTemporaryPipe =376            typeof(Pipe).GetMethod(nameof(Pipe.SetVariableListForTemporaryPipe), InstanceFlags);377 378        internal static readonly MethodInfo PipelineOps_CheckAutomationNullInCommandArgument =379            typeof(PipelineOps).GetMethod(nameof(PipelineOps.CheckAutomationNullInCommandArgument), StaticFlags);380 381        internal static readonly MethodInfo PipelineOps_CheckAutomationNullInCommandArgumentArray =382            typeof(PipelineOps).GetMethod(nameof(PipelineOps.CheckAutomationNullInCommandArgumentArray), StaticFlags);383 384        internal static readonly MethodInfo PipelineOps_CheckForInterrupts =385            typeof(PipelineOps).GetMethod(nameof(PipelineOps.CheckForInterrupts), StaticFlags);386 387        internal static readonly MethodInfo PipelineOps_GetExitException =388            typeof(PipelineOps).GetMethod(nameof(PipelineOps.GetExitException), StaticFlags);389 390        internal static readonly MethodInfo PipelineOps_FlushPipe =391            typeof(PipelineOps).GetMethod(nameof(PipelineOps.FlushPipe), StaticFlags);392 393        internal static readonly MethodInfo PipelineOps_InvokePipeline =394            typeof(PipelineOps).GetMethod(nameof(PipelineOps.InvokePipeline), StaticFlags);395 396        internal static readonly MethodInfo PipelineOps_InvokePipelineInBackground =397            typeof(PipelineOps).GetMethod(nameof(PipelineOps.InvokePipelineInBackground), StaticFlags);398 399        internal static readonly MethodInfo PipelineOps_Nop =400            typeof(PipelineOps).GetMethod(nameof(PipelineOps.Nop), StaticFlags);401 402        internal static readonly MethodInfo PipelineOps_PipelineResult =403            typeof(PipelineOps).GetMethod(nameof(PipelineOps.PipelineResult), StaticFlags);404 405        internal static readonly MethodInfo PipelineOps_ClearPipe =406            typeof(PipelineOps).GetMethod(nameof(PipelineOps.ClearPipe), StaticFlags);407 408        internal static readonly MethodInfo PSGetDynamicMemberBinder_GetIDictionaryMember =409            typeof(PSGetDynamicMemberBinder).GetMethod(nameof(PSGetDynamicMemberBinder.GetIDictionaryMember), StaticFlags);410 411        internal static readonly MethodInfo PSGetMemberBinder_CloneMemberInfo =412            typeof(PSGetMemberBinder).GetMethod(nameof(PSGetMemberBinder.CloneMemberInfo), StaticFlags);413 414        internal static readonly MethodInfo PSGetMemberBinder_GetAdaptedValue =415            typeof(PSGetMemberBinder).GetMethod(nameof(PSGetMemberBinder.GetAdaptedValue), StaticFlags);416 417        internal static readonly MethodInfo PSGetMemberBinder_GetTypeTableFromTLS =418            typeof(PSGetMemberBinder).GetMethod(nameof(PSGetMemberBinder.GetTypeTableFromTLS), StaticFlags);419 420        internal static readonly MethodInfo PSGetMemberBinder_IsTypeNameSame =421            typeof(PSGetMemberBinder).GetMethod(nameof(PSGetMemberBinder.IsTypeNameSame), StaticFlags);422 423        internal static readonly MethodInfo PSGetMemberBinder_TryGetGenericDictionaryValue =424            typeof(PSGetMemberBinder).GetMethod(nameof(PSGetMemberBinder.TryGetGenericDictionaryValue), StaticFlags);425 426        internal static readonly MethodInfo PSGetMemberBinder_TryGetInstanceMember =427            typeof(PSGetMemberBinder).GetMethod(nameof(PSGetMemberBinder.TryGetInstanceMember), StaticFlags);428 429        internal static readonly MethodInfo PSGetMemberBinder_TryGetIDictionaryValue =430            typeof(PSGetMemberBinder).GetMethod(nameof(PSGetMemberBinder.TryGetIDictionaryValue), StaticFlags);431 432        internal static readonly MethodInfo PSInvokeMemberBinder_InvokeAdaptedMember =433            typeof(PSInvokeMemberBinder).GetMethod(nameof(PSInvokeMemberBinder.InvokeAdaptedMember), StaticFlags);434 435        internal static readonly MethodInfo PSInvokeMemberBinder_InvokeAdaptedSetMember =436            typeof(PSInvokeMemberBinder).GetMethod(nameof(PSInvokeMemberBinder.InvokeAdaptedSetMember), StaticFlags);437 438        internal static readonly MethodInfo PSInvokeMemberBinder_IsHeterogeneousArray =439            typeof(PSInvokeMemberBinder).GetMethod(nameof(PSInvokeMemberBinder.IsHeterogeneousArray), StaticFlags);440 441        internal static readonly MethodInfo PSInvokeMemberBinder_IsHomogeneousArray =442            typeof(PSInvokeMemberBinder).GetMethod(nameof(PSInvokeMemberBinder.IsHomogeneousArray), StaticFlags);443 444        internal static readonly MethodInfo PSInvokeMemberBinder_TryGetInstanceMethod =445            typeof(PSInvokeMemberBinder).GetMethod(nameof(PSInvokeMemberBinder.TryGetInstanceMethod), StaticFlags);446 447        internal static readonly MethodInfo PSMethodInfo_Invoke =448            typeof(PSMethodInfo).GetMethod(nameof(PSMethodInfo.Invoke));449 450        internal static readonly PropertyInfo PSNoteProperty_Value =451            typeof(PSNoteProperty).GetProperty(nameof(PSNoteProperty.Value));452 453        internal static readonly MethodInfo PSObject_Base =454            typeof(PSObject).GetMethod(nameof(PSObject.Base), StaticFlags);455 456        internal static readonly PropertyInfo PSObject_BaseObject =457            typeof(PSObject).GetProperty(nameof(PSObject.BaseObject));458 459        internal static readonly PropertyInfo PSObject_IsDeserialized =460            typeof(PSObject).GetProperty(nameof(PSObject.IsDeserialized), InstanceFlags);461 462        internal static readonly MethodInfo PSObject_ToStringParser =463            typeof(PSObject).GetMethod(nameof(PSObject.ToStringParser), StaticFlags, null, new[] { typeof(ExecutionContext), typeof(object) }, null);464 465        internal static readonly PropertyInfo PSReference_Value =466            typeof(PSReference).GetProperty(nameof(PSReference.Value));467 468        internal static readonly MethodInfo PSScriptMethod_InvokeScript =469            typeof(PSScriptMethod).GetMethod(nameof(PSScriptMethod.InvokeScript), StaticFlags);470 471        internal static readonly MethodInfo PSScriptProperty_InvokeGetter =472            typeof(PSScriptProperty).GetMethod(nameof(PSScriptProperty.InvokeGetter), InstanceFlags);473 474        internal static readonly MethodInfo PSScriptProperty_InvokeSetter =475            typeof(PSScriptProperty).GetMethod(nameof(PSScriptProperty.InvokeSetter), InstanceFlags);476 477        internal static readonly MethodInfo PSSetMemberBinder_SetAdaptedValue =478            typeof(PSSetMemberBinder).GetMethod(nameof(PSSetMemberBinder.SetAdaptedValue), StaticFlags);479 480        internal static readonly MethodInfo PSTraceSource_WriteLine =481            typeof(PSTraceSource).GetMethod(nameof(PSTraceSource.WriteLine), InstanceFlags, new[] { typeof(string), typeof(object) });482 483        internal static readonly MethodInfo PSVariableAssignmentBinder_CopyInstanceMembersOfValueType =484            typeof(PSVariableAssignmentBinder).GetMethod(nameof(PSVariableAssignmentBinder.CopyInstanceMembersOfValueType), StaticFlags);485 486        internal static readonly FieldInfo PSVariableAssignmentBinder__mutableValueWithInstanceMemberVersion =487            typeof(PSVariableAssignmentBinder).GetField(nameof(PSVariableAssignmentBinder.s_mutableValueWithInstanceMemberVersion), StaticFlags);488 489        internal static readonly MethodInfo PSCreateInstanceBinder_IsTargetTypeNonPublic =490            typeof(PSCreateInstanceBinder).GetMethod(nameof(PSCreateInstanceBinder.IsTargetTypeNonPublic), StaticFlags);491 492        internal static readonly MethodInfo PSCreateInstanceBinder_IsTargetTypeByRefLike =493            typeof(PSCreateInstanceBinder).GetMethod(nameof(PSCreateInstanceBinder.IsTargetTypeByRefLike), StaticFlags);494 495        internal static readonly MethodInfo PSCreateInstanceBinder_GetTargetTypeName =496            typeof(PSCreateInstanceBinder).GetMethod(nameof(PSCreateInstanceBinder.GetTargetTypeName), StaticFlags);497 498        internal static readonly MethodInfo ReservedNameMembers_GeneratePSAdaptedMemberSet =499            typeof(ReservedNameMembers).GetMethod(nameof(ReservedNameMembers.GeneratePSAdaptedMemberSet), StaticFlags);500 501        internal static readonly MethodInfo ReservedNameMembers_GeneratePSBaseMemberSet =502            typeof(ReservedNameMembers).GetMethod(nameof(ReservedNameMembers.GeneratePSBaseMemberSet), StaticFlags);503 504        internal static readonly MethodInfo ReservedNameMembers_GeneratePSExtendedMemberSet =505            typeof(ReservedNameMembers).GetMethod(nameof(ReservedNameMembers.GeneratePSExtendedMemberSet), StaticFlags);506 507        internal static readonly MethodInfo ReservedNameMembers_GeneratePSObjectMemberSet =508            typeof(ReservedNameMembers).GetMethod(nameof(ReservedNameMembers.GeneratePSObjectMemberSet), StaticFlags);509 510        internal static readonly MethodInfo ReservedNameMembers_PSTypeNames =511            typeof(ReservedNameMembers).GetMethod(nameof(ReservedNameMembers.PSTypeNames));512 513        internal static readonly MethodInfo RestrictedLanguageChecker_CheckDataStatementLanguageModeAtRuntime =514            typeof(RestrictedLanguageChecker).GetMethod(nameof(RestrictedLanguageChecker.CheckDataStatementLanguageModeAtRuntime), StaticFlags);515 516        internal static readonly MethodInfo RestrictedLanguageChecker_CheckDataStatementAstAtRuntime =517            typeof(RestrictedLanguageChecker).GetMethod(nameof(RestrictedLanguageChecker.CheckDataStatementAstAtRuntime), StaticFlags);518 519        internal static readonly MethodInfo RestrictedLanguageChecker_EnsureUtilityModuleLoaded =520            typeof(RestrictedLanguageChecker).GetMethod(nameof(RestrictedLanguageChecker.EnsureUtilityModuleLoaded), StaticFlags);521 522        internal static readonly ConstructorInfo ReturnException_ctor =523            typeof(ReturnException).GetConstructor(InstanceFlags, null, CallingConventions.Standard, new Type[] { typeof(object) }, null);524 525        internal static readonly PropertyInfo RuntimeException_ErrorRecord =526            typeof(RuntimeException).GetProperty(nameof(RuntimeException.ErrorRecord));527 528        internal static readonly MethodInfo ScriptBlock_DoInvokeReturnAsIs =529            typeof(ScriptBlock).GetMethod(nameof(ScriptBlock.DoInvokeReturnAsIs), InstanceFlags);530 531        internal static readonly MethodInfo ScriptBlock_InvokeAsDelegateHelper =532            typeof(ScriptBlock).GetMethod(nameof(ScriptBlock.InvokeAsDelegateHelper), InstanceFlags);533 534        internal static readonly MethodInfo ScriptBlockExpressionWrapper_GetScriptBlock =535            typeof(ScriptBlockExpressionWrapper).GetMethod(nameof(ScriptBlockExpressionWrapper.GetScriptBlock), InstanceFlags);536 537        internal static readonly ConstructorInfo SetValueException_ctor =538            typeof(SetValueException).GetConstructor(539                InstanceFlags,540                null,541                new[] { typeof(string), typeof(Exception), typeof(string), typeof(object[]) },542                null);543 544        internal static readonly ConstructorInfo GetValueException_ctor =545            typeof(GetValueException).GetConstructor(546                InstanceFlags,547                null,548                new[] { typeof(string), typeof(Exception), typeof(string), typeof(object[]) },549                null);550 551        internal static readonly ConstructorInfo StreamReader_ctor =552            typeof(StreamReader).GetConstructor(new Type[] { typeof(string) });553 554        internal static readonly MethodInfo StreamReader_ReadLine =555            typeof(StreamReader).GetMethod(nameof(StreamReader.ReadLine), Type.EmptyTypes);556 557        internal static readonly ConstructorInfo String_ctor_char_int =558            typeof(string).GetConstructor(new Type[] { typeof(char), typeof(int) });559 560        internal static readonly MethodInfo String_Concat_String =561            typeof(string).GetMethod(562                nameof(string.Concat),563                StaticPublicFlags, null,564                CallingConventions.Standard,565                new Type[] { typeof(string), typeof(string) },566                null);567 568        internal static readonly MethodInfo String_Equals =569            typeof(string).GetMethod(570                nameof(string.Equals),571                StaticPublicFlags,572                null,573                CallingConventions.Standard,574                new Type[] { typeof(string), typeof(string), typeof(StringComparison) },575                null);576 577        internal static readonly MethodInfo StringOps_Compare =578            typeof(StringOps).GetMethod(nameof(StringOps.Compare), StaticFlags);579 580        internal static readonly MethodInfo StringOps_Equals =581            typeof(StringOps).GetMethod(nameof(StringOps.Equals), StaticFlags);582 583        internal static readonly MethodInfo StringOps_FormatOperator =584            typeof(StringOps).GetMethod(nameof(StringOps.FormatOperator), StaticFlags);585 586        internal static readonly MethodInfo StringOps_Multiply =587            typeof(StringOps).GetMethod(nameof(StringOps.Multiply), StaticFlags);588 589        internal static readonly MethodInfo SwitchOps_ConditionSatisfiedRegex =590            typeof(SwitchOps).GetMethod(nameof(SwitchOps.ConditionSatisfiedRegex), StaticFlags);591 592        internal static readonly MethodInfo SwitchOps_ConditionSatisfiedWildcard =593            typeof(SwitchOps).GetMethod(nameof(SwitchOps.ConditionSatisfiedWildcard), StaticFlags);594 595        internal static readonly MethodInfo SwitchOps_ResolveFilePath =596            typeof(SwitchOps).GetMethod(nameof(SwitchOps.ResolveFilePath), StaticFlags);597 598        internal static readonly MethodInfo TypeOps_AsOperator =599            typeof(TypeOps).GetMethod(nameof(TypeOps.AsOperator), StaticFlags);600 601        internal static readonly MethodInfo TypeOps_AddPowerShellTypesToTheScope =602            typeof(TypeOps).GetMethod(nameof(TypeOps.AddPowerShellTypesToTheScope), StaticFlags);603 604        internal static readonly MethodInfo TypeOps_InitPowerShellTypesAtRuntime =605            typeof(TypeOps).GetMethod(nameof(TypeOps.InitPowerShellTypesAtRuntime), StaticFlags);606 607        internal static readonly MethodInfo TypeOps_SetCurrentTypeResolutionState =608            typeof(TypeOps).GetMethod(nameof(TypeOps.SetCurrentTypeResolutionState), StaticFlags);609 610        internal static readonly MethodInfo TypeOps_SetAssemblyDefiningPSTypes =611            typeof(TypeOps).GetMethod(nameof(TypeOps.SetAssemblyDefiningPSTypes), StaticFlags);612 613        internal static readonly MethodInfo TypeOps_IsInstance =614            typeof(TypeOps).GetMethod(nameof(TypeOps.IsInstance), StaticFlags);615 616        internal static readonly MethodInfo TypeOps_ResolveTypeName =617            typeof(TypeOps).GetMethod(nameof(TypeOps.ResolveTypeName), StaticFlags);618 619        internal static readonly MethodInfo VariableOps_GetUsingValue =620            typeof(VariableOps).GetMethod(nameof(VariableOps.GetUsingValue), StaticFlags);621 622        internal static readonly MethodInfo VariableOps_GetVariableAsRef =623            typeof(VariableOps).GetMethod(nameof(VariableOps.GetVariableAsRef), StaticFlags);624 625        internal static readonly MethodInfo VariableOps_GetVariableValue =626            typeof(VariableOps).GetMethod(nameof(VariableOps.GetVariableValue), StaticFlags);627 628        internal static readonly MethodInfo VariableOps_GetAutomaticVariableValue =629            typeof(VariableOps).GetMethod(nameof(VariableOps.GetAutomaticVariableValue), StaticFlags);630 631        internal static readonly MethodInfo VariableOps_SetVariableValue =632            typeof(VariableOps).GetMethod(nameof(VariableOps.SetVariableValue), StaticFlags);633 634        internal static readonly MethodInfo Utils_IsComObject =635            typeof(Utils).GetMethod(nameof(Utils.IsComObject), StaticFlags);636 637        internal static readonly MethodInfo ClassOps_ValidateSetProperty =638            typeof(ClassOps).GetMethod(nameof(ClassOps.ValidateSetProperty), StaticPublicFlags);639 640        internal static readonly MethodInfo ClassOps_CallBaseCtor =641            typeof(ClassOps).GetMethod(nameof(ClassOps.CallBaseCtor), StaticPublicFlags);642 643        internal static readonly MethodInfo ClassOps_CallMethodNonVirtually =644            typeof(ClassOps).GetMethod(nameof(ClassOps.CallMethodNonVirtually), StaticPublicFlags);645 646        internal static readonly MethodInfo ClassOps_CallVoidMethodNonVirtually =647            typeof(ClassOps).GetMethod(nameof(ClassOps.CallVoidMethodNonVirtually), StaticPublicFlags);648 649        internal static readonly MethodInfo ArgumentTransformationAttribute_Transform =650            typeof(ArgumentTransformationAttribute).GetMethod(nameof(ArgumentTransformationAttribute.Transform), InstancePublicFlags);651 652        internal static readonly MethodInfo MemberInvocationLoggingOps_LogMemberInvocation =653            typeof(MemberInvocationLoggingOps).GetMethod(nameof(MemberInvocationLoggingOps.LogMemberInvocation), StaticFlags);654    }655 656    internal static class ExpressionCache657    {658        internal static readonly Expression NullConstant = Expression.Constant(null);659        internal static readonly Expression NullExecutionContext = Expression.Constant(null, typeof(ExecutionContext));660        internal static readonly Expression NullPSObject = Expression.Constant(null, typeof(PSObject));661        internal static readonly Expression NullEnumerator = Expression.Constant(null, typeof(IEnumerator));662        internal static readonly Expression NullExtent = Expression.Constant(null, typeof(IScriptExtent));663        internal static readonly Expression NullTypeTable = Expression.Constant(null, typeof(TypeTable));664        internal static readonly Expression NullFormatProvider = Expression.Constant(null, typeof(IFormatProvider));665        internal static readonly Expression NullObjectArray = Expression.Constant(null, typeof(object[]));666        internal static readonly Expression AutomationNullConstant = Expression.Constant(AutomationNull.Value, typeof(object));667        internal static readonly Expression NullCommandRedirections = Expression.Constant(null, typeof(CommandRedirection[][]));668        internal static readonly Expression NullTypeArray = Expression.Constant(null, typeof(Type[]));669        internal static readonly Expression NullType = Expression.Constant(null, typeof(Type));670        internal static readonly Expression NullDelegateArray = Expression.Constant(null, typeof(Action<FunctionContext>[]));671        internal static readonly Expression NullPipe = Expression.Constant(new Pipe { NullPipe = true });672        internal static readonly Expression ConstEmptyString = Expression.Constant(string.Empty);673        internal static readonly Expression CompareOptionsIgnoreCase = Expression.Constant(CompareOptions.IgnoreCase);674        internal static readonly Expression CompareOptionsNone = Expression.Constant(CompareOptions.None);675        internal static readonly Expression Ordinal = Expression.Constant(StringComparison.Ordinal);676        internal static readonly Expression InvariantCulture = Expression.Constant(CultureInfo.InvariantCulture);677        internal static readonly Expression OrdinalIgnoreCaseComparer = Expression.Constant(StringComparer.OrdinalIgnoreCase, typeof(StringComparer));678        internal static readonly Expression CatchAllType = Expression.Constant(typeof(ExceptionHandlingOps.CatchAll), typeof(Type));679        // Empty expression is used at the end of blocks to give them the void expression result680        internal static readonly Expression Empty = Expression.Empty();681 682        internal static readonly Expression GetExecutionContextFromTLS =683            Expression.Call(CachedReflectionInfo.LocalPipeline_GetExecutionContextFromTLS);684 685        internal static readonly Expression BoxedTrue = Expression.Field(null, typeof(Boxed).GetField("True", BindingFlags.Static | BindingFlags.NonPublic));686        internal static readonly Expression BoxedFalse = Expression.Field(null, typeof(Boxed).GetField("False", BindingFlags.Static | BindingFlags.NonPublic));687 688        private static readonly Expression[] s_intConstants = new Expression[102];689 690        internal static Expression Constant(int i)691        {692            // We cache -1..100, anything else don't bother caching693            if (i < -1 || i > 100)694            {695                return Expression.Constant(i);696            }697 698            Expression result = s_intConstants[i + 1];699            if (result == null)700            {701                result = Expression.Constant(i);702                s_intConstants[i + 1] = result;703            }704 705            return result;706        }707 708        internal static readonly Expression TrueConstant = Expression.Constant(true);709        internal static readonly Expression FalseConstant = Expression.Constant(false);710 711        internal static Expression Constant(bool b)712        {713            return b ? TrueConstant : FalseConstant;714        }715    }716 717    internal static class ExpressionExtensions718    {719        internal static Expression Convert(this Expression expr, Type type)720        {721            if (expr.Type == type)722            {723                return expr;724            }725 726            if (expr.Type == typeof(void))727            {728                // If we're converting from void, use $null instead to figure the conversion.729                expr = ExpressionCache.NullConstant;730            }731 732            var conversion = LanguagePrimitives.GetConversionRank(expr.Type, type);733            if (conversion == ConversionRank.Assignable)734            {735                return Expression.Convert(expr, type);736            }737 738            if (type.ContainsGenericParameters || type.IsByRefLike)739            {740                return Expression.Call(741                    CachedReflectionInfo.LanguagePrimitives_ThrowInvalidCastException,742                    expr.Cast(typeof(object)),743                    Expression.Constant(type, typeof(Type)));744            }745 746            return DynamicExpression.Dynamic(PSConvertBinder.Get(type), type, expr);747        }748 749        internal static Expression Cast(this Expression expr, Type type)750        {751            if (expr.Type == type)752            {753                return expr;754            }755 756            if ((expr.Type.IsFloating() || expr.Type == typeof(decimal)) && type.IsPrimitive)757            {758                // Convert correctly handles most "primitive" conversions for PowerShell,759                // but it does not correctly handle floating point.760                expr = Expression.Call(761                    CachedReflectionInfo.Convert_ChangeType,762                    Expression.Convert(expr, typeof(object)),763                    Expression.Constant(type, typeof(Type)));764            }765 766            return Expression.Convert(expr, type);767        }768 769#if ENABLE_BINDER_DEBUG_LOGGING770        internal static string ToDebugString(this Expression expr)771        {772            using (var writer = new StringWriter(CultureInfo.InvariantCulture))773            {774                DebugViewWriter.WriteTo(expr, writer);775                return writer.ToString();776            }777        }778#endif779    }780 781    internal class FunctionContext782    {783        internal ScriptBlock _scriptBlock;784        internal string _file;785        internal bool _debuggerHidden;786        internal bool _debuggerStepThrough;787        internal IScriptExtent[] _sequencePoints;788        internal ExecutionContext _executionContext;789        internal Pipe _outputPipe;790        internal BitArray _breakPoints;791        internal Dictionary<int, List<LineBreakpoint>> _boundBreakpoints;792        internal int _currentSequencePointIndex;793        internal MutableTuple _localsTuple;794        internal List<Tuple<Type[], Action<FunctionContext>[], Type[]>> _traps = new List<Tuple<Type[], Action<FunctionContext>[], Type[]>>();795        internal string _functionName;796 797        internal IScriptExtent CurrentPosition798        {799            get { return _sequencePoints != null ? _sequencePoints[_currentSequencePointIndex] : PositionUtilities.EmptyExtent; }800        }801 802        internal void PushTrapHandlers(Type[] type, Action<FunctionContext>[] handler, Type[] tupleType)803        {804            _traps.Add(Tuple.Create(type, handler, tupleType));805        }806 807        internal void PopTrapHandlers()808        {809            _traps.RemoveAt(_traps.Count - 1);810        }811    }812 813    internal class Compiler : ICustomAstVisitor2814    {815        internal static readonly ParameterExpression s_executionContextParameter;816        internal static readonly ParameterExpression s_functionContext;817        private static readonly ParameterExpression s_returnPipe;818        private static readonly Expression s_notDollarQuestion;819        private static readonly Expression s_getDollarQuestion;820        private static readonly Expression s_setDollarQuestionToTrue;821        private static readonly Expression s_callCheckForInterrupts;822        private static readonly Expression s_getCurrentPipe;823        private static readonly Expression s_currentExceptionBeingHandled;824        private static readonly CatchBlock s_catchFlowControl;825 826        private static readonly CatchBlock[] s_stmtCatchHandlers;827        internal static readonly Type DottedLocalsTupleType = MutableTuple.MakeTupleType(SpecialVariables.AutomaticVariableTypes);828 829        internal static readonly Dictionary<string, int> DottedLocalsNameIndexMap =830            new Dictionary<string, int>(SpecialVariables.AutomaticVariableTypes.Length, StringComparer.OrdinalIgnoreCase);831 832        internal static readonly Dictionary<string, int> DottedScriptCmdletLocalsNameIndexMap =833            new Dictionary<string, int>(834                SpecialVariables.AutomaticVariableTypes.Length + SpecialVariables.PreferenceVariableTypes.Length,835                StringComparer.OrdinalIgnoreCase);836 837        static Compiler()838        {839            Diagnostics.Assert(SpecialVariables.AutomaticVariables.Length == (int)AutomaticVariable.NumberOfAutomaticVariables840                && SpecialVariables.AutomaticVariableTypes.Length == (int)AutomaticVariable.NumberOfAutomaticVariables,841                "The 'AutomaticVariable' enum length does not match both 'AutomaticVariables' and 'AutomaticVariableTypes' length.");842 843            Diagnostics.Assert(Enum.GetNames(typeof(PreferenceVariable)).Length == SpecialVariables.PreferenceVariables.Length844                && Enum.GetNames(typeof(PreferenceVariable)).Length == SpecialVariables.PreferenceVariableTypes.Length,845                "The 'PreferenceVariable' enum length does not match both 'PreferenceVariables' and 'PreferenceVariableTypes' length.");846 847            s_functionContext = Expression.Parameter(typeof(FunctionContext), "funcContext");848            s_executionContextParameter = Expression.Variable(typeof(ExecutionContext), "context");849 850            s_getDollarQuestion = Expression.Property(s_executionContextParameter, CachedReflectionInfo.ExecutionContext_QuestionMarkVariableValue);851 852            s_notDollarQuestion = Expression.Not(s_getDollarQuestion);853 854            s_setDollarQuestionToTrue = Expression.Assign(855                s_getDollarQuestion,856                ExpressionCache.TrueConstant);857 858            s_callCheckForInterrupts = Expression.Call(859                CachedReflectionInfo.PipelineOps_CheckForInterrupts,860                s_executionContextParameter);861 862            s_getCurrentPipe = Expression.Field(s_functionContext, CachedReflectionInfo.FunctionContext__outputPipe);863            s_returnPipe = Expression.Variable(s_getCurrentPipe.Type, "returnPipe");864 865            var exception = Expression.Variable(typeof(Exception), "exception");866 867            s_catchFlowControl = Expression.Catch(typeof(FlowControlException), Expression.Rethrow());868            var catchAll = Expression.Catch(869                exception,870                Expression.Block(871                    Expression.Call(872                        CachedReflectionInfo.ExceptionHandlingOps_CheckActionPreference,873                        Compiler.s_functionContext, exception)));874            s_stmtCatchHandlers = new CatchBlock[] { s_catchFlowControl, catchAll };875 876            s_currentExceptionBeingHandled = Expression.Property(877                s_executionContextParameter, CachedReflectionInfo.ExecutionContext_CurrentExceptionBeingHandled);878 879            int i;880            for (i = 0; i < SpecialVariables.AutomaticVariables.Length; ++i)881            {882                DottedLocalsNameIndexMap.Add(SpecialVariables.AutomaticVariables[i], i);883                DottedScriptCmdletLocalsNameIndexMap.Add(SpecialVariables.AutomaticVariables[i], i);884            }885 886            for (i = 0; i < SpecialVariables.PreferenceVariables.Length; ++i)887            {888                DottedScriptCmdletLocalsNameIndexMap.Add(889                    SpecialVariables.PreferenceVariables[i],890                    i + (int)AutomaticVariable.NumberOfAutomaticVariables);891            }892 893            s_builtinAttributeGenerator.Add(typeof(CmdletBindingAttribute), NewCmdletBindingAttribute);894            s_builtinAttributeGenerator.Add(typeof(ExperimentalAttribute), NewExperimentalAttribute);895            s_builtinAttributeGenerator.Add(typeof(ParameterAttribute), NewParameterAttribute);896            s_builtinAttributeGenerator.Add(typeof(OutputTypeAttribute), NewOutputTypeAttribute);897            s_builtinAttributeGenerator.Add(typeof(AliasAttribute), NewAliasAttribute);898            s_builtinAttributeGenerator.Add(typeof(ValidateSetAttribute), NewValidateSetAttribute);899            s_builtinAttributeGenerator.Add(typeof(DebuggerHiddenAttribute), NewDebuggerHiddenAttribute);900            s_builtinAttributeGenerator.Add(typeof(ValidateNotNullAttribute), NewValidateNotNullAttribute);901            s_builtinAttributeGenerator.Add(typeof(ValidateNotNullOrEmptyAttribute), NewValidateNotNullOrEmptyAttribute);902        }903 904        private Compiler(List<IScriptExtent> sequencePoints, Dictionary<IScriptExtent, int> sequencePointIndexMap)905        {906            _sequencePoints = sequencePoints;907            _sequencePointIndexMap = sequencePointIndexMap;908        }909 910        internal Compiler()911        {912            _sequencePoints = new List<IScriptExtent>();913            _sequencePointIndexMap = new Dictionary<IScriptExtent, int>();914        }915 916        internal bool CompilingConstantExpression { get; set; }917 918        internal bool Optimize { get; private set; }919 920        internal Type LocalVariablesTupleType { get; private set; }921 922        internal ParameterExpression LocalVariablesParameter { get; private set; }923 924        private SymbolDocumentInfo _debugSymbolDocument;925        internal TypeDefinitionAst _memberFunctionType;926        private bool _compilingTrap;927        private bool _compilingSingleExpression;928        private bool _compilingScriptCmdlet;929        private string _currentFunctionName;930        private int _switchTupleIndex = VariableAnalysis.Unanalyzed;931        private int _foreachTupleIndex = VariableAnalysis.Unanalyzed;932        private readonly List<IScriptExtent> _sequencePoints;933        private readonly Dictionary<IScriptExtent, int> _sequencePointIndexMap;934        private int _stmtCount;935 936        internal bool CompilingMemberFunction { get; set; }937 938        internal SpecialMemberFunctionType SpecialMemberFunctionType { get; set; }939 940        internal Type MemberFunctionReturnType941        {942            get943            {944                Diagnostics.Assert(CompilingMemberFunction, "Return not only set for member functions");945                return _memberFunctionReturnType;946            }947 948            set949            {950                _memberFunctionReturnType = value;951            }952        }953 954        private Type _memberFunctionReturnType;955 956        #region Helpers for AST Compile methods957 958        internal Expression Compile(Ast ast)959        {960            return (Expression)ast.Accept(this);961        }962 963        internal Expression CompileExpressionOperand(ExpressionAst exprAst)964        {965            var result = Compile(exprAst);966            if (result.Type == typeof(void))967            {968                result = Expression.Block(result, ExpressionCache.NullConstant);969            }970 971            return result;972        }973 974        private IEnumerable<Expression> CompileInvocationArguments(IReadOnlyList<ExpressionAst> arguments)975        {976            if (arguments is null || arguments.Count == 0)977            {978                return Array.Empty<Expression>();979            }980 981            var result = new Expression[arguments.Count];982            for (int i = 0; i < result.Length; i++)983            {984                result[i] = CompileExpressionOperand(arguments[i]);985            }986 987            return result;988        }989 990        internal Expression ReduceAssignment(ISupportsAssignment left, TokenKind tokenKind, Expression right)991        {992            IAssignableValue av = left.GetAssignableValue();993            ExpressionType et = ExpressionType.Extension;994 995            switch (tokenKind)996            {997                case TokenKind.Equals: return av.SetValue(this, right);998                case TokenKind.PlusEquals: et = ExpressionType.Add; break;999                case TokenKind.MinusEquals: et = ExpressionType.Subtract; break;1000                case TokenKind.MultiplyEquals: et = ExpressionType.Multiply; break;1001                case TokenKind.DivideEquals: et = ExpressionType.Divide; break;1002                case TokenKind.RemainderEquals: et = ExpressionType.Modulo; break;1003                case TokenKind.QuestionQuestionEquals: et = ExpressionType.Coalesce; break;1004            }1005 1006            var exprs = new List<Expression>();1007            var temps = new List<ParameterExpression>();1008            var getExpr = av.GetValue(this, exprs, temps);1009 1010            if (et == ExpressionType.Coalesce)1011            {1012                exprs.Add(av.SetValue(this, Coalesce(getExpr, right)));1013            }1014            else1015            {1016                exprs.Add(av.SetValue(this, DynamicExpression.Dynamic(PSBinaryOperationBinder.Get(et), typeof(object), getExpr, right)));1017            }1018 1019            return Expression.Block(temps, exprs);1020        }1021 1022        private static Expression Coalesce(Expression left, Expression right)1023        {1024            Type leftType = left.Type;1025 1026            if (leftType.IsValueType)1027            {1028                return left;1029            }1030            else1031            {1032                ParameterExpression lhsStoreVar = Expression.Variable(typeof(object));1033                var blockParameters = new ParameterExpression[] { lhsStoreVar };1034                var blockStatements = new Expression[]1035                {1036                    Expression.Assign(lhsStoreVar, left.Cast(typeof(object))),1037                    Expression.Condition(1038                        Expression.Call(CachedReflectionInfo.LanguagePrimitives_IsNull, lhsStoreVar),1039                        right.Cast(typeof(object)),1040                        lhsStoreVar),1041                };1042 1043                return Expression.Block(1044                    typeof(object),1045                    blockParameters,1046                    blockStatements);1047            }1048        }1049 1050        internal Expression GetLocal(int tupleIndex)1051        {1052            Expression result = LocalVariablesParameter;1053            foreach (var property in MutableTuple.GetAccessPath(LocalVariablesTupleType, tupleIndex))1054            {1055                result = Expression.Property(result, property);1056            }1057 1058            return result;1059        }1060 1061        internal static Expression CallGetVariable(Expression variablePath, VariableExpressionAst varAst)1062        {1063            return Expression.Call(1064                CachedReflectionInfo.VariableOps_GetVariableValue,1065                variablePath,1066                s_executionContextParameter,1067                Expression.Constant(varAst).Cast(typeof(VariableExpressionAst)));1068        }1069 1070        internal static Expression CallSetVariable(Expression variablePath, Expression rhs, Expression attributes = null)1071        {1072            return Expression.Call(1073                CachedReflectionInfo.VariableOps_SetVariableValue,1074                variablePath, rhs.Cast(typeof(object)),1075                s_executionContextParameter,1076                attributes ?? ExpressionCache.NullConstant.Cast(typeof(AttributeAst[])));1077        }1078 1079        internal Expression GetAutomaticVariable(VariableExpressionAst varAst)1080        {1081            // Generate, in pseudo code:1082            //1083            //     return (localsTuple.IsValueSet(tupleIndex)1084            //          ? localsTuple.ItemXXX1085            //          : VariableOps.GetAutomaticVariable(tupleIndex, executionContextParameter);1086            //1087            // We could be smarter about the generated code.  For example:1088            //1089            //     * $PSCmdlet - always set if the script uses cmdletbinding.1090            //     * $_ - always set in process and end block, otherwise need dynamic checks.1091            //     * $this - can never know if it's set, always need above pseudo code.1092            //     * $input - also can never know - it's always set from a command process, but not necessarily set from ScriptBlock.Invoke.1093            //1094            // These optimizations are not yet performed.1095            //1096            int tupleIndex = varAst.TupleIndex;1097            var expr = GetLocal(tupleIndex);1098            var callGetAutomaticVariable = Expression.Call(1099                CachedReflectionInfo.VariableOps_GetAutomaticVariableValue,1100                ExpressionCache.Constant(tupleIndex),1101                s_executionContextParameter,1102                Expression.Constant(varAst)).Convert(expr.Type);1103            if (!Optimize)1104                return callGetAutomaticVariable;1105 1106            return Expression.Condition(1107                Expression.Call(1108                    LocalVariablesParameter,1109                    CachedReflectionInfo.MutableTuple_IsValueSet,1110                    ExpressionCache.Constant(tupleIndex)),1111                expr,1112                callGetAutomaticVariable);1113        }1114 1115        internal static Expression CallStringEquals(Expression left, Expression right, bool ignoreCase)1116        {1117            return Expression.Call(1118                CachedReflectionInfo.StringOps_Equals,1119                left,1120                right,1121                ExpressionCache.InvariantCulture,1122                ignoreCase ? ExpressionCache.CompareOptionsIgnoreCase : ExpressionCache.CompareOptionsNone);1123        }1124 1125        internal static Expression IsStrictMode(int version, Expression executionContext = null)1126        {1127            executionContext ??= ExpressionCache.NullExecutionContext;1128 1129            return Expression.Call(1130                CachedReflectionInfo.ExecutionContext_IsStrictVersion,1131                executionContext,1132                ExpressionCache.Constant(version));1133        }1134 1135        private int AddSequencePoint(IScriptExtent extent)1136        {1137            // Make sure we don't add the same extent to the sequence point list twice.1138            if (!_sequencePointIndexMap.TryGetValue(extent, out int index))1139            {1140                _sequencePoints.Add(extent);1141                index = _sequencePoints.Count - 1;1142                _sequencePointIndexMap.Add(extent, index);1143            }1144 1145            return index;1146        }1147 1148        private Expression UpdatePosition(Ast ast)1149        {1150            IScriptExtent extent = ast.Extent;1151            int index = AddSequencePoint(extent);1152 1153            // If we just added the first sequence point, then we don't want to check for breakpoints - we'll do that1154            // in EnterScriptFunction.1155            // Except for while/do loops, in this case we want to check breakpoints on the first sequence point since it1156            // will be executed multiple times.1157            return (index == 0 && !_generatingWhileOrDoLoop)1158                       ? ExpressionCache.Empty1159                       : new UpdatePositionExpr(extent, index, _debugSymbolDocument, !_compilingSingleExpression);1160        }1161 1162        private int _tempCounter;1163 1164        internal ParameterExpression NewTemp(Type type, string name)1165        {1166            return Expression.Variable(type, string.Create(CultureInfo.InvariantCulture, $"{name}{_tempCounter++}"));1167        }1168 1169        internal static Type GetTypeConstraintForMethodResolution(ExpressionAst expr)1170        {1171            while (expr is ParenExpressionAst)1172            {1173                expr = ((ParenExpressionAst)expr).Pipeline.GetPureExpression();1174            }1175 1176            ConvertExpressionAst firstConvert = null;1177            while (expr is AttributedExpressionAst)1178            {1179                if (expr is ConvertExpressionAst && !((ConvertExpressionAst)expr).IsRef())1180                {1181                    firstConvert = (ConvertExpressionAst)expr;1182                    break;1183                }1184 1185                expr = ((AttributedExpressionAst)expr).Child;1186            }1187 1188            return firstConvert?.Type.TypeName.GetReflectionType();1189        }1190 1191        internal static PSMethodInvocationConstraints CombineTypeConstraintForMethodResolution(Type targetType, Type argType)1192        {1193            if (targetType is null && argType is null)1194            {1195                return null;1196            }1197 1198            return new PSMethodInvocationConstraints(targetType, new[] { argType });1199        }1200 

Showing the first 1,200 of 7080 lines. Download the file for the rest.