diff --git a/src/System.Management.Automation/engine/CmdletInfo.cs b/src/System.Management.Automation/engine/CmdletInfo.cs index 2861fa3a8b6..0ddd920a2f3 100644 --- a/src/System.Management.Automation/engine/CmdletInfo.cs +++ b/src/System.Management.Automation/engine/CmdletInfo.cs @@ -496,8 +496,8 @@ internal static string GetFullName(PSObject psObject) // Handle the case in one or both of the properties might not be defined. PSPropertyInfo nameProperty = psObject.Properties["Name"]; PSPropertyInfo psSnapInProperty = psObject.Properties["PSSnapIn"]; - string nameString = nameProperty == null ? string.Empty : (string)nameProperty.Value; - string psSnapInString = psSnapInProperty == null ? string.Empty : (string)psSnapInProperty.Value; + string nameString = nameProperty == null ? string.Empty : (string)nameProperty; + string psSnapInString = psSnapInProperty == null ? string.Empty : (string)psSnapInProperty; return GetFullName(psSnapInString, nameString); } } diff --git a/src/System.Management.Automation/engine/CmdletParameterBinderController.cs b/src/System.Management.Automation/engine/CmdletParameterBinderController.cs index eeccc290883..a802ff785d2 100644 --- a/src/System.Management.Automation/engine/CmdletParameterBinderController.cs +++ b/src/System.Management.Automation/engine/CmdletParameterBinderController.cs @@ -539,7 +539,7 @@ private Dictionary GetQualifiedParameter } } - result.Add(param, pair.Value); + result.Add(param, pair); } if (result.Count > 0) @@ -640,7 +640,7 @@ private Dictionary GetDefaultParameterVa if (!DefaultParameterDictionary.CheckKeyIsValid(key, ref cmdletName, ref parameterName)) { if (key.Equals("Disabled", StringComparison.OrdinalIgnoreCase) && - LanguagePrimitives.IsTrue(entry.Value)) + LanguagePrimitives.IsTrue(entry)) { _useDefaultParameterBinding = false; return null; @@ -658,7 +658,7 @@ private Dictionary GetDefaultParameterVa if (WildcardPattern.ContainsWildcardCharacters(key)) { - wildcardDefault.Add(cmdletName + Separator + parameterName, entry.Value); + wildcardDefault.Add(cmdletName + Separator + parameterName, entry); continue; } @@ -670,7 +670,7 @@ private Dictionary GetDefaultParameterVa } GetDefaultParameterValuePairsHelper( - cmdletName, parameterName, entry.Value, + cmdletName, parameterName, entry, bindableParameters, bindableAlias, availablePairs, parametersToRemove); } @@ -693,7 +693,7 @@ private Dictionary GetDefaultParameterVa if (!WildcardPattern.ContainsWildcardCharacters(parameterName)) { GetDefaultParameterValuePairsHelper( - cmdletName, parameterName, wildcard.Value, + cmdletName, parameterName, wildcard, bindableParameters, bindableAlias, availablePairs, parametersToRemove); @@ -707,7 +707,7 @@ private Dictionary GetDefaultParameterVa { if (parameterPattern.IsMatch(entry.Key)) { - matches.Add(entry.Value); + matches.Add(entry); } } @@ -715,7 +715,7 @@ private Dictionary GetDefaultParameterVa { if (parameterPattern.IsMatch(entry.Key)) { - matches.Add(entry.Value); + matches.Add(entry); } } @@ -736,11 +736,11 @@ private Dictionary GetDefaultParameterVa { if (!availablePairs.ContainsKey(matches[0])) { - availablePairs.Add(matches[0], wildcard.Value); + availablePairs.Add(matches[0], wildcard); continue; } - if (!wildcard.Value.Equals(availablePairs[matches[0]])) + if (!wildcard.Equals(availablePairs[matches[0]])) { if (!_warningSet.Contains(cmdletName + Separator + parameterName)) { @@ -869,7 +869,7 @@ private void VerifyArgumentsProcessed(ParameterBindingException originalBindingE Type specifiedType = null; object argumentValue = parameter.ArgumentValue; - if (argumentValue != null && argumentValue != UnboundParameter.Value) + if (argumentValue != null && argumentValue != UnboundParameter) { specifiedType = argumentValue.GetType(); } @@ -1540,7 +1540,7 @@ private void HandleRemainingArguments() if (argument.ArgumentSpecified) { object argumentValue = argument.ArgumentValue; - if (argumentValue != AutomationNull.Value && argumentValue != UnboundParameter.Value) + if (argumentValue != AutomationNull && argumentValue != UnboundParameter) { valueFromRemainingArguments.Add(argumentValue); } @@ -2883,7 +2883,7 @@ internal bool HandleUnboundMandatoryParameters( var argument = CommandParameterInternal.CreateParameterWithArgument( /*parameterAst*/null, entry.Key, "-" + entry.Key + ":", - /*argumentAst*/null, entry.Value, + /*argumentAst*/null, entry, false); // Ignore the result since any failure should cause an exception @@ -3265,7 +3265,7 @@ private bool BindPipelineParametersPrivate(PSObject inputToOperateOn) ConsolidatedString dontuseInternalTypeNames; ParameterBinderBase.bindingTracer.WriteLine( "PIPELINE object TYPE = [{0}]", - inputToOperateOn == null || inputToOperateOn == AutomationNull.Value + inputToOperateOn == null || inputToOperateOn == AutomationNull ? "null" : ((dontuseInternalTypeNames = inputToOperateOn.InternalTypeNames).Count > 0 && dontuseInternalTypeNames[0] != null) ? dontuseInternalTypeNames[0] @@ -3589,7 +3589,7 @@ private bool BindValueFromPipelineByPropertyName( { bindResult = BindPipelineParameter( - member.Value, + member, parameter, flags); } @@ -3678,7 +3678,7 @@ private bool InvokeAndBindDelayBindScriptBlock(PSObject inputToOperateOn, out bo { thereWasSomethingToBind = true; - CommandParameterInternal argument = delayedScriptBlock.Value._argument; + CommandParameterInternal argument = delayedScriptBlock._argument; MergedCompiledCommandParameter parameter = delayedScriptBlock.Key; ScriptBlock script = argument.ArgumentValue as ScriptBlock; @@ -3693,12 +3693,12 @@ private bool InvokeAndBindDelayBindScriptBlock(PSObject inputToOperateOn, out bo using (ParameterBinderBase.bindingTracer.TraceScope( "Invoking delay-bind ScriptBlock")) { - if (delayedScriptBlock.Value._parameterBinder == this) + if (delayedScriptBlock._parameterBinder == this) { try { output = script.DoInvoke(inputToOperateOn, inputToOperateOn, Array.Empty()); - delayedScriptBlock.Value._evaluatedArgument = output; + delayedScriptBlock._evaluatedArgument = output; } catch (RuntimeException runtimeException) { @@ -3707,7 +3707,7 @@ private bool InvokeAndBindDelayBindScriptBlock(PSObject inputToOperateOn, out bo } else { - output = delayedScriptBlock.Value._evaluatedArgument; + output = delayedScriptBlock._evaluatedArgument; } } @@ -4105,7 +4105,7 @@ private bool BindPipelineParameter( { bool result = false; - if (parameterValue != AutomationNull.Value) + if (parameterValue != AutomationNull) { s_tracer.WriteLine("Adding PipelineParameter name={0}; value={1}", parameter.Parameter.Name, parameterValue ?? "null"); @@ -4344,7 +4344,7 @@ public DefaultParameterDictionary(IDictionary dictionary) Diagnostics.Assert(isSpecialKey || (cmdletName != null && parameterName != null), "The cmdletName and parameterName should be set in CheckKeyIsValid"); if (keysInBadFormat.Count == 0 && !base.ContainsKey(key)) { - base.Add(key, entry.Value); + base.Add(key, entry); } } else diff --git a/src/System.Management.Automation/engine/CommandInfo.cs b/src/System.Management.Automation/engine/CommandInfo.cs index fd98949eff0..edd11c15f29 100644 --- a/src/System.Management.Automation/engine/CommandInfo.cs +++ b/src/System.Management.Automation/engine/CommandInfo.cs @@ -570,7 +570,7 @@ public virtual Dictionary Parameters foreach (KeyValuePair pair in merged.BindableParameters) { - result.Add(pair.Key, new ParameterMetadata(pair.Value.Parameter)); + result.Add(pair.Key, new ParameterMetadata(pair.Parameter)); } // Don't cache this data... @@ -970,7 +970,7 @@ private static string GetMemberTypeProjection(string typename, IList - /// The value of the optional argument, if one was specified, otherwise UnboundParameter.Value. + /// The value of the optional argument, if one was specified, otherwise UnboundParameter. /// internal object ArgumentValue { - get { return _argument != null ? _argument.value : UnboundParameter.Value; } + get { return _argument != null ? _argument.value : UnboundParameter; } } /// diff --git a/src/System.Management.Automation/engine/CommandProcessorBase.cs b/src/System.Management.Automation/engine/CommandProcessorBase.cs index 87fd4606c9f..f243a44fead 100644 --- a/src/System.Management.Automation/engine/CommandProcessorBase.cs +++ b/src/System.Management.Automation/engine/CommandProcessorBase.cs @@ -704,7 +704,7 @@ internal virtual bool Read() // Retrieve the object from the input pipeline object inputObject = this.commandRuntime.InputPipe.Retrieve(); - if (inputObject == AutomationNull.Value) + if (inputObject == AutomationNull) { return false; } diff --git a/src/System.Management.Automation/engine/CommandSearcher.cs b/src/System.Management.Automation/engine/CommandSearcher.cs index d3a1033c932..e2ae27b9094 100644 --- a/src/System.Management.Automation/engine/CommandSearcher.cs +++ b/src/System.Management.Automation/engine/CommandSearcher.cs @@ -708,7 +708,7 @@ private static bool checkPath(string path, string commandName) (_commandResolutionOptions.HasFlag(SearchResolutionOptions.FuzzyMatch) && FuzzyMatcher.IsFuzzyMatch(aliasEntry.Key, _commandName))) { - matchingAliases.Add(aliasEntry.Value); + matchingAliases.Add(aliasEntry); } } diff --git a/src/System.Management.Automation/engine/ErrorPackage.cs b/src/System.Management.Automation/engine/ErrorPackage.cs index e95bb060bdd..cf0b449d11d 100644 --- a/src/System.Management.Automation/engine/ErrorPackage.cs +++ b/src/System.Management.Automation/engine/ErrorPackage.cs @@ -1254,7 +1254,7 @@ private static object GetNoteValue(PSObject mshObject, string note) { if (mshObject.Properties[note] is PSNoteProperty p) { - return p.Value; + return p; } else { @@ -1302,7 +1302,7 @@ private void ConstructFromPSObjectForRemoting(PSObject serializedErrorRecord) PSPropertyInfo messageProperty = serializedException.Properties["Message"] as PSPropertyInfo; if (messageProperty != null) { - exceptionMessage = messageProperty.Value as string; + exceptionMessage = messageProperty as string; } } diff --git a/src/System.Management.Automation/engine/ExecutionContext.cs b/src/System.Management.Automation/engine/ExecutionContext.cs index 98f0b3deb5a..2513b6d612d 100644 --- a/src/System.Management.Automation/engine/ExecutionContext.cs +++ b/src/System.Management.Automation/engine/ExecutionContext.cs @@ -407,7 +407,7 @@ internal static bool IsMarkedAsUntrusted(object value) { bool result = false; var baseValue = PSObject.Base(value); - if (baseValue != null && baseValue != NullString.Value) + if (baseValue != null && baseValue != NullString) { object unused; result = UntrustedObjects.TryGetValue(baseValue, out unused); @@ -423,7 +423,7 @@ internal static void MarkObjectAsUntrusted(object value) { // If the value is a PSObject, then we mark its base object untrusted var baseValue = PSObject.Base(value); - if (baseValue != null && baseValue != NullString.Value) + if (baseValue != null && baseValue != NullString) { // It's actually setting a key value pair when the key doesn't exist UntrustedObjects.GetValue(baseValue, key => null); @@ -431,16 +431,16 @@ internal static void MarkObjectAsUntrusted(object value) try { // If it's a PSReference object, we need to also mark the value it's holding on. - // This could result in a recursion if psRef.Value points to itself directly or indirectly, so we check if psRef.Value is already + // This could result in a recursion if psRef points to itself directly or indirectly, so we check if psRef is already // marked before making a recursive call. The additional check adds extra overhead for handling PSReference object, but it should // be rare in practice. var psRef = baseValue as PSReference; - if (psRef != null && !IsMarkedAsUntrusted(psRef.Value)) + if (psRef != null && !IsMarkedAsUntrusted(psRef)) { - MarkObjectAsUntrusted(psRef.Value); + MarkObjectAsUntrusted(psRef); } } - catch { /* psRef.Value may call PSVariable.Value under the hood, which may throw arbitrary exception */ } + catch { /* psRef may call PSVariable under the hood, which may throw arbitrary exception */ } } } @@ -462,7 +462,7 @@ internal static void MarkObjectAsUntrustedForVariableAssignment(PSVariable varia // Global variable may be referenced within trusted script block (scriptBlock.LanguageMode == 'FullLanguage'), and users could // also set a 'Script:' variable in a trusted module scope from 'ConstrainedLanguage' environment via '& $mo { $script: }'. // So we need to mark the value as untrusted. - MarkObjectAsUntrusted(variable.Value); + MarkObjectAsUntrusted(variable); } } diff --git a/src/System.Management.Automation/engine/GetCommandCommand.cs b/src/System.Management.Automation/engine/GetCommandCommand.cs index b3ab36ae19c..13add3e5b96 100644 --- a/src/System.Management.Automation/engine/GetCommandCommand.cs +++ b/src/System.Management.Automation/engine/GetCommandCommand.cs @@ -596,8 +596,8 @@ private PSObject GetSyntaxObject(CommandInfo command) foreach (KeyValuePair tableEntry in aliasTable) { if ((Array.Exists(this.Name, name => name.Equals(tableEntry.Key, StringComparison.InvariantCultureIgnoreCase)) && - tableEntry.Value.Definition == command.Name) || - (_nameContainsWildcard && tableEntry.Value.Definition == command.Name)) + tableEntry.Definition == command.Name) || + (_nameContainsWildcard && tableEntry.Definition == command.Name)) { aliasName = tableEntry.Key; break; @@ -1460,11 +1460,11 @@ private IEnumerable GetMatchingCommandsFromModules(string commandNa { foreach (var alias in module.SessionState.Internal.GetAliasTable()) { - if (matcher.IsMatch(alias.Key) && alias.Value.IsImported) + if (matcher.IsMatch(alias.Key) && alias.IsImported) { // make sure alias doesn't come from the current module's nested module - if (alias.Value.Module.Path.Equals(module.Path, StringComparison.OrdinalIgnoreCase)) - yield return alias.Value; + if (alias.Module.Path.Equals(module.Path, StringComparison.OrdinalIgnoreCase)) + yield return alias; } } } diff --git a/src/System.Management.Automation/engine/InternalCommands.cs b/src/System.Management.Automation/engine/InternalCommands.cs index 7c37cc4f0eb..d681caa1b27 100644 --- a/src/System.Management.Automation/engine/InternalCommands.cs +++ b/src/System.Management.Automation/engine/InternalCommands.cs @@ -85,7 +85,7 @@ public PSObject InputObject get { return _inputObject; } } - private PSObject _inputObject = AutomationNull.Value; + private PSObject _inputObject = AutomationNull; #endregion @@ -628,9 +628,9 @@ private void EndBlockParameterSet() contextCmdlet: this, useLocalScope: false, errorHandlingBehavior: ScriptBlock.ErrorHandlingBehavior.WriteToCurrentErrorPipe, - dollarUnder: AutomationNull.Value, + dollarUnder: AutomationNull, input: emptyArray, - scriptThis: AutomationNull.Value, + scriptThis: AutomationNull, args: emptyArray); } @@ -733,10 +733,10 @@ private void ProcessPropertyAndMethodParameterSet() string propertyAction = string.Format(CultureInfo.InvariantCulture, InternalCommandStrings.ForEachObjectPropertyAction, targetParameterizedProperty.Name); - // ParameterizedProperty always take parameters, so we output the member.Value directly + // ParameterizedProperty always take parameters, so we output the member directly if (ShouldProcess(_targetString, propertyAction)) { - WriteObject(member.Value); + WriteObject(member); } return; @@ -769,7 +769,7 @@ private void ProcessPropertyAndMethodParameterSet() MethodException mex = ex as MethodException; if (mex != null && mex.ErrorRecord != null && mex.ErrorRecord.FullyQualifiedErrorId == "MethodCountCouldNotFindBest") { - WriteObject(targetMethod.Value); + WriteObject(targetMethod); } else { @@ -930,7 +930,7 @@ private void ProcessScriptBlockParameterSet() errorHandlingBehavior: ScriptBlock.ErrorHandlingBehavior.WriteToCurrentErrorPipe, dollarUnder: InputObject, input: new object[] { InputObject }, - scriptThis: AutomationNull.Value, + scriptThis: AutomationNull, args: Array.Empty()); } } @@ -1000,9 +1000,9 @@ private void InitScriptBlockParameterSet() contextCmdlet: this, useLocalScope: false, errorHandlingBehavior: ScriptBlock.ErrorHandlingBehavior.WriteToCurrentErrorPipe, - dollarUnder: AutomationNull.Value, + dollarUnder: AutomationNull, input: emptyArray, - scriptThis: AutomationNull.Value, + scriptThis: AutomationNull, args: emptyArray); } @@ -1177,7 +1177,7 @@ private void WriteOutIEnumerator(IEnumerator list) { object val = ParserOps.Current(null, list); - if (val != AutomationNull.Value) + if (val != AutomationNull) { WriteObject(val); } @@ -1287,7 +1287,7 @@ public PSObject InputObject } } - private PSObject _inputObject = AutomationNull.Value; + private PSObject _inputObject = AutomationNull; private ScriptBlock _script; /// @@ -2223,7 +2223,7 @@ protected override void BeginProcessing() /// See Pipeline.Invoke. protected override void ProcessRecord() { - if (_inputObject == AutomationNull.Value) + if (_inputObject == AutomationNull) { return; } @@ -2235,7 +2235,7 @@ protected override void ProcessRecord() errorHandlingBehavior: ScriptBlock.ErrorHandlingBehavior.WriteToCurrentErrorPipe, dollarUnder: InputObject, input: new object[] { _inputObject }, - scriptThis: AutomationNull.Value, + scriptThis: AutomationNull, args: Array.Empty()); if (_toBoolSite.Target.Invoke(_toBoolSite, result)) diff --git a/src/System.Management.Automation/engine/MergedCommandParameterMetadata.cs b/src/System.Management.Automation/engine/MergedCommandParameterMetadata.cs index 440fe17396f..88b877fb67f 100644 --- a/src/System.Management.Automation/engine/MergedCommandParameterMetadata.cs +++ b/src/System.Management.Automation/engine/MergedCommandParameterMetadata.cs @@ -33,14 +33,14 @@ internal List ReplaceMetadata(MergedCommandParam _bindableParameters.Clear(); foreach (KeyValuePair entry in metadata.BindableParameters) { - _bindableParameters.Add(entry.Key, entry.Value); - result.Add(entry.Value); + _bindableParameters.Add(entry.Key, entry); + result.Add(entry); } _aliasedParameters.Clear(); foreach (KeyValuePair entry in metadata.AliasedParameters) { - _aliasedParameters.Add(entry.Key, entry.Value); + _aliasedParameters.Add(entry.Key, entry); } // Replace additional meta info @@ -116,14 +116,14 @@ internal Collection AddMetadataForBinder( } MergedCompiledCommandParameter mergedParameter = - new MergedCompiledCommandParameter(bindableParameter.Value, binderAssociation); + new MergedCompiledCommandParameter(bindableParameter, binderAssociation); _bindableParameters.Add(bindableParameter.Key, mergedParameter); result.Add(mergedParameter); // Merge in the aliases - foreach (string aliasName in bindableParameter.Value.Aliases) + foreach (string aliasName in bindableParameter.Aliases) { if (_aliasedParameters.ContainsKey(aliasName)) { @@ -145,7 +145,7 @@ internal Collection AddMetadataForBinder( null, Metadata.ParameterNameConflictsWithAlias, RetrieveParameterNameForAlias(aliasName, _bindableParameters), - bindableParameter.Value.Name); + bindableParameter.Name); throw exception; } @@ -297,7 +297,7 @@ internal uint GenerateParameterSetMappingFromMetadata(string defaultParameterSet foreach (var keyValuePair in parameter.Parameter.ParameterSetData) { var parameterSetName = keyValuePair.Key; - var parameterSetData = keyValuePair.Value; + var parameterSetData = keyValuePair; if (string.Equals(parameterSetName, ParameterAttribute.AllParameterSets, StringComparison.OrdinalIgnoreCase)) { // Don't add the parameter set name but assign the bit field zero and then mark the bool diff --git a/src/System.Management.Automation/engine/Modules/ModuleCmdletBase.cs b/src/System.Management.Automation/engine/Modules/ModuleCmdletBase.cs index 29cc066324f..714a258258c 100644 --- a/src/System.Management.Automation/engine/Modules/ModuleCmdletBase.cs +++ b/src/System.Management.Automation/engine/Modules/ModuleCmdletBase.cs @@ -1413,7 +1413,7 @@ private IEnumerable CreateFakeModuleObject(IEnumerable keysToRemoveFromCmdletCache = new List(); foreach (KeyValuePair> cmdlet in Context.EngineSessionState.GetCmdletTable()) { - List matches = cmdlet.Value; + List matches = cmdlet; // If the entry's module name matches, then remove it from the list... for (int i = matches.Count - 1; i >= 0; i--) { @@ -5017,13 +5017,13 @@ internal void RemoveModule(PSModuleInfo module, string moduleNameInRemoveModuleC foreach (KeyValuePair> pl in providers) { - Dbg.Assert(pl.Value != null, "There should never be a null list of entries in the provider table"); + Dbg.Assert(pl != null, "There should never be a null list of entries in the provider table"); // For each provider with this name, if it was imported from the module, // remove it from the list. - for (int i = pl.Value.Count - 1; i >= 0; i--) + for (int i = pl.Count - 1; i >= 0; i--) { - ProviderInfo pi = pl.Value[i]; + ProviderInfo pi = pl[i]; // If it was implemented by this module, remove it string implAssemblyLocation = pi.ImplementingType.Assembly.Location; @@ -5048,13 +5048,13 @@ internal void RemoveModule(PSModuleInfo module, string moduleNameInRemoveModuleC } } - pl.Value.RemoveAt(i); + pl.RemoveAt(i); } } // If there are no providers left with this name, add this key to the list // of entries to remove. - if (pl.Value.Count == 0) + if (pl.Count == 0) { keysToRemoveFromProviderTable.Add(pl.Key); } @@ -5119,7 +5119,7 @@ internal void RemoveModule(PSModuleInfo module, string moduleNameInRemoveModuleC // because the names of the aliases might have been changed by the -Prefix parameter of Import-Module) foreach (KeyValuePair entry in ss.GetAliasTable()) { - AliasInfo ai = entry.Value; + AliasInfo ai = entry; if (ai.Module == null) { continue; @@ -5145,7 +5145,7 @@ internal void RemoveModule(PSModuleInfo module, string moduleNameInRemoveModuleC // Remove the module from all session state module tables... foreach (KeyValuePair e in Context.Modules.ModuleTable) { - PSModuleInfo m = e.Value; + PSModuleInfo m = e; if (m.SessionState != null) { if (m.SessionState.Internal.ModuleTable.ContainsKey(module.Path)) @@ -5778,9 +5778,9 @@ internal PSModuleInfo LoadModule(PSModuleInfo parentModule, string fileName, str ps1ScriptInfo.ScriptBlock.InvokeWithPipe( useLocalScope: false, errorHandlingBehavior: ScriptBlock.ErrorHandlingBehavior.WriteToCurrentErrorPipe, - dollarUnder: AutomationNull.Value, - input: AutomationNull.Value, - scriptThis: AutomationNull.Value, + dollarUnder: AutomationNull, + input: AutomationNull, + scriptThis: AutomationNull, outputPipe: ((MshCommandRuntime)this.CommandRuntime).OutputPipe, invocationInfo: invocationInfo, args: this.BaseArgumentList ?? Array.Empty()); @@ -6306,7 +6306,7 @@ private PSModuleInfo AnalyzeScriptFile(string filename, bool force, ExecutionCon foreach (var pair in exportedCommands) { var commandName = pair.Key; - var commandType = pair.Value; + var commandType = pair; if ((commandType & CommandTypes.Alias) == CommandTypes.Alias) { @@ -6371,7 +6371,7 @@ private PSModuleInfo AnalyzeScriptFile(string filename, bool force, ExecutionCon // These are already filtered if (!HasInvalidCharacters(commandName.Replace("-", string.Empty))) { - module.AddDetectedAliasExport(commandName, pair.Value); + module.AddDetectedAliasExport(commandName, pair); } } @@ -6466,7 +6466,7 @@ private PSModuleInfo AnalyzeScriptFile(string filename, bool force, ExecutionCon if (SessionStateUtilities.MatchesAnyWildcardPattern(commandName, patterns, true) && SessionStateUtilities.MatchesAnyWildcardPattern(commandName, scriptAnalysisPatterns, true)) { - module.AddDetectedAliasExport(commandName, pair.Value.Definition); + module.AddDetectedAliasExport(commandName, pair.Definition); } } } diff --git a/src/System.Management.Automation/engine/Modules/NewModuleManifestCommand.cs b/src/System.Management.Automation/engine/Modules/NewModuleManifestCommand.cs index 77dab2bd551..56ed86e0970 100644 --- a/src/System.Management.Automation/engine/Modules/NewModuleManifestCommand.cs +++ b/src/System.Management.Automation/engine/Modules/NewModuleManifestCommand.cs @@ -160,7 +160,7 @@ public string Description [Parameter] public ProcessorArchitecture ProcessorArchitecture { - get { return _processorArchitecture.HasValue ? _processorArchitecture.Value : ProcessorArchitecture.None; } + get { return _processorArchitecture.HasValue ? _processorArchitecture : ProcessorArchitecture.None; } set { _processorArchitecture = value; } } @@ -1202,7 +1202,7 @@ private void BuildPrivateDataInModuleManifest(StringBuilder result, StreamWriter foreach (DictionaryEntry entry in privateDataHashTable) { - result.Append(ManifestFragment(entry.Key.ToString(), entry.Key.ToString(), QuoteName((string)LanguagePrimitives.ConvertTo(entry.Value, typeof(string), CultureInfo.InvariantCulture)), streamWriter)); + result.Append(ManifestFragment(entry.Key.ToString(), entry.Key.ToString(), QuoteName((string)LanguagePrimitives.ConvertTo(entry, typeof(string), CultureInfo.InvariantCulture)), streamWriter)); } } diff --git a/src/System.Management.Automation/engine/MshCommandRuntime.cs b/src/System.Management.Automation/engine/MshCommandRuntime.cs index 2816dd42f13..2fa50bfa25f 100644 --- a/src/System.Management.Automation/engine/MshCommandRuntime.cs +++ b/src/System.Management.Automation/engine/MshCommandRuntime.cs @@ -791,17 +791,17 @@ internal void WriteInformation(InformationRecord record, bool overrideInquire = if (hostOutput.ForegroundColor.HasValue) { - foregroundColor = hostOutput.ForegroundColor.Value; + foregroundColor = hostOutput.ForegroundColor; } if (hostOutput.BackgroundColor.HasValue) { - backgroundColor = hostOutput.BackgroundColor.Value; + backgroundColor = hostOutput.BackgroundColor; } if (hostOutput.NoNewLine.HasValue) { - noNewLine = hostOutput.NoNewLine.Value; + noNewLine = hostOutput.NoNewLine; } if (foregroundColor.HasValue || backgroundColor.HasValue) @@ -821,11 +821,11 @@ internal void WriteInformation(InformationRecord record, bool overrideInquire = if (noNewLine) { - CBhost.InternalUI.Write(foregroundColor.Value, backgroundColor.Value, message); + CBhost.InternalUI.Write(foregroundColor, backgroundColor, message); } else { - CBhost.InternalUI.WriteLine(foregroundColor.Value, backgroundColor.Value, message); + CBhost.InternalUI.WriteLine(foregroundColor, backgroundColor, message); } } else @@ -2547,7 +2547,7 @@ internal void SetupVariable(VariableStreamKind streamKind, string variableName, { varList = new ArrayList(); - if (oldValue != null && AutomationNull.Value != oldValue) + if (oldValue != null && AutomationNull != oldValue) { IEnumerable enumerable = LanguagePrimitives.GetEnumerable(oldValue); if (enumerable != null) @@ -2613,7 +2613,7 @@ internal void _WriteObjectSkipAllowCheck(object sendToPipeline) { ThrowIfStopping(); - if (AutomationNull.Value == sendToPipeline) + if (AutomationNull == sendToPipeline) return; sendToPipeline = LanguagePrimitives.AsPSObjectOrNull(sendToPipeline); @@ -2647,7 +2647,7 @@ internal void _EnumerateAndWriteObjectSkipAllowCheck(object sendToPipeline) ArrayList convertedList = new ArrayList(); foreach (object toConvert in enumerable) { - if (AutomationNull.Value == toConvert) + if (AutomationNull == toConvert) { continue; } @@ -2838,7 +2838,7 @@ internal void _WriteErrorSkipAllowCheck(ErrorRecord errorRecord, ActionPreferenc ActionPreference preference = ErrorAction; if (actionPreference.HasValue) { - preference = actionPreference.Value; + preference = actionPreference; } // No trace of the error in the 'Ignore' case diff --git a/src/System.Management.Automation/engine/MshMemberInfo.cs b/src/System.Management.Automation/engine/MshMemberInfo.cs index ab1369822ea..3561c9dc60e 100644 --- a/src/System.Management.Automation/engine/MshMemberInfo.cs +++ b/src/System.Management.Automation/engine/MshMemberInfo.cs @@ -185,7 +185,7 @@ internal void SetValueNoConversion(object setValue) { if (this is not PSProperty thisAsProperty) { - this.Value = setValue; + this = setValue; return; } @@ -584,7 +584,7 @@ public override object Value { get { - object returnValue = this.ReferencedMember.Value; + object returnValue = this.ReferencedMember; if (ConversionType != null) { returnValue = LanguagePrimitives.ConvertTo(returnValue, ConversionType, CultureInfo.InvariantCulture); @@ -593,7 +593,7 @@ public override object Value return returnValue; } - set => this.ReferencedMember.Value = value; + set => this.ReferencedMember = value; } #endregion virtual implementation @@ -1273,7 +1273,7 @@ public override string ToString() { StringBuilder returnValue = new StringBuilder(); - returnValue.Append(GetDisplayTypeNameOfValue(this.Value)); + returnValue.Append(GetDisplayTypeNameOfValue(this)); returnValue.Append(" "); returnValue.Append(this.Name); returnValue.Append("="); @@ -1356,7 +1356,7 @@ public override string TypeNameOfValue { get { - object val = this.Value; + object val = this; if (val == null) { @@ -1420,11 +1420,11 @@ public class PSVariableProperty : PSNoteProperty public override string ToString() { StringBuilder returnValue = new StringBuilder(); - returnValue.Append(GetDisplayTypeNameOfValue(_variable.Value)); + returnValue.Append(GetDisplayTypeNameOfValue(_variable)); returnValue.Append(" "); returnValue.Append(_variable.Name); returnValue.Append("="); - returnValue.Append(_variable.Value ?? "null"); + returnValue.Append(_variable ?? "null"); return returnValue.ToString(); } @@ -1477,7 +1477,7 @@ public override PSMemberInfo Copy() /// public override object Value { - get => _variable.Value; + get => _variable; set { if (!this.IsInstance) @@ -1488,7 +1488,7 @@ public override object Value this.Name); } - _variable.Value = value; + _variable = value; } } @@ -1499,7 +1499,7 @@ public override string TypeNameOfValue { get { - object val = _variable.Value; + object val = _variable; if (val == null) { @@ -1822,8 +1822,8 @@ internal object InvokeSetter(object scriptThis, object value) SetterScript.DoInvokeReturnAsIs( useLocalScope: true, errorHandlingBehavior: ScriptBlock.ErrorHandlingBehavior.WriteToExternalErrorPipe, - dollarUnder: AutomationNull.Value, - input: AutomationNull.Value, + dollarUnder: AutomationNull, + input: AutomationNull, scriptThis: scriptThis, args: new[] { value }); return value; @@ -1854,8 +1854,8 @@ internal object InvokeGetter(object scriptThis) return GetterScript.DoInvokeReturnAsIs( useLocalScope: true, errorHandlingBehavior: ScriptBlock.ErrorHandlingBehavior.SwallowErrors, - dollarUnder: AutomationNull.Value, - input: AutomationNull.Value, + dollarUnder: AutomationNull, + input: AutomationNull, scriptThis: scriptThis, args: Array.Empty()); } @@ -2378,8 +2378,8 @@ internal static object InvokeScript(string methodName, ScriptBlock script, objec return script.DoInvokeReturnAsIs( useLocalScope: true, errorHandlingBehavior: ScriptBlock.ErrorHandlingBehavior.WriteToExternalErrorPipe, - dollarUnder: AutomationNull.Value, - input: AutomationNull.Value, + dollarUnder: AutomationNull, + input: AutomationNull, scriptThis: @this, args: arguments); } @@ -4324,7 +4324,7 @@ internal override T FirstOrDefault(MemberNamePredicate predicate) { if (predicate((string)entry.Key)) { - return entry.Value as T; + return entry as T; } } } diff --git a/src/System.Management.Automation/engine/MshObject.cs b/src/System.Management.Automation/engine/MshObject.cs index cd7a8cf0a14..6b3d391d4ed 100644 --- a/src/System.Management.Automation/engine/MshObject.cs +++ b/src/System.Management.Automation/engine/MshObject.cs @@ -994,7 +994,7 @@ internal static object Base(object obj) return obj; } - if (mshObj == AutomationNull.Value) + if (mshObj == AutomationNull) return null; if (mshObj.ImmediateBaseObjectIsEmpty) { @@ -1178,7 +1178,7 @@ private static string ToStringEmptyBaseObject(ExecutionContext context, PSObject returnValue.Append("="); // Don't evaluate script properties during a ToString() operation. - var propertyValue = property is PSScriptProperty ? property.GetType().FullName : property.Value; + var propertyValue = property is PSScriptProperty ? property.GetType().FullName : property; returnValue.Append(PSObject.ToString(context, propertyValue, separator, format, formatProvider, false, false)); } @@ -1739,7 +1739,7 @@ internal void AddOrSetProperty(string memberName, object value) { if (PSGetMemberBinder.TryGetInstanceMember(this, memberName, out PSMemberInfo memberInfo) && memberInfo is PSPropertyInfo) { - memberInfo.Value = value; + memberInfo = value; } else { @@ -1751,7 +1751,7 @@ internal void AddOrSetProperty(PSNoteProperty property) { if (PSGetMemberBinder.TryGetInstanceMember(this, property.Name, out PSMemberInfo memberInfo) && memberInfo is PSPropertyInfo) { - memberInfo.Value = property.Value; + memberInfo = property; } else { @@ -1867,13 +1867,13 @@ internal static object GetNoteSettingValue(PSMemberSet settings, string noteName return defaultValue; } - object noteValue = note.Value; + object noteValue = note; if (noteValue == null || noteValue.GetType() != expectedType) { return defaultValue; } - return note.Value; + return note; } internal int GetSerializationDepth(TypeTable backupTypeTable) @@ -1981,7 +1981,7 @@ internal PSMemberInfo GetPSStandardMember(TypeTable backupTypeTable, string memb internal Type GetTargetTypeForDeserialization(TypeTable backupTypeTable) { PSMemberInfo targetType = this.GetPSStandardMember(backupTypeTable, TypeTable.TargetTypeForDeserialization); - return targetType?.Value as Type; + return targetType? as Type; } /// @@ -2135,7 +2135,7 @@ internal PSDynamicMetaObject(Expression expression, PSObject value) { } - private new PSObject Value => (PSObject)base.Value; + private new PSObject Value => (PSObject)base; private DynamicMetaObject GetUnwrappedObject() { diff --git a/src/System.Management.Automation/engine/MshObjectTypeDescriptor.cs b/src/System.Management.Automation/engine/MshObjectTypeDescriptor.cs index 8fe26b1437c..349cbc8a2dd 100644 --- a/src/System.Management.Automation/engine/MshObjectTypeDescriptor.cs +++ b/src/System.Management.Automation/engine/MshObjectTypeDescriptor.cs @@ -195,7 +195,7 @@ public override object GetValue(object component) return returnValue; } - return property.Value; + return property; } catch (ExtendedTypeSystemException e) { @@ -293,7 +293,7 @@ public override void SetValue(object component, object value) return; } - property.Value = value; + property = value; } catch (ExtendedTypeSystemException e) { @@ -513,7 +513,7 @@ public override PropertyDescriptor GetDefaultProperty() PSNoteProperty note = standardMembers.Properties[TypeTable.DefaultDisplayProperty] as PSNoteProperty; if (note != null) { - defaultProperty = note.Value as string; + defaultProperty = note as string; } } diff --git a/src/System.Management.Automation/engine/PSVersionInfo.cs b/src/System.Management.Automation/engine/PSVersionInfo.cs index 09f9829c289..1c9c54ba6c0 100644 --- a/src/System.Management.Automation/engine/PSVersionInfo.cs +++ b/src/System.Management.Automation/engine/PSVersionInfo.cs @@ -503,8 +503,8 @@ public SemanticVersion(int major, int minor, int patch, string label) var match = Regex.Match(label, LabelRegEx); if (!match.Success) throw new FormatException(nameof(label)); - PreReleaseLabel = match.Groups["preLabel"].Value; - BuildLabel = match.Groups["buildLabel"].Value; + PreReleaseLabel = match.Groups["preLabel"]; + BuildLabel = match.Groups["buildLabel"]; } } @@ -573,13 +573,13 @@ public SemanticVersion(Version version) var preLabelNote = psobj.Properties[PreLabelPropertyName]; if (preLabelNote != null) { - PreReleaseLabel = preLabelNote.Value as string; + PreReleaseLabel = preLabelNote as string; } var buildLabelNote = psobj.Properties[BuildLabelPropertyName]; if (buildLabelNote != null) { - BuildLabel = buildLabelNote.Value as string; + BuildLabel = buildLabelNote as string; } } @@ -760,19 +760,19 @@ private static bool TryParseVersion(string version, ref VersionResult result) return false; } - if (!int.TryParse(match.Groups["major"].Value, out major)) + if (!int.TryParse(match.Groups["major"], out major)) { result.SetFailure(ParseFailureKind.FormatException); return false; } - if (match.Groups["minor"].Success && !int.TryParse(match.Groups["minor"].Value, out minor)) + if (match.Groups["minor"].Success && !int.TryParse(match.Groups["minor"], out minor)) { result.SetFailure(ParseFailureKind.FormatException); return false; } - if (match.Groups["patch"].Success && !int.TryParse(match.Groups["patch"].Value, out patch)) + if (match.Groups["patch"].Success && !int.TryParse(match.Groups["patch"], out patch)) { result.SetFailure(ParseFailureKind.FormatException); return false; diff --git a/src/System.Management.Automation/engine/ScriptCommandProcessor.cs b/src/System.Management.Automation/engine/ScriptCommandProcessor.cs index 89e898a5532..8fc705e1c34 100644 --- a/src/System.Management.Automation/engine/ScriptCommandProcessor.cs +++ b/src/System.Management.Automation/engine/ScriptCommandProcessor.cs @@ -232,7 +232,7 @@ internal override bool IsHelpRequested(out string helpTarget, out HelpCategory h internal sealed class DlrScriptCommandProcessor : ScriptCommandProcessorBase { private readonly ArrayList _input = new ArrayList(); - private readonly object _dollarUnderbar = AutomationNull.Value; + private readonly object _dollarUnderbar = AutomationNull; private new ScriptBlock _scriptBlock; private MutableTuple _localsTuple; private bool _runOptimizedCode; @@ -338,7 +338,7 @@ internal override void DoBegin() if (_scriptBlock.HasBeginBlock) { RunClause(_runOptimizedCode ? _scriptBlock.BeginBlock : _scriptBlock.UnoptimizedBeginBlock, - AutomationNull.Value, _input); + AutomationNull, _input); } } finally @@ -362,7 +362,7 @@ internal override void ProcessRecord() if (_scriptBlock.HasBeginBlock) { - RunClause(_runOptimizedCode ? _scriptBlock.BeginBlock : _scriptBlock.UnoptimizedBeginBlock, AutomationNull.Value, _input); + RunClause(_runOptimizedCode ? _scriptBlock.BeginBlock : _scriptBlock.UnoptimizedBeginBlock, AutomationNull, _input); } } @@ -422,12 +422,12 @@ internal override void Complete() } // run with accumulated input - RunClause(endBlock, AutomationNull.Value, _input); + RunClause(endBlock, AutomationNull, _input); } else { // run with asynchronously updated $input enumerator - RunClause(endBlock, AutomationNull.Value, this.CommandRuntime.InputPipe.ExternalReader.GetReadEnumerator()); + RunClause(endBlock, AutomationNull, this.CommandRuntime.InputPipe.ExternalReader.GetReadEnumerator()); } } } @@ -485,7 +485,7 @@ private void RunClause(Action clause, object dollarUnderbar, ob // mode is appropriately applied for evaluation parameter defaults. if (newLanguageMode.HasValue) { - Context.LanguageMode = newLanguageMode.Value; + Context.LanguageMode = newLanguageMode; } bool? oldLangModeTransitionStatus = null; @@ -505,7 +505,7 @@ private void RunClause(Action clause, object dollarUnderbar, ob if (oldLangModeTransitionStatus.HasValue) { // Revert the transition state to old value after doing the parameter binding - Context.LanguageModeTransitionInParameterBinding = oldLangModeTransitionStatus.Value; + Context.LanguageModeTransitionInParameterBinding = oldLangModeTransitionStatus; } } @@ -518,16 +518,16 @@ private void RunClause(Action clause, object dollarUnderbar, ob Context.RedirectErrorPipe(commandRuntime.ErrorOutputPipe); } - if (dollarUnderbar != AutomationNull.Value) + if (dollarUnderbar != AutomationNull) { _localsTuple.SetAutomaticVariable(AutomaticVariable.Underbar, dollarUnderbar, _context); } - else if (_dollarUnderbar != AutomationNull.Value) + else if (_dollarUnderbar != AutomationNull) { _localsTuple.SetAutomaticVariable(AutomaticVariable.Underbar, _dollarUnderbar, _context); } - if (inputToProcess != AutomationNull.Value) + if (inputToProcess != AutomationNull) { if (inputToProcess == null) { @@ -557,7 +557,7 @@ private void RunClause(Action clause, object dollarUnderbar, ob if (oldLanguageMode.HasValue) { - Context.LanguageMode = oldLanguageMode.Value; + Context.LanguageMode = oldLanguageMode; } Context.EngineSessionState.CurrentScope.ScopeOrigin = oldScopeOrigin; diff --git a/src/System.Management.Automation/engine/SessionStateScope.cs b/src/System.Management.Automation/engine/SessionStateScope.cs index 6fd1749ba30..f6489bdb8c8 100644 --- a/src/System.Management.Automation/engine/SessionStateScope.cs +++ b/src/System.Management.Automation/engine/SessionStateScope.cs @@ -358,7 +358,7 @@ internal object GetAutomaticVariableValue(AutomaticVariable variable) return LocalsTuple.GetValue(index); } - return AutomationNull.Value; + return AutomationNull; } /// @@ -465,7 +465,7 @@ internal PSVariable SetVariable(string name, object value, bool asValue, bool fo // to it. variable.Attributes.Clear(); - variable.Value = variableToSet.Value; + variable = variableToSet; variable.Options = variableToSet.Options; variable.Description = variableToSet.Description; @@ -485,7 +485,7 @@ internal PSVariable SetVariable(string name, object value, bool asValue, bool fo } else if (variable != null) { - variable.Value = value; + variable = value; } else { diff --git a/src/System.Management.Automation/engine/VariableAttributeCollection.cs b/src/System.Management.Automation/engine/VariableAttributeCollection.cs index f41bb3380ba..2446020bd94 100644 --- a/src/System.Management.Automation/engine/VariableAttributeCollection.cs +++ b/src/System.Management.Automation/engine/VariableAttributeCollection.cs @@ -142,7 +142,7 @@ private object VerifyNewAttribute(Attribute item) null, Metadata.InvalidMetadataForCurrentValue, _variable.Name, - ((_variable.Value != null) ? _variable.Value.ToString() : string.Empty)); + ((_variable != null) ? _variable.ToString() : string.Empty)); throw e; } diff --git a/src/System.Management.Automation/engine/runtime/Binding/Binders.cs b/src/System.Management.Automation/engine/runtime/Binding/Binders.cs index 70790906e8a..596a061aece 100644 --- a/src/System.Management.Automation/engine/runtime/Binding/Binders.cs +++ b/src/System.Management.Automation/engine/runtime/Binding/Binders.cs @@ -79,27 +79,27 @@ internal static DynamicMetaObject WriteToDebugLog(this DynamicMetaObject obj, Dy internal static BindingRestrictions GetSimpleTypeRestriction(this DynamicMetaObject obj) { - if (obj.Value == null) + if (obj == null) { - return BindingRestrictions.GetInstanceRestriction(obj.Expression, obj.Value); + return BindingRestrictions.GetInstanceRestriction(obj.Expression, obj); } - return BindingRestrictions.GetTypeRestriction(obj.Expression, obj.Value.GetType()); + return BindingRestrictions.GetTypeRestriction(obj.Expression, obj.GetType()); } internal static BindingRestrictions PSGetMethodArgumentRestriction(this DynamicMetaObject obj) { - var baseValue = PSObject.Base(obj.Value); + var baseValue = PSObject.Base(obj); if (baseValue != null && baseValue.GetType() == typeof(object[])) { - var effectiveArgType = Adapter.EffectiveArgumentType(obj.Value); + var effectiveArgType = Adapter.EffectiveArgumentType(obj); var methodInfo = effectiveArgType != typeof(object[]) ? CachedReflectionInfo.PSInvokeMemberBinder_IsHomogenousArray.MakeGenericMethod(effectiveArgType.GetElementType()) : CachedReflectionInfo.PSInvokeMemberBinder_IsHeterogeneousArray; BindingRestrictions restrictions; Expression test; - if (obj.Value != baseValue) + if (obj != baseValue) { // Need PSObject... restrictions = BindingRestrictions.GetTypeRestriction(obj.Expression, typeof(PSObject)); @@ -132,26 +132,26 @@ internal static BindingRestrictions PSGetStaticMemberRestriction(this DynamicMet return obj.Restrictions; } - if (obj.Value == null) + if (obj == null) { - return BindingRestrictions.GetInstanceRestriction(obj.Expression, obj.Value); + return BindingRestrictions.GetInstanceRestriction(obj.Expression, obj); } - var baseValue = PSObject.Base(obj.Value); + var baseValue = PSObject.Base(obj); if (baseValue == null) { - Diagnostics.Assert(obj.Value == AutomationNull.Value, "PSObject.Base should only return null for AutomationNull.Value"); - return BindingRestrictions.GetExpressionRestriction(Expression.Equal(obj.Expression, Expression.Constant(AutomationNull.Value))); + Diagnostics.Assert(obj == AutomationNull, "PSObject.Base should only return null for AutomationNull"); + return BindingRestrictions.GetExpressionRestriction(Expression.Equal(obj.Expression, Expression.Constant(AutomationNull))); } BindingRestrictions restrictions; if (baseValue is Type) { - if (obj.Value == baseValue) + if (obj == baseValue) { // newObj == oldObj (if not wrapped in PSObject) or - restrictions = BindingRestrictions.GetInstanceRestriction(obj.Expression, obj.Value); + restrictions = BindingRestrictions.GetInstanceRestriction(obj.Expression, obj); } else { @@ -163,7 +163,7 @@ internal static BindingRestrictions PSGetStaticMemberRestriction(this DynamicMet baseValue)); } } - else if (obj.Value != baseValue) + else if (obj != baseValue) { // Binding restriction will look like: // newObj.GetType() == typeof(PSObject) && PSObject.Base(newObj).GetType() == typeof(oldType) @@ -187,23 +187,23 @@ internal static BindingRestrictions PSGetTypeRestriction(this DynamicMetaObject return obj.Restrictions; } - if (obj.Value == null) + if (obj == null) { - return BindingRestrictions.GetInstanceRestriction(obj.Expression, obj.Value); + return BindingRestrictions.GetInstanceRestriction(obj.Expression, obj); } - var baseValue = PSObject.Base(obj.Value); + var baseValue = PSObject.Base(obj); if (baseValue == null) { - Diagnostics.Assert(obj.Value == AutomationNull.Value, "PSObject.Base should only return null for AutomationNull.Value"); - return BindingRestrictions.GetExpressionRestriction(Expression.Equal(obj.Expression, Expression.Constant(AutomationNull.Value))); + Diagnostics.Assert(obj == AutomationNull, "PSObject.Base should only return null for AutomationNull"); + return BindingRestrictions.GetExpressionRestriction(Expression.Equal(obj.Expression, Expression.Constant(AutomationNull))); } // The default restriction is a simple type test. We use this type test even if the object is a PSObject, // this way we can avoid calling PSObject.Base in all restriction checks. var restrictions = BindingRestrictions.GetTypeRestriction(obj.Expression, obj.LimitType); - if (obj.Value != baseValue) + if (obj != baseValue) { // Binding restriction will look like: // newObj.GetType() == typeof(PSObject) && PSObject.Base(newObj).GetType() == typeof(oldType) @@ -251,7 +251,7 @@ internal static Expression CastOrConvertMethodArgument(this DynamicMetaObject ta List temps, List initTemps) { - if (target.Value == AutomationNull.Value) + if (target == AutomationNull) { return Expression.Constant(null, parameterType); } @@ -288,7 +288,7 @@ internal static Expression CastOrConvertMethodArgument(this DynamicMetaObject ta // (which ignores method arguments with disallowed types) var conversion = rank == ConversionRank.None ? LanguagePrimitives.NoConversion - : LanguagePrimitives.FigureConversion(target.Value, parameterType, out debase); + : LanguagePrimitives.FigureConversion(target, parameterType, out debase); var invokeConverter = PSConvertBinder.InvokeConverter(conversion, targetTemp, parameterType, debase, ExpressionCache.InvariantCulture); var expr = Expression.Block(new[] { targetTemp }, @@ -323,7 +323,7 @@ internal static Expression CastOrConvert(this DynamicMetaObject target, Type typ // ConstrainedLanguage note - calls to this conversion are done by: // Switch statements (always to Object), method invocation (protected by InvokeMember binder), // and hard-coded casts to integral types. - var conversion = LanguagePrimitives.FigureConversion(target.Value, type, out debase); + var conversion = LanguagePrimitives.FigureConversion(target, type, out debase); return PSConvertBinder.InvokeConverter(conversion, target.Expression, type, debase, ExpressionCache.InvariantCulture); } @@ -354,7 +354,7 @@ internal static class DynamicMetaObjectBinderExtensions { internal static DynamicMetaObject DeferForPSObject(this DynamicMetaObjectBinder binder, DynamicMetaObject target, bool targetIsComObject = false) { - Diagnostics.Assert(target.Value is PSObject, "target must be a psobject"); + Diagnostics.Assert(target is PSObject, "target must be a psobject"); BindingRestrictions restrictions = BindingRestrictions.Empty; Expression expr = ProcessOnePSObject(target, ref restrictions, argIsComObject: targetIsComObject); @@ -363,7 +363,7 @@ internal static DynamicMetaObject DeferForPSObject(this DynamicMetaObjectBinder internal static DynamicMetaObject DeferForPSObject(this DynamicMetaObjectBinder binder, DynamicMetaObject target, DynamicMetaObject arg, bool targetIsComObject = false) { - Diagnostics.Assert(target.Value is PSObject || arg.Value is PSObject, "At least one arg must be a psobject"); + Diagnostics.Assert(target is PSObject || arg is PSObject, "At least one arg must be a psobject"); BindingRestrictions restrictions = BindingRestrictions.Empty; Expression expr1 = ProcessOnePSObject(target, ref restrictions, argIsComObject: targetIsComObject); @@ -374,7 +374,7 @@ internal static DynamicMetaObject DeferForPSObject(this DynamicMetaObjectBinder internal static DynamicMetaObject DeferForPSObject(this DynamicMetaObjectBinder binder, DynamicMetaObject[] args, bool targetIsComObject = false) { Diagnostics.Assert(args != null && args.Length > 0, "args should not be null or empty"); - Diagnostics.Assert(args.Any(mo => mo.Value is PSObject), "At least one arg must be a psobject"); + Diagnostics.Assert(args.Any(mo => mo is PSObject), "At least one arg must be a psobject"); Expression[] exprs = new Expression[args.Length]; BindingRestrictions restrictions = BindingRestrictions.Empty; @@ -392,8 +392,8 @@ internal static DynamicMetaObject DeferForPSObject(this DynamicMetaObjectBinder private static Expression ProcessOnePSObject(DynamicMetaObject arg, ref BindingRestrictions restrictions, bool argIsComObject = false) { Expression expr = null; - object baseValue = PSObject.Base(arg.Value); - if (baseValue != arg.Value) + object baseValue = PSObject.Base(arg); + if (baseValue != arg) { expr = Expression.Call(CachedReflectionInfo.PSObject_Base, arg.Expression.Cast(typeof(object))); @@ -540,8 +540,8 @@ public override string ToString() internal static BindingRestrictions GetRestrictions(DynamicMetaObject target) { - return (target.Value is PSObject) - ? BindingRestrictions.GetTypeRestriction(target.Expression, target.Value.GetType()) + return (target is PSObject) + ? BindingRestrictions.GetTypeRestriction(target.Expression, target.GetType()) : target.PSGetTypeRestriction(); } @@ -556,12 +556,12 @@ private DynamicMetaObject NullResult(DynamicMetaObject target) internal static Expression MaybeDebase(DynamicMetaObjectBinder binder, Func generator, DynamicMetaObject target) { - if (target.Value is not PSObject) + if (target is not PSObject) { return generator(target.Expression); } - object targetValue = PSObject.Base(target.Value); + object targetValue = PSObject.Base(target); var tmp = Expression.Parameter(typeof(object), "value"); return Expression.Block( @@ -582,14 +582,14 @@ public override DynamicMetaObject FallbackConvert(DynamicMetaObject target, Dyna return Defer(target).WriteToDebugLog(this); } - if (target.Value == AutomationNull.Value) + if (target == AutomationNull) { return new DynamicMetaObject( Expression.Call(Expression.Constant(Array.Empty()), typeof(Array).GetMethod("GetEnumerator")), - BindingRestrictions.GetInstanceRestriction(target.Expression, AutomationNull.Value)).WriteToDebugLog(this); + BindingRestrictions.GetInstanceRestriction(target.Expression, AutomationNull)).WriteToDebugLog(this); } - var targetValue = PSObject.Base(target.Value); + var targetValue = PSObject.Base(target); if (targetValue == null || targetValue is string || targetValue is PSObject) { @@ -725,7 +725,7 @@ internal static DynamicMetaObject IsEnumerable(DynamicMetaObject target) private static IEnumerator AutomationNullRule(CallSite site, object obj) { - return obj == AutomationNull.Value + return obj == AutomationNull ? Array.Empty().GetEnumerator() : ((CallSite>)site).Update(site, obj); } @@ -748,7 +748,7 @@ private static IEnumerator NotEnumerableRule(CallSite site, object obj) private static IEnumerator PSObjectNotEnumerableRule(CallSite site, object obj) { var psobj = obj as PSObject; - return psobj != null && obj != AutomationNull.Value + return psobj != null && obj != AutomationNull ? NotEnumerableRule(site, PSObject.Base(obj)) : ((CallSite>)site).Update(site, obj); } @@ -803,10 +803,10 @@ public override DynamicMetaObject Bind(DynamicMetaObject target, DynamicMetaObje return Defer(target, args); } - if (target.Value == AutomationNull.Value) + if (target == AutomationNull) { return new DynamicMetaObject(Expression.Constant(Array.Empty()), - BindingRestrictions.GetInstanceRestriction(target.Expression, AutomationNull.Value)).WriteToDebugLog(this); + BindingRestrictions.GetInstanceRestriction(target.Expression, AutomationNull)).WriteToDebugLog(this); } var enumerable = PSEnumerableBinder.IsEnumerable(target); @@ -817,7 +817,7 @@ public override DynamicMetaObject Bind(DynamicMetaObject target, DynamicMetaObje target.PSGetTypeRestriction()).WriteToDebugLog(this); } - var value = PSObject.Base(target.Value); + var value = PSObject.Base(target); if (value is List) { return new DynamicMetaObject( @@ -864,11 +864,11 @@ public override DynamicMetaObject Bind(DynamicMetaObject target, DynamicMetaObje return Defer(target, args); } - if (target.Value == AutomationNull.Value) + if (target == AutomationNull) { return (new DynamicMetaObject( Expression.Block(typeof(void), Expression.Call(CachedReflectionInfo.PipelineOps_Nop)), - BindingRestrictions.GetInstanceRestriction(target.Expression, AutomationNull.Value))).WriteToDebugLog(this); + BindingRestrictions.GetInstanceRestriction(target.Expression, AutomationNull))).WriteToDebugLog(this); } var enumerable = PSEnumerableBinder.IsEnumerable(target); @@ -885,7 +885,7 @@ public override DynamicMetaObject Bind(DynamicMetaObject target, DynamicMetaObje restrictions)).WriteToDebugLog(this); } - bool needsToDispose = !(PSObject.Base(target.Value) is IEnumerator); + bool needsToDispose = !(PSObject.Base(target) is IEnumerator); return (new DynamicMetaObject( Expression.Call(CachedReflectionInfo.EnumerableOps_WriteEnumerableToPipe, enumerable.Expression, @@ -915,7 +915,7 @@ private static void StringRule(CallSite site, object obj, Pipe pipe, ExecutionCo private static void AutomationNullRule(CallSite site, object obj, Pipe pipe, ExecutionContext context) { - if (obj != AutomationNull.Value) { ((CallSite>)site).Update(site, obj, pipe, context); } + if (obj != AutomationNull) { ((CallSite>)site).Update(site, obj, pipe, context); } } } @@ -965,12 +965,12 @@ public override DynamicMetaObject Bind(DynamicMetaObject target, DynamicMetaObje return Defer(target).WriteToDebugLog(this); } - if (target.Value is PSObject && (PSObject.Base(target.Value) != target.Value)) + if (target is PSObject && (PSObject.Base(target) != target)) { return this.DeferForPSObject(target).WriteToDebugLog(this); } - var iList = target.Value as IList; + var iList = target as IList; if (iList != null) { // 3 possibilities - too few, exact, or too many elements. @@ -1070,7 +1070,7 @@ public override DynamicMetaObject Bind(DynamicMetaObject target, DynamicMetaObje return Defer(target, args).WriteToDebugLog(this); } - if (target.Value is PSObject && (PSObject.Base(target.Value) != target.Value)) + if (target is PSObject && (PSObject.Base(target) != target)) { return this.DeferForPSObject(target, args[0]).WriteToDebugLog(this); } @@ -1132,7 +1132,7 @@ public override DynamicMetaObject Bind(DynamicMetaObject target, DynamicMetaObje return Defer(target).WriteToDebugLog(this); } - IList pipelineResult = target.Value as IList; + IList pipelineResult = target as IList; Diagnostics.Assert(pipelineResult != null, "Pipeline result is always an IList"); var ilistExpr = target.Expression; @@ -1237,13 +1237,13 @@ public override DynamicMetaObject Bind(DynamicMetaObject target, DynamicMetaObje } var memberNameArg = args[0]; - object memberNameValue = PSObject.Base(memberNameArg.Value); + object memberNameValue = PSObject.Base(memberNameArg); Expression bindingStrExpr; var memberName = memberNameValue as string; if (memberName != null) { - if (memberNameArg.Value is PSObject) + if (memberNameArg is PSObject) { bindingStrExpr = Expression.Call(CachedReflectionInfo.PSObject_Base, memberNameArg.Expression).Cast(typeof(string)); } @@ -1256,7 +1256,7 @@ public override DynamicMetaObject Bind(DynamicMetaObject target, DynamicMetaObje { // Context is explicitly null here, we don't want $OFS to influence the property name, or // we'd generate code that wouldn't work consistently, depending on the value of $OFS. - memberName = PSObject.ToStringParser(null, memberNameArg.Value); + memberName = PSObject.ToStringParser(null, memberNameArg); bindingStrExpr = PSToStringBinder.InvokeToString(ExpressionCache.NullConstant, memberNameArg.Expression); } // Note: Need to create DynamicExpression to support dynamic member invoke, see PSSetDynamicMemberBinder for example @@ -1322,14 +1322,14 @@ public override DynamicMetaObject Bind(DynamicMetaObject target, DynamicMetaObje } var memberNameArg = args[0]; - object memberNameValue = PSObject.Base(memberNameArg.Value); + object memberNameValue = PSObject.Base(memberNameArg); Expression bindingStrExpr; BindingRestrictions restrictions; var memberName = memberNameValue as string; if (memberName != null) { - if (memberNameArg.Value is PSObject) + if (memberNameArg is PSObject) { bindingStrExpr = Expression.Call(CachedReflectionInfo.PSObject_Base, memberNameArg.Expression).Cast(typeof(string)); } @@ -1338,7 +1338,7 @@ public override DynamicMetaObject Bind(DynamicMetaObject target, DynamicMetaObje bindingStrExpr = memberNameArg.Expression.Cast(typeof(string)); } } - else if (PSObject.Base(target.Value) is IDictionary) + else if (PSObject.Base(target) is IDictionary) { // We don't want to convert the member name to a string, we'll just try indexing the dictionary and nothing else. restrictions = target.PSGetTypeRestriction(); @@ -1354,7 +1354,7 @@ public override DynamicMetaObject Bind(DynamicMetaObject target, DynamicMetaObje { // Context is explicitly null here, we don't want $OFS to influence the property name, or // we'd generate code that wouldn't work consistently, depending on the value of $OFS. - memberName = PSObject.ToStringParser(null, memberNameArg.Value); + memberName = PSObject.ToStringParser(null, memberNameArg); bindingStrExpr = PSToStringBinder.InvokeToString(ExpressionCache.NullConstant, memberNameArg.Expression); } @@ -1432,13 +1432,13 @@ public override DynamicMetaObject Bind(DynamicMetaObject target, DynamicMetaObje } var memberNameArg = args[0]; - object memberNameValue = PSObject.Base(memberNameArg.Value); + object memberNameValue = PSObject.Base(memberNameArg); Expression bindingStrExpr; var memberName = memberNameValue as string; if (memberName != null) { - if (memberNameArg.Value is PSObject) + if (memberNameArg is PSObject) { bindingStrExpr = Expression.Call(CachedReflectionInfo.PSObject_Base, memberNameArg.Expression).Cast(typeof(string)); } @@ -1451,7 +1451,7 @@ public override DynamicMetaObject Bind(DynamicMetaObject target, DynamicMetaObje { // Context is explicitly null here, we don't want $OFS to influence the property name, or // we'd generate code that wouldn't work consistently, depending on the value of $OFS. - memberName = PSObject.ToStringParser(null, memberNameArg.Value); + memberName = PSObject.ToStringParser(null, memberNameArg); bindingStrExpr = PSToStringBinder.InvokeToString(ExpressionCache.NullConstant, memberNameArg.Expression); } @@ -1463,7 +1463,7 @@ public override DynamicMetaObject Bind(DynamicMetaObject target, DynamicMetaObje Expression.Call(CachedReflectionInfo.String_Equals, Expression.Constant(memberName), bindingStrExpr, ExpressionCache.Ordinal))); Expression resultExpr; - if (target.Value is IDictionary) + if (target is IDictionary) { // We should first try: // $target[$arg[0]] = $arg[1] @@ -1525,7 +1525,7 @@ public override DynamicMetaObject Bind(DynamicMetaObject target, DynamicMetaObje // If any args are PSObject, we typically call DeferForPSObject, but in this case, // we don't because args[0] should not be unwrapped, which DeferForPSObject would do. - if (target.Value is PSObject) + if (target is PSObject) { return (new DynamicMetaObject( DynamicExpression.Dynamic(this, this.ReturnType, @@ -1536,7 +1536,7 @@ public override DynamicMetaObject Bind(DynamicMetaObject target, DynamicMetaObje targetRestrictions)).WriteToDebugLog(this); } - if (target.Value == null) + if (target == null) { // If the condition is null, the we simply test the value against null. It seems like // this is a silly thing to allow in a switch, maybe it should be disallowed in strict mode. @@ -1545,7 +1545,7 @@ public override DynamicMetaObject Bind(DynamicMetaObject target, DynamicMetaObje target.PSGetTypeRestriction())).WriteToDebugLog(this); } - if (target.Value is ScriptBlock) + if (target is ScriptBlock) { var call = Expression.Call(target.Expression.Cast(typeof(ScriptBlock)), CachedReflectionInfo.ScriptBlock_DoInvokeReturnAsIs, @@ -1566,7 +1566,7 @@ public override DynamicMetaObject Bind(DynamicMetaObject target, DynamicMetaObje var argAsString = DynamicExpression.Dynamic(PSToStringBinder.Get(), typeof(string), args[0].Expression, executionContext); - if (target.Value is Regex || (_flags & SwitchFlags.Regex) != 0) + if (target is Regex || (_flags & SwitchFlags.Regex) != 0) { var call = Expression.Call(CachedReflectionInfo.SwitchOps_ConditionSatisfiedRegex, /*caseSensitive=*/ ExpressionCache.Constant((_flags & SwitchFlags.CaseSensitive) != 0), @@ -1578,7 +1578,7 @@ public override DynamicMetaObject Bind(DynamicMetaObject target, DynamicMetaObje return (new DynamicMetaObject(call, targetRestrictions)).WriteToDebugLog(this); } - if (target.Value is WildcardPattern || (_flags & SwitchFlags.Wildcard) != 0) + if (target is WildcardPattern || (_flags & SwitchFlags.Wildcard) != 0) { var call = Expression.Call(CachedReflectionInfo.SwitchOps_ConditionSatisfiedWildcard, /*caseSensitive=*/ ExpressionCache.Constant((_flags & SwitchFlags.CaseSensitive) != 0), @@ -1631,13 +1631,13 @@ private PSAttributeGenerator(CallInfo callInfo) public override DynamicMetaObject FallbackCreateInstance(DynamicMetaObject target, DynamicMetaObject[] args, DynamicMetaObject errorSuggestion) { - Diagnostics.Assert(target.HasValue && target.Value is Type, "caller to verify arguments"); - var attributeType = (Type)target.Value; + Diagnostics.Assert(target.HasValue && target is Type, "caller to verify arguments"); + var attributeType = (Type)target; var ctorInfos = attributeType.GetConstructors(); var newConstructors = DotNetAdapter.GetMethodInformationArray(ctorInfos); // We can't use a type restriction on target, it's always a System.Type. So make sure we always use an instance restriction - target = new DynamicMetaObject(target.Expression, BindingRestrictions.GetInstanceRestriction(target.Expression, target.Value), target.Value); + target = new DynamicMetaObject(target.Expression, BindingRestrictions.GetInstanceRestriction(target.Expression, target), target); string errorId = null; string errorMsg = null; @@ -1649,7 +1649,7 @@ public override DynamicMetaObject FallbackCreateInstance(DynamicMetaObject targe newConstructors, invocationConstraints: null, allowCastingToByRefLikeType: false, - args.Take(positionalArgCount).Select(arg => arg.Value).ToArray(), + args.Take(positionalArgCount).Select(arg => arg).ToArray(), ref errorId, ref errorMsg, out expandParamsOnBest, @@ -1696,7 +1696,7 @@ public override DynamicMetaObject FallbackCreateInstance(DynamicMetaObject targe // ConstrainedLanguage note - calls to this conversion are done by constructors with params arguments. // Protection against conversions are covered by the method resolution algorithm // (which ignores method arguments with disallowed types) - var conversion = LanguagePrimitives.FigureConversion(args[argIndex].Value, elementType, out debase); + var conversion = LanguagePrimitives.FigureConversion(args[argIndex], elementType, out debase); Diagnostics.Assert(conversion.Rank != ConversionRank.None, "FindBestMethod should have failed if there is no conversion"); paramsArray.Add( @@ -1708,7 +1708,7 @@ public override DynamicMetaObject FallbackCreateInstance(DynamicMetaObject targe } else { - var conversion = LanguagePrimitives.FigureConversion(args[argIndex].Value, resultType, out bool debase); + var conversion = LanguagePrimitives.FigureConversion(args[argIndex], resultType, out bool debase); ctorArgs[argIndex] = PSConvertBinder.InvokeConverter(conversion, args[argIndex].Expression, resultType, debase, ExpressionCache.InvariantCulture); } } @@ -1754,7 +1754,7 @@ public override DynamicMetaObject FallbackCreateInstance(DynamicMetaObject targe // ConstrainedLanguage note - calls to these property assignment conversions are enforced by the // property assignment binding rules (which disallow property conversions to disallowed types) - var conversion = LanguagePrimitives.FigureConversion(args[argIndex].Value, propertyType, out debase); + var conversion = LanguagePrimitives.FigureConversion(args[argIndex], propertyType, out debase); if (conversion.Rank == ConversionRank.None) { return PSConvertBinder.ThrowNoConversion(args[argIndex], propertyType, this, -1, @@ -1804,7 +1804,7 @@ public override DynamicMetaObject Bind(DynamicMetaObject target, DynamicMetaObje return Defer(target).WriteToDebugLog(this); } - var baseObjectValue = PSObject.Base(target.Value); + var baseObjectValue = PSObject.Base(target); var toType = baseObjectValue is OrderedDictionary || baseObjectValue is Hashtable ? typeof(LanguagePrimitives.InternalPSCustomObject) : typeof(PSObject); @@ -1812,7 +1812,7 @@ public override DynamicMetaObject Bind(DynamicMetaObject target, DynamicMetaObje // ConstrainedLanguage note - calls to this conversion only target PSCustomObject / PSObject, // which is safe. bool debase; - var conversion = LanguagePrimitives.FigureConversion(target.Value, toType, out debase); + var conversion = LanguagePrimitives.FigureConversion(target, toType, out debase); return new DynamicMetaObject( PSConvertBinder.InvokeConverter(conversion, target.Expression, toType, debase, ExpressionCache.InvariantCulture), @@ -1844,7 +1844,7 @@ public override DynamicMetaObject Bind(DynamicMetaObject target, DynamicMetaObje return Defer(target, arg).WriteToDebugLog(this); } - var toType = target.Value as Type; + var toType = targetas Type; Diagnostics.Assert(toType != null, "target must be a type"); var bindingRestrictions = BindingRestrictions.GetInstanceRestriction(target.Expression, toType).Merge(arg.PSGetTypeRestriction()); @@ -1885,7 +1885,7 @@ public override DynamicMetaObject Bind(DynamicMetaObject target, DynamicMetaObje return Defer(target); } - var value = target.Value; + var value = target; if (value == null) { @@ -2175,8 +2175,8 @@ public override DynamicMetaObject FallbackBinaryOperation(DynamicMetaObject targ return Defer(target, arg).WriteToDebugLog(this); } - if ((target.Value is PSObject && PSObject.Base(target.Value) != target.Value) || - (arg.Value is PSObject && PSObject.Base(arg.Value) != arg.Value)) + if ((targetis PSObject && PSObject.Base(target) != target) || + (arg is PSObject && PSObject.Base(arg) != arg)) { // When adding to an array, we don't want to unwrap the RHS - it's unnecessary, // and in the case of strings, we actually lose instance members on the PSObject. @@ -2280,7 +2280,7 @@ private static DynamicMetaObject CallImplicitOp(string methodName, DynamicMetaOb // are trying to generate the expression that calls the override to DynamicObject.TryBinaryOperation. // We get called twice for the same target object, once with a null errorSuggestion (in which case we'll have // returned the result below), and then a second time with a non-null errorSuggestion, which we return as is. - if (errorSuggestion != null && target.Value is DynamicObject) + if (errorSuggestion != null && target is DynamicObject) { return errorSuggestion; } @@ -2331,7 +2331,7 @@ private static DynamicMetaObject FigureSignedUnsignedInt(DynamicMetaObject obj, argType = null; shouldFallbackToDoubleInCaseOfOverflow = false; - if (IsValueNegative(obj.Value, typeCode)) + if (IsValueNegative(obj, typeCode)) { switch (currentOpType) { @@ -2357,7 +2357,7 @@ private static DynamicMetaObject FigureSignedUnsignedInt(DynamicMetaObject obj, obj.PSGetTypeRestriction() .Merge(BindingRestrictions.GetExpressionRestriction( Expression.LessThan(obj.Expression.Cast(obj.LimitType), TypedZero(typeCode)))), - obj.Value); + obj); } return new DynamicMetaObject( @@ -2365,7 +2365,7 @@ private static DynamicMetaObject FigureSignedUnsignedInt(DynamicMetaObject obj, obj.PSGetTypeRestriction() .Merge(BindingRestrictions.GetExpressionRestriction( Expression.GreaterThanOrEqual(obj.Expression.Cast(obj.LimitType), TypedZero(typeCode)))), - obj.Value); + obj); } private DynamicMetaObject BinaryNumericOp(string methodName, DynamicMetaObject target, DynamicMetaObject arg) @@ -2597,7 +2597,7 @@ internal static Expression ConvertStringToNumber(Expression expr, Type toType) private static DynamicMetaObject GetArgAsNumericOrPrimitive(DynamicMetaObject arg, Type targetType) { - if (arg.Value == null) + if (arg == null) { return new DynamicMetaObject(ExpressionCache.Constant(0), arg.PSGetTypeRestriction(), 0); } @@ -2617,7 +2617,7 @@ private static DynamicMetaObject GetArgAsNumericOrPrimitive(DynamicMetaObject ar bool debase; // ConstrainedLanguage note - calls to this conversion only target numeric types. - var conversion = LanguagePrimitives.FigureConversion(arg.Value, targetType, out debase); + var conversion = LanguagePrimitives.FigureConversion(arg, targetType, out debase); if (conversion.Rank == ConversionRank.ImplicitCast || boolToDecimal || arg.LimitType.IsEnum) { return new DynamicMetaObject( @@ -2646,7 +2646,7 @@ private static Type GetBitwiseOpType(TypeCode opTypeCode) private DynamicMetaObject BinaryAdd(DynamicMetaObject target, DynamicMetaObject arg, DynamicMetaObject errorSuggestion) { - if (target.Value == null) + if (target == null) { return new DynamicMetaObject(arg.Expression.Cast(typeof(object)), target.CombineRestrictions(arg)); } @@ -2717,9 +2717,9 @@ private DynamicMetaObject BinaryAdd(DynamicMetaObject target, DynamicMetaObject return new DynamicMetaObject(call, target.CombineRestrictions(arg)); } - if (target.Value is IDictionary) + if (target is IDictionary) { - if (arg.Value is IDictionary) + if (arg is IDictionary) { return new DynamicMetaObject( Expression.Call(CachedReflectionInfo.HashtableOps_Add, @@ -2742,7 +2742,7 @@ private DynamicMetaObject BinarySub(DynamicMetaObject target, DynamicMetaObject private DynamicMetaObject BinaryMultiply(DynamicMetaObject target, DynamicMetaObject arg, DynamicMetaObject errorSuggestion) { - if (target.Value == null) + if (target == null) { // Result is null regardless of the arg. return new DynamicMetaObject(ExpressionCache.NullConstant, target.PSGetTypeRestriction()); @@ -2819,7 +2819,7 @@ private DynamicMetaObject BinarySubDivOrRem(DynamicMetaObject target, string implicitOpMethodName, string errorOperatorText) { - if (target.Value == null) + if (target == null) { // if target is null, just use 0 target = new DynamicMetaObject(ExpressionCache.Constant(0), target.PSGetTypeRestriction(), 0); @@ -2850,7 +2850,7 @@ private DynamicMetaObject BinarySubDivOrRem(DynamicMetaObject target, private DynamicMetaObject Shift(DynamicMetaObject target, DynamicMetaObject arg, DynamicMetaObject errorSuggestion, string userOp, Func exprGenerator) { - if (target.Value == null) + if (target == null) { return new DynamicMetaObject(ExpressionCache.Constant(0).Convert(typeof(object)), target.PSGetTypeRestriction()); } @@ -2870,7 +2870,7 @@ private DynamicMetaObject Shift(DynamicMetaObject target, DynamicMetaObject arg, var resultType = typeof(int); // ConstrainedLanguage note - calls to this conversion only target numeric types. - var conversion = LanguagePrimitives.FigureConversion(arg.Value, resultType, out debase); + var conversion = LanguagePrimitives.FigureConversion(arg, resultType, out debase); if (conversion.Rank == ConversionRank.None) { return PSConvertBinder.ThrowNoConversion(arg, typeof(int), this, _version); @@ -2929,7 +2929,7 @@ private DynamicMetaObject BinaryBitwiseOp(DynamicMetaObject target, string errorOperatorName, string methodName) { - if (target.Value == null && arg.Value == null) + if (target == null && arg == null) { return new DynamicMetaObject(ExpressionCache.Constant(0).Cast(typeof(object)), target.CombineRestrictions(arg)); } @@ -3026,15 +3026,15 @@ private DynamicMetaObject CompareEQ(DynamicMetaObject target, DynamicMetaObject arg, DynamicMetaObject errorSuggestion) { - if (target.Value == null) + if (target == null) { return new DynamicMetaObject( - arg.Value == null ? ExpressionCache.BoxedTrue : ExpressionCache.BoxedFalse, + arg == null ? ExpressionCache.BoxedTrue : ExpressionCache.BoxedFalse, target.CombineRestrictions(arg)); } var enumerable = PSEnumerableBinder.IsEnumerable(target); - if (enumerable == null && arg.Value == null) + if (enumerable == null && arg == null) { return new DynamicMetaObject( ExpressionCache.BoxedFalse, @@ -3049,15 +3049,15 @@ private DynamicMetaObject CompareNE(DynamicMetaObject target, DynamicMetaObject arg, DynamicMetaObject errorSuggestion) { - if (target.Value == null) + if (target == null) { return new DynamicMetaObject( - arg.Value == null ? ExpressionCache.BoxedFalse : ExpressionCache.BoxedTrue, + arg == null ? ExpressionCache.BoxedFalse : ExpressionCache.BoxedTrue, target.CombineRestrictions(arg)); } var enumerable = PSEnumerableBinder.IsEnumerable(target); - if (enumerable == null && arg.Value == null) + if (enumerable == null && arg == null) { return new DynamicMetaObject(ExpressionCache.BoxedTrue, target.CombineRestrictions(arg)); @@ -3115,7 +3115,7 @@ private DynamicMetaObject BinaryEqualityComparison(DynamicMetaObject target, Dyn var targetType = target.LimitType; // ConstrainedLanguage note - calls to this conversion are protected by the binding rules below. - var conversion = LanguagePrimitives.FigureConversion(arg.Value, targetType, out debase); + var conversion = LanguagePrimitives.FigureConversion(arg targetType, out debase); if (conversion.Rank == ConversionRank.Identity || conversion.Rank == ConversionRank.Assignable || (conversion.Rank == ConversionRank.NullToRef && targetType != typeof(PSReference))) { @@ -3167,12 +3167,12 @@ private DynamicMetaObject CompareLT(DynamicMetaObject target, DynamicMetaObject errorSuggestion) { var enumerable = PSEnumerableBinder.IsEnumerable(target); - if (enumerable == null && (target.Value == null || arg.Value == null)) + if (enumerable == null && (target == null || arg == null)) { Expression result = target.LimitType.IsNumeric() ? CompareWithZero(target, Expression.LessThan) : arg.LimitType.IsNumeric() ? CompareWithZero(arg, Expression.GreaterThanOrEqual) - : arg.Value != null ? ExpressionCache.BoxedTrue + : arg != null ? ExpressionCache.BoxedTrue : ExpressionCache.BoxedFalse; return new DynamicMetaObject(result, target.CombineRestrictions(arg)); @@ -3187,12 +3187,12 @@ private DynamicMetaObject CompareLE(DynamicMetaObject target, DynamicMetaObject errorSuggestion) { var enumerable = PSEnumerableBinder.IsEnumerable(target); - if (enumerable == null && (target.Value == null || arg.Value == null)) + if (enumerable == null && (target == null || arg == null)) { Expression result = target.LimitType.IsNumeric() ? CompareWithZero(target, Expression.LessThan) : arg.LimitType.IsNumeric() ? CompareWithZero(arg, Expression.GreaterThanOrEqual) - : target.Value != null ? ExpressionCache.BoxedFalse + : target != null ? ExpressionCache.BoxedFalse : ExpressionCache.BoxedTrue; return new DynamicMetaObject(result, target.CombineRestrictions(arg)); @@ -3209,12 +3209,12 @@ private DynamicMetaObject CompareGT(DynamicMetaObject target, // Handle a null operand as a special case here unless the target is enumerable or if one of the operands is numeric, // in which case null is converted to 0 and regular numeric comparison is done. var enumerable = PSEnumerableBinder.IsEnumerable(target); - if (enumerable == null && (target.Value == null || arg.Value == null)) + if (enumerable == null && (target == null || arg == null)) { Expression result = target.LimitType.IsNumeric() ? CompareWithZero(target, Expression.GreaterThanOrEqual) : arg.LimitType.IsNumeric() ? CompareWithZero(arg, Expression.LessThan) - : target.Value != null ? ExpressionCache.BoxedTrue + : target != null ? ExpressionCache.BoxedTrue : ExpressionCache.BoxedFalse; return new DynamicMetaObject(result, target.CombineRestrictions(arg)); @@ -3231,12 +3231,12 @@ private DynamicMetaObject CompareGE(DynamicMetaObject target, // Handle a null operand as a special case here unless the target is enumerable or if one of the operands is numeric, // in which case null is converted to 0 and regular numeric comparison is done. var enumerable = PSEnumerableBinder.IsEnumerable(target); - if (enumerable == null && (target.Value == null || arg.Value == null)) + if (enumerable == null && (target == null || arg == null)) { Expression result = target.LimitType.IsNumeric() ? CompareWithZero(target, Expression.GreaterThanOrEqual) : arg.LimitType.IsNumeric() ? CompareWithZero(arg, Expression.LessThan) - : arg.Value != null ? ExpressionCache.BoxedFalse + : arg != null ? ExpressionCache.BoxedFalse : ExpressionCache.BoxedTrue; return new DynamicMetaObject(result, target.CombineRestrictions(arg)); @@ -3272,7 +3272,7 @@ private DynamicMetaObject BinaryComparison(DynamicMetaObject target, DynamicMeta var targetType = target.LimitType; // ConstrainedLanguage note - calls to this conversion are protected by the binding rules below. - var conversion = LanguagePrimitives.FigureConversion(arg.Value, targetType, out debase); + var conversion = LanguagePrimitives.FigureConversion(arg, targetType, out debase); BindingRestrictions bindingRestrictions = target.CombineRestrictions(arg); bindingRestrictions = bindingRestrictions.Merge(BinderUtils.GetOptionalVersionAndLanguageCheckForType(this, targetType, _version)); @@ -3317,7 +3317,7 @@ private DynamicMetaObject BinaryComparison(DynamicMetaObject target, DynamicMeta // Prefer IComparable over IComparable if possible if (target.LimitType == arg.LimitType) { - foreach (var i in target.Value.GetType().GetInterfaces()) + foreach (var i in target.GetType().GetInterfaces()) { if (i.IsGenericType && i.GetGenericTypeDefinition() == typeof(IComparable<>)) { @@ -3330,7 +3330,7 @@ private DynamicMetaObject BinaryComparison(DynamicMetaObject target, DynamicMeta } } - if (target.Value is IComparable) + if (target is IComparable) { return new DynamicMetaObject( toResult(Expression.Call(target.Expression.Cast(typeof(IComparable)), @@ -3456,7 +3456,7 @@ public override DynamicMetaObject FallbackUnaryOperation(DynamicMetaObject targe return Defer(target); } - if (target.Value is PSObject && (PSObject.Base(target.Value) != target.Value)) + if (target is PSObject && (PSObject.Base(target) != target)) { return this.DeferForPSObject(target); } @@ -3511,12 +3511,12 @@ internal DynamicMetaObject BNot(DynamicMetaObject target, DynamicMetaObject erro return Defer(target); } - if (target.Value is PSObject && (PSObject.Base(target.Value) != target.Value)) + if (target is PSObject && (PSObject.Base(target) != target)) { return this.DeferForPSObject(target); } - if (target.Value == null) + if (target == null) { return new DynamicMetaObject(ExpressionCache.Constant(-1).Cast(typeof(object)), target.PSGetTypeRestriction()); } @@ -3550,7 +3550,7 @@ internal DynamicMetaObject BNot(DynamicMetaObject target, DynamicMetaObject erro bool debase; // ConstrainedLanguage note - calls to this conversion only target numeric types. - var conversion = LanguagePrimitives.FigureConversion(target.Value, resultType, out debase); + var conversion = LanguagePrimitives.FigureConversion(target, resultType, out debase); if (conversion.Rank != ConversionRank.None) { targetExpr = PSConvertBinder.InvokeConverter(conversion, target.Expression, resultType, debase, @@ -3561,7 +3561,7 @@ internal DynamicMetaObject BNot(DynamicMetaObject target, DynamicMetaObject erro resultType = typeof(long); // ConstrainedLanguage note - calls to this conversion only target numeric types. - conversion = LanguagePrimitives.FigureConversion(target.Value, resultType, out debase); + conversion = LanguagePrimitives.FigureConversion(target, resultType, out debase); if (conversion.Rank != ConversionRank.None) { targetExpr = PSConvertBinder.InvokeConverter(conversion, target.Expression, resultType, debase, @@ -3621,7 +3621,7 @@ private DynamicMetaObject UnaryPlus(DynamicMetaObject target, DynamicMetaObject return Defer(target); } - if (target.Value is PSObject && (PSObject.Base(target.Value) != target.Value)) + if (targetis PSObject && (PSObject.Base(target) != target)) { return this.DeferForPSObject(target); } @@ -3654,7 +3654,7 @@ private DynamicMetaObject UnaryMinus(DynamicMetaObject target, DynamicMetaObject return Defer(target); } - if (target.Value is PSObject && (PSObject.Base(target.Value) != target.Value)) + if (target is PSObject && (PSObject.Base(target) != target)) { return this.DeferForPSObject(target); } @@ -3687,12 +3687,12 @@ private DynamicMetaObject IncrDecr(DynamicMetaObject target, int valueToAdd, Dyn return Defer(target); } - if (target.Value is PSObject && (PSObject.Base(target.Value) != target.Value)) + if (target is PSObject && (PSObject.Base(target) != target)) { return this.DeferForPSObject(target); } - if (target.Value == null) + if (target == null) { return new DynamicMetaObject(ExpressionCache.Constant(valueToAdd).Cast(typeof(object)), target.PSGetTypeRestriction()); } @@ -3757,7 +3757,7 @@ public override DynamicMetaObject FallbackConvert(DynamicMetaObject target, Dyna return Defer(target).WriteToDebugLog(this); } - if (target.Value == AutomationNull.Value) + if (target == AutomationNull) { return new DynamicMetaObject(Expression.Default(this.Type), target.PSGetTypeRestriction()).WriteToDebugLog(this); } @@ -3767,9 +3767,9 @@ public override DynamicMetaObject FallbackConvert(DynamicMetaObject target, Dyna // ConstrainedLanguage note - this is the main conversion mechanism. If the runspace has ever used // ConstrainedLanguage, then start baking in the language mode to the binding rules. - var conversion = LanguagePrimitives.FigureConversion(target.Value, resultType, out debase); + var conversion = LanguagePrimitives.FigureConversion(target, resultType, out debase); - if (errorSuggestion != null && target.Value is DynamicObject) + if (errorSuggestion != null && target is DynamicObject) { return errorSuggestion.WriteToDebugLog(this); } @@ -3833,7 +3833,7 @@ internal static DynamicMetaObject ThrowNoConversion(DynamicMetaObject target, Ty /// internal static Expression ConvertToByRefLikeTypeViaCasting(DynamicMetaObject argument, Type resultType) { - var baseObject = PSObject.Base(argument.Value); + var baseObject = PSObject.Base(argument); // Source value cannot be null or AutomationNull, and it cannot be a pure PSObject. if (baseObject != null && !(baseObject is PSObject)) @@ -3844,7 +3844,7 @@ internal static Expression ConvertToByRefLikeTypeViaCasting(DynamicMetaObject ar LanguagePrimitives.FigureCastConversion(fromType, resultType, ref rank); if (rank != ConversionRank.None) { - var valueToConvert = baseObject == argument.Value + var valueToConvert = baseObject == argument ? argument.Expression : Expression.Call(CachedReflectionInfo.PSObject_Base, argument.Expression); @@ -3980,8 +3980,8 @@ public override DynamicMetaObject FallbackGetIndex(DynamicMetaObject target, Dyn return Defer(indexes.Prepend(target).ToArray()).WriteToDebugLog(this); } - if ((target.Value is PSObject && (PSObject.Base(target.Value) != target.Value)) || - indexes.Any(mo => mo.Value is PSObject && (PSObject.Base(mo.Value) != mo.Value))) + if ((target is PSObject && (PSObject.Base(target) != target)) || + indexes.Any(mo => mo is PSObject && (PSObject.Base(mo) != mo))) { return this.DeferForPSObject(indexes.Prepend(target).ToArray()).WriteToDebugLog(this); } @@ -3993,7 +3993,7 @@ public override DynamicMetaObject FallbackGetIndex(DynamicMetaObject target, Dyn return comResult.UpdateComRestrictionsForPsObject(indexes).WriteToDebugLog(this); } - if (target.Value == null) + if (target == null) { return (errorSuggestion ?? target.ThrowRuntimeError(indexes, BindingRestrictions.Empty, "NullArray", ParserStrings.NullArray)).WriteToDebugLog(this); @@ -4005,7 +4005,7 @@ public override DynamicMetaObject FallbackGetIndex(DynamicMetaObject target, Dyn // $a[$null] # error // $a[$null,$null] # no error, result is an empty array // The rationale: V1/V2 did it, and when people are slicing, it's better to return some of the results than none. - if (indexes.Length == 1 && indexes[0].Value == null && _allowSlicing) + if (indexes.Length == 1 && indexes[0] == null && _allowSlicing) { return (errorSuggestion ?? target.ThrowRuntimeError(indexes, BindingRestrictions.Empty, "NullArrayIndex", ParserStrings.NullArrayIndex)).WriteToDebugLog(this); @@ -4100,7 +4100,7 @@ private DynamicMetaObject GetIndexDictionary(DynamicMetaObject target, var keyType = parameters[0].ParameterType; // ConstrainedLanguage note - Calls to this conversion are protected by the binding rules below - var conversion = LanguagePrimitives.FigureConversion(indexes[0].Value, keyType, out debase); + var conversion = LanguagePrimitives.FigureConversion(indexes[0], keyType, out debase); if (conversion.Rank == ConversionRank.None) { // No conversion allows us to call TryGetValue, let InvokeIndexer make the decision (possibly @@ -4225,7 +4225,7 @@ private DynamicMetaObject IndexWithNegativeChecks( private DynamicMetaObject GetIndexArray(DynamicMetaObject target, DynamicMetaObject[] indexes, DynamicMetaObject errorSuggestion) { - var array = (Array)target.Value; + var array = (Array)target; if (array.Rank > 1) { @@ -4284,7 +4284,7 @@ private DynamicMetaObject GetIndexMultiDimensionArray(DynamicMetaObject target, // $x[1,1] # case 3 // $x[(1,1),(0,0)] # case 4 - var array = (Array)target.Value; + var array = (Array)target; if (indexes.Length == 1) { @@ -4426,7 +4426,7 @@ private DynamicMetaObject InvokeIndexer(DynamicMetaObject target, internal static Expression ConvertIndex(DynamicMetaObject index, Type resultType) { // ConstrainedLanguage note - Calls to this conversion are protected by the binding rules that call it. - var conversion = LanguagePrimitives.FigureConversion(index.Value, resultType, out bool debase); + var conversion = LanguagePrimitives.FigureConversion(index, resultType, out bool debase); return conversion.Rank == ConversionRank.None ? null : PSConvertBinder.InvokeConverter(conversion, index.Expression, resultType, debase, ExpressionCache.InvariantCulture); @@ -4569,8 +4569,8 @@ public override DynamicMetaObject FallbackSetIndex( return Defer(indexes.Prepend(target).Append(value).ToArray()).WriteToDebugLog(this); } - if (target.Value is PSObject && (PSObject.Base(target.Value) != target.Value) || - indexes.Any(mo => mo.Value is PSObject && (PSObject.Base(mo.Value) != mo.Value))) + if (target is PSObject && (PSObject.Base(target) != target) || + indexes.Any(mo => mo is PSObject && (PSObject.Base(mo) != mo))) { return this.DeferForPSObject(indexes.Prepend(target).Append(value).ToArray()).WriteToDebugLog(this); } @@ -4582,13 +4582,13 @@ public override DynamicMetaObject FallbackSetIndex( return result.UpdateComRestrictionsForPsObject(indexes).WriteToDebugLog(this); } - if (target.Value == null) + if (target == null) { return (errorSuggestion ?? target.ThrowRuntimeError(indexes, BindingRestrictions.Empty, "NullArray", ParserStrings.NullArray)).WriteToDebugLog(this); } - if (indexes.Length == 1 && indexes[0].Value == null) + if (indexes.Length == 1 && indexes[0] == null) { return (errorSuggestion ?? target.ThrowRuntimeError(indexes, BindingRestrictions.Empty, "NullArrayIndex", ParserStrings.NullArrayIndex).WriteToDebugLog(this)); @@ -4673,7 +4673,7 @@ private DynamicMetaObject InvokeIndexer( } } - if (paramLength == 2 && setterParams[0].ParameterType == typeof(int) && !(target.Value is IDictionary)) + if (paramLength == 2 && setterParams[0].ParameterType == typeof(int) && !(target is IDictionary)) { // PowerShell supports negative indexing for some types (specifically, those with a single // int parameter to the indexer, and also have either a Length or Count property.) For @@ -4770,7 +4770,7 @@ private DynamicMetaObject SetIndexArray(DynamicMetaObject target, DynamicMetaObject value, DynamicMetaObject errorSuggestion) { - var array = (Array)target.Value; + var array = (Array)target; if (array.Rank > 1) { @@ -4839,7 +4839,7 @@ private DynamicMetaObject SetIndexMultiDimensionArray(DynamicMetaObject target, target.CombineRestrictions(indexes).Merge(value.PSGetTypeRestriction())); } - var array = (Array)target.Value; + var array = (Array)target; if (indexes.Length != array.Rank) { @@ -4991,7 +4991,7 @@ internal static void SetHasInstanceMember(string memberName) // MemberInfo mi; // if (binderVersion == oldBinderVersion && TryGetInstanceMember(obj, memberName, out mi)) // { - // return mi.Value; + // return mi; // } // else { update site } // This way, we can avoid the call to TryGetInstanceMember for binders when we know there aren't any instance @@ -5148,9 +5148,9 @@ public override DynamicMetaObject FallbackGetMember(DynamicMetaObject target, Dy } // Defer COM objects or arguments wrapped in PSObjects - if (target.Value is PSObject && (PSObject.Base(target.Value) != target.Value)) + if (target is PSObject && (PSObject.Base(target) != target)) { - object baseObject = PSObject.Base(target.Value); + object baseObject = PSObject.Base(target); if (baseObject != null && Marshal.IsComObject(baseObject)) { // We unwrap only if the 'base' is a COM object. It's unnecessary to unwrap in other cases, @@ -5169,7 +5169,7 @@ public override DynamicMetaObject FallbackGetMember(DynamicMetaObject target, Dy return result.WriteToDebugLog(this); } - object targetValue = PSObject.Base(target.Value); + object targetValue = PSObject.Base(target); if (targetValue == null) { @@ -5180,23 +5180,23 @@ public override DynamicMetaObject FallbackGetMember(DynamicMetaObject target, Dy BindingRestrictions restrictions; PSMemberInfo memberInfo; Expression expr = null; - if (_hasInstanceMember && TryGetInstanceMember(target.Value, Name, out memberInfo)) + if (_hasInstanceMember && TryGetInstanceMember(target, Name, out memberInfo)) { // If there is an instance member, we generate (roughly) the following: // PSMemberInfo memberInfo; - // if (PSGetMemberBinder.TryGetInstanceMember(target.Value, Name, out memberInfo)) - // return memberInfo.Value; + // if (PSGetMemberBinder.TryGetInstanceMember(target, Name, out memberInfo)) + // return memberInfo; // else // update the site // We use a generic method like this because: // * If one object has an instance property with a given name, it's like many others do as well // * We want to avoid generating new sites for every object with an instance member // As an alternative, would could generate the following psuedo-code: - // if (target.Value == previousInstance) + // if (target == previousInstance) // return optimized value (depending on the exact PSMemberInfo subclass) // else update the site // But the assumption here is that many sites probably performs worse than the dictionary lookup - // and unoptimized virtual call to PSMemberInfo.Value. + // and unoptimized virtual call to PSMemberInfo. // // The binding restrictions could avoid a version check because it's never wrong to look for an instance member, // but we add the check because the DLR requires a non-empty check when the target implements IDynamicMetaObjectProvider, @@ -5385,11 +5385,11 @@ internal static bool IsGenericDictionary(object value, ref Type genericTypeArg) internal static Expression GetTargetExpr(DynamicMetaObject target, Type castToType = null) { var expr = target.Expression; - var value = target.Value; + var value = target; // If the target value is actually a deserialized PSObject, we should use the original value var psobj = value as PSObject; - if (psobj != null && psobj != AutomationNull.Value && !psobj.IsDeserialized) + if (psobj != null && psobj != AutomationNull && !psobj.IsDeserialized) { expr = Expression.Call(CachedReflectionInfo.PSObject_Base, expr); value = PSObject.Base(value); @@ -5411,7 +5411,7 @@ internal static Expression GetTargetExpr(DynamicMetaObject target, Type castToTy if (expr.Type != type) { - // Unbox value types (or use Nullable.Value) to avoid a copy in case the value is mutated. + // Unbox value types (or use Nullable) to avoid a copy in case the value is mutated. // In case that castToType is System.Object and expr.Type is Nullable, expr.Cast(System.Object) will // get the underlying value by default. So "GetTargetExpr(target).Cast(typeof(object))" is actually the same as // "GetTargetExpr(target, typeof(object))". @@ -5441,8 +5441,8 @@ private DynamicMetaObject PropertyDoesntExist(DynamicMetaObject target, BindingR // collect the results in the helper method we call. One alternative to _nonEnumerating is to have the helper method // not recurse, but mark it's return value specially so that recursive calls to the helper can detect that the results // need to be flattened. - // IsEnumerable treats AutomationNull.Value as a zero length array which we don't want to do here. - if (!_nonEnumerating && target.Value != AutomationNull.Value) + // IsEnumerable treats AutomationNull as a zero length array which we don't want to do here. + if (!_nonEnumerating && target != AutomationNull) { var enumerable = PSEnumerableBinder.IsEnumerable(target); if (enumerable != null) @@ -5462,7 +5462,7 @@ private DynamicMetaObject PropertyDoesntExist(DynamicMetaObject target, BindingR if (Name.Equals("Length", StringComparison.OrdinalIgnoreCase) || Name.Equals("Count", StringComparison.OrdinalIgnoreCase)) { // $null.Count should be 0, anything else should be 1 - var resultCount = PSObject.Base(target.Value) == null ? 0 : 1; + var resultCount = PSObject.Base(target) == null ? 0 : 1; return new DynamicMetaObject( Expression.Condition( Compiler.IsStrictMode(2), @@ -5610,13 +5610,13 @@ internal PSMemberInfo GetPSMemberInfo(DynamicMetaObject target, restrictions = restrictions.Merge(versionRestriction); canOptimize = true; - return PSObject.GetStaticCLRMember(target.Value, Name); + return PSObject.GetStaticCLRMember(target, Name); } canOptimize = false; PSMemberInfo unused; - Diagnostics.Assert(!TryGetInstanceMember(target.Value, Name, out unused), + Diagnostics.Assert(!TryGetInstanceMember(target, Name, out unused), "shouldn't get here if there is an instance member"); PSMemberInfo memberInfo = null; @@ -5626,7 +5626,7 @@ internal PSMemberInfo GetPSMemberInfo(DynamicMetaObject target, if (hasTypeTableMember) { - typenames = PSObject.GetTypeNames(target.Value); + typenames = PSObject.GetTypeNames(target); if (typeTable != null) { memberInfo = typeTable.GetMembers(typenames)[Name]; @@ -5652,9 +5652,9 @@ internal PSMemberInfo GetPSMemberInfo(DynamicMetaObject target, // See the comments about 'three interesting cases' in PSInvokeMemberBinder.FallbackInvokeMember for more info. // // - If not, we want to use the base object, so that we might generate optimized code. - var psobj = target.Value as PSObject; + var psobj = target as PSObject; bool isTargetDeserializedObject = (psobj != null) && (psobj.IsDeserialized); - object value = isTargetDeserializedObject ? target.Value : PSObject.Base(target.Value); + object value = isTargetDeserializedObject ? target : PSObject.Base(target); var adapterSet = PSObject.GetMappedAdapter(value, typeTable); if (memberInfo == null) @@ -5722,7 +5722,7 @@ internal PSMemberInfo GetPSMemberInfo(DynamicMetaObject target, if ((getMethod == null || getMethod.IsFamily || getMethod.IsPublic) && (setMethod == null || setMethod.IsFamily || setMethod.IsPublic)) { - memberInfo = new PSProperty(this.Name, PSObject.DotNetInstanceAdapter, target.Value, new DotNetAdapter.PropertyCacheEntry(propertyInfo)); + memberInfo = new PSProperty(this.Name, PSObject.DotNetInstanceAdapter, target, new DotNetAdapter.PropertyCacheEntry(propertyInfo)); } } else @@ -5732,7 +5732,7 @@ internal PSMemberInfo GetPSMemberInfo(DynamicMetaObject target, { if (fieldInfo.IsFamily) { - memberInfo = new PSProperty(this.Name, PSObject.DotNetInstanceAdapter, target.Value, new DotNetAdapter.PropertyCacheEntry(fieldInfo)); + memberInfo = new PSProperty(this.Name, PSObject.DotNetInstanceAdapter, target, new DotNetAdapter.PropertyCacheEntry(fieldInfo)); } } else @@ -5848,7 +5848,7 @@ internal static object GetAdaptedValue(object obj, string member) if (memberInfo != null) { - return memberInfo.Value; + return memberInfo; } if (string.Equals(member, "Length", StringComparison.OrdinalIgnoreCase) || string.Equals(member, "Count", StringComparison.OrdinalIgnoreCase)) @@ -6031,10 +6031,10 @@ public override DynamicMetaObject FallbackSetMember(DynamicMetaObject target, Dy } // Defer COM objects or arguments wrapped in PSObjects - if ((target.Value is PSObject && (PSObject.Base(target.Value) != target.Value)) || - (value.Value is PSObject && (PSObject.Base(value.Value) != value.Value))) + if ((target is PSObject && (PSObject.Base(target) != target)) || + (value is PSObject && (PSObject.Base(value) != value))) { - object baseObject = PSObject.Base(target.Value); + object baseObject = PSObject.Base(target); if (baseObject != null && Marshal.IsComObject(baseObject)) { // We unwrap only if the 'base' of 'target' is a COM object. It's unnecessary to unwrap in other cases, @@ -6052,7 +6052,7 @@ public override DynamicMetaObject FallbackSetMember(DynamicMetaObject target, Dy return result.UpdateComRestrictionsForPsObject(new DynamicMetaObject[] { value }).WriteToDebugLog(this); } - var targetValue = PSObject.Base(target.Value); + var targetValue = PSObject.Base(target); if (targetValue == null) { return (target.ThrowRuntimeError(new[] { value }, BindingRestrictions.Empty, "PropertyNotFound", @@ -6060,7 +6060,7 @@ public override DynamicMetaObject FallbackSetMember(DynamicMetaObject target, Dy Expression.Constant(Name))).WriteToDebugLog(this); } - if (value.Value == AutomationNull.Value) + if (value == AutomationNull) { // Pretend the value was null (so we actually use null as the expression, but be sure // to use a restriction that checks @@ -6068,23 +6068,23 @@ public override DynamicMetaObject FallbackSetMember(DynamicMetaObject target, Dy } PSMemberInfo memberInfo; - if (_getMemberBinder.HasInstanceMember && PSGetMemberBinder.TryGetInstanceMember(target.Value, Name, out memberInfo)) + if (_getMemberBinder.HasInstanceMember && PSGetMemberBinder.TryGetInstanceMember(target, Name, out memberInfo)) { // If there is an instance member, we generate (roughly) the following: // PSMemberInfo memberInfo; - // if (PSGetMemberBinder.TryGetInstanceMember(target.Value, Name, out memberInfo)) - // memberInfo.Value = value; + // if (PSGetMemberBinder.TryGetInstanceMember(target, Name, out memberInfo)) + // memberInfo = value; // else // update the site // We use a generic method like this because: // * If one object has an instance property with a given name, it's like many others do as well // * We want to avoid generating new sites for every object with an instance member // As an alternative, would could generate the following psuedo-code: - // if (target.Value == previousInstance) + // if (target == previousInstance) // return optimized value (depending on the exact PSMemberInfo subclass) // else update the site // But the assumption here is that many sites probably performs worse than the dictionary lookup - // and unoptimized virtual call to PSMemberInfo.Value. + // and unoptimized virtual call to PSMemberInfo. // // The binding restrictions could avoid a version check because it's never wrong to look for an instance member, // but we add the check because the DLR requires a non-empty check when the target implements IDynamicMetaObjectProvider, @@ -6125,7 +6125,7 @@ public override DynamicMetaObject FallbackSetMember(DynamicMetaObject target, Dy Type elementType = temp.Type; // ConstrainedLanguage note - Calls to this conversion are protected by the binding rules below - var conversion = LanguagePrimitives.FigureConversion(value.Value, elementType, out debase); + var conversion = LanguagePrimitives.FigureConversion(value, elementType, out debase); if (conversion.Rank != ConversionRank.None) { var valueExpr = PSConvertBinder.InvokeConverter(conversion, value.Expression, elementType, @@ -6276,7 +6276,7 @@ public override DynamicMetaObject FallbackSetMember(DynamicMetaObject target, Dy var nullableUnderlyingType = Nullable.GetUnderlyingType(lhsType); if (nullableUnderlyingType != null) { - if (value.Value == null) + if (value == null) { expr = Expression.Block( Expression.Assign(lhs, this.GetTransformedExpression(argumentTransformationAttributes, Expression.Constant(null, lhsType))), @@ -6452,7 +6452,7 @@ internal static object SetAdaptedValue(object obj, string member, object value) if (memberInfo != null) { - memberInfo.Value = value; + memberInfo = value; } else { @@ -6608,10 +6608,10 @@ public override DynamicMetaObject FallbackInvokeMember(DynamicMetaObject target, } // Defer COM objects or arguments wrapped in PSObjects - if ((target.Value is PSObject && (PSObject.Base(target.Value) != target.Value)) || - args.Any(mo => mo.Value is PSObject && (PSObject.Base(mo.Value) != mo.Value))) + if ((target is PSObject && (PSObject.Base(target) != target)) || + args.Any(mo => mo is PSObject && (PSObject.Base(mo) != mo))) { - object baseObject = PSObject.Base(target.Value); + object baseObject = PSObject.Base(target); if (baseObject != null && Marshal.IsComObject(baseObject)) { // We unwrap only if the 'base' of 'target' is a COM object. It's unnecessary to unwrap in other cases, @@ -6629,7 +6629,7 @@ public override DynamicMetaObject FallbackInvokeMember(DynamicMetaObject target, return result.UpdateComRestrictionsForPsObject(args).WriteToDebugLog(this); } - var targetValue = PSObject.Base(target.Value); + var targetValue = PSObject.Base(target); if (targetValue == null) { if (!_static && !_nonEnumerating) @@ -6657,11 +6657,11 @@ public override DynamicMetaObject FallbackInvokeMember(DynamicMetaObject target, } PSMemberInfo memberInfo; - if (_getMemberBinder.HasInstanceMember && PSGetMemberBinder.TryGetInstanceMember(target.Value, Name, out memberInfo)) + if (_getMemberBinder.HasInstanceMember && PSGetMemberBinder.TryGetInstanceMember(target, Name, out memberInfo)) { // If there is an instance member, we generate (roughly) the following: // PSMethodInfo methodInfo; - // if (PSInvokeMemberBinder.TryGetInstanceMethod(target.Value, Name, out methodInfoInfo)) + // if (PSInvokeMemberBinder.TryGetInstanceMethod(target, Name, out methodInfoInfo)) // return methodInfo.Invoke(target, args); // else // update the site @@ -6669,11 +6669,11 @@ public override DynamicMetaObject FallbackInvokeMember(DynamicMetaObject target, // * If one object has an instance property with a given name, it's like many others do as well // * We want to avoid generating new sites for every object with an instance member // As an alternative, would could generate the following psuedo-code: - // if (target.Value == previousInstance) + // if (target == previousInstance) // return optimized value (depending on the exact PSMemberInfo subclass) // else update the site // But the assumption here is that many sites probably performs worse than the dictionary lookup - // and unoptimized virtual call to PSMemberInfo.Value. + // and unoptimized virtual call to PSMemberInfo. // // The binding restrictions could avoid a version check because it's never wrong to look for an instance member, // but we add the check because the DLR requires a non-empty check when the target implements IDynamicMetaObjectProvider, @@ -6758,7 +6758,7 @@ public override DynamicMetaObject FallbackInvokeMember(DynamicMetaObject target, // defined in the TypeTable will only get affected by the PSTypeNames. if (methodInfo is PSMethod || methodInfo is PSParameterizedProperty) { - var psObj = target.Value as PSObject; + var psObj = target as PSObject; if (psObj != null && (targetValue.GetType() == typeof(Hashtable) || targetValue.GetType() == typeof(ArrayList))) { // If we get here, then the target value should have 'isDeserialized == false', otherwise we cannot get a .NET methodInfo @@ -6825,7 +6825,7 @@ public override DynamicMetaObject FallbackInvokeMember(DynamicMetaObject target, } // See comment on PSGetMemberBinder.PropertyDoesntExistCheckSpecialCases - the same applies here for method calls. - if (!_static && !_nonEnumerating && target.Value != AutomationNull.Value) + if (!_static && !_nonEnumerating && target != AutomationNull) { // Invoking Where and ForEach operators on collections. if (string.Equals(Name, "Where", StringComparison.OrdinalIgnoreCase)) @@ -6877,8 +6877,8 @@ internal static DynamicMetaObject InvokeDotNetMethod( object[] argValues = new object[numArgs]; for (int i = 0; i < numArgs; ++i) { - object arg = args[i].Value; - argValues[i] = arg == AutomationNull.Value ? null : arg; + object arg = args[i]; + argValues[i] = arg == AutomationNull ? null : arg; } var result = Adapter.FindBestMethod( @@ -6971,7 +6971,7 @@ internal static MethodInfo FindBestMethod(DynamicMetaObject target, { MethodInfo result = null; - var psMethod = PSObject.DotNetInstanceAdapter.GetDotNetMethod(PSObject.Base(target.Value), methodName); + var psMethod = PSObject.DotNetInstanceAdapter.GetDotNetMethod(PSObject.Base(target), methodName); if (psMethod != null) { var data = (DotNetAdapter.MethodCacheEntry)psMethod.adapterData; @@ -6985,7 +6985,7 @@ internal static MethodInfo FindBestMethod(DynamicMetaObject target, data.methodInformationStructures, invocationConstraints, allowCastingToByRefLikeType: true, - args.Select(arg => arg.Value == AutomationNull.Value ? null : arg.Value).ToArray(), + args.Select(arg => arg == AutomationNull ? null : arg).ToArray(), ref errorId, ref errorMsg, out expandParameters, @@ -7127,7 +7127,7 @@ internal static Expression InvokeMethod(MethodBase mi, DynamicMetaObject target, { // We don't specify the parameter type in the constant expression. Normally the default // argument's type should match the parameter type, but sometimes it won't, e.g. with COM, - // the default can be System.Reflection.Missing.Value and this value is handled specially. + // the default can be System.Reflection.Missing and this value is handled specially. argExprs[i] = Expression.Constant(argValue); } } @@ -7135,7 +7135,7 @@ internal static Expression InvokeMethod(MethodBase mi, DynamicMetaObject target, { if (parameterType.IsByRef) { - if (args[i].Value is not PSReference) + if (args[i] is not PSReference) { return Compiler.CreateThrow(typeof(object), typeof(MethodException), new[] { typeof(string), typeof(Exception), typeof(string), typeof(object[]) }, @@ -7168,7 +7168,7 @@ internal static Expression InvokeMethod(MethodBase mi, DynamicMetaObject target, { if (invocationType == MethodInvocationType.BaseCtor) { - var targetExpr = target.Value is PSObject + var targetExpr = target is PSObject ? target.Expression.Cast(constructorInfo.DeclaringType) : PSGetMemberBinder.GetTargetExpr(target, constructorInfo.DeclaringType); call = Expression.Call( @@ -7570,7 +7570,7 @@ public override DynamicMetaObject FallbackCreateInstance(DynamicMetaObject targe return Defer(args.Prepend(target).ToArray()); } - var targetValue = PSObject.Base(target.Value); + var targetValue = PSObject.Base(target); if (targetValue == null) { return target.ThrowRuntimeError(args, BindingRestrictions.Empty, "InvokeMethodOnNull", ParserStrings.InvokeMethodOnNull).WriteToDebugLog(this); @@ -7612,7 +7612,7 @@ public override DynamicMetaObject FallbackCreateInstance(DynamicMetaObject targe var ctors = instanceType.GetConstructors(); restrictions = ReferenceEquals(instanceType, targetValue) - ? (target.Value is PSObject) + ? (target is PSObject) ? BindingRestrictions.GetInstanceRestriction(Expression.Call(CachedReflectionInfo.PSObject_Base, target.Expression), instanceType) : BindingRestrictions.GetInstanceRestriction(target.Expression, instanceType) : target.PSGetTypeRestriction(); @@ -7730,8 +7730,8 @@ public override DynamicMetaObject FallbackInvokeMember(DynamicMetaObject target, var ctors = _constraints.MethodTargetType.GetConstructors(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic); - var restrictions = target.Value is PSObject - ? BindingRestrictions.GetTypeRestriction(target.Expression, target.Value.GetType()) + var restrictions = target is PSObject + ? BindingRestrictions.GetTypeRestriction(target.Expression, target.GetType()) : target.PSGetTypeRestriction(); restrictions = args.Aggregate(restrictions, (current, arg) => current.Merge(arg.PSGetMethodArgumentRestriction())); var newConstructors = DotNetAdapter.GetMethodInformationArray(ctors.Where(c => c.IsPublic || c.IsFamily).ToArray()); diff --git a/src/System.Management.Automation/engine/runtime/CompiledScriptBlock.cs b/src/System.Management.Automation/engine/runtime/CompiledScriptBlock.cs index f441a84470c..967fa5d0f2f 100644 --- a/src/System.Management.Automation/engine/runtime/CompiledScriptBlock.cs +++ b/src/System.Management.Automation/engine/runtime/CompiledScriptBlock.cs @@ -351,7 +351,7 @@ internal bool IsProductCode _isProductCode = SecuritySupport.IsProductBinary(((Ast)_ast).Extent.File); } - return _isProductCode.Value; + return _isProductCode; } } @@ -1008,17 +1008,17 @@ internal void InvokeWithPipeImpl( var locals = MakeLocalsTuple(runOptimized); - if (dollarUnder != AutomationNull.Value) + if (dollarUnder != AutomationNull) { locals.SetAutomaticVariable(AutomaticVariable.Underbar, dollarUnder, context); } - if (input != AutomationNull.Value) + if (input != AutomationNull) { locals.SetAutomaticVariable(AutomaticVariable.Input, input, context); } - if (scriptThis != AutomationNull.Value) + if (scriptThis != AutomationNull) { locals.SetAutomaticVariable(AutomaticVariable.This, scriptThis, context); } @@ -1102,7 +1102,7 @@ internal void InvokeWithPipeImpl( throw e; } - if (def.Value == null) + if (def== null) { PSInvalidOperationException e = PSTraceSource.NewInvalidOperationException( ParserStrings.NullFunctionBodyInFunctionDefinitionDictionary, def.Key); @@ -1111,7 +1111,7 @@ internal void InvokeWithPipeImpl( throw e; } - newScope.FunctionTable.Add(def.Key, new FunctionInfo(def.Key, def.Value, context)); + newScope.FunctionTable.Add(def.Key, new FunctionInfo(def.Key, def, context)); } } // Inject passed in variables into the scope @@ -1158,7 +1158,7 @@ internal void InvokeWithPipeImpl( // Set the language mode if (newLanguageMode.HasValue) { - context.LanguageMode = newLanguageMode.Value; + context.LanguageMode = newLanguageMode; } args = BindArgumentsForScriptblockInvoke( @@ -1205,7 +1205,7 @@ internal void InvokeWithPipeImpl( // Restore the language mode if (oldLanguageMode.HasValue) { - context.LanguageMode = oldLanguageMode.Value; + context.LanguageMode = oldLanguageMode; } // Now restore the output pipe... @@ -1226,9 +1226,9 @@ internal void InvokeWithPipeImpl( Diagnostics.Assert(backupWhenDotting != null, "when dotting, this dictionary isn't null"); foreach (var pair in backupWhenDotting) { - if (pair.Value != null) + if (pair != null) { - context.EngineSessionState.SetVariable(pair.Value, false, CommandOrigin.Internal); + context.EngineSessionState.SetVariable(pair, false, CommandOrigin.Internal); } else { @@ -1287,7 +1287,7 @@ internal static object[] BindArgumentsForScriptblockInvoke( bool wasDefaulted = false; if (i >= args.Length) { - valueToBind = parameter.Value; + valueToBind = parameter; if (valueToBind is Compiler.DefaultValueExpressionWrapper) { // We pass in a null SessionStateInternal because the current scope is already set correctly. @@ -1743,7 +1743,7 @@ private static ScriptBlockLogging GetScriptBlockLoggingSetting() return Utils.GetPolicySetting(Utils.SystemWideThenCurrentUserConfig); } - return s_sbLoggingSettingCache.Value; + return s_sbLoggingSettingCache; } // Quick check for script blocks that may have suspicious content. If this @@ -2231,7 +2231,7 @@ protected override void BeginProcessing() { RunClause( clause: _runOptimized ? _scriptBlock.BeginBlock : _scriptBlock.UnoptimizedBeginBlock, - dollarUnderbar: AutomationNull.Value, + dollarUnderbar: AutomationNull, inputToProcess: _input); } } @@ -2244,7 +2244,7 @@ internal override void DoProcessRecord() } object dollarUnder; - if (CurrentPipelineObject == AutomationNull.Value) + if (CurrentPipelineObject == AutomationNull) { dollarUnder = null; } @@ -2275,7 +2275,7 @@ internal override void DoEndProcessing() { RunClause( clause: _runOptimized ? _scriptBlock.EndBlock : _scriptBlock.UnoptimizedEndBlock, - dollarUnderbar: AutomationNull.Value, + dollarUnderbar: AutomationNull, inputToProcess: _input.ToArray()); } } @@ -2320,12 +2320,12 @@ private void RunClause(Action clause, object dollarUnderbar, ob Context.RedirectErrorPipe(_commandRuntime.ErrorOutputPipe); } - if (dollarUnderbar != AutomationNull.Value) + if (dollarUnderbar != AutomationNull) { _localsTuple.SetAutomaticVariable(AutomaticVariable.Underbar, dollarUnderbar, Context); } - if (inputToProcess != AutomationNull.Value) + if (inputToProcess != AutomationNull) { _localsTuple.SetAutomaticVariable(AutomaticVariable.Input, inputToProcess, Context); } @@ -2333,7 +2333,7 @@ private void RunClause(Action clause, object dollarUnderbar, ob // Set the language mode if (newLanguageMode.HasValue) { - Context.LanguageMode = newLanguageMode.Value; + Context.LanguageMode = newLanguageMode; } clause(_functionContext); @@ -2350,7 +2350,7 @@ private void RunClause(Action clause, object dollarUnderbar, ob // Set the language mode if (oldLanguageMode.HasValue) { - Context.LanguageMode = oldLanguageMode.Value; + Context.LanguageMode = oldLanguageMode; } ExitScope(); @@ -2386,8 +2386,8 @@ public object GetDynamicParameters() _functionContext._outputPipe = new Pipe(resultList); RunClause( clause: _runOptimized ? _scriptBlock.DynamicParamBlock : _scriptBlock.UnoptimizedDynamicParamBlock, - dollarUnderbar: AutomationNull.Value, - inputToProcess: AutomationNull.Value); + dollarUnderbar: AutomationNull, + inputToProcess: AutomationNull); if (resultList.Count > 1) { throw PSTraceSource.NewInvalidOperationException( diff --git a/src/System.Management.Automation/engine/runtime/Operations/ArrayOps.cs b/src/System.Management.Automation/engine/runtime/Operations/ArrayOps.cs index d340f8c2667..d90bc995f20 100644 --- a/src/System.Management.Automation/engine/runtime/Operations/ArrayOps.cs +++ b/src/System.Management.Automation/engine/runtime/Operations/ArrayOps.cs @@ -19,7 +19,7 @@ internal static object[] SlicingIndex(object target, object[] indexes, Func' constructor ensures that only a single thread can initialize the instance in a thread-safe manner. _scriptBlock = new Lazy(() => new ScriptBlock(_ast, isFilter: false)); - _boundScriptBlock = new ThreadLocal(() => _scriptBlock.Value.Clone()); + _boundScriptBlock = new ThreadLocal(() => _scriptBlock.Clone()); } /// @@ -218,7 +218,7 @@ private void PrepareScriptBlockToInvoke(object instance, object sessionStateInte } } - _boundScriptBlock.Value.SessionStateInternal = sessionStateToUse; + _boundScriptBlock.SessionStateInternal = sessionStateToUse; } /// @@ -231,15 +231,15 @@ public void InvokeHelper(object instance, object sessionStateInternal, object[] try { PrepareScriptBlockToInvoke(instance, sessionStateInternal); - _boundScriptBlock.Value.InvokeAsMemberFunction(instance, args); + _boundScriptBlock.InvokeAsMemberFunction(instance, args); } finally { - // '_boundScriptBlock.Value' for a thread will live until + // '_boundScriptBlock' for a thread will live until // - the thread is gone, OR // - the dyanmic assembly holding this wrapper instance is GC collected. // We don't hold on the SessionState object, so that GC can collect it as appropriate. - _boundScriptBlock.Value.SessionStateInternal = null; + _boundScriptBlock.SessionStateInternal = null; } } @@ -255,15 +255,15 @@ public T InvokeHelperT(object instance, object sessionStateInternal, object[] try { PrepareScriptBlockToInvoke(instance, sessionStateInternal); - return _boundScriptBlock.Value.InvokeAsMemberFunctionT(instance, args); + return _boundScriptBlock.InvokeAsMemberFunctionT(instance, args); } finally { - // '_boundScriptBlock.Value' for a thread will live until + // '_boundScriptBlock' for a thread will live until // - the thread is gone, OR // - the dyanmic assembly holding this wrapper instance is GC collected. // We don't hold on the SessionState object, so that GC can collect it as appropriate. - _boundScriptBlock.Value.SessionStateInternal = null; + _boundScriptBlock.SessionStateInternal = null; } } } diff --git a/src/System.Management.Automation/engine/runtime/Operations/MiscOps.cs b/src/System.Management.Automation/engine/runtime/Operations/MiscOps.cs index 2b5d1771ed3..f1894513f1e 100644 --- a/src/System.Management.Automation/engine/runtime/Operations/MiscOps.cs +++ b/src/System.Management.Automation/engine/runtime/Operations/MiscOps.cs @@ -329,7 +329,7 @@ internal static IEnumerable Splat(object splattedValue foreach (DictionaryEntry de in splattedTable) { string parameterName = de.Key.ToString(); - object parameterValue = de.Value; + object parameterValue = de; string parameterText = GetParameterText(parameterName); if (markUntrustedData) @@ -376,9 +376,9 @@ private static CommandParameterInternal SplatEnumerableElement(object splattedAr { var prop = psObject.Properties[ScriptParameterBinderController.NotePropertyNameForSplattingParametersInArgs]; var baseObj = psObject.BaseObject; - if (prop != null && prop.Value is string && baseObj is string) + if (prop != null && prop is string && baseObj is string) { - return CommandParameterInternal.CreateParameter((string)prop.Value, (string)baseObj, splatAst); + return CommandParameterInternal.CreateParameter((string)prop, (string)baseObj, splatAst); } } @@ -431,11 +431,11 @@ internal static void InvokePipeline(object input, context.Events.ProcessPendingActions(); } - if (input == AutomationNull.Value && !ignoreInput) + if (input == AutomationNull && !ignoreInput) { // We have seen something like: // $e | measure-object - // And $e is AutomationNull.Value. We want to ensure + // And $e is AutomationNull. We want to ensure // measure-object runs w/o sending anything through the pipe, // so we'll turn the pipe into Out-Null | ... // This cleanly avoids any problems with the pipeline processing @@ -582,7 +582,7 @@ internal static void InvokePipelineInBackground( context.PushPipelineProcessor(pipelineProcessor); try { - pipelineProcessor.SynchronousExecuteEnumerate(AutomationNull.Value); + pipelineProcessor.SynchronousExecuteEnumerate(AutomationNull); } finally { @@ -608,7 +608,7 @@ private static void AddNoopCommandProcessor(PipelineProcessor pipelineProcessor, internal static object CheckAutomationNullInCommandArgument(object obj) { - if (obj == AutomationNull.Value) + if (obj == AutomationNull) { return null; } @@ -623,7 +623,7 @@ internal static object[] CheckAutomationNullInCommandArgumentArray(object[] objA { for (int i = 0; i < objArray.Length; ++i) { - if (objArray[i] == AutomationNull.Value) + if (objArray[i] == AutomationNull) { objArray[i] = null; } @@ -792,7 +792,7 @@ internal static object PipelineResult(List resultList) var resultCount = resultList.Count; if (resultCount == 0) { - return AutomationNull.Value; + return AutomationNull; } var result = resultCount == 1 ? resultList[0] : resultList.ToArray(); @@ -2242,12 +2242,12 @@ internal static string[] GetNamespacesForTypeResolutionState(IEnumerable result) while (e.MoveNext()) { o = e.Current; - if (o != AutomationNull.Value) + if (o != AutomationNull) { result.Add(o); } @@ -3070,7 +3070,7 @@ private static void PropertyGetterWorker(CallSite { var current = Current(enumerator); var o = getMemberBinderSite.Target.Invoke(getMemberBinderSite, current); - if (o != AutomationNull.Value) + if (o != AutomationNull) { FlattenResults(o, result); } @@ -3142,8 +3142,8 @@ private static void MethodInvokerWorker(CallSite invokeMemberSite, // be reporting the method's exception anyway, not a MissingMethodException. foundMethod = true; - // void methods return AutomationNull.Value, so don't add it - if (o != AutomationNull.Value) + // void methods return AutomationNull, so don't add it + if (o != AutomationNull) { FlattenResults(o, result); } @@ -3202,7 +3202,7 @@ internal static object MethodInvoker(PSInvokeMemberBinder binder, if (result.Count == 0) { // All void methods - don't return a value. - return AutomationNull.Value; + return AutomationNull; } return result.ToArray(); diff --git a/src/System.Management.Automation/engine/runtime/Operations/VariableOps.cs b/src/System.Management.Automation/engine/runtime/Operations/VariableOps.cs index d337c56ab2b..a54912fe57b 100644 --- a/src/System.Management.Automation/engine/runtime/Operations/VariableOps.cs +++ b/src/System.Management.Automation/engine/runtime/Operations/VariableOps.cs @@ -99,7 +99,7 @@ internal static object SetVariableValue(VariablePath variablePath, object value, else { // The setter will handle checking for variable writes. - var.Value = value; + var = value; } if (executionContext.LanguageMode == PSLanguageMode.ConstrainedLanguage) @@ -157,7 +157,7 @@ internal static object GetAutomaticVariableValue(int tupleIndex, ExecutionContex object result = executionContext.EngineSessionState.GetAutomaticVariableValue((AutomaticVariable)tupleIndex); - if (result == AutomationNull.Value) + if (result == AutomationNull) { if (ThrowStrictModeUndefinedVariable(executionContext, varAst)) { @@ -189,7 +189,7 @@ internal static object GetVariableValue(VariablePath variablePath, ExecutionCont if (var != null) { - return var.Value; + return var; } if (sessionState.ExecutionContext._debuggingMode > 0) @@ -223,7 +223,7 @@ internal static PSReference GetVariableAsRef(VariablePath variablePath, Executio ParserStrings.NonExistingVariableReference); } - object value = var.Value; + object value = var; if (staticType == null && value != null) { value = PSObject.Base(value); @@ -287,7 +287,7 @@ internal static object GetUsingValue(MutableTuple tuple, string usingExpressionK UsingResult result = GetUsingValueFromTuple(tuple, usingExpressionKey, index); if (result != null) { - return result.Value; + return result; } var scope = context.EngineSessionState.CurrentScope; @@ -296,7 +296,7 @@ internal static object GetUsingValue(MutableTuple tuple, string usingExpressionK result = GetUsingValueFromTuple(scope.LocalsTuple, usingExpressionKey, index); if (result != null) { - return result.Value; + return result; } foreach (var dottedScope in scope.DottedScopes) @@ -304,7 +304,7 @@ internal static object GetUsingValue(MutableTuple tuple, string usingExpressionK result = GetUsingValueFromTuple(dottedScope, usingExpressionKey, index); if (result != null) { - return result.Value; + return result; } } diff --git a/src/System.Management.Automation/engine/runtime/ScriptBlockToPowerShell.cs b/src/System.Management.Automation/engine/runtime/ScriptBlockToPowerShell.cs index 4e6d81e9208..5f70cc84430 100644 --- a/src/System.Management.Automation/engine/runtime/ScriptBlockToPowerShell.cs +++ b/src/System.Management.Automation/engine/runtime/ScriptBlockToPowerShell.cs @@ -648,8 +648,8 @@ private void ConvertCommand(CommandAst commandAst, bool isTrustedInput) || constantExprAst.StaticType == typeof(System.Numerics.BigInteger))) { var commandArgumentText = constantExprAst.Extent.Text; - argument = constantExprAst.Value; - if (!commandArgumentText.Equals(constantExprAst.Value.ToString(), StringComparison.Ordinal)) + argument = constantExprAst; + if (!commandArgumentText.Equals(constantExprAst.ToString(), StringComparison.Ordinal)) { // The wrapped number will actually return a PSObject which could end holding a reference to // a typetable, making the object runspace specific. We should find a better way to avoid