Apply the InlineAsTypeCheck rule in the engine code - 1st pass (#19692)

This commit is contained in:
Dmitry Volodin
2023-07-10 17:16:32 -07:00
committed by GitHub
parent ac87d2ae0e
commit b679b59e73
17 changed files with 63 additions and 106 deletions
@@ -1935,8 +1935,7 @@ namespace Microsoft.PowerShell.DesiredStateConfiguration.Internal
object evalResultObject;
if (IsConstantValueVisitor.IsConstant(pair.Item1, out evalResultObject, forAttribute: false, forRequires: false))
{
var presentName = evalResultObject as string;
if (presentName != null)
if (evalResultObject is string presentName)
{
if (mandatoryPropertiesNames.Remove(presentName) && mandatoryPropertiesNames.Count == 0)
{
@@ -2298,8 +2297,7 @@ namespace Microsoft.PowerShell.DesiredStateConfiguration.Internal
internal static string MapTypeNameToMofType(ITypeName typeName, string memberName, string className, out bool isArrayType, out string embeddedInstanceType, List<object> embeddedInstanceTypes, ref string[] enumNames)
{
TypeName propTypeName;
var arrayTypeName = typeName as ArrayTypeName;
if (arrayTypeName != null)
if (typeName is ArrayTypeName arrayTypeName)
{
isArrayType = true;
propTypeName = arrayTypeName.ElementType as TypeName;
@@ -2362,15 +2360,13 @@ namespace Microsoft.PowerShell.DesiredStateConfiguration.Internal
while (bases.Count > 0)
{
var b = bases.Dequeue();
var tc = b as TypeConstraintAst;
if (tc != null)
if (b is TypeConstraintAst tc)
{
b = tc.TypeName.GetReflectionType();
if (b == null)
{
var td = tc.TypeName as TypeName;
if (td != null && td._typeDefinitionAst != null)
if (tc.TypeName is TypeName td && td._typeDefinitionAst != null)
{
ProcessMembers(sb, embeddedInstanceTypes, td._typeDefinitionAst, className);
foreach (var b1 in td._typeDefinitionAst.BaseTypes)
@@ -2412,8 +2408,7 @@ namespace Microsoft.PowerShell.DesiredStateConfiguration.Internal
methodsLinePosition = new Dictionary<string, int>();
foreach (var member in typeDefinitionAst.Members)
{
var functionMemberAst = member as FunctionMemberAst;
if (functionMemberAst != null)
if (member is FunctionMemberAst functionMemberAst)
{
if (functionMemberAst.Name.Equals(getMethodName, StringComparison.OrdinalIgnoreCase))
{
@@ -2493,9 +2488,7 @@ namespace Microsoft.PowerShell.DesiredStateConfiguration.Internal
{
foreach (var member in typeDefinitionAst.Members)
{
var property = member as PropertyMemberAst;
if (property == null || property.IsStatic ||
if (member is not PropertyMemberAst property || property.IsStatic ||
property.Attributes.All(a => a.TypeName.GetReflectionAttributeType() != typeof(DscPropertyAttribute)))
{
continue;
@@ -2598,8 +2591,7 @@ namespace Microsoft.PowerShell.DesiredStateConfiguration.Internal
resourceDefinitions = ast.FindAll(n =>
{
var typeAst = n as TypeDefinitionAst;
if (typeAst != null)
if (n is TypeDefinitionAst typeAst)
{
for (int i = 0; i < typeAst.Attributes.Count; i++)
{
@@ -2674,13 +2666,9 @@ namespace Microsoft.PowerShell.DesiredStateConfiguration.Internal
{
foreach (var na in attr.NamedArguments)
{
if (na.ArgumentName.Equals("RunAsCredential", StringComparison.OrdinalIgnoreCase))
if (na.ArgumentName.Equals("RunAsCredential", StringComparison.OrdinalIgnoreCase) && attr.GetAttribute() is DscResourceAttribute dscResourceAttribute)
{
var dscResourceAttribute = attr.GetAttribute() as DscResourceAttribute;
if (dscResourceAttribute != null)
{
runAsBehavior = dscResourceAttribute.RunAsCredential;
}
runAsBehavior = dscResourceAttribute.RunAsCredential;
}
}
}
@@ -2914,8 +2902,7 @@ namespace Microsoft.PowerShell.DesiredStateConfiguration.Internal
bool needComma = false;
foreach (var attr in customAttributes)
{
var dscProperty = attr as DscPropertyAttribute;
if (dscProperty != null)
if (attr is DscPropertyAttribute dscProperty)
{
if (dscProperty.Key)
{
@@ -2938,8 +2925,7 @@ namespace Microsoft.PowerShell.DesiredStateConfiguration.Internal
continue;
}
var validateSet = attr as ValidateSetAttribute;
if (validateSet != null)
if (attr is ValidateSetAttribute validateSet)
{
bool valueMapComma = false;
StringBuilder sbValues = new(", Values{");
@@ -62,20 +62,17 @@ namespace Microsoft.PowerShell.Cmdletization
continue;
}
var objectInstance = methodParameter.Value as T;
if (objectInstance != null)
if (methodParameter.Value is T objectInstance)
{
result.Add(objectInstance);
continue;
}
var objectInstanceArray = methodParameter.Value as IEnumerable;
if (objectInstanceArray != null)
if (methodParameter.Value is IEnumerable objectInstanceArray)
{
foreach (object element in objectInstanceArray)
{
var objectInstance2 = element as T;
if (objectInstance2 != null)
if (element is T objectInstance2)
{
result.Add(objectInstance2);
}
@@ -29,8 +29,7 @@ namespace Microsoft.PowerShell.Cmdletization
_classVersion = classVersion;
_privateData = privateData;
var compiledScript = this.Cmdlet as PSScriptCmdlet;
if (compiledScript != null)
if (this.Cmdlet is PSScriptCmdlet compiledScript)
{
compiledScript.StoppingEvent += delegate { this.StopProcessing(); };
compiledScript.DisposingEvent +=
@@ -100,14 +100,12 @@ namespace Microsoft.PowerShell.Cmdletization
}
catch (InvalidOperationException e)
{
XmlSchemaException schemaException = e.InnerException as XmlSchemaException;
if (schemaException != null)
if (e.InnerException is XmlSchemaException schemaException)
{
throw new XmlException(schemaException.Message, schemaException, schemaException.LineNumber, schemaException.LinePosition);
}
XmlException xmlException = e.InnerException as XmlException;
if (xmlException != null)
if (e.InnerException is XmlException xmlException)
{
throw xmlException;
}
@@ -828,8 +826,7 @@ function __cmdletization_BindCommonParameters
private CommandMetadata GetCommandMetadata(CommonCmdletMetadata cmdletMetadata)
{
string defaultParameterSetName = null;
StaticCmdletMetadataCmdletMetadata staticCmdletMetadata = cmdletMetadata as StaticCmdletMetadataCmdletMetadata;
if (staticCmdletMetadata != null)
if (cmdletMetadata is StaticCmdletMetadataCmdletMetadata staticCmdletMetadata)
{
if (!string.IsNullOrEmpty(staticCmdletMetadata.DefaultCmdletParameterSet))
{
@@ -61,8 +61,7 @@ namespace Microsoft.PowerShell.Cim
public override System.Collections.ObjectModel.Collection<PSAdaptedProperty> GetProperties(object baseObject)
{
// baseObject should never be null
CimInstance cimInstance = baseObject as CimInstance;
if (cimInstance == null)
if (baseObject is not CimInstance cimInstance)
{
string msg = string.Format(CultureInfo.InvariantCulture,
CimInstanceTypeAdapterResources.BaseObjectNotCimInstance,
@@ -107,8 +106,7 @@ namespace Microsoft.PowerShell.Cim
}
// baseObject should never be null
CimInstance cimInstance = baseObject as CimInstance;
if (cimInstance == null)
if (baseObject is not CimInstance cimInstance)
{
string msg = string.Format(CultureInfo.InvariantCulture,
CimInstanceTypeAdapterResources.BaseObjectNotCimInstance,
@@ -142,8 +140,7 @@ namespace Microsoft.PowerShell.Cim
}
// baseObject should never be null
CimInstance cimInstance = baseObject as CimInstance;
if (cimInstance == null)
if (baseObject is not CimInstance cimInstance)
{
string msg = string.Format(
CultureInfo.InvariantCulture,
@@ -197,8 +194,7 @@ namespace Microsoft.PowerShell.Cim
{
ArgumentNullException.ThrowIfNull(adaptedProperty);
CimProperty cimProperty = adaptedProperty.Tag as CimProperty;
if (cimProperty != null)
if (adaptedProperty.Tag is CimProperty cimProperty)
{
return CimTypeToTypeNameDisplayString(cimProperty.CimType);
}
@@ -219,8 +215,7 @@ namespace Microsoft.PowerShell.Cim
{
ArgumentNullException.ThrowIfNull(adaptedProperty);
CimProperty cimProperty = adaptedProperty.Tag as CimProperty;
if (cimProperty != null)
if (adaptedProperty.Tag is CimProperty cimProperty)
{
return cimProperty.Value;
}
@@ -200,9 +200,7 @@ namespace System.Management.Automation
{
sb.AppendLine(StringUtil.Format(EtwLoggingStrings.ErrorRecordMessage, except.Message));
IContainsErrorRecord ier = except as IContainsErrorRecord;
if (ier != null)
if (except is IContainsErrorRecord ier)
{
ErrorRecord er = ier.ErrorRecord;
@@ -211,9 +211,11 @@ namespace System.Management.Automation
}
InvocationInfo invocationInfo = null;
IContainsErrorRecord icer = exception as IContainsErrorRecord;
if (icer != null && icer.ErrorRecord != null)
if (exception is IContainsErrorRecord icer && icer.ErrorRecord != null)
{
invocationInfo = icer.ErrorRecord.InvocationInfo;
}
foreach (LogProvider provider in GetLogProvider(executionContext))
{
if (NeedToLogEngineHealthEvent(provider, executionContext))
@@ -413,9 +415,11 @@ namespace System.Management.Automation
}
InvocationInfo invocationInfo = null;
IContainsErrorRecord icer = exception as IContainsErrorRecord;
if (icer != null && icer.ErrorRecord != null)
if (exception is IContainsErrorRecord icer && icer.ErrorRecord != null)
{
invocationInfo = icer.ErrorRecord.InvocationInfo;
}
foreach (LogProvider provider in GetLogProvider(executionContext))
{
if (NeedToLogCommandHealthEvent(provider, executionContext))
@@ -605,9 +609,11 @@ namespace System.Management.Automation
}
InvocationInfo invocationInfo = null;
IContainsErrorRecord icer = exception as IContainsErrorRecord;
if (icer != null && icer.ErrorRecord != null)
if (exception is IContainsErrorRecord icer && icer.ErrorRecord != null)
{
invocationInfo = icer.ErrorRecord.InvocationInfo;
}
foreach (LogProvider provider in GetLogProvider(executionContext))
{
if (NeedToLogProviderHealthEvent(provider, executionContext))
@@ -804,9 +810,7 @@ namespace System.Management.Automation
logContext.User = Logging.UnknownUserName;
}
System.Management.Automation.Remoting.PSSenderInfo psSenderInfo =
executionContext.SessionState.PSVariable.GetValue("PSSenderInfo") as System.Management.Automation.Remoting.PSSenderInfo;
if (psSenderInfo != null)
if (executionContext.SessionState.PSVariable.GetValue("PSSenderInfo") is System.Management.Automation.Remoting.PSSenderInfo psSenderInfo)
{
logContext.ConnectedUser = psSenderInfo.UserInfo.Identity.Name;
}
@@ -651,8 +651,7 @@ namespace Microsoft.PowerShell
break;
case CommandTypes.ExternalScript:
ExternalScriptInfo si = commandInfo as ExternalScriptInfo;
if (si == null)
if (commandInfo is not ExternalScriptInfo si)
{
reason = PSTraceSource.NewArgumentException("scriptInfo");
}
@@ -663,8 +663,7 @@ namespace System.Management.Automation.Internal
{
foreach (X509Extension extension in c.Extensions)
{
X509KeyUsageExtension keyUsageExtension = extension as X509KeyUsageExtension;
if (keyUsageExtension != null)
if (extension is X509KeyUsageExtension keyUsageExtension)
{
if ((keyUsageExtension.KeyUsages & keyUsage) == keyUsage)
{
@@ -761,8 +761,7 @@ namespace System.Management.Automation
if (msv == null)
{
// Check if the value is in string format
string singleValue = value as string;
if (singleValue != null)
if (value is string singleValue)
{
msv = new string[1];
msv[0] = singleValue;
@@ -866,12 +866,10 @@ namespace System.Management.Automation.Internal
internal override string EncryptSecureString(SecureString secureString)
{
ServerRemoteSession session = Session as ServerRemoteSession;
// session!=null check required for DRTs TestEncryptSecureString* entries in CryptoUtilsTest/UTUtils.dll
// for newer clients, server will never initiate key exchange.
// for server, just the session key is required to encrypt/decrypt anything
if ((session != null) && (session.Context.ClientCapability.ProtocolVersion >= RemotingConstants.ProtocolVersionWin8RTM))
if (Session is ServerRemoteSession session && session.Context.ClientCapability.ProtocolVersion >= RemotingConstants.ProtocolVersionWin8RTM)
{
_rsaCryptoProvider.GenerateSessionKey();
}
@@ -54,8 +54,7 @@ namespace System.Management.Automation
ArgumentNullException.ThrowIfNull(innerException);
// invocationInfo may be null
IContainsErrorRecord icer = innerException as IContainsErrorRecord;
if (icer != null && icer.ErrorRecord != null)
if (innerException is IContainsErrorRecord icer && icer.ErrorRecord != null)
{
_errorRecord = new ErrorRecord(icer.ErrorRecord, innerException);
}
@@ -637,8 +637,7 @@ namespace System.Management.Automation
errorId,
args)
{
ValidationMetadataException validationException = innerException as ValidationMetadataException;
if (validationException != null && validationException.SwallowException)
if (innerException is ValidationMetadataException validationException && validationException.SwallowException)
{
_swallowException = true;
}
@@ -120,9 +120,8 @@ namespace System.Management.Automation
try
{
PSObject pso = obj as PSObject;
string result;
if (pso != null)
if (obj is PSObject pso)
{
object baseObject = pso.BaseObject;
if (baseObject != null && baseObject is not PSCustomObject)
@@ -354,33 +354,28 @@ namespace System.Management.Automation
}
var pipeline = ast.GetSimplePipeline(false, out _, out _);
if (pipeline != null)
if (pipeline?.GetPureExpression() is HashtableAst hashtableAst)
{
var hashtableAst = pipeline.GetPureExpression() as HashtableAst;
if (hashtableAst != null)
var result = new Hashtable(StringComparer.OrdinalIgnoreCase);
foreach (var pair in hashtableAst.KeyValuePairs)
{
var result = new Hashtable(StringComparer.OrdinalIgnoreCase);
foreach (var pair in hashtableAst.KeyValuePairs)
if (pair.Item1 is StringConstantExpressionAst key && keys.Contains(key.Value, StringComparer.OrdinalIgnoreCase))
{
var key = pair.Item1 as StringConstantExpressionAst;
if (key != null && keys.Contains(key.Value, StringComparer.OrdinalIgnoreCase))
try
{
try
{
var val = pair.Item2.SafeGetValue();
result[key.Value] = val;
}
catch
{
throw PSTraceSource.NewInvalidOperationException(
ParserStrings.InvalidPowerShellDataFile,
psDataFilePath);
}
var val = pair.Item2.SafeGetValue();
result[key.Value] = val;
}
catch
{
throw PSTraceSource.NewInvalidOperationException(
ParserStrings.InvalidPowerShellDataFile,
psDataFilePath);
}
}
return result;
}
return result;
}
throw PSTraceSource.NewInvalidOperationException(
@@ -252,13 +252,9 @@ namespace System.Management.Automation
set
{
_thrownByThrowStatement = value;
if (_errorRecord != null)
if (_errorRecord?.Exception is RuntimeException exception)
{
RuntimeException exception = _errorRecord.Exception as RuntimeException;
if (exception != null)
{
exception.WasThrownFromThrowStatement = value;
}
exception.WasThrownFromThrowStatement = value;
}
}
}
@@ -66,8 +66,7 @@ namespace System.Management.Automation
_message = base.Message;
_providerInfo = provider;
IContainsErrorRecord icer = innerException as IContainsErrorRecord;
if (icer != null && icer.ErrorRecord != null)
if (innerException is IContainsErrorRecord icer && icer.ErrorRecord != null)
{
_errorRecord = new ErrorRecord(icer.ErrorRecord, innerException);
}
@@ -199,8 +198,7 @@ namespace System.Management.Automation
errorRecordException = new ParentContainsErrorRecordException(this);
}
IContainsErrorRecord icer = innerException as IContainsErrorRecord;
if (icer != null && icer.ErrorRecord != null)
if (innerException is IContainsErrorRecord icer && icer.ErrorRecord != null)
{
_errorRecord = new ErrorRecord(icer.ErrorRecord, errorRecordException);
}