Browse Source

Inline variable declarations/modernize parts of our code base.

pull/1984/head
Siegfried Pammer 5 years ago
parent
commit
8925b4ff7b
  1. 9
      ICSharpCode.Decompiler/CSharp/Annotations.cs
  2. 24
      ICSharpCode.Decompiler/CSharp/ExpressionBuilder.cs
  3. 3
      ICSharpCode.Decompiler/CSharp/Resolver/CSharpConversions.cs
  4. 9
      ICSharpCode.Decompiler/CSharp/Resolver/CSharpResolver.cs
  5. 3
      ICSharpCode.Decompiler/CSharp/Resolver/MethodGroupResolveResult.cs
  6. 3
      ICSharpCode.Decompiler/CSharp/StatementBuilder.cs
  7. 3
      ICSharpCode.Decompiler/CSharp/Transforms/DeclareVariables.cs
  8. 3
      ICSharpCode.Decompiler/CSharp/Transforms/FixNameCollisions.cs
  9. 3
      ICSharpCode.Decompiler/Documentation/IdStringProvider.cs
  10. 3
      ICSharpCode.Decompiler/Documentation/XmlDocLoader.cs
  11. 7
      ICSharpCode.Decompiler/Documentation/XmlDocumentationProvider.cs
  12. 18
      ICSharpCode.Decompiler/FlowAnalysis/DataFlowVisitor.cs
  13. 3
      ICSharpCode.Decompiler/IL/BlockBuilder.cs
  14. 6
      ICSharpCode.Decompiler/IL/ControlFlow/DetectPinnedRegions.cs
  15. 3
      ICSharpCode.Decompiler/IL/Transforms/DynamicCallSiteTransform.cs
  16. 4
      ILSpy.BamlDecompiler/BamlResourceNodeFactory.cs
  17. 9
      ILSpy.BamlDecompiler/Rewrite/ConnectionIdRewritePass.cs

9
ICSharpCode.Decompiler/CSharp/Annotations.cs

@ -155,8 +155,7 @@ namespace ICSharpCode.Decompiler.CSharp @@ -155,8 +155,7 @@ namespace ICSharpCode.Decompiler.CSharp
/// </summary>
public static ILVariable GetILVariable(this IdentifierExpression expr)
{
var rr = expr.Annotation<ResolveResult>() as ILVariableResolveResult;
if (rr != null)
if (expr.Annotation<ResolveResult>() is ILVariableResolveResult rr)
return rr.Variable;
else
return null;
@ -167,8 +166,7 @@ namespace ICSharpCode.Decompiler.CSharp @@ -167,8 +166,7 @@ namespace ICSharpCode.Decompiler.CSharp
/// </summary>
public static ILVariable GetILVariable(this VariableInitializer vi)
{
var rr = vi.Annotation<ResolveResult>() as ILVariableResolveResult;
if (rr != null)
if (vi.Annotation<ResolveResult>() is ILVariableResolveResult rr)
return rr.Variable;
else
return null;
@ -179,8 +177,7 @@ namespace ICSharpCode.Decompiler.CSharp @@ -179,8 +177,7 @@ namespace ICSharpCode.Decompiler.CSharp
/// </summary>
public static ILVariable GetILVariable(this ForeachStatement loop)
{
var rr = loop.Annotation<ResolveResult>() as ILVariableResolveResult;
if (rr != null)
if (loop.Annotation<ResolveResult>() is ILVariableResolveResult rr)
return rr.Variable;
else
return null;

24
ICSharpCode.Decompiler/CSharp/ExpressionBuilder.cs

@ -383,14 +383,13 @@ namespace ICSharpCode.Decompiler.CSharp @@ -383,14 +383,13 @@ namespace ICSharpCode.Decompiler.CSharp
protected internal override TranslatedExpression VisitLocAllocSpan(LocAllocSpan inst, TranslationContext context)
{
return TranslateLocAllocSpan(inst, context.TypeHint, out var elementType)
return TranslateLocAllocSpan(inst, context.TypeHint, out _)
.WithILInstruction(inst).WithRR(new ResolveResult(inst.Type));
}
StackAllocExpression TranslateLocAllocSpan(LocAllocSpan inst, IType typeHint, out IType elementType)
{
elementType = inst.Type.TypeArguments[0];
PointerType pointerType = new PointerType(elementType);
TranslatedExpression countExpression = Translate(inst.Argument)
.ConvertTo(compilation.FindType(KnownTypeCode.Int32), this);
return new StackAllocExpression {
@ -696,8 +695,7 @@ namespace ICSharpCode.Decompiler.CSharp @@ -696,8 +695,7 @@ namespace ICSharpCode.Decompiler.CSharp
return ErrorExpression("Nullable comparisons with three-valued-logic not supported in C#");
}
if (inst.Kind.IsEqualityOrInequality()) {
bool negateOutput;
var result = TranslateCeq(inst, out negateOutput);
var result = TranslateCeq(inst, out bool negateOutput);
if (negateOutput)
return LogicNot(result).WithILInstruction(inst);
else
@ -2573,31 +2571,29 @@ namespace ICSharpCode.Decompiler.CSharp @@ -2573,31 +2571,29 @@ namespace ICSharpCode.Decompiler.CSharp
{
var stloc = block.Instructions.FirstOrDefault() as StLoc;
var final = block.FinalInstruction as LdLoc;
IType type;
if (stloc == null || final == null || !stloc.Value.MatchNewArr(out type) || stloc.Variable != final.Variable || stloc.Variable.Kind != VariableKind.InitializerTarget)
if (stloc == null || final == null || !stloc.Value.MatchNewArr(out IType type))
throw new ArgumentException("given Block is invalid!");
if (stloc.Variable != final.Variable || stloc.Variable.Kind != VariableKind.InitializerTarget)
throw new ArgumentException("given Block is invalid!");
var newArr = (NewArr)stloc.Value;
var translatedDimensions = newArr.Indices.Select(i => Translate(i)).ToArray();
var translatedDimensions = newArr.Indices.SelectArray(i => Translate(i));
if (!translatedDimensions.All(dim => dim.ResolveResult.IsCompileTimeConstant))
throw new ArgumentException("given Block is invalid!");
int dimensions = newArr.Indices.Count;
int[] dimensionSizes = translatedDimensions.Select(dim => (int)dim.ResolveResult.ConstantValue).ToArray();
int[] dimensionSizes = translatedDimensions.SelectArray(dim => (int)dim.ResolveResult.ConstantValue);
var container = new Stack<ArrayInitializer>();
var root = new ArrayInitializer(new ArrayInitializerExpression());
container.Push(root);
var elementResolveResults = new List<ResolveResult>();
for (int i = 1; i < block.Instructions.Count; i++) {
ILInstruction target, value, array;
IType t;
ILVariable v;
if (!block.Instructions[i].MatchStObj(out target, out value, out t) || !type.Equals(t))
if (!block.Instructions[i].MatchStObj(out ILInstruction target, out ILInstruction value, out IType t) || !type.Equals(t))
throw new ArgumentException("given Block is invalid!");
if (!target.MatchLdElema(out t, out array) || !type.Equals(t))
if (!target.MatchLdElema(out t, out ILInstruction array) || !type.Equals(t))
throw new ArgumentException("given Block is invalid!");
if (!array.MatchLdLoc(out v) || v != final.Variable)
if (!array.MatchLdLoc(out ILVariable v) || v != final.Variable)
throw new ArgumentException("given Block is invalid!");
while (container.Count < dimensions) {
var aie = new ArrayInitializerExpression();

3
ICSharpCode.Decompiler/CSharp/Resolver/CSharpConversions.cs

@ -163,8 +163,7 @@ namespace ICSharpCode.Decompiler.CSharp.Resolver @@ -163,8 +163,7 @@ namespace ICSharpCode.Decompiler.CSharp.Resolver
throw new ArgumentNullException(nameof(toType));
TypePair pair = new TypePair(fromType, toType);
Conversion c;
if (implicitConversionCache.TryGetValue(pair, out c))
if (implicitConversionCache.TryGetValue(pair, out Conversion c))
return c;
c = ImplicitConversion(fromType, toType, allowUserDefined: true, allowTuple: true);

9
ICSharpCode.Decompiler/CSharp/Resolver/CSharpResolver.cs

@ -1740,8 +1740,7 @@ namespace ICSharpCode.Decompiler.CSharp.Resolver @@ -1740,8 +1740,7 @@ namespace ICSharpCode.Decompiler.CSharp.Resolver
void CheckForEnumerableInterface(ResolveResult expression, out IType collectionType, out IType enumeratorType, out IType elementType, out ResolveResult getEnumeratorInvocation)
{
bool? isGeneric;
elementType = expression.Type.GetElementTypeFromIEnumerable(compilation, false, out isGeneric);
elementType = expression.Type.GetElementTypeFromIEnumerable(compilation, false, out bool? isGeneric);
if (isGeneric == true) {
ITypeDefinition enumerableOfT = compilation.FindType(KnownTypeCode.IEnumerableOfT).GetDefinition();
if (enumerableOfT != null)
@ -1886,8 +1885,7 @@ namespace ICSharpCode.Decompiler.CSharp.Resolver @@ -1886,8 +1885,7 @@ namespace ICSharpCode.Decompiler.CSharp.Resolver
TypeInference ti = new TypeInference(compilation, conversions);
ResolveResult[] arguments = { new ResolveResult(targetType) };
IType[] parameterTypes = { method.Parameters[0].Type };
bool success;
var inferredTypes = ti.InferTypeArguments(method.TypeParameters, arguments, parameterTypes, out success);
var inferredTypes = ti.InferTypeArguments(method.TypeParameters, arguments, parameterTypes, out _);
var substitution = new TypeParameterSubstitution(null, inferredTypes);
// Validate that the types that could be inferred (aren't unknown) satisfy the constraints:
bool hasInferredTypes = false;
@ -2563,8 +2561,7 @@ namespace ICSharpCode.Decompiler.CSharp.Resolver @@ -2563,8 +2561,7 @@ namespace ICSharpCode.Decompiler.CSharp.Resolver
throw new ArgumentException("sizeArguments.Length must not be 0");
if (elementType == null) {
TypeInference typeInference = new TypeInference(compilation, conversions);
bool success;
elementType = typeInference.GetBestCommonType(initializerElements, out success);
elementType = typeInference.GetBestCommonType(initializerElements, out _);
}
IType arrayType = new ArrayType(compilation, elementType, dimensions);

3
ICSharpCode.Decompiler/CSharp/Resolver/MethodGroupResolveResult.cs

@ -199,8 +199,7 @@ namespace ICSharpCode.Decompiler.CSharp.Resolver @@ -199,8 +199,7 @@ namespace ICSharpCode.Decompiler.CSharp.Resolver
foreach (var methodGroup in GetExtensionMethods()) {
var outputGroup = new List<IMethod>();
foreach (var method in methodGroup) {
IType[] inferredTypes;
if (CSharpResolver.IsEligibleExtensionMethod(this.TargetType, method, true, out inferredTypes)) {
if (CSharpResolver.IsEligibleExtensionMethod(this.TargetType, method, true, out IType[] inferredTypes)) {
if (substituteInferredTypes && inferredTypes != null) {
outputGroup.Add(method.Specialize(new TypeParameterSubstitution(null, inferredTypes)));
} else {

3
ICSharpCode.Decompiler/CSharp/StatementBuilder.cs

@ -1047,8 +1047,7 @@ namespace ICSharpCode.Decompiler.CSharp @@ -1047,8 +1047,7 @@ namespace ICSharpCode.Decompiler.CSharp
blockStatement.Add(Convert(block.FinalInstruction));
}
}
string label;
if (endContainerLabels.TryGetValue(container, out label)) {
if (endContainerLabels.TryGetValue(container, out string label)) {
if (isLoop && !(blockStatement.LastOrDefault() is ContinueStatement)) {
blockStatement.Add(new ContinueStatement());
}

3
ICSharpCode.Decompiler/CSharp/Transforms/DeclareVariables.cs

@ -282,8 +282,7 @@ namespace ICSharpCode.Decompiler.CSharp.Transforms @@ -282,8 +282,7 @@ namespace ICSharpCode.Decompiler.CSharp.Transforms
}
}
}
VariableToDeclare v;
if (variableDict.TryGetValue(variable, out v)) {
if (variableDict.TryGetValue(variable, out VariableToDeclare v)) {
v.InsertionPoint = FindCommonParent(v.InsertionPoint, newPoint);
} else {
v = new VariableToDeclare(variable, variable.HasInitialValue,

3
ICSharpCode.Decompiler/CSharp/Transforms/FixNameCollisions.cs

@ -61,8 +61,7 @@ namespace ICSharpCode.Decompiler.CSharp.Transforms @@ -61,8 +61,7 @@ namespace ICSharpCode.Decompiler.CSharp.Transforms
foreach (var node in rootNode.DescendantsAndSelf) {
if (node is IdentifierExpression || node is MemberReferenceExpression) {
ISymbol symbol = node.GetSymbol();
string newName;
if (symbol != null && renamedSymbols.TryGetValue(symbol, out newName)) {
if (symbol != null && renamedSymbols.TryGetValue(symbol, out string newName)) {
node.GetChildByRole(Roles.Identifier).Name = newName;
}
}

3
ICSharpCode.Decompiler/Documentation/IdStringProvider.cs

@ -296,8 +296,7 @@ namespace ICSharpCode.Decompiler.Documentation @@ -296,8 +296,7 @@ namespace ICSharpCode.Decompiler.Documentation
} else {
// not a type parameter reference: read the actual type name
List<ITypeReference> typeArguments = new List<ITypeReference>();
int typeParameterCount;
string typeNameWithoutSuffix = ReadTypeName(typeName, ref pos, true, out typeParameterCount, typeArguments);
string typeNameWithoutSuffix = ReadTypeName(typeName, ref pos, true, out int typeParameterCount, typeArguments);
result = new GetPotentiallyNestedClassTypeReference(typeNameWithoutSuffix, typeParameterCount);
while (pos < typeName.Length && typeName[pos] == '.') {
pos++;

3
ICSharpCode.Decompiler/Documentation/XmlDocLoader.cs

@ -51,8 +51,7 @@ namespace ICSharpCode.Decompiler.Documentation @@ -51,8 +51,7 @@ namespace ICSharpCode.Decompiler.Documentation
if (module == null)
throw new ArgumentNullException(nameof(module));
lock (cache) {
XmlDocumentationProvider xmlDoc;
if (!cache.TryGetValue(module, out xmlDoc)) {
if (!cache.TryGetValue(module, out XmlDocumentationProvider xmlDoc)) {
string xmlDocFile = LookupLocalizedXmlDoc(module.FileName);
if (xmlDocFile == null) {
xmlDocFile = FindXmlDocumentation(Path.GetFileName(module.FileName), module.GetRuntime());

7
ICSharpCode.Decompiler/Documentation/XmlDocumentationProvider.cs

@ -266,10 +266,8 @@ namespace ICSharpCode.Decompiler.Documentation @@ -266,10 +266,8 @@ namespace ICSharpCode.Decompiler.Documentation
int b = fs.ReadByte();
if (b < 0)
throw new EndOfStreamException();
int bytesUsed, charsUsed;
bool completed;
input[0] = (byte)b;
decoder.Convert(input, 0, 1, output, 0, 1, false, out bytesUsed, out charsUsed, out completed);
decoder.Convert(input, 0, 1, output, 0, 1, false, out int bytesUsed, out int charsUsed, out _);
Debug.Assert(bytesUsed == 1);
if (charsUsed == 1) {
if ((prevChar != '\r' && output[0] == '\n') || output[0] == '\r')
@ -357,8 +355,7 @@ namespace ICSharpCode.Decompiler.Documentation @@ -357,8 +355,7 @@ namespace ICSharpCode.Decompiler.Documentation
XmlDocumentationCache cache = this.cache;
lock (cache) {
string val;
if (!cache.TryGet(key, out val)) {
if (!cache.TryGet(key, out string val)) {
try {
// go through all items that have the correct hash
while (++m < index.Length && index[m].HashCode == hashcode) {

18
ICSharpCode.Decompiler/FlowAnalysis/DataFlowVisitor.cs

@ -235,9 +235,8 @@ namespace ICSharpCode.Decompiler.FlowAnalysis @@ -235,9 +235,8 @@ namespace ICSharpCode.Decompiler.FlowAnalysis
{
#if DEBUG
Debug.Assert(initialized, "Initialize() was not called");
State previousState;
if (debugDict.TryGetValue(inst, out previousState)) {
if (debugDict.TryGetValue(inst, out State previousState)) {
Debug.Assert(previousState.LessThanOrEqual(state));
previousState.JoinWith(state);
} else {
@ -246,7 +245,7 @@ namespace ICSharpCode.Decompiler.FlowAnalysis @@ -246,7 +245,7 @@ namespace ICSharpCode.Decompiler.FlowAnalysis
debugDict.Add(inst, state.Clone());
}
}
// currentStateOnException should be all states within the try block joined together
// -> state should already have been joined into currentStateOnException.
Debug.Assert(state.LessThanOrEqual(currentStateOnException));
@ -344,8 +343,7 @@ namespace ICSharpCode.Decompiler.FlowAnalysis @@ -344,8 +343,7 @@ namespace ICSharpCode.Decompiler.FlowAnalysis
/// </remarks>
State GetBlockInputState(Block block)
{
State s;
if (stateOnBranch.TryGetValue(block, out s)) {
if (stateOnBranch.TryGetValue(block, out State s)) {
return s;
} else {
s = bottomState.Clone();
@ -388,8 +386,7 @@ namespace ICSharpCode.Decompiler.FlowAnalysis @@ -388,8 +386,7 @@ namespace ICSharpCode.Decompiler.FlowAnalysis
state.ReplaceWith(stateOnBranch[block]);
block.AcceptVisitor(this);
}
State stateOnExit;
if (stateOnLeave.TryGetValue(container, out stateOnExit)) {
if (stateOnLeave.TryGetValue(container, out State stateOnExit)) {
state.ReplaceWith(stateOnExit);
} else {
MarkUnreachable();
@ -476,14 +473,13 @@ namespace ICSharpCode.Decompiler.FlowAnalysis @@ -476,14 +473,13 @@ namespace ICSharpCode.Decompiler.FlowAnalysis
protected State HandleTryBlock(TryInstruction inst)
{
State oldStateOnException = currentStateOnException;
State newStateOnException;
if (stateOnException.TryGetValue(inst, out newStateOnException)) {
if (stateOnException.TryGetValue(inst, out State newStateOnException)) {
newStateOnException.JoinWith(state);
} else {
newStateOnException = state.Clone();
stateOnException.Add(inst, newStateOnException);
}
currentStateOnException = newStateOnException;
inst.TryBlock.AcceptVisitor(this);
// swap back to the old object instance

3
ICSharpCode.Decompiler/IL/BlockBuilder.cs

@ -142,8 +142,7 @@ namespace ICSharpCode.Decompiler.IL @@ -142,8 +142,7 @@ namespace ICSharpCode.Decompiler.IL
}
}
// Enter a handler if necessary
BlockContainer handlerContainer;
if (handlerContainers.TryGetValue(start, out handlerContainer)) {
if (handlerContainers.TryGetValue(start, out BlockContainer handlerContainer)) {
containerStack.Push(currentContainer);
currentContainer = handlerContainer;
currentBlock = handlerContainer.EntryPoint;

6
ICSharpCode.Decompiler/IL/ControlFlow/DetectPinnedRegions.cs

@ -94,8 +94,7 @@ namespace ICSharpCode.Decompiler.IL.ControlFlow @@ -94,8 +94,7 @@ namespace ICSharpCode.Decompiler.IL.ControlFlow
var block = container.Blocks[i];
for (int j = 0; j < block.Instructions.Count - 1; j++) {
var inst = block.Instructions[j];
ILVariable v;
if (inst.MatchStLoc(out v) && v.Kind == VariableKind.PinnedLocal) {
if (inst.MatchStLoc(out ILVariable v) && v.Kind == VariableKind.PinnedLocal) {
if (block.Instructions[j + 1].OpCode != OpCode.Branch) {
// split block after j:
context.Step("Split block after pinned local write", inst);
@ -357,10 +356,9 @@ namespace ICSharpCode.Decompiler.IL.ControlFlow @@ -357,10 +356,9 @@ namespace ICSharpCode.Decompiler.IL.ControlFlow
// stloc P(ldelema(ldloc V, ldc.i4 0, ...))
// br B_target
// }
ILInstruction value;
if (block.Instructions.Count != 2)
return false;
if (!block.Instructions[0].MatchStLoc(out var p2, out value))
if (!block.Instructions[0].MatchStLoc(out var p2, out ILInstruction value))
return false;
if (p != p2) {
// If the pointer is unused, the variable P might have been split.

3
ICSharpCode.Decompiler/IL/Transforms/DynamicCallSiteTransform.cs

@ -522,8 +522,7 @@ namespace ICSharpCode.Decompiler.IL.Transforms @@ -522,8 +522,7 @@ namespace ICSharpCode.Decompiler.IL.Transforms
return false;
if (!createCall.Arguments[0].MatchLdcI4(out var argumentInfoFlags))
return false;
string argumentName = null;
if (!createCall.Arguments[1].MatchLdStr(out argumentName))
if (!createCall.Arguments[1].MatchLdStr(out string argumentName))
if (!createCall.Arguments[1].MatchLdNull())
return false;
callSiteInfo.ArgumentInfos[i] = new CSharpArgumentInfo { Flags = (CSharpArgumentInfoFlags)argumentInfoFlags, Name = argumentName, CompileTimeType = compileTimeTypes[i + 1] };

4
ILSpy.BamlDecompiler/BamlResourceNodeFactory.cs

@ -21,8 +21,8 @@ namespace ILSpy.BamlDecompiler @@ -21,8 +21,8 @@ namespace ILSpy.BamlDecompiler
public ILSpyTreeNode CreateNode(string key, object data)
{
if (key.EndsWith(".baml", StringComparison.OrdinalIgnoreCase) && data is Stream)
return new BamlResourceEntryNode(key, (Stream)data);
if (key.EndsWith(".baml", StringComparison.OrdinalIgnoreCase) && data is Stream stream)
return new BamlResourceEntryNode(key, stream);
else
return null;
}

9
ILSpy.BamlDecompiler/Rewrite/ConnectionIdRewritePass.cs

@ -114,8 +114,7 @@ namespace ILSpy.BamlDecompiler.Rewrite @@ -114,8 +114,7 @@ namespace ILSpy.BamlDecompiler.Rewrite
var comp = ifInst.Condition as Comp;
if (comp.Kind != ComparisonKind.Inequality && comp.Kind != ComparisonKind.Equality)
continue;
int id;
if (!comp.Right.MatchLdcI4(out id))
if (!comp.Right.MatchLdcI4(out int id))
continue;
var events = FindEvents(comp.Kind == ComparisonKind.Inequality ? ifInst.FalseInst : ifInst.TrueInst);
result.Add((new LongSet(id), events));
@ -150,8 +149,7 @@ namespace ILSpy.BamlDecompiler.Rewrite @@ -150,8 +149,7 @@ namespace ILSpy.BamlDecompiler.Rewrite
if (call == null || call.OpCode == OpCode.NewObj)
return;
string eventName, handlerName;
if (IsAddEvent(call, out eventName, out handlerName) || IsAddAttachedEvent(call, out eventName, out handlerName))
if (IsAddEvent(call, out string eventName, out string handlerName) || IsAddAttachedEvent(call, out eventName, out handlerName))
events.Add(new EventRegistration { EventName = eventName, MethodName = handlerName });
}
@ -164,8 +162,7 @@ namespace ILSpy.BamlDecompiler.Rewrite @@ -164,8 +162,7 @@ namespace ILSpy.BamlDecompiler.Rewrite
var addMethod = call.Method;
if (addMethod.Name != "AddHandler" || addMethod.Parameters.Count != 2)
return false;
IField field;
if (!call.Arguments[1].MatchLdsFld(out field))
if (!call.Arguments[1].MatchLdsFld(out IField field))
return false;
eventName = field.DeclaringType.Name + "." + field.Name;
if (eventName.EndsWith("Event", StringComparison.Ordinal) && eventName.Length > "Event".Length)

Loading…
Cancel
Save